How can I get latest 10 block data by using web3.js like most block explorer does?
Use web3.eth.getBlock
with web3.eth.blockNumber
for (var i=0; i < 10; i++) {
console.log(web3.eth.getBlock(web3.eth.blockNumber - i));
}
There are a few issues with the accepted answer:
.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.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()