ERC20 – Efficient Methods to Read Token Balances Without Address Knowledge

balanceserc-20explorerstokensweb3js

There are plenty of examples of reading the balance of an ERC20 token from an address via a balanceOf.call when knowing the token contract address beforehand. However, how would one go about reading the balance of an address without knowing which tokens the address might hold?

For example, a user wishes to know the total balance (ETH + tokens) of his address. What would be the most efficient way of retrieving this information without doing any unnecessary calculations?

Should I just loop through an array of the most popular token contract addresses? Look at the incoming token transfer events? or are there more efficient ways?

Just to specify, I am looking for a solution with a private node not an API.

Examples of pages that have achieved this:

Any help would be greatly appreciated!

Best Answer

If you're interested in just a relatively small subset of popular ERC20 tokens, then looping over them might be okay.

But if you want everything, I think your best bet is to process the logs as you go and look for Transfer(address,address,uint256) events. For each event, if the source looks like an ERC20 token (e.g. has name/symbol/decimals), do some accounting in your database where you're keeping track of these things.

Related Topic