Search code examples
javascriptethereumweb3jsmetamask

How to get a list of accounts from the new MetaMask ethereum API?


MetaMask recently changed how they inject their API and no longer expose the window.web3 object.

MetaMask no longer injects web3. For details, see: https://docs.metamask.io/guide/provider-migration.html#replacing-window-web3

Uncaught TypeError: web3.eth is undefined

How to get a list of accounts from the new MetaMask ethereum API?


Solution

  • You can use the window.ethereum object injected by MetaMask or other wallets.

    if (typeof window.ethereum !== 'undefined') {
      // connects to MetaMask
      const accounts = await ethereum.request({ method: 'eth_requestAccounts' });
    } else {
      // tell the user to install an `ethereum` provider extension
    }
    

    This uses the new API calling an asynchronous Ethereum request on the provider. It accepts most of the Ethereum APIs and is pretty generic in the implementation.