< All Blog

How to Watch Accounts Changed with MetaMask Ethereum Provider API

November 08, 2022

If users install the MetaMask browser extension, you can use MetaMask's Ethereum Provider API to watch Events, which implements Node.js EventEmitter API.

Ethereum Provider API

When MetaMask is installed, window.ethereum is available. It has on() methods, and you can filter events that notify you when accounts are changed with accountsChanged:

function handleAccountsChanged(accounts) {
  console.log(accounts)
}

// register the event listener
ethereum.on('accountsChanged', handleAccountsChanged);

// deregister the event listener
ethereum.removeListener('accountsChanged', handleAccountsChanged);

If you take care of edge cases like when MetaMask is not installed, the full source code would look like as follows:

function  watchAccountsChange(fn) {
  const { ethereum } = window
  if (ethereum) {
    ethereum.on('accountsChanged', (accounts) => {
      fn(accounts)
    })
  } else {
    throw new Error('MetaMask not installed')
  }
}

watchAccountsChange((accounts) => {
  if (accounts.length > 0) {
    const account = accounts[0]
    console.log(account)
  }
})

Recommended Posts

  1. Hardhat: How to set initial accounts balance

    November 05, 2022
    Hardhat is a toolkit for local smart contracts development. The toolset comes with Hardhat Network, which is a local blockchain network simulator where you can…