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.
Get your 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— a keyword identifying the type of event to subscribe to,newBlockHeadersin this case. In ethers.js v6 this maps to the"block"event on aWebSocketProvider.function— a listener function that will be called every time a new block is received. With ethers.js v6, the listener receives the block number of the newly added block.
Response
-
object— a block object with the following fields:number— the block number of the requested block, encoded as hexadecimal.nullif the block is pending.hash— the block hash of the requested block.nullif 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.nullif the block pending. It returns0x0000000000000000when 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.nullif pending.transactionsroot— the root of the transaction trie of the block. ThetransactionsRootfield allows Ethereum nodes to verify the integrity of the transactions in a block.stateroot— the root of the final state trie of the block. Thestaterootfield is included in the block header and is used to verify the integrity of the state at the time the block was processedreceiptsroot— 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 subscriptions require a WebSocket connection. Use a
WebSocketProvider in ethers.js v6.provider.on("block", listener)— fires for each new block and passes the block number to the listener.provider.on("error", listener)— fires if an error is detected on the connection.provider.off("block", listener)— removes a single listener for the"block"event.provider.removeAllListeners()— removes every listener, which effectively unsubscribes.
Use case
A practical use case forsubscribe("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 ethers.js v6 subscriptions:
"block" event on a WebSocketProvider. Attaching a listener with provider.on("block", ...) starts the subscription and invokes the listener for every new block.
The code defines two listener functions that are attached to the provider: handleNewBlock and handleError. The handleNewBlock function is called when a new block is received; it fetches the full block with provider.getBlock and extracts the block number and base fee per gas, formatting the latter to gwei with ethers.formatUnits. The handleError function is called when an error occurs, and it logs an error message.
This code includes an unsubscribeFromNewBlocks function which removes the listeners with provider.removeAllListeners and quits 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.