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

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

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

  1. Cache block numbers to reduce RPC calls
  2. Use WebSocket subscriptions for real-time updates
  3. Implement retry logic for network issues
  4. Consider block finality for critical operations
  5. Monitor block production rate for network health

Error Codes

CodeMessageDescription
-32600Invalid RequestThe JSON sent is not valid
-32601Method not foundMethod doesn't exist
-32602Invalid paramsInvalid parameters
-32603Internal errorInternal JSON-RPC error
-32000Server errorGeneric server error