Search code examples
next.jsblockchainethereum

How can I get 2nd balance from MetaMask?


Please give me a solution to get 2 balance(HPB, ESR) from an account. enter image description here


Solution

  • In order to get a token balance, you need to know the address of the token contract, because the token balance of an address is stored on the token contract.

    MetaMask only shares the saved accounts to the requesting app (and the user needs to manually confirm this action first). But it doesn't share the token addresses, that the user added to their MM UI.

    So if you know the token address, you can use a simple web3 call for example:

    const jsonAbi = {}; // JSON ABI of the token contract
    const contractAddress = "0x123"; // address of the token contract
    const tokenAddress = "0xfF3d"; // address of which you want to get the token balance
    
    const token = new web3.eth.Contract(jsonAbi, contractAddress);
    const balance = await token.balanceOf(tokenAddress);