< All Blog

How to Get Accounts from Ethereum with MetaMask Ethereum Provider API

November 07, 2022

If users install the MetaMask browser extension, you can use MetaMask's Ethereum Provider API to get accounts from the Ethereum blockchain.

Ethereum Provider API

When MetaMask is installed, window.ethereum is available. It has request(args) function, that accepcts method and params as arguments. It internally calls Ethereum's JSON RPC.

interface RequestArguments {
  method: string;
  params?: unknown[] | object;
}

ethereum.request(args: RequestArguments): Promise<unknown>;

As of writing this post, eth_accounts is defined to return a list of addresses. Therefore all you need is to call ethereum.request() wrapper function with eth_accounts method without any parameters.

window.ethereum.request({ method: 'eth_accounts' })

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

async function getAccounts() {
  const { ethereum } = window
  if (ethereum) {
    const accounts = ethereum.request({ method: 'eth_accounts' })
    if (accounts.length > 0) {
      return accounts
    } else {
      throw new Error('cannot get accounts, check that you login MetaMask')
    }
  }
  throw new Error('MetaMast not installed')
}

Please note that it returns an empty array when users do not log in to MetaMask.

>> await window.ethereum.request({ method: 'eth_accounts' })
<- Array []

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…