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!

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:

shell
$mkdir get-num-block-txns
>cd get-num-block-txns

2. Install HTTP client library

You can use any HTTP library of your choosing. In this guide, we will make use of the Axios library for HTTP requests.

$npm install axios

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

index.js
1const options = {
2 method: "POST",
3 url: "https://eth-mainnet.g.alchemy.com/v2/{your-api-key}",
4 headers: { accept: "application/json", "content-type": "application/json" },
5 data: {
6 id: 1,
7 jsonrpc: "2.0",
8 method: "eth_getBlockTransactionCountByNumber",
9 params: "finalized",
10 },
11};
12
13axios
14 .request(options)
15 .then(function (response) {
16 console.log(response.data);
17 })
18 .catch(function (error) {
19 console.error(error);
20 });

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

shell
$node index.js

You will see the following response logged to the console:

json
1{ 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:

javascript
1function hexToDec(hex) {
2 return parseInt(hex, 16);
3}

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

index.js
1 result = response.data.result;
2 console.log(hexToDec(result));

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

json
1179

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