⚠️Blast API (blastapi.io) ends Oct 31. Migrate to Dwellir and skip Alchemy's expensive compute units.
Switch Today →
Skip to main content

eth_getBlockByNumber

Returns information about a block by block number on Avalanche C-Chain.

When to Use This Method

eth_getBlockByNumber is essential for:

  • Block Explorers - Display detailed block information
  • Transaction Analysis - Get all transactions in a specific block
  • Data Analytics - Analyze block patterns and network activity
  • Timestamp Queries - Get precise block timestamps for events

Parameters

  1. Block Number - QUANTITY|TAG

    • Block number in hexadecimal format (e.g., 0x1b4)
    • "earliest" - Genesis block
    • "latest" - Most recent block
    • "pending" - Pending state
    • "safe" - Latest safe block
    • "finalized" - Latest finalized block
  2. Transaction Detail Flag - Boolean

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

Returns

Object - A block object, or null when no block was found:

  • number - Block number in hex
  • hash - 32-byte block hash
  • parentHash - Hash of the parent block
  • timestamp - Unix timestamp when block was collated
  • gasLimit - Maximum gas allowed in this block
  • gasUsed - Total gas used by all transactions
  • transactions - Array of transaction objects or hashes
  • size - Block size in bytes
  • Additional fields...

Implementation Examples

curl -X POST https://api-avalanche-mainnet-archive.n.dwellir.com/YOUR_API_KEY/ext/bc/C/rpc \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "eth_getBlockByNumber",
"params": ["0x1b4", true],
"id": 1
}'

Response Example

Successful Response

{
"jsonrpc": "2.0",
"id": 1,
"result": {
"number": "0x1b4",
"hash": "0x0e670ec64341771606e55d6b4ca35a1a6b75ee3d5145a99d05921026d1527331",
"parentHash": "0x9646252be9520f6e71339a8df9c55e4d7619deeb018d2a3f2d21fc165dde5eb5",
"nonce": "0xe04d296d2460cfb8472af2c5fd05b5a214109c25688d3704aed5484f9a7792f2",
"sha3Uncles": "0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347",
"logsBloom": "0x0",
"transactionsRoot": "0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421",
"stateRoot": "0xd5855eb08b3387c0af375e9cdb6acfc05eb8f519e419b874b6ff2ffda7ed1dff",
"receiptsRoot": "0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421",
"miner": "0x4e65fda2159562a496f9f3522f89122a3088497a",
"difficulty": "0x27f07",
"totalDifficulty": "0x27f07",
"extraData": "0x0000000000000000000000000000000000000000000000000000000000000000",
"size": "0x27f07",
"gasLimit": "0x9f759",
"gasUsed": "0x9f759",
"timestamp": "0x54e34e8e",
"transactions": [],
"uncles": []
}
}

Common Use Cases

1. Block Explorer Data

Build block explorer functionality:

async function getBlockExplorerData(blockNumber) {
const block = await provider.getBlock(blockNumber, true);

const txSummary = block.transactions.map(tx => ({
hash: tx.hash,
from: tx.from,
to: tx.to,
value: formatEther(tx.value || 0),
gasUsed: tx.gasLimit?.toString()
}));

return {
basic: {
number: block.number,
hash: block.hash,
timestamp: new Date(block.timestamp * 1000),
miner: block.miner,
gasUsed: block.gasUsed.toString(),
gasLimit: block.gasLimit.toString()
},
transactions: txSummary,
stats: {
transactionCount: block.transactions.length,
avgGasUsed: txSummary.length > 0 ?
txSummary.reduce((sum, tx) => sum + Number(tx.gasUsed || 0), 0) / txSummary.length : 0
}
};
}

2. Network Activity Analysis

Analyze network activity patterns:

async function analyzeNetworkActivity(fromBlock, toBlock) {
const analysis = {
totalBlocks: toBlock - fromBlock + 1,
totalTransactions: 0,
totalGasUsed: 0n,
avgBlockTime: 0,
blockTimes: []
};

let previousTimestamp = null;

for (let i = fromBlock; i <= toBlock; i++) {
const block = await provider.getBlock(i);

analysis.totalTransactions += block.transactions.length;
analysis.totalGasUsed += block.gasUsed;

if (previousTimestamp) {
const blockTime = block.timestamp - previousTimestamp;
analysis.blockTimes.push(blockTime);
}

previousTimestamp = block.timestamp;
}

if (analysis.blockTimes.length > 0) {
analysis.avgBlockTime = analysis.blockTimes.reduce((sum, time) => sum + time, 0) / analysis.blockTimes.length;
}

analysis.avgTransactionsPerBlock = analysis.totalTransactions / analysis.totalBlocks;
analysis.avgGasPerBlock = analysis.totalGasUsed / BigInt(analysis.totalBlocks);

return analysis;
}

3. Timestamp-based Block Finder

Find blocks by timestamp:

async function findBlockByTimestamp(targetTimestamp, tolerance = 60) {
let low = 1;
let high = await provider.getBlockNumber();
let closest = null;

while (low <= high) {
const mid = Math.floor((low + high) / 2);
const block = await provider.getBlock(mid);

const timeDiff = Math.abs(block.timestamp - targetTimestamp);

if (!closest || timeDiff < Math.abs(closest.timestamp - targetTimestamp)) {
closest = block;
}

if (timeDiff <= tolerance) {
return closest;
}

if (block.timestamp < targetTimestamp) {
low = mid + 1;
} else {
high = mid - 1;
}
}

return closest;
}

// Find block closest to a specific date
async function findBlockByDate(dateString) {
const targetDate = new Date(dateString);
const targetTimestamp = Math.floor(targetDate.getTime() / 1000);
return findBlockByTimestamp(targetTimestamp);
}

4. Gas Usage Monitoring

Monitor gas usage patterns:

async function monitorGasUsage(blockCount = 100) {
const currentBlock = await provider.getBlockNumber();
const gasData = [];

for (let i = 0; i < blockCount; i++) {
const block = await provider.getBlock(currentBlock - i);

gasData.push({
blockNumber: block.number,
gasUsed: Number(block.gasUsed),
gasLimit: Number(block.gasLimit),
utilization: (Number(block.gasUsed) / Number(block.gasLimit)) * 100
});
}

// Calculate statistics
const avgUtilization = gasData.reduce((sum, data) => sum + data.utilization, 0) / gasData.length;
const maxUtilization = Math.max(...gasData.map(d => d.utilization));
const minUtilization = Math.min(...gasData.map(d => d.utilization));

return {
blocks: gasData,
stats: {
avgUtilization: avgUtilization.toFixed(2) + '%',
maxUtilization: maxUtilization.toFixed(2) + '%',
minUtilization: minUtilization.toFixed(2) + '%'
}
};
}

Performance Optimization

Batch Block Queries

Query multiple blocks efficiently:

async function batchGetBlocks(blockNumbers) {
const batch = blockNumbers.map((blockNum, i) => ({
jsonrpc: '2.0',
method: 'eth_getBlockByNumber',
params: [`0x${blockNum.toString(16)}`, false],
id: i
}));

const response = await fetch('https://api-avalanche-mainnet-archive.n.dwellir.com/YOUR_API_KEY/ext/bc/C/rpc', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(batch)
});

const results = await response.json();
return results.map(r => r.result);
}

Block Caching

Cache immutable block data:

class BlockCache {
constructor() {
this.cache = new Map();
}

async getBlock(provider, blockNumber, includeTransactions = false) {
const key = `${blockNumber}-${includeTransactions}`;

if (this.cache.has(key)) {
return this.cache.get(key);
}

const block = await provider.getBlock(blockNumber, includeTransactions);

// Only cache if not the latest block
if (typeof blockNumber === 'number' || blockNumber !== 'latest') {
this.cache.set(key, block);
}

return block;
}
}

Error Handling

Common errors and solutions:

Error CodeDescriptionSolution
-32602Invalid block numberUse valid hex format or block tag
-32000Block not foundBlock may not exist yet
-32603Internal errorRetry request
async function safeGetBlock(blockNumber, includeTransactions = false) {
try {
const block = await provider.getBlock(blockNumber, includeTransactions);

if (!block) {
return { success: false, error: 'Block not found' };
}

return { success: true, block };

} catch (error) {
if (error.code === -32000) {
return { success: false, error: 'Block not found' };
}

return { success: false, error: error.message };
}
}

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