Are there any best practices to fetching all ERC20 token balances for a given address? I am open to using external APIs.
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:
- 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.
- 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.
- You can just do a few
eth_callto the candidates from step 1, to check the result is successful for functions such as
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.