3

I'm using to get the balance of a single token/contract address within my wallet address.

If I have an array of tokens eg

[
    "0x2a9718deff471f3bb91fa0eceab14154f150a385",
    "0xad90c05bc51672eedfee36e58b3ff1a78bbc146d",
    "0x33a3d962955a3862c8093d1273344719f03ca17c",
    "0x85102c0062aa918cb9e26d94a284aafca602df13"
]

Is there a possibility to pass that array into a single call that retrieves the balance for each? Or would we need to iterate through the list one by one?

3

You cannot do this through regular JSONRPC calls, but it is possible to limit the number of calls needed by using a smart contract. You can use the library eth-scan to do this for you. Simply pass in the array of addresses, and it will fetch the balance for each token through the eth-scan smart contract.

By default, the library will do a single call for every 1,000 tokens, but this is configurable.

For example:

import { getTokensBalance } from '@mycrypto/eth-scan';
import Web3 from 'web3';

// Get a Web3 provider from somewhere
const web3 = new Web3;

const address = "0x....";
const tokens = [
  // ...
];

// `eth-scan` can use a Web3 provider, but Ethers.js, HTTP URLs and EIP-1193 providers
// (e.g., `window.ethereum`) are also supported
getTokensBalance(web3, address, tokens)
  .then(console.log)
  .catch(console.error);

Disclaimer: I am the author of eth-scan.

2
  • This sounds great, I'll give it a shot when I'm back at pc. Would this work for binance smart chain bep 20 tokens too? Great work on that btw
    – Gangrel
    May 1 at 12:16
  • 1
    The contract is currently not deployed on BSC, but assuming BSC is compatible with EVM smart contracts, it should work as well if the contract was deployed.
    – Morten
    May 1 at 12:21
0

You can use multicall to batch several call results to a single RPC call.

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.