0

Are there any best practices to fetching all ERC20 token balances for a given address? I am open to using external APIs.

1

One approach is identifying the ERC20 contract first, you can do this by different heuristics. Once you have the list of ERC20 contract addresses you use JSON RPC to do a eth_call for each ERC20 using the ERC20 ABI to obtain the balance of the address you want. To identify the ERC20 contracts in a blockchain you can:

  1. Download the code of each contract and search for the function signatures (32 bits) of the ERC20 methods. The bytecode of all the ERC20 contracts will include those 32 bits for each method. You can have false positives.
  2. You can do this after step 1, you check the events emitted for each address to identify the standard ERC20 events, this will eliminate false positives.
  3. You can just do a few eth_call to the candidates from step 1, to check the result is successful for functions such as totalSupply, decimals, symbol

You could do 3 without without doing 1 first but that would be more time consuming.

If you will do this often then you need to create an indexed DB. Once you have the ERC20 identified you create a service to monitor events from those contracts using JSON RPC. That server will extract the source and destination address from events such as Transfer and update the balance for those addresses in the DB.

If you use a third party service you will be trusting a third party and that is not a good decentralized system practice.

| improve this answer | |
  • I don't have a particular contract in mind, I'd like to fetch all ERC20 tokens for a given address (kind of like what Etherscan does). – Tarek Jul 28 at 22:06
  • You can use a third party API, what I described is how those API work. There isn't an index in the blockchain where you can ask all the ERC20 tokens owned by a given address. You can search events but you don't know if they are from ERC20 tokens, you need to get the list of ERC20 tokens contracts first. – nultrino Jul 28 at 22:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.