Web3 Get All Tokens by Wallet Address

10,647

ERC-20 (and ERC-20-like such as TRC-20, BEP-20, etc.) token balance of each address is stored in the contract of the token.

Blockchain explorers scan each transaction for Transfer() events and if the emitter is a token contract, they update the token balances in their separate DB. The balance of all tokens per each address (from this separate DB) is then displayed as the token balance on the address detail page.

Etherscan and BSCScan currently don't provide an API that would return the token balances per address.

In order to get all ERC-20 token balances of an address, the easiest solution (apart from finding an API that returns the data) is to loop through all token contracts (or just the tokens that you're interested in), and call their balanceOf(address) function.

const tokenAddresses = [
    '0x123',
    '0x456',
];
const myAddress = '0x789';

for (let tokenAddress of tokenAddresses) {
    const contract = new web3.eth.Contract(erc20AbiJson, tokenAddress);
    const tokenBalance = await contract.methods.balanceOf(myAddress).call();
}
Share:
10,647
Admin
Author by

Admin

Updated on June 18, 2022

Comments

  • Admin
    Admin almost 2 years

    I am trying to pull a list of token contracts held by a wallet address, similar to how bscscan does, except programmatically. bscscan.com/apis does not have an endpoint, and web3 seems to only report the ETH balance.

    This is possible to achieve, since bscscan reports the list and many token trackers ( such as farmfol.io ) also seem to pull that information. I am just not finding the correct methodology. Any assistance is appreciated!

  • Admin
    Admin almost 3 years
    I just tested it, and your code worked like an absolute charm. Thanks for your help!
  • AllJs
    AllJs over 2 years
    Hi there. Thanks for your answer. Looking at your code I am wondering if in addition of all erc20 token addresses, you will also need their respective abis to make this work. Correct? Please clarify that for me if you can. Thanks again
  • Petr Hejda
    Petr Hejda over 2 years
    @AllJs In this case, you just need the ABI of the balanceOf() function, which is the same for all token contracts (assuming they all follow the ERC20 standard), because you're only calling this function... If you wanted to call other functions, you'd need to add them to the ABI as well.