0

We want to get the n latest Blocks from ethereum mainnet. After initializing our web3 provider we need to acquire the block number of the latest block:

const latest = await web3.eth.getBlockNumber();

Based on latest's number, we now define a range from latest to latest - n - 1. This will give the 5 latest blocknumbers:

const blockNumbers = range(latest - n, latest - 1);

No we batchrequest getBlock n times:

const batch = new web3.BatchRequest();
  blockNumbers.forEach((blockNumber) => {
    batch.add(web3.eth.getBlock.request(blockNumber));
  })

We need an array for storing the return values:

let blocks = [];

Here comes the problem. Executing:

blocks = await batch.execute();

Returns one singular undefined. What am I doing wrong? I am fairly sure it's not the web3 provider, because

const latest = await web3.eth.getBlockNumber();

Returns valid numbers.

Here is the full code:

import web3 from "../ethereum/web3";

let blocks = [];
const range = (start, end, length = end - start + 1) =>
  Array.from({ length }, (_, i) => start + i)


export default async function getLatestBlocks(n) {
  console.log(`Get ${n} Blocks`)
  const latest = await web3.eth.getBlockNumber();
  const blockNumbers = range(latest - n, latest - 1);
  
  const batch = new web3.BatchRequest();
  
  blockNumbers.forEach((blockNumber) => {
    batch.add(web3.eth.getBlock.request(blockNumber));
  })

  blocks = await batch.execute();
  console.log(blocks)
  return blocks;
  
}
TylerH
  • 20,799
  • 66
  • 75
  • 101
schmark
  • 53
  • 1
  • 4

1 Answers1

0

If you use the current version web3@^1 then the execute method returns indeed void. You should handle each response separately when adding the request to the batch:

batch.add(web3.eth.getBlock.request(blockNumber), (err, block) => {
   // handle response, and check if all requests are completed.
});

This behavior we have implemented in dequanto library

tenbits
  • 7,568
  • 5
  • 34
  • 53