2

I'm trying to use the web3 Batch in order to call token balances all together. When I call batch.execute() it returns undefined instead of the resolved requests that have been added to the batch.

Can someone enlighten me where I am messing things up?

Here is my code.

async generateContractFunctionList(
    address: Address,
    tokens: Token[],
    blockNumber: number
  ) {
    const batch = new this.web3.BatchRequest();

    for (let i = 0; i < tokens.length; i++) {
      const contract = new this.web3.eth.Contract(balanceABI as AbiItem[]);
      contract.options.address = tokens[i].address;

      batch.add(
        contract.methods
          .balanceOf(address.address)
          .call.request({}, blockNumber)
      );
    }

    return batch;
  }
 async updateBalances() {
    try {
      const addresses = await this.addressService.find();
      const tokens = await this.tokenService.find();
      const blockNumber = await this.web3.eth.getBlockNumber();

      for (let i = 0; i < addresses.length; i++) {
        const address = addresses[i];
        const batch = this.generateContractFunctionList(address, tokens, blockNumber);

        const response = await (await batch).execute();
        console.log(response);  //returns undefined 
      } 
    } catch (error: unknown) {
      if (error instanceof Error) {
        console.log(`UpdateBalanceService updateBalances`, error.message);
      }
    }
  }

why does batch.execute() not return anything and is void? I went by this example from this article and modified it to my needs but did not change too much of the stuff that could be messing it up.

https://chainstack.com/the-ultimate-guide-to-getting-multiple-token-balances-on-ethereum/

when I add a callback function to the "batch.add" and console log, balance get logged to console. But I am trying to use async await on the .execute() so how can I get a result from the method calls with await batch.execute() and have all the callback results in there like its written in the blog post.

TylerH
  • 20,799
  • 66
  • 75
  • 101
user16780074
  • 429
  • 2
  • 7
  • 20

2 Answers2

2

A quick and dirty solution is to use an outdated version of the package.

package.json:

....
"dependencies": {
    ...
    "web3": "^2.0.0-alpha.1",
    ...
    }
....

TylerH
  • 20,799
  • 66
  • 75
  • 101
1

I'm a developer advocate at Chainstack.

batch.add()requires a callback function as the last parameter. You can either change your code to pass a callback or, as mentioned above use version 2.0.0-alpha as used in the article.

We'll update the article soon to use the latest version of web3.js

TylerH
  • 20,799
  • 66
  • 75
  • 101
Antonio U
  • 141
  • 4