< All Blog
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.
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 []