Web3js

應為參數指定 JSONRPC 方法:“未定義”,同時在 web3 js 中批處理請求

  • October 23, 2018

我能夠在循環中獲得 ERC20 令牌的餘額,但是當我嘗試使用 BatchRequest 時,我收到以下錯誤JSONRPC method should be specified for params: “undefined”

下面的程式碼拋出一個錯誤:

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提到了方法名稱,balanceHex其中是 const balanceHex = "0x70a08231000000000000000000000000";

沒有批處理請求的工作程式碼:

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

有什麼我想念的,任何幫助將不勝感激。

打回來:

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

中的add()方法BatchRequest接受一個請求對象:

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

注意.request下面的.call

最終答案:

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

引用自:https://ethereum.stackexchange.com/questions/41561