首页 > 解决方案 > Web3 BatchRequest 总是返回未定义,我做错了什么?

问题描述

我试图使用 web3 Batch 来调用代币余额。当我调用 batch.execute() 时,它返回未定义而不是已添加到批处理中的已解决请求。有人可以告诉我我在哪里搞砸了?这是我的代码。

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);
      }
    }
  }

为什么 batch.execute() 不返回任何东西并且是无效的?我参考了这篇文章中的这个例子,并根据我的需要对其进行了修改,但并没有改变太多可能会搞砸的东西。

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

当我向“batch.add”和控制台日志添加回调函数时,余额被记录到控制台。但是我正在尝试在 .execute() 上使用异步等待,所以我怎样才能从使用 await batch.execute() 的方法调用中获得结果,并将所有回调结果都保存在其中,就像它在博客文章中所写的那样。

标签: node.jsweb3erc20ethers.js

解决方案


面临同样的问题。一个快速而肮脏的解决方案是使用包的过时版本。

包.json

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


推荐阅读