eth_blockNumber
Returns the number of the most recent block on xdc.
When to Use This Method
Use eth_blockNumber
to:
- Track Blockchain Progress - Monitor new block production
- Sync Status - Determine if your node is synchronized
- Transaction Confirmation - Calculate confirmation depth
- Event Monitoring - Set up block-based event listeners
- Cross-Chain Timing - Coordinate omnichain operations
Parameters
This method accepts no parameters.
{
"jsonrpc": "2.0",
"method": "eth_blockNumber",
"params": [],
"id": 1
}
Returns
QUANTITY
- The current block number as a hexadecimal value.
- Type: Hexadecimal string
- Format:
0x
prefixed - Example:
0x1b4
(436 in decimal)
Implementation Examples
- cURL
- JavaScript
- Python
curl -X POST https://api-xdc-mainnet.n.dwellir.com/YOUR_API_KEY \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "eth_blockNumber",
"params": [],
"id": 1
}'
// Using fetch
const response = await fetch('https://api-xdc-mainnet.n.dwellir.com/YOUR_API_KEY', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
jsonrpc: '2.0',
method: 'eth_blockNumber',
params: [],
id: 1,
}),
});
const data = await response.json();
const blockNumber = parseInt(data.result, 16);
console.log('Current block:', blockNumber);
// Using ethers.js
import { ethers } from 'ethers';
const provider = new ethers.JsonRpcProvider('https://api-xdc-mainnet.n.dwellir.com/YOUR_API_KEY');
const blockNumber = await provider.getBlockNumber();
console.log('Latest xdc block:', blockNumber);
// Using web3.js
import Web3 from 'web3';
const web3 = new Web3('https://api-xdc-mainnet.n.dwellir.com/YOUR_API_KEY');
const blockNumber = await web3.eth.getBlockNumber();
console.log('Current block height:', blockNumber);
// With error handling and retry
async function getBlockNumberWithRetry(maxRetries = 3) {
for (let i = 0; i < maxRetries; i++) {
try {
const block = await provider.getBlockNumber();
return block;
} catch (error) {
if (i === maxRetries - 1) throw error;
await new Promise(r => setTimeout(r, 1000 * (i + 1)));
}
}
}
import requests
import json
from web3 import Web3
# Using requests
url = 'https://api-xdc-mainnet.n.dwellir.com/YOUR_API_KEY'
headers = {'Content-Type': 'application/json'}
payload = {
'jsonrpc': '2.0',
'method': 'eth_blockNumber',
'params': [],
'id': 1
}
response = requests.post(url, headers=headers, data=json.dumps(payload))
result = response.json()
block_number = int(result['result'], 16)
print(f'Current block: {block_number}')
# Using web3.py
w3 = Web3(Web3.HTTPProvider('https://api-xdc-mainnet.n.dwellir.com/YOUR_API_KEY'))
block_number = w3.eth.block_number
print(f'Latest xdc block: {block_number}')
# Monitor block production
import time
def monitor_blocks(duration=60):
start_time = time.time()
start_block = w3.eth.block_number
while time.time() - start_time < duration:
current_block = w3.eth.block_number
blocks_produced = current_block - start_block
elapsed = time.time() - start_time
print(f'Blocks: {blocks_produced}, Time: {elapsed:.1f}s, Rate: {blocks_produced/elapsed:.2f} blocks/s')
time.sleep(5)
Example Response
{
"jsonrpc": "2.0",
"id": 1,
"result": "0x5bad55"
}
Converting to decimal: 0x5bad55
= 5,999,957
xdc Block Production
Block Time
- Average: 6 seconds
- Consensus: Tendermint BFT
- Finality: Instant (no reorgs)
Block Structure for Omnichain
// xdc blocks contain cross-chain information
async function getOmnichainBlockInfo() {
const blockNumber = await provider.getBlockNumber();
const block = await provider.getBlock(blockNumber);
return {
height: block.number,
timestamp: block.timestamp,
// xdc-specific: cross-chain transactions
crossChainTxCount: block.transactions.filter(tx =>
isCrossChainTx(tx)
).length,
connectedChains: await getConnectedChainsAtBlock(block.number)
};
}
Common Use Cases
1. Real-Time Block Monitoring
class xdcBlockMonitor {
constructor(provider) {
this.provider = provider;
this.subscribers = new Set();
}
async start() {
let lastBlock = await this.provider.getBlockNumber();
setInterval(async () => {
const currentBlock = await this.provider.getBlockNumber();
if (currentBlock > lastBlock) {
const newBlocks = currentBlock - lastBlock;
for (let i = 1; i <= newBlocks; i++) {
const blockNumber = lastBlock + i;
this.notifySubscribers(blockNumber);
// Check for cross-chain events
await this.checkCrossChainEvents(blockNumber);
}
lastBlock = currentBlock;
}
}, 3000); // Check every 3 seconds (half block time)
}
async checkCrossChainEvents(blockNumber) {
const block = await this.provider.getBlock(blockNumber);
// Process cross-chain messages in this block
console.log(`Block ${blockNumber}: ${block.transactions.length} transactions`);
}
subscribe(callback) {
this.subscribers.add(callback);
}
notifySubscribers(blockNumber) {
this.subscribers.forEach(cb => cb(blockNumber));
}
}
2. Transaction Confirmation Tracker
async function waitForConfirmations(txHash, requiredConfirmations = 12) {
const receipt = await provider.getTransactionReceipt(txHash);
if (!receipt) throw new Error('Transaction not found');
const txBlock = receipt.blockNumber;
console.log(`Transaction mined in block ${txBlock}`);
return new Promise((resolve) => {
const checkConfirmations = setInterval(async () => {
const currentBlock = await provider.getBlockNumber();
const confirmations = currentBlock - txBlock + 1;
console.log(`Confirmations: ${confirmations}/${requiredConfirmations}`);
if (confirmations >= requiredConfirmations) {
clearInterval(checkConfirmations);
resolve({
confirmed: true,
confirmations,
finalBlock: currentBlock
});
}
}, 6000); // Check every block (6 seconds on xdc)
});
}
3. Cross-Chain Synchronization
async function syncCrossChainState() {
// Get xdc block
const zetaBlock = await zetaProvider.getBlockNumber();
// Get connected chain blocks
const chainStates = {
xdc: zetaBlock,
ethereum: await ethProvider.getBlockNumber(),
bitcoin: await getBitcoinHeight(),
bsc: await bscProvider.getBlockNumber()
};
// Calculate relative timing for cross-chain operations
const crossChainTiming = {
xdc: 0, // Reference point
ethereum: (chainStates.ethereum * 12) - (zetaBlock * 6), // seconds diff
bsc: (chainStates.bsc * 3) - (zetaBlock * 6)
};
console.log('Cross-chain synchronization:', crossChainTiming);
return chainStates;
}
4. Performance Metrics
class BlockchainMetrics {
constructor(provider, windowSize = 100) {
this.provider = provider;
this.windowSize = windowSize;
this.blockTimes = [];
}
async start() {
let lastBlock = await this.provider.getBlockNumber();
let lastTimestamp = Date.now();
setInterval(async () => {
const currentBlock = await this.provider.getBlockNumber();
if (currentBlock > lastBlock) {
const currentTimestamp = Date.now();
const blockTime = (currentTimestamp - lastTimestamp) / (currentBlock - lastBlock);
this.blockTimes.push(blockTime);
if (this.blockTimes.length > this.windowSize) {
this.blockTimes.shift();
}
const metrics = this.calculateMetrics();
console.log('xdc Metrics:', metrics);
lastBlock = currentBlock;
lastTimestamp = currentTimestamp;
}
}, 5000);
}
calculateMetrics() {
const avgBlockTime = this.blockTimes.reduce((a, b) => a + b, 0) / this.blockTimes.length;
const tps = this.estimateTPS(avgBlockTime);
return {
averageBlockTime: (avgBlockTime / 1000).toFixed(2) + 's',
blocksPerMinute: (60000 / avgBlockTime).toFixed(1),
estimatedTPS: tps,
networkHealth: avgBlockTime < 7000 ? 'Healthy' : 'Degraded'
};
}
estimateTPS(blockTime) {
// Estimate based on xdc's typical load
const avgTxPerBlock = 50; // Typical value
return ((avgTxPerBlock * 1000) / blockTime).toFixed(0);
}
}
5. Omnichain Event Indexer
async function indexOmnichainEvents(fromBlock, toBlock) {
const events = {
crossChainCalls: [],
crossChainDeposits: [],
crossChainWithdrawals: []
};
for (let block = fromBlock; block <= toBlock; block++) {
const blockData = await provider.getBlockWithTransactions(block);
for (const tx of blockData.transactions) {
// Check for cross-chain contract calls
if (tx.to === CONNECTOR_CONTRACT) {
const receipt = await provider.getTransactionReceipt(tx.hash);
receipt.logs.forEach(log => {
if (log.topics[0] === CROSS_CHAIN_CALL_TOPIC) {
events.crossChainCalls.push({
block: block,
tx: tx.hash,
from: tx.from,
destChain: parseDestinationChain(log.data)
});
}
});
}
}
console.log(`Indexed block ${block}: ${events.crossChainCalls.length} cross-chain calls`);
}
return events;
}
Block Production Statistics
Network Performance
async function getNetworkStats() {
const currentBlock = await provider.getBlockNumber();
const dayAgoBlock = currentBlock - (24 * 60 * 60 / 6); // 6 second blocks
const currentBlockData = await provider.getBlock(currentBlock);
const dayAgoBlockData = await provider.getBlock(dayAgoBlock);
return {
currentHeight: currentBlock,
dailyBlocks: currentBlock - dayAgoBlock,
averageBlockTime: '6s',
validatorCount: 66,
uptimePercent: 99.95,
crossChainTxDaily: await countDailyCrossChainTx(dayAgoBlock, currentBlock)
};
}
Best Practices
- Cache block numbers to reduce RPC calls
- Use WebSocket subscriptions for real-time updates
- Implement retry logic for network issues
- Consider block finality for critical operations
- Monitor block production rate for network health
Error Codes
Code | Message | Description |
---|---|---|
-32600 | Invalid Request | The JSON sent is not valid |
-32601 | Method not found | Method doesn't exist |
-32602 | Invalid params | Invalid parameters |
-32603 | Internal error | Internal JSON-RPC error |
-32000 | Server error | Generic server error |
Related Methods
- eth_getBlockByNumber - Get full block details
- eth_getBlockByHash - Get block by hash
- eth_syncing - Check sync status
eth_getBlockTransactionCountByNumber
- Get transaction count in block