How to Get the Number of Transactions in a Block

This is a simple script to teach you how to communicate with the blockchain and read the number of transactions in a block.

This guide assumes you've gone through the getting started steps and have an Alchemy account!

📘

API Endpoint

This tutorial uses the eth_getBlockTransactionCountByNumber endpoint.

Each Block in a Blockchain is assigned a block number. It is the unique sequential number for each Block. Follow the steps below to return all transactions in the current finalized Block on Ethereum:

1. From your command line, create a new project directory and cd into it:

mkdir get-num-block-txns
cd get-num-block-txns

2. Install the Alchemy SDK if you have not already

You can use any web3 library of your choosing. However, there are tons of benefits to using the Alchemy SDK. In this guide, we will make use of the Axios library as well.

npm install alchemy-sdk axios
yarn add alchemy-sdk axios

3. Create a file named index.js and add the following contents:

const options = {
  method: "POST",
  url: "https://eth-mainnet.g.alchemy.com/v2/{your-api-key}",
  headers: { accept: "application/json", "content-type": "application/json" },
  data: {
    id: 1,
    jsonrpc: "2.0",
    method: "eth_getBlockTransactionCountByNumber",
    params: "finalized",
  },
};

axios
  .request(options)
  .then(function (response) {
       console.log(response.data);
  })
  .catch(function (error) {
    console.error(error);
  });

This is an axios call, where a POST request is made to the Alchemy API and the data sent contains the particular endpoint called

method: "eth_getBlockTransactionCountByNumber",

And the param which specifies, returning information on the most recent finalized Block:

params: "finalized",

4. Run it using node

node index.js

You will see the following response logged to the console:

{ jsonrpc: '2.0', id: 1, result: '0xb3' }

This response is in HEX. To view it in decimal, you can add a simple convert function to the code:

5. Converting HEX to Decimal:

function hexToDec(hex) {
  return parseInt(hex, 16);
}

Convert the result response from Hexademical to Decimal. Target the result by updating the response in the then block.

. . . .
 result = response.data.result;
 console.log(hexToDec(result));

The result will be returned as a number in the console:

179

Once you complete this tutorial, let us know how your experience was or if you have any feedback by tagging us on Twitter @alchemyplatform! 🎉


ReadMe