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.
Developer advocate at Chainstack here.
This is one of the common tasks that should have a simple way but don't, unfortunately. Getting this kind of data from the chain is certainly possible but not as straightforward as it should be; I'll give you two options here.
The first and best option if you want to index the data yourself is to use a Subgraph, which allows you to index data coming from smart contracts; since smart contracts manage ERC-20 tokens, this is a good solution.
Here, you can find a guide from the Chainstack dev portal showing you how to index ERC-20 tokens with Subgraphs, which include balances. You can essentially make an API from this.
You can then query the data using Python if you want to.
Chainstack offers Subgraphs for various chains, so you can do this for multiple networks if needed.
Use third party APIs
Full disclosure: I am a dev advocate at Chainstack, and feel free to reach out!