How can I get the data of the latest 10 blocks via web3.js?

by Satoshi Nakanishi   Last Updated December 06, 2018 14:28 PM

How can I get latest 10 block data by using web3.js like most block explorer does?



Answers 2


Use web3.eth.getBlock with web3.eth.blockNumber

for (var i=0; i < 10; i++) {
  console.log(web3.eth.getBlock(web3.eth.blockNumber - i));
}
eth
eth
February 25, 2016 03:25 AM

There are a few issues with the accepted answer:

  1. as @Lam-Le mentions, .getBlock() and .getBlockNumber() are both asynchronous so if a new block is created during the loop not only will you no longer obtain the 'latest' blocks but you will also have duplicates.
  2. the loop creates an disproportionate amount of network request (2 x i+1).

To solve the first concern you must keep a reference to the latest blockNumber:

const latest = await web3.eth.getBlockNumber()

In order to reduce the amount of network request web3 you can use BatchRequests.

const batch = new web3.eth.BatchRequest()
batch.add(web3.eth.getBlock.request(blockNumber, callback))
batch.execute()

Notice that in order to pass the arguments to the function, you need to use the special request method.

Putting them together, you can retrieve the last n blocks with:

const latest = await web3.eth.getBlockNumber()
const blockNumbers = _range(latest - n, latest + 1, 1)
const batch = new web3.eth.BatchRequest()

blockNumbers.forEach((blockNumber) => {
  batch.add(
    web3.eth.getBlock.request(blockNumber, storeLocalCopy)
  )
})

batch.execute()
vilsbole
vilsbole
December 06, 2018 14:04 PM

Related Questions


Dump all contract Address created?

Updated August 27, 2017 02:28 AM

Extension Node formatting

Updated November 22, 2017 02:28 AM


Search blockchain without having own node running?

Updated March 30, 2018 14:28 PM