subscribe("newBlockHeaders") | Ethereum

web3.js subscription equivalent to eth_newBlockFilter. subscribe("newBlockHeaders") allows developers to subscribe to real-time updates about new block headers on the Ethereum blockchain; the application will receive notifications whenever a new block is added to the blockchain. The notification will include information about the new block, such as its block number, hash, and timestamp.

Parameters

  • string β€” a keyword identifying the type of event to subscribe to, newBlockHeaders in this case.
  • function β€” (optional) a callback function that will be called every time a new event of the specified type is received. This function takes two parameters: error and result. The error parameter contains any error that occurred while subscribing to the event, and the result parameter contains the data for the event that was received.

Response

  • objectβ€” a block object with the following fields:
    • number β€” the block number of the requested block, encoded as hexadecimal. null if the block is pending.
    • hash β€” the block hash of the requested block. null if the block pending.
    • parenthash β€” hash of the previous block used to generate the current block. Also known as the 'parent block'.
    • nonce β€” the hash used to demonstrate proof-of-work. null if the block pending. It returns 0x0000000000000000 when the consensus is proof-of-stake.
    • sha3uncles β€” the hash of the list of uncles included in the block. It is used to identify the block uniquely and to verify the integrity of the block's data.
    • logsbloom β€” the bloom filter for the logs of the block, a data structure that allows for efficient membership testing of elements in a set, in this case, the logs included in the block. null if pending.
    • transactionsroot β€” the root of the transaction trie of the block. The transactionsRoot field allows Ethereum nodes to verify the integrity of the transactions in a block.
    • stateroot β€” the root of the final state trie of the block. The stateroot field is included in the block header and is used to verify the integrity of the state at the time the block was processed
    • receiptsroot β€” the root of the receipts trie of the block. A 32-byte hash of the root node of the receipts trie of all transactions in the block. It is used to verify the integrity of the receipts data for all transactions in the block.
    • miner β€” the address of the miner receiving the reward.
    • difficulty β€” a measure of how hard it is to find a valid block for the Ethereum blockchain. It is a number that increases as more miners join the network and more blocks are added to the chain, encoded as hexadecimal.
    • totaldifficulty β€” the cumulative sum of the difficulty of all blocks that have been mined in the Ethereum network since the inception of the network. It measures the overall security and integrity of the Ethereum network.
    • extradata β€” extra data included in a block by the miner who mined it. It often includes messages or other information related to the block.
    • size β€” the size of this block in bytes as an integer value, encoded as hexadecimal.
    • gaslimit β€” the maximum gas allowed in this block, encoded as hexadecimal.
    • gasused β€” the total used gas by all transactions in this block, encoded as hexadecimal.
    • timestamp β€” the Unix timestamp for when the block was collated.
    • transactions β€” an array of transaction objects. See eth_getTransactionByHash for the exact shape.
    • uncles β€” an array of uncle hashes.

subscribe("newBlockHeaders") code example

πŸ“˜

Note that web3.js subscriptions require a WebSocket connection.

Use the event emitter instances to attach event listeners to the subscription object:

  • data β€” activates for each new syncing event:
  • error β€” activates if an error is detected during the subscription.
  • connected β€” activates after the subscription is successfully connected and returns the subscription ID.
  • unsubscribe β€” unsubscribes the subscription and returns true if successful.
const Web3 = require("web3");
const NODE_URL = "CHAINSTACK_WSS_URL";
const web3 = new Web3(NODE_URL);

async function subscribeToNewBlocks() {
    try {
        // Create a new subscription to the 'newBlockHeaders' event
        const subscription = await web3.eth.subscribe('newBlockHeaders');

        // Attach event listeners to the subscription object
        subscription.on('connected', handleConnected);
        subscription.on('data', handleNewBlock);
        subscription.on('error', handleError);
    } catch (error) {
        console.error(`Error subscribing to new blocks: ${error}`);
    }
}

/* Fallback functions to react to the different events */

// Event listener that logs a message when the subscription is connected
function handleConnected(subscriptionId) {
    console.log(`New subscription: ${subscriptionId}`);
}

// Event listener that logs the received block header data
function handleNewBlock(blockHeader) {
    console.log(blockHeader);
}

// Event listener that logs any errors that occur
function handleError(error) {
    console.error(`Error receiving new blocks: ${error}`);
}

subscribeToNewBlocks();

Use case

A practical use case for subscribe("newBlockHeaders") is a DApp that continuously listens for new block headers, then isolates the block number and baseFeePerGas for analytics purposes.

The following is an implementation of this concept using web3.js subscriptions:

const Web3 = require("web3");
const NODE_URL = "CHAINSTACK_WSS_URL";
const web3 = new Web3(NODE_URL);

let subscription;
let blockCount = 0;

async function subscribeToNewBlocks() {
    try {
        // Create a new subscription to the 'newBlockHeaders' event
        subscription = await web3.eth.subscribe('newBlockHeaders');

        // Attach event listeners to the subscription object
        subscription.on('connected', handleConnected);
        subscription.on('data', handleNewBlock);
        subscription.on('error', handleError);
    } catch (error) {
        console.error(`Error subscribing to new blocks: ${error}`);
    }
}

function unsubscribeFromNewBlocks() {
    subscription.unsubscribe(function(error, success) {
        if (success) console.log("Successfully unsubscribed!");
      	return process.exit(1)
    });
}

/* Fallback functions to react to the different events */

// Event listener that logs a message when the subscription is connected
function handleConnected(subscriptionId) {
    console.log(`New subscription: ${subscriptionId}`);
}

// Event listener that extracts block number and base fee per gas from the received block header data
function handleNewBlock(blockHeader) {

    const blockNumber = blockHeader.number;
    const baseFeePerGas = web3.utils.toBN(blockHeader.baseFeePerGas);
    const baseFeeGwei = web3.utils.fromWei(baseFeePerGas, 'Gwei');

    blockCount++;
    console.log(`Block number: ${blockNumber} \n Base Fee per Gas: ${baseFeeGwei} Gwei \n`);
    if (blockCount === 100) {
        unsubscribeFromNewBlocks();
    }
}

// Event listener that logs any errors that occur
function handleError(error) {
    console.error(`Error receiving new blocks: ${error}`);
}

subscribeToNewBlocks();

This code creates a new subscription to the newBlockHeaders event using the web3.eth.subscribe method. This method returns a subscription object that can be used to attach event listeners to the subscription.

The code defines three event listener functions that are attached to the subscription object: handleConnected, handleNewBlock, and handleError. The handleConnected function is called when the subscription is connected, and it logs a message with the subscription ID. The handleNewBlock function is called when a new block header is received, and it extracts the block number and base fee per gas from the block header data using the web3.utils methods. The handleError function is called when an error occurs, and it logs an error message.

This code includes an unsubscribeFromNewBlocks function which unsubscribes from the newBlockHeaders subscription and quit the program using return process.exit(1) after it received 100 new blocks. This is to demonstrate its use.

Finally, the code calls the subscribeToNewBlocks function, which creates the subscription and attaches the event listeners. When a new block header is received, the handleNewBlock function is called to extract the block data and log it to the console.