Lesson

Inspecting Blocks with Web3.js

Inspecting blocks is often useful when analyzing history on The Ethereum Blockchain. Web3.js has lots of functionality that helps us to do just that. For example, we could build something that looks like this block history feature on Etherscan:

Etherscan Block History

Let’s set up an app.js file to start using some of this functionality provided by Web3.js. This setup will be much simpler than the previous lessons. We’ll connect to the main net to inspect blocks there:

const Web3 = require('web3')
const web3 = new Web3('https://mainnet.infura.io/YOUR_INFURA_API_KEY')

First, we can get the latest block number like this:

web3.eth.getBlockNumber().then(console.log)

We can also get all the data for the latest block like this:

web3.eth.getBlock('latest').then(console.log)

You can watch the video above as I explain all the data that gets logged by this function.

If we were going to build a block history feature like the one on Etherscan pictured above, we would need to get a list of the most recent blocks in the chain. We can do this by fetching the most recent block and counting backwards until we have the last 10 blocks in the chain. We can do that with a for loop like this:

web3.eth.getBlockNumber().then((latest) => {
  for (let i = 0; i < 10; i++) {
    web3.eth.getBlock(latest - i).then(console.log)
  }
})

Web3.js has another nice feature that allows you to inspect transactions contained within a specific block. We can do that like this:

const hash = '0x66b3fd79a49dafe44507763e9b6739aa0810de2c15590ac22b5e2f0a3f502073'
web3.eth.getTransactionFromBlock(hash, 2).then(console.log)

That’s it! That’s how easy it is to inspect blocks with Web3.js. Check out the video above for more in depth explanation of the data returned by the blocks. At this point, all of the tutorial code should look like this:

const Web3 = require('web3')
const web3 = new Web3('https://mainnet.infura.io/YOUR_INFURA_API_KEY')

// get latest block number
web3.eth.getBlockNumber().then(console.log)

// // get latest block
web3.eth.getBlock('latest').then(console.log)

// get latest 10 blocks
web3.eth.getBlockNumber().then((latest) => {
  for (let i = 0; i < 10; i++) {
    web3.eth.getBlock(latest - i).then(console.log)
  }
})

// get transaction from specific block
const hash = '0x66b3fd79a49dafe44507763e9b6739aa0810de2c15590ac22b5e2f0a3f502073'
web3.eth.getTransactionFromBlock(hash, 2).then(console.log)

Now you can run the app.js file from your terminal with NodeJS like this:

$ node app.js

Or simply:

$ node app

Feel free to reference the video above if you get stuck! You can also download all the code examples in this tutorial series from github.

Course Discussion