Skip to content
Advertisement

How to speed up token balance on multiple contracts

I’m using ethers to call balanceOf method on all contracts to check if user has any balance there, if not, the token will not show up in his dashboard, but it takes a lot of time, is there a more finesse way to achieve the same goal?

my code:

        for (let key in tokens) {
        if (tokens.hasOwnProperty(key)) {
            let contract_address_to_check = tokens[key].address;
            if (contract_address_to_check != "0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee") {
                const Contract = new ethers.Contract(contract_address_to_check, Abi, provider);
                let balance_wei = await Contract.balanceOf(address);
                
                if (balance_wei > 0) {
                    let decimals = await Contract.decimals();
                    let balance = balance_wei / 10 ** decimals;
                    console.log(tokens[key].address);
                    console.log(tokens[key].decimals);
                    console.log(tokens[key].symbol);
                    console.log(balance);
                }
            }
        }
    

Advertisement

Answer

You can use Multicall contract for small wins. A proper solution is indexers like TheGraph that continuously read the blockchain and keep the data available indexed.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement