Docs

eth_getBlockByNumber - Get Block Details

Retrieve complete block information by block number on Centrifuge Mainnet. Essential for block explorers and chain analysis.

Returns information about a block by block number on Centrifuge Mainnet.

When to Use This Method

eth_getBlockByNumber is crucial for:

  • Block Explorers - Display block information and transactions
  • Chain Analytics - Analyze block patterns and metrics
  • Transaction Verification - Confirm transaction inclusion
  • DApp Synchronization - Process blocks sequentially

Implementation Examples

Common Use Cases

1. Block Explorer Display

JavaScript
async function formatBlockForExplorer(blockNumber) {
  const block = await provider.getBlock(blockNumber, true);
  
  return {
    number: block.number,
    hash: block.hash,
    timestamp: new Date(block.timestamp * 1000).toISOString(),
    miner: block.miner,
    transactionCount: block.transactions.length,
    gasUsed: `${(Number(block.gasUsed) / 1e6).toFixed(2)}M`,
    gasLimit: `${(Number(block.gasLimit) / 1e6).toFixed(2)}M`,
    utilization: `${(Number(block.gasUsed) / Number(block.gasLimit) * 100).toFixed(2)}%`,
    baseFee: `${Number(block.baseFeePerGas) / 1e9} Gwei`,
    burnt: formatEther(block.gasUsed * block.baseFeePerGas)
  };
}

2. Transaction Confirmation

JavaScript
async function confirmTransaction(txHash, confirmations = 6) {
  const tx = await provider.getTransaction(txHash);
  if (!tx) throw new Error('Transaction not found');
  
  const receipt = await provider.getTransactionReceipt(txHash);
  if (!receipt) {
    console.log('Transaction pending...');
    return false;
  }
  
  const currentBlock = await provider.getBlockNumber();
  const confirmCount = currentBlock - receipt.blockNumber + 1;
  
  if (confirmCount >= confirmations) {
    const block = await provider.getBlock(receipt.blockNumber, true);
    const txInBlock = block.transactions.find(t => t.hash === txHash);
    
    return {
      confirmed: true,
      confirmations: confirmCount,
      block: receipt.blockNumber,
      timestamp: block.timestamp,
      position: txInBlock ? block.transactions.indexOf(txInBlock) : -1
    };
  }
  
  return {
    confirmed: false,
    confirmations: confirmCount,
    needed: confirmations - confirmCount
  };
}

3. Block Time Analysis

JavaScript
async function analyzeBlockTimes(count = 100) {
  const latest = await provider.getBlockNumber();
  const blocks = [];
  
  for (let i = 0; i < count; i++) {
    const block = await provider.getBlock(latest - i);
    blocks.push({
      number: block.number,
      timestamp: block.timestamp
    });
  }
  
  const blockTimes = [];
  for (let i = 1; i < blocks.length; i++) {
    blockTimes.push(blocks[i-1].timestamp - blocks[i].timestamp);
  }
  
  return {
    average: blockTimes.reduce((a, b) => a + b, 0) / blockTimes.length,
    min: Math.min(...blockTimes),
    max: Math.max(...blockTimes),
    blocks: blockTimes
  };
}

4. Gas Price Tracking

JavaScript
async function trackGasPrices(blocks = 10) {
  const latest = await provider.getBlockNumber();
  const gasPrices = [];
  
  for (let i = 0; i < blocks; i++) {
    const block = await provider.getBlock(latest - i, true);
    
    // Calculate effective gas prices from transactions
    const prices = block.transactions
      .filter(tx => tx.gasPrice || tx.maxFeePerGas)
      .map(tx => {
        if (tx.type === 2) { // EIP-1559
          return BigInt(tx.maxFeePerGas) < BigInt(block.baseFeePerGas) + BigInt(tx.maxPriorityFeePerGas)
            ? BigInt(tx.maxFeePerGas)
            : BigInt(block.baseFeePerGas) + BigInt(tx.maxPriorityFeePerGas);
        }
        return BigInt(tx.gasPrice);
      });
    
    if (prices.length > 0) {
      const avgPrice = prices.reduce((a, b) => a + b, 0n) / BigInt(prices.length);
      gasPrices.push({
        block: block.number,
        baseFee: Number(block.baseFeePerGas) / 1e9,
        avgPrice: Number(avgPrice) / 1e9,
        txCount: block.transactions.length
      });
    }
  }
  
  return gasPrices;
}

Performance Optimization

Parallel Block Fetching

JavaScript
async function getBlocksParallel(startBlock, count) {
  const promises = [];
  
  for (let i = 0; i < count; i++) {
    promises.push(provider.getBlock(startBlock + i));
  }
  
  const blocks = await Promise.all(promises);
  return blocks;
}

Block Caching

JavaScript
class BlockCache {
  constructor(maxSize = 100) {
    this.cache = new Map();
    this.maxSize = maxSize;
  }
  
  async getBlock(provider, blockNumber, fullTx = false) {
    const key = `${blockNumber}-${fullTx}`;
    
    if (this.cache.has(key)) {
      return this.cache.get(key);
    }
    
    const block = await provider.getBlock(blockNumber, fullTx);
    
    // LRU eviction
    if (this.cache.size >= this.maxSize) {
      const firstKey = this.cache.keys().next().value;
      this.cache.delete(firstKey);
    }
    
    this.cache.set(key, block);
    return block;
  }
}