我正在尝试使用 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/ https://chainstack.com/the-ultimate-guide-to-getting-multiple-token-balances-on-ethereum/
当我将回调函数添加到“batch.add”和控制台日志时,余额会记录到控制台。但我正在尝试在 .execute() 上使用 async wait ,那么如何从使用 wait batch.execute() 的方法调用中获取结果,并将所有回调结果都放在其中,就像博客文章中所写的那样。