According to the MetaMask docs the recommended way to access the web3 is by creating a new instance of the Web3 class by passing the window.web3.currentProvider, which is injected by the MetaMask extension, to it's constructor:

const Web3 = require('web3');

const web3 = new Web3(window.web3.currentProvider);

However, when instantiated this way, the web3.eth.defaultAccount property is null and when I change accounts in the extension, the current account is not reflected in the Web3 instance.

On contrary, when I use the Web3 instance, which is injected directly, it works perfectly fine. I can access the web3.eth.defaultAccount right away and it's updated dynamically when I change current account in the extension:

const web3 = window.web3;

Why is that and how do I implement the correct integration with MetaMask?

  • MetaMask version: 3.12.1
  • web3 version: 0.19.0

Try web3.eth.accounts[0].

Or async, web3.eth.getAccounts(_accounts => selectedAccount = _accounts[0]). This will save the currently selected Metamask account to selectedAccount

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.