eth_getBlockByNumber
Returns information about a block by block number.
When to Use This Method
Use eth_getBlockByNumber
to:
- Query Block Details - Get complete block information
- Monitor Chain Progress - Track new blocks and transactions
- Analyze Cross-Chain Activity - Review omnichain transactions
- Historical Analysis - Study past network activity
- Transaction Verification - Confirm transaction inclusion
Parameters
-
Block Parameter (required):
latest
- Most recent blockearliest
- Genesis blockpending
- Pending statesafe
- Latest safe blockfinalized
- Latest finalized block- Block number as hexadecimal
-
Transaction Details (required):
true
- Returns full transaction objectsfalse
- Returns only transaction hashes
{
"jsonrpc": "2.0",
"method": "eth_getBlockByNumber",
"params": [
"0x5BAD55",
true
],
"id": 1
}
Returns
Block object with:
number
: Block numberhash
: Block hashparentHash
: Parent block hashtimestamp
: Unix timestamptransactions
: Array of transactionsgasLimit
: Block gas limitgasUsed
: Total gas used- And more fields...
Implementation Examples
- cURL
- JavaScript
- Python
# Get latest block with transaction details
curl -X POST https://api-zetachain-mainnet.n.dwellir.com/YOUR_API_KEY \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "eth_getBlockByNumber",
"params": [
"latest",
true
],
"id": 1
}'
# Get specific block with only transaction hashes
curl -X POST https://api-zetachain-mainnet.n.dwellir.com/YOUR_API_KEY \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "eth_getBlockByNumber",
"params": [
"0x5BAD55",
false
],
"id": 1
}'
// Using ethers.js
import { ethers } from 'ethers';
const provider = new ethers.JsonRpcProvider('https://api-zetachain-mainnet.n.dwellir.com/YOUR_API_KEY');
// Get latest block with transactions
const blockWithTx = await provider.getBlock('latest', true);
console.log('Block number:', blockWithTx.number);
console.log('Transactions:', blockWithTx.transactions.length);
// Get block without transaction details
const blockNoTx = await provider.getBlock(5999957);
console.log('Block hash:', blockNoTx.hash);
console.log('Timestamp:', new Date(blockNoTx.timestamp * 1000));
// Using web3.js
import Web3 from 'web3';
const web3 = new Web3('https://api-zetachain-mainnet.n.dwellir.com/YOUR_API_KEY');
// Get latest block
const latestBlock = await web3.eth.getBlock('latest');
console.log('Latest block:', latestBlock);
// Get block with full transactions
const blockWithTransactions = await web3.eth.getBlock('latest', true);
blockWithTransactions.transactions.forEach(tx => {
console.log('Transaction:', tx.hash, 'Value:', web3.utils.fromWei(tx.value, 'ether'));
});
from web3 import Web3
import json
# Connect to ZetaChain
w3 = Web3(Web3.HTTPProvider('https://api-zetachain-mainnet.n.dwellir.com/YOUR_API_KEY'))
# Get latest block
latest_block = w3.eth.get_block('latest')
print(f"Block #{latest_block['number']}")
print(f"Transactions: {len(latest_block['transactions'])}")
# Get block with full transaction objects
block_with_tx = w3.eth.get_block('latest', full_transactions=True)
for tx in block_with_tx['transactions']:
print(f"TX: {tx['hash'].hex()} Value: {w3.from_wei(tx['value'], 'ether')} ZETA")
# Get specific historical block
historical_block = w3.eth.get_block(1000000)
print(f"Block timestamp: {historical_block['timestamp']}")
Example Response
{
"jsonrpc": "2.0",
"id": 1,
"result": {
"difficulty": "0x0",
"extraData": "0x",
"gasLimit": "0x1c9c380",
"gasUsed": "0x5208",
"hash": "0x9fc76417374aa880d4449a1f7f31ec597f00b1f6f3dd2d66f4c9c6c445836d8b",
"logsBloom": "0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000",
"miner": "0x0000000000000000000000000000000000000000",
"mixHash": "0x0000000000000000000000000000000000000000000000000000000000000000",
"nonce": "0x0000000000000000",
"number": "0x5bad55",
"parentHash": "0x9b3e4f7a65f3c2c1e8c7a8a0d5f6e4c3b2a1f0e9d8c7b6a5f4e3d2c1b0a9f8e7",
"receiptsRoot": "0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421",
"sha3Uncles": "0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347",
"size": "0x220",
"stateRoot": "0xd5855eb08b3387c0af375e9cdb6acfc05eb8f519e419b874b6ff2ffda7ed1dff",
"timestamp": "0x65a7b4d2",
"totalDifficulty": "0x0",
"transactions": [
"0x88df016429689c079f3b2f6ad39fa052532c56795b733da78a91ebe6a713944b"
],
"transactionsRoot": "0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421",
"uncles": []
}
}
Omnichain Block Analysis
ZetaChain blocks contain cross-chain transaction information:
class OmnichainBlockAnalyzer {
constructor(provider) {
this.provider = provider;
}
async analyzeCrossChainActivity(blockNumber) {
const block = await this.provider.getBlock(blockNumber, true);
const crossChainTxs = [];
const regularTxs = [];
for (const tx of block.transactions) {
if (this.isCrossChainTx(tx)) {
const decoded = await this.decodeCrossChainTx(tx);
crossChainTxs.push({
hash: tx.hash,
from: tx.from,
sourceChain: 7000,
destChain: decoded.destChainId,
amount: ethers.formatEther(tx.value),
message: decoded.message
});
} else {
regularTxs.push(tx);
}
}
return {
blockNumber: block.number,
timestamp: block.timestamp,
totalTransactions: block.transactions.length,
crossChainTransactions: crossChainTxs.length,
regularTransactions: regularTxs.length,
crossChainDetails: crossChainTxs,
gasUsed: block.gasUsed,
baseFeePerGas: block.baseFeePerGas
};
}
isCrossChainTx(tx) {
// Check if transaction is to connector contract
const connectorAddress = '0x239e96c8f17C85c30100AC26F635Ea15f23E9c67';
return tx.to?.toLowerCase() === connectorAddress.toLowerCase();
}
}
Common Use Cases
1. Block Explorer Implementation
class BlockExplorer {
async getBlockDetails(blockId) {
const block = await provider.getBlock(blockId, true);
return {
overview: {
height: block.number,
hash: block.hash,
timestamp: new Date(block.timestamp * 1000),
transactionCount: block.transactions.length,
gasUsed: block.gasUsed,
gasLimit: block.gasLimit,
baseFeePerGas: block.baseFeePerGas
},
transactions: await this.processTransactions(block.transactions),
metrics: {
utilizationRate: (Number(block.gasUsed) / Number(block.gasLimit) * 100).toFixed(2) + '%',
avgGasPrice: this.calculateAvgGasPrice(block.transactions)
}
};
}
}
2. Chain Activity Monitor
async function monitorChainActivity(duration = 60000) {
const startBlock = await provider.getBlockNumber();
const stats = {
blocks: [],
totalTransactions: 0,
totalGasUsed: 0n,
crossChainTxCount: 0
};
const interval = setInterval(async () => {
const currentBlock = await provider.getBlockNumber();
for (let i = startBlock + 1; i <= currentBlock; i++) {
const block = await provider.getBlock(i, true);
stats.blocks.push(block);
stats.totalTransactions += block.transactions.length;
stats.totalGasUsed += block.gasUsed;
// Count cross-chain transactions
for (const tx of block.transactions) {
if (tx.to === '0x239e96c8f17C85c30100AC26F635Ea15f23E9c67') {
stats.crossChainTxCount++;
}
}
}
}, 6000); // Check every block (6 seconds)
setTimeout(() => {
clearInterval(interval);
console.log('Chain Activity Summary:', stats);
}, duration);
}
3. Transaction Finality Checker
async function checkTransactionFinality(txHash, confirmations = 12) {
const receipt = await provider.getTransactionReceipt(txHash);
if (!receipt) throw new Error('Transaction not found');
const txBlock = await provider.getBlock(receipt.blockNumber, false);
const currentBlock = await provider.getBlockNumber();
const currentConfirmations = currentBlock - receipt.blockNumber;
return {
transactionHash: txHash,
blockNumber: receipt.blockNumber,
blockHash: txBlock.hash,
timestamp: new Date(txBlock.timestamp * 1000),
confirmations: currentConfirmations,
finalized: currentConfirmations >= confirmations,
requiredConfirmations: confirmations
};
}
Block Fields Reference
Field | Type | Description |
---|---|---|
number | Quantity | Block number |
hash | Data, 32 bytes | Block hash |
parentHash | Data, 32 bytes | Parent block hash |
nonce | Data, 8 bytes | Proof of work nonce |
sha3Uncles | Data, 32 bytes | SHA3 of uncles data |
logsBloom | Data, 256 bytes | Bloom filter for logs |
transactionsRoot | Data, 32 bytes | Root of transaction trie |
stateRoot | Data, 32 bytes | Root of state trie |
receiptsRoot | Data, 32 bytes | Root of receipts trie |
miner | Data, 20 bytes | Address of miner |
difficulty | Quantity | Block difficulty |
totalDifficulty | Quantity | Total chain difficulty |
extraData | Data | Extra data field |
size | Quantity | Block size in bytes |
gasLimit | Quantity | Maximum gas allowed |
gasUsed | Quantity | Total gas used |
timestamp | Quantity | Unix timestamp |
transactions | Array | Transaction objects or hashes |
uncles | Array | Uncle block hashes |
Best Practices
- Use
false
for transaction details when only block info is needed - Cache frequently accessed blocks
- Batch multiple block requests when analyzing ranges
- Monitor reorgs in recent blocks
- Handle null responses for pending blocks
Error Codes
Code | Message | Description |
---|---|---|
-32600 | Invalid Request | Invalid JSON |
-32602 | Invalid params | Invalid method parameters |
-32603 | Internal error | Internal JSON-RPC error |
-32000 | Block not found | Specified block doesn't exist |
Related Methods
- eth_getBlockByHash - Get block by hash
- eth_blockNumber - Get latest block number
- eth_getTransactionByHash - Get transaction details
- eth_getTransactionReceipt - Get transaction receipt