eth_blockNumber
Returns the number of the most recent block on Linea zkEVM.
Parameters
None
Returns
QUANTITY
- Integer of the current block number the client is on.
Request Example
{
"jsonrpc": "2.0",
"method": "eth_blockNumber",
"params": [],
"id": 1
}
Response Example
{
"jsonrpc": "2.0",
"id": 1,
"result": "0x5bad55"
}
Implementation Examples
- JavaScript
- Python
import { JsonRpcProvider } from 'ethers';
const provider = new JsonRpcProvider('https://api-linea-mainnet-archive.n.dwellir.com/YOUR_API_KEY');
// Get current block number
async function getCurrentBlock() {
const blockNumber = await provider.getBlockNumber();
console.log('Current block:', blockNumber);
return blockNumber;
}
// Monitor new blocks
async function watchBlocks() {
provider.on('block', (blockNumber) => {
console.log('New block:', blockNumber);
// Process new block
});
}
// Calculate block production rate
async function getBlockProductionRate() {
const block1 = await provider.getBlock('latest');
// Wait for next block
await new Promise(resolve => {
provider.once('block', resolve);
});
const block2 = await provider.getBlock('latest');
const timeDiff = block2.timestamp - block1.timestamp;
console.log(`Block time: ${timeDiff} seconds`);
return timeDiff;
}
from web3 import Web3
import time
w3 = Web3(Web3.HTTPProvider('https://api-linea-mainnet-archive.n.dwellir.com/YOUR_API_KEY'))
def get_current_block():
"""Get the current block number"""
block_number = w3.eth.block_number
print(f"Current block: {block_number}")
return block_number
def monitor_blocks(duration=60):
"""Monitor block production for specified duration"""
start_time = time.time()
start_block = w3.eth.block_number
blocks_seen = []
while time.time() - start_time < duration:
current_block = w3.eth.block_number
if current_block > start_block:
blocks_seen.append(current_block)
print(f"New block: {current_block}")
start_block = current_block
time.sleep(1)
return blocks_seen
def calculate_block_rate():
"""Calculate average block production rate"""
block1 = w3.eth.get_block('latest')
time.sleep(60) # Wait 1 minute
block2 = w3.eth.get_block('latest')
blocks_produced = block2['number'] - block1['number']
time_elapsed = block2['timestamp'] - block1['timestamp']
avg_block_time = time_elapsed / blocks_produced if blocks_produced > 0 else 0
return {
'blocks_in_minute': blocks_produced,
'average_block_time': avg_block_time
}
Common Use Cases
1. Block Synchronization Status
// Check if node is synced
async function checkSyncStatus() {
const blockNumber = await provider.getBlockNumber();
const block = await provider.getBlock(blockNumber);
const currentTime = Math.floor(Date.now() / 1000);
const blockAge = currentTime - block.timestamp;
// Consider synced if block is less than 60 seconds old
const isSynced = blockAge < 60;
return {
blockNumber,
blockTime: new Date(block.timestamp * 1000).toISOString(),
blockAge: `${blockAge} seconds`,
isSynced,
status: isSynced ? 'Fully Synced' : 'Syncing'
};
}
2. Block Range Queries
// Get blocks in a specific range
async function getBlockRange(startBlock, endBlock) {
const current = await provider.getBlockNumber();
// Validate range
if (endBlock > current) {
endBlock = current;
}
const blocks = [];
const batchSize = 10; // Process in batches
for (let i = startBlock; i <= endBlock; i += batchSize) {
const batch = [];
for (let j = i; j < Math.min(i + batchSize, endBlock + 1); j++) {
batch.push(provider.getBlock(j));
}
const batchResults = await Promise.all(batch);
blocks.push(...batchResults);
}
return blocks;
}
3. Block Confirmation Tracking
// Wait for specific number of confirmations
async function waitForConfirmations(txHash, confirmations = 12) {
const receipt = await provider.waitForTransaction(txHash, 1);
const txBlock = receipt.blockNumber;
console.log(`Transaction included in block ${txBlock}`);
// Wait for additional confirmations
return new Promise((resolve) => {
const checkConfirmations = async () => {
const currentBlock = await provider.getBlockNumber();
const confirmationCount = currentBlock - txBlock + 1;
if (confirmationCount >= confirmations) {
console.log(`Transaction has ${confirmationCount} confirmations`);
resolve(receipt);
} else {
console.log(`Waiting... ${confirmationCount}/${confirmations} confirmations`);
setTimeout(checkConfirmations, 12000); // Check every ~12 seconds (Linea block time)
}
};
checkConfirmations();
});
}
zkEVM Block Production
Linea's zkEVM has unique block production characteristics:
// Monitor zkEVM block production patterns
async function analyzeBlockProduction() {
const blocks = [];
const duration = 10; // Monitor for 10 blocks
for (let i = 0; i < duration; i++) {
const block = await provider.getBlock('latest');
blocks.push({
number: block.number,
timestamp: block.timestamp,
transactions: block.transactions.length,
gasUsed: block.gasUsed.toString()
});
// Wait for next block
await new Promise(resolve => {
provider.once('block', resolve);
});
}
// Analyze block times
const blockTimes = [];
for (let i = 1; i < blocks.length; i++) {
blockTimes.push(blocks[i].timestamp - blocks[i-1].timestamp);
}
const avgBlockTime = blockTimes.reduce((a, b) => a + b, 0) / blockTimes.length;
const avgTxPerBlock = blocks.reduce((a, b) => a + b.transactions, 0) / blocks.length;
return {
averageBlockTime: avgBlockTime,
averageTxPerBlock: avgTxPerBlock,
blocksAnalyzed: blocks.length,
zkEvmMetrics: {
proofGenerationInterval: avgBlockTime,
throughput: avgTxPerBlock / avgBlockTime
}
};
}
Error Handling
async function safeGetBlockNumber() {
const maxRetries = 3;
let lastError;
for (let i = 0; i < maxRetries; i++) {
try {
const blockNumber = await provider.getBlockNumber();
// Validate response
if (blockNumber < 0) {
throw new Error('Invalid block number received');
}
return blockNumber;
} catch (error) {
lastError = error;
console.log(`Attempt ${i + 1} failed:`, error.message);
if (i < maxRetries - 1) {
// Exponential backoff
await new Promise(r => setTimeout(r, 2 ** i * 1000));
}
}
}
throw lastError;
}
Need help? Contact our support team or check the Linea documentation.