eth_getBlockByNumber | Avalanche

Recipes
πŸ“¨
Monitor incoming transactions to an Ethereum address in real time using subscriptions and web3.js
Open Recipe

Avalanche API method that returns information about the block matching the given block number. This method can retrieve a wide range of information about the block, such as its hash, timestamp, difficulty, and gas limit. You can also retrieve transaction objects included in the block if needed.

πŸ‘

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

  • quantity or tag β€” the integer of a block encoded as hexadecimal or the string with:

    • latest β€” the most recent block in the blockchain and the current state of the blockchain at the most recent block

    • earliest β€” the earliest available or genesis block

    • pending β€” the pending state and transactions block. The current state of transactions that have been broadcast to the network but have not yet been included in a block.

      πŸ“˜

      See the default block parameter.

  • boolean β€” if true, it returns the detail of each transaction. If false, only the hashes of the transactions.

Response

  • object β€” a block object, or null when no block was found.
    • 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 β€” array of transaction objects. See eth_getTransactionByHash for the exact shape.
    • uncles β€” array of uncle hashes.

eth_getBlockByNumber code examples

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

async function getBlock(blockNumber) {
    const block = await web3.eth.getBlock(blockNumber, false);
    console.log(block);
  }
  
getBlock("latest")
const ethers = require('ethers');
const NODE_URL = "CHAINSTACK_NODE_URL";
const provider = new ethers.JsonRpcProvider(NODE_URL);

const eth_getBlockByNumber = async () => {
    const blockByNumber = await provider.send("eth_getBlockByNumber", ["latest",false]);
     console.log(blockByNumber);
   };

eth_getBlockByNumber();
# Avalanche is a Proof of Authority (POA) chain. Web3.py requires the use of the POA compatibility middleware.
from web3 import Web3
from web3.middleware import geth_poa_middleware

node_url = "CHAINSTACK_NODE_URL"
web3 = Web3(Web3.HTTPProvider(node_url))

# Inject the POA compatibility middleware to the innermost layer.
web3.middleware_onion.inject(geth_poa_middleware, layer=0)

print(web3.eth.get_block("latest", False))

Use case

The eth_getBlockByNumber method can determine whether a block you are analyzing has been included in the main chain or was forked due to a 'reorg'.

A block hash is generated through a cryptographic hash function, which takes the block's data, including transactions and other information, and the hash of the parent block (the previous block) and outputs a unique, fixed-length digest. This hash represents the current block within the blockchain.

The script compares the parent hash of the following block with the hash under inspection. If the two values match, it can be concluded that the block was included in the main chain. Conversely, if the values do not match, it indicates that the block was not used to generate the next block's hash and has therefore been excluded from the main chain, resulting in a forked block.

const Web3 = require("web3");

const NODE_URL = "YOUR_CHAINSTACK_ENDPOINT"
const web3 = new Web3(NODE_URL)

// If the hash of the block to inspect is === to the parent hash of the next block, then this is not a forked block.
async function isForked(block) {

    const nextBlock = blockToInspect + 1
    console.log(`Block to inspect: ${block}`)
    console.log(`Next block: ${nextBlock} \n`)
    
    const blockToInspectHash = (await web3.eth.getBlock(block, false)).hash
    console.log(`Block hash of the block you are inspecting: ${blockToInspectHash} \n`)

    const nextBlockParentHash = (await web3.eth.getBlock(nextBlock, false)).parentHash
    console.log(`Parent hash of the next block: ${nextBlockParentHash} \n`)

    if (String(nextBlockParentHash) == String(nextBlockParentHash)) {
        console.log(`You are inspecting the correct block`)
        return false

    } else {
        console.log(`You are inspecting a forked block!`)
        return true
    }
}

const blockToInspect = 27425409
isForked(blockToInspect)

In this case, the eth_getBlockByNumber is used to retrieve the hash of a block you want to analyze and the parent hash of the next block.

Try the eth_getBlockByNumber RPC method yourself

Language
Click Try It! to start a request and see the response here!