5

I am able to get the balance for an ERC20 tokens in a loop, but when I try to use BatchRequest I get the following error JSONRPC method should be specified for params: "undefined"

Below code is throwing an error:

async function getBalanceInBatch(address) {
  const batch = new web3.BatchRequest();
  const contractData = balanceHex + address.substring(2);

  for (let token of tokens) {
    const params = { to: token.address, data: contractData, from: address };
    batch.add(web3.eth.call(params), callBack)
  }

  batch.execute()
}

balanceOf method name is mentioned in balanceHex which is const balanceHex = "0x70a08231000000000000000000000000";

Working code without batch request:

const contractData = balanceHex + address.substring(2);
const params = { to: contractAddress, data: contractData };
const result = await web3.eth.call(params);

Is anything I am missing, any help will be appreciated.

Callback:

function callBack(result) {
  console.warn("callback:", result)
}
6
+50

The add() method in BatchRequest accepts a request object:

batch.add(web3.eth.call.request(param, callBack))

Notice the .request that follows .call

Final answer:

function getBalanceInBatch(address) {
      const batch = new web3.BatchRequest();
      const contractData = balanceHex + address.substring(2);

      for (let token of tokens) { // tokens is list of erc20 tokens
        const params = { to: token.address, data: contractData, from: address };
        batch.add(web3.eth.call.request(params, callBack));
      }

      batch.execute()
    }

    function callBack(err, result) {
      const totalTokens = web3.utils.toBN(result).toString();
      const balance = web3.utils.fromWei(totalTokens, "ether");
      console.warn("balance", balance);
    }
5
  • Thanks for the answer, It fix the error but callback is not being called. I have updated the answer with call back function as well. Mar 12 '18 at 19:42
  • Changed my answer. The callBack should be passed as the second parameter to request() not to add(). Also the callBack function should accept 2 parameters: function callBack(err, data) Mar 12 '18 at 19:51
  • Yeah that worked, the only issue now result is always null, how can I get a balance for an erc20 tokens. Mar 12 '18 at 20:21
  • It works for me. Do you use the 1st or 2nd argument in the callback? Mar 12 '18 at 20:27
  • Yup, it worked for me as well now:) thanks a lot of the help. Mar 12 '18 at 20:37

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.