eth_subscribe("newHeads") | Avalanche

Avalanche API method allowing developers to receive real-time notifications regarding new block headers on the Avalanche blockchain; it sends notifications whenever a new block is added.

👍

Get you own node endpoint today

Start for free and get your app to production levels immediately. No credit card required.

You can sign up with your GitHub, X, Google, or Microsoft account.

Parameters

  • string — keyword identifying the type of event to subscribe to, newHeads in this case.

Response

  • subscription — the subscription ID.
  • 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 Avalanche 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 Avalanche 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 Avalanche network since the inception of the network. It measures the overall security and integrity of the Avalanche 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.

eth_subscribe("newHeads") code examples

📘

Note that subscriptions require a WebSocket connection and WebSocket cat for you to use this method in the console.

Install WebSocket cat with:

npm install -g wscat

$ wscat -c YOUR_CHAINSTACK_WEBSOCKET_ENDPOINT
# Wait for the connection to be established

Connected (press CTRL+C to quit)

> {"id":1,"jsonrpc":"2.0","method":"eth_subscribe","params":["newHeads"]}
const WebSocket = require('ws');

const webSocket = new WebSocket('CHAINSTACK_WSS_URL');

async function subscribeToNewBlocks() {
  
  const request = {
    id: 1,
    jsonrpc: '2.0',
    method: 'eth_subscribe',
    params: ['newHeads'],
  };

  const onOpen = (event) => {
    webSocket.send(JSON.stringify(request));
  };

  const onMessage = (event) => {
    const response = JSON.parse(event.data);
    console.log(response);
  };

  try {
    webSocket.addEventListener('open', onOpen);
    webSocket.addEventListener('message', onMessage);
  } catch (error) {
    console.error(error);
  }
}

subscribeToNewBlocks();

This will generate a continuous stream of data displaying new block headers as they are added to the chain.

Use eth_unsubscribe to remove the subscription.

Use case

The eth_subscribe("newHeads") method can be useful in a variety of real-world scenarios, such as:

  • Real-time monitoring of blockchain activity. Companies or individuals who rely on the Avalanche network for their business can use eth_subscribe("newHeads") to receive real-time notifications about new blocks being added to the chain. This can help them keep track of important transactions, such as high-value trades, in real time and respond quickly to any issues that may arise.

  • Decentralized Finance (DeFi) applications. DeFi applications, such as lending platforms, can use eth_subscribe("newHeads") to monitor the blockchain for new blocks that might contain important data, such as changes in interest rates or new lending opportunities.

  • Smart contract automation. Developers can use eth_subscribe("newHeads") to trigger automated smart contract actions whenever a new block is added to the chain. For example, a smart contract could automatically execute an action order whenever a new block is added that meets certain criteria.