Skip to main content

eth_getBlockByNumber

Returns information about a block by block number on Polygon PoS.

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

Parameters​

  1. Block Parameter - QUANTITY|TAG

    • "latest" - Most recent mined block
    • "earliest" - Genesis block
    • "pending" - Pending block
    • "safe" - Latest safe block
    • "finalized" - Latest finalized block
    • Hex string block number (e.g., "0x5BAD55")
  2. Transaction Details - Boolean

    • true - Returns full transaction objects
    • false - Returns only transaction hashes
{
"jsonrpc": "2.0",
"method": "eth_getBlockByNumber",
"params": [
"0x5BAD55",
true
],
"id": 1
}

Returns​

Block object with the following fields:

FieldTypeDescription
numberQUANTITYBlock number, null if pending
hashDATA, 32 bytesBlock hash, null if pending
parentHashDATA, 32 bytesParent block hash
nonceDATA, 8 bytesProof-of-work nonce (always 0 on Polygon)
sha3UnclesDATA, 32 bytesSHA3 of uncles (always empty on Polygon)
logsBloomDATA, 256 bytesBloom filter for logs
transactionsRootDATA, 32 bytesRoot of transaction trie
stateRootDATA, 32 bytesRoot of final state trie
receiptsRootDATA, 32 bytesRoot of receipts trie
minerDATA, 20 bytesBeneficiary address (sequencer on Polygon)
difficultyQUANTITYDifficulty (always 0 on Polygon)
totalDifficultyQUANTITYTotal difficulty
extraDataDATAExtra data field
sizeQUANTITYBlock size in bytes
gasLimitQUANTITYMaximum gas allowed
gasUsedQUANTITYTotal gas used by transactions
timestampQUANTITYUnix timestamp
transactionsArrayTransaction objects or hashes
unclesArrayUncle hashes (always empty on Polygon)
baseFeePerGasQUANTITYBase fee per gas (EIP-1559)
l1BlockNumberQUANTITYCorresponding L1 block (Base specific)

Implementation Examples​

# Get block with transaction hashes only
curl -X POST https://api-polygon-mainnet-full.n.dwellir.com/YOUR_API_KEY \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "eth_getBlockByNumber",
"params": ["latest", false],
"id": 1
}'

# Get block with full transaction details
curl -X POST https://api-polygon-mainnet-full.n.dwellir.com/YOUR_API_KEY \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "eth_getBlockByNumber",
"params": ["0x5BAD55", true],
"id": 1
}'

Response Example​

Block with Transaction Hashes​

{
"jsonrpc": "2.0",
"id": 1,
"result": {
"baseFeePerGas": "0x3e",
"difficulty": "0x0",
"extraData": "0x",
"gasLimit": "0x1c9c380",
"gasUsed": "0x4f916",
"hash": "0x1234567890abcdef...",
"logsBloom": "0x00000000...",
"miner": "0x4200000000000000000000000000000000000011",
"mixHash": "0x0000000000000000000000000000000000000000000000000000000000000000",
"nonce": "0x0000000000000000",
"number": "0x5bad55",
"parentHash": "0xabcdef1234567890...",
"receiptsRoot": "0x...",
"sha3Uncles": "0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347",
"size": "0x4d6",
"stateRoot": "0x...",
"timestamp": "0x64f1b438",
"totalDifficulty": "0x0",
"transactions": [
"0xhash1...",
"0xhash2...",
"0xhash3..."
],
"transactionsRoot": "0x...",
"uncles": []
}
}

Common Use Cases​

1. Block Explorer Display​

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​

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​

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​

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​

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​

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;
}
}

Error Handling​

Error CodeDescriptionSolution
-32602Invalid block numberCheck block exists and format
-32000Block not foundBlock may not be mined yet
-32005Rate limit exceededImplement backoff strategy
async function safeGetBlock(blockNumber, maxRetries = 3) {
for (let i = 0; i < maxRetries; i++) {
try {
const block = await provider.getBlock(blockNumber);
if (!block) {
throw new Error(`Block ${blockNumber} not found`);
}
return block;
} catch (error) {
if (i === maxRetries - 1) throw error;

// Exponential backoff for rate limits
if (error.code === -32005) {
await new Promise(r => setTimeout(r, Math.pow(2, i) * 1000));
}
}
}
}

Need help? Contact our support team or check the Polygon documentation.