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
-
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
- Block number in hexadecimal format (e.g.,
-
Transaction Detail Flag -
Boolean
true
- Returns full transaction objectsfalse
- 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 hexhash
- 32-byte block hashparentHash
- Hash of the parent blocktimestamp
- Unix timestamp when block was collatedgasLimit
- Maximum gas allowed in this blockgasUsed
- Total gas used by all transactionstransactions
- Array of transaction objects or hashessize
- Block size in bytes- Additional fields...
Implementation Examples
- cURL
- JavaScript
- Python
- Go
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
}'
import { JsonRpcProvider } from 'ethers';
const provider = new JsonRpcProvider('https://api-avalanche-mainnet-archive.n.dwellir.com/YOUR_API_KEY/ext/bc/C/rpc');
// Get latest block with full transaction details
async function getLatestBlock() {
const block = await provider.getBlock('latest', true);
console.log('Block number:', block.number);
console.log('Block hash:', block.hash);
console.log('Timestamp:', new Date(block.timestamp * 1000));
console.log('Gas used:', block.gasUsed.toString());
console.log('Transaction count:', block.transactions.length);
return block;
}
// Get specific block by number
async function getBlockByNumber(blockNumber) {
const block = await provider.getBlock(blockNumber);
return {
number: block.number,
hash: block.hash,
timestamp: block.timestamp,
gasUsed: block.gasUsed.toString(),
gasLimit: block.gasLimit.toString(),
transactions: block.transactions.length,
miner: block.miner,
difficulty: block.difficulty?.toString() || '0',
size: block.transactions.length // Approximate
};
}
// Analyze recent blocks
async function analyzeRecentBlocks(count = 10) {
const latestBlockNumber = await provider.getBlockNumber();
const blocks = [];
for (let i = 0; i < count; i++) {
const block = await provider.getBlock(latestBlockNumber - i);
blocks.push({
number: block.number,
timestamp: block.timestamp,
gasUsed: Number(block.gasUsed),
transactionCount: block.transactions.length
});
}
return blocks;
}
from web3 import Web3
import datetime
w3 = Web3(Web3.HTTPProvider('https://api-avalanche-mainnet-archive.n.dwellir.com/YOUR_API_KEY/ext/bc/C/rpc'))
def get_block_by_number(block_number, full_transactions=True):
"""Get block information by block number"""
block = w3.eth.get_block(block_number, full_transactions)
return {
'number': block['number'],
'hash': block['hash'].hex(),
'timestamp': block['timestamp'],
'gasUsed': block['gasUsed'],
'gasLimit': block['gasLimit'],
'transactionCount': len(block['transactions']),
'miner': block.get('miner', ''),
'difficulty': block.get('difficulty', 0),
'size': block.get('size', 0)
}
def get_latest_blocks(count=10):
"""Get information about the latest blocks"""
latest_block = w3.eth.block_number
blocks = []
for i in range(count):
block_number = latest_block - i
block = get_block_by_number(block_number, False)
blocks.append(block)
return blocks
def analyze_block_times():
"""Analyze block production times"""
latest_block = w3.eth.block_number
timestamps = []
for i in range(20): # Last 20 blocks
block = w3.eth.get_block(latest_block - i)
timestamps.append(block['timestamp'])
# Calculate average block time
time_diffs = [timestamps[i] - timestamps[i+1] for i in range(len(timestamps)-1)]
avg_block_time = sum(time_diffs) / len(time_diffs)
return {
'average_block_time': avg_block_time,
'min_block_time': min(time_diffs),
'max_block_time': max(time_diffs)
}
package main
import (
"context"
"fmt"
"log"
"math/big"
"github.com/ethereum/go-ethereum/ethclient"
)
func main() {
client, err := ethclient.Dial("https://api-avalanche-mainnet-archive.n.dwellir.com/YOUR_API_KEY/ext/bc/C/rpc")
if err != nil {
log.Fatal(err)
}
// Get latest block
block, err := client.BlockByNumber(context.Background(), nil)
if err != nil {
log.Fatal(err)
}
fmt.Printf("Block Number: %d\n", block.Number().Uint64())
fmt.Printf("Block Hash: %s\n", block.Hash().Hex())
fmt.Printf("Parent Hash: %s\n", block.ParentHash().Hex())
fmt.Printf("Gas Used: %d\n", block.GasUsed())
fmt.Printf("Gas Limit: %d\n", block.GasLimit())
fmt.Printf("Transaction Count: %d\n", len(block.Transactions()))
// Get specific block by number
blockNumber := big.NewInt(1000)
specificBlock, err := client.BlockByNumber(context.Background(), blockNumber)
if err != nil {
log.Fatal(err)
}
fmt.Printf("Block %d has %d transactions\n",
specificBlock.Number().Uint64(),
len(specificBlock.Transactions()))
}
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 Code | Description | Solution |
---|---|---|
-32602 | Invalid block number | Use valid hex format or block tag |
-32000 | Block not found | Block may not exist yet |
-32603 | Internal error | Retry 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.