Web3js

從一系列區塊號 web3 中的區塊中獲取所有交易

  • March 28, 2022

以前看過類似的文章,但可以縫合以使任何工作。我正在嘗試從一系列塊(startBlock-endBlock)中提取塊數據(主要是所有事務),但不斷收到錯誤或函式檢出但我返回“未定義”

使用我在這裡找到的一個函式來按塊範圍獲取事務計數(直到完整列表):geth 的常用 JavaScript 片段

function checkTransactionCount(startBlockNumber, endBlockNumber) {
 console.log("Searching for non-zero transaction counts between blocks "  + startBlockNumber + " and " + endBlockNumber);

 for (var i = startBlockNumber; i <= endBlockNumber; i++) {
   var block = web3.eth.getBlock(i);
   if (block != null) {
     if (block.transactions != null && block.transactions.length != 0) {
       console.log("Block #" + i + " has " + block.transactions + " transactions")
     }
   }
 }  
}

但是當我跑步時得到“未定義”checkTransactionCount(startBlockNumber, endBlockNumber).

web3.js 很新,任何幫助表示讚賞

web3.eth.getBlock(i)是一個非同步函式,你應該使用回調或非同步/等待。因為你不是在等待結果,你undefined只是因為沒有結果(還)。

這是使用回調的版本:

function checkTransactionCount(startBlockNumber, endBlockNumber) {
 console.log(
   "Searching for non-zero transaction counts between blocks " +
     startBlockNumber +
     " and " +
     endBlockNumber
 );

 for (var i = startBlockNumber; i <= endBlockNumber; i++) {
   web3.eth.getBlock(i, (err, block) => {
     if (err == null && block != null) {
       if (block.transactions != null && block.transactions.length != 0) {
         console.log(
           "\n\nBlock #" + i + " has " + block.transactions + " transactions"
         );
       }
     }
   });
 }
}

或者如上所述,您可以像這樣使用 async / await :

async function checkTransactionCount(startBlockNumber, endBlockNumber) {
 console.log(
   "Searching for non-zero transaction counts between blocks " +
     startBlockNumber +
     " and " +
     endBlockNumber
 );

 for (var i = startBlockNumber; i <= endBlockNumber; i++) {
   let block = await web3.eth.getBlock(i);
   if (block != null) {
     if (block.transactions != null && block.transactions.length != 0) {
       console.log(
         "\n\nBlock #" + i + " has " + block.transactions + " transactions"
       );
     }
   }
 }
}

編輯:這是一個使用 async / await 返回一個數組的範例,其中包含startBlockNumber和之間存在的事務雜湊endBlockNumber

const Web3 = require("Web3");
const ENDPOINT = "https://mainnet.infura.io/v3/YOUR_PROJECT_ID";

let web3 = new Web3(ENDPOINT);

async function checkTransactionCount(startBlockNumber, endBlockNumber) {
 transactions = [];

 for (var i = startBlockNumber; i <= endBlockNumber; i++) {
   let block = await web3.eth.getBlock(i);
   if (block != null) {
     if (block.transactions != null && block.transactions.length != 0) {
       transactions = transactions.concat(block.transactions);
     }
   }
 }

 return transactions;
}

async function main() {
 console.log(
   "Searching for non-zero transaction counts between blocks 2000000 and 2000010"
 );
 let transactions = await checkTransactionCount(2000000, 2000010);

 console.log(transactions.length + " transactions found");
 console.log(transactions);
}

main();

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