eth_blockNumber
Returns the number of the most recent block on Ethereum Mainnet.
When to Use This Method#
eth_blockNumber is fundamental for:
- Syncing Applications - Keep your dApp in sync with the latest blockchain state
- Transaction Monitoring - Verify confirmations by comparing block numbers
- Event Filtering - Set the correct block range for querying logs
- Health Checks - Monitor node connectivity and sync status
Parameters#
This method accepts no parameters.
[]
Returns#
QUANTITY - Integer of the current block number the node is synced to.
- Type: Hexadecimal string
- Format:
0xprefixed - Example:
0x5bad55(6008149 in decimal)
Implementation Examples#
- cURL
- JavaScript
- Python
- Go
curl -X POST ${S.rpcBase} \
-H "Content-Type: application/json" \
-d '
"jsonrpc": "2.0",
"method": "eth_blockNumber",
"params": [],
"id": 1
}'
// Using fetch API
const getBlockNumber = async () => {
const response = await fetch('${S.rpcBase}', {
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);
return blockNumber;
};
// Using ethers.js
import { JsonRpcProvider } from 'ethers';
const provider = new JsonRpcProvider('${S.rpcBase}');
const blockNumber = await provider.getBlockNumber();
console.log('Current block:', blockNumber);
import requests
import json
def get_block_number():
url = '${S.rpcBase}'
payload = {
"jsonrpc": "2.0",
"method": "eth_blockNumber",
"params": [],
"id": 1
}
response = requests.post(url, json=payload)
data = response.json()
# Convert hex to decimal
block_number = int(data['result'], 16)
print(f"Current block: {block_number}")
return block_number
# Using web3.py
from web3 import Web3
w3 = Web3(Web3.HTTPProvider('${S.rpcBase}'))
block_number = w3.eth.block_number
print(f"Current block: {block_number}")
package main
import (
"context"
"fmt"
"log"
"math/big"
"github.com/ethereum/go-ethereum/ethclient"
)
func main() {
client, err := ethclient.Dial("${S.rpcBase}")
if err != nil {
log.Fatal(err)
}
blockNumber, err := client.BlockNumber(context.Background())
if err != nil {
log.Fatal(err)
}
fmt.Printf("Current block: %d\n", blockNumber)
}
Response Example#
Successful Response#
{
"jsonrpc": "2.0",
"id": 1,
"result": "0x5bad55"
}
Error Response#
{
"jsonrpc": "2.0",
"id": 1,
"error": {
"code": -32603,
"message": "Internal error"
}
}
Common Use Cases#
1. Block Confirmation Counter#
Monitor transaction confirmations:
async function getConfirmations(txHash) {
const tx = await provider.getTransaction(txHash);
if (!tx || !tx.blockNumber) return 0;
const currentBlock = await provider.getBlockNumber();
return currentBlock - tx.blockNumber + 1;
}
// Wait for specific confirmations
async function waitForConfirmations(txHash, confirmations = 6) {
let currentConfirmations = 0;
while (currentConfirmations < confirmations) {
currentConfirmations = await getConfirmations(txHash);
console.log(`Confirmations: ${currentConfirmations}/${confirmations}`);
await new Promise(r => setTimeout(r, 2000)); // Check every 2 seconds
}
return true;
}
2. Event Log Filtering#
Query events from recent blocks:
async function getRecentEvents(contract, eventName, blockRange = 100) {
const currentBlock = await provider.getBlockNumber();
const fromBlock = currentBlock - blockRange;
const filter = contract.filters[eventName]();
const events = await contract.queryFilter(filter, fromBlock, currentBlock);
return events;
}
3. Node Health Monitoring#
Check if your node is synced:
async function checkNodeHealth() {
try {
const blockNumber = await provider.getBlockNumber();
const block = await provider.getBlock(blockNumber);
const now = Date.now() / 1000;
const blockAge = now - block.timestamp;
if (blockAge > 60) {
console.warn(`Node may be behind. Last block was ${blockAge}s ago`);
return false;
}
console.log(`Node healthy. Latest block: ${blockNumber}`);
return true;
} catch (error) {
console.error('Node unreachable:', error);
return false;
}
}
Performance Optimization#
Caching Strategy#
Cache block numbers to reduce API calls:
class BlockNumberCache {
constructor(ttl = 2000) { // 2 second cache
this.cache = null;
this.timestamp = 0;
this.ttl = ttl;
}
async get(provider) {
const now = Date.now();
if (this.cache && (now - this.timestamp) < this.ttl) {
return this.cache;
}
this.cache = await provider.getBlockNumber();
this.timestamp = now;
return this.cache;
}
invalidate() {
this.cache = null;
this.timestamp = 0;
}
}
const blockCache = new BlockNumberCache();
Batch Requests#
Combine with other calls for efficiency:
const batch = [
{ jsonrpc: '2.0', method: 'eth_blockNumber', params: [], id: 1 },
{ jsonrpc: '2.0', method: 'eth_gasPrice', params: [], id: 2 },
{ jsonrpc: '2.0', method: 'eth_chainId', params: [], id: 3 }
];
const response = await fetch('https://api-monad-mainnet-full.n.dwellir.com/YOUR_API_KEY', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(batch)
});
const results = await response.json();
Error Handling#
Common errors and solutions:
| Error Code | Description | Solution |
|---|---|---|
| -32603 | Internal error | Retry with exponential backoff |
| -32005 | Rate limit exceeded | Implement rate limiting client-side |
| -32000 | Execution reverted | Check node sync status |
async function safeGetBlockNumber(maxRetries = 3) {
for (let i = 0; i < maxRetries; i++) {
try {
return await provider.getBlockNumber();
} catch (error) {
if (error.code === -32005) {
// Rate limited, wait exponentially
await new Promise(r => setTimeout(r, Math.pow(2, i) * 1000));
} else if (i === maxRetries - 1) {
throw error;
}
}
}
}
Live Test Example on Monad#
Request#
Get the current block number on Monad:
curl -X POST https://api-monad-mainnet-full.n.dwellir.com/YOUR_API_KEY \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "eth_blockNumber",
"params": [],
"id": 1
}'
Response#
{
"jsonrpc": "2.0",
"id": 1,
"result": "0x24bcfb9"
}
Decoded: Block number 38,666,169 in decimal
Using the Block Number with eth_getBlockByNumber#
Once you have the block number, you can retrieve full block details:
curl -X POST https://api-monad-mainnet-full.n.dwellir.com/YOUR_API_KEY \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "eth_getBlockByNumber",
"params": ["0x24bcfb9", true],
"id": 1
}'
Sample Block Response (Truncated)#
{
"jsonrpc": "2.0",
"id": 1,
"result": {
"hash": "0x6e23adcfaaf68a331fa4af150e993c82ac2b8e440c7e64a6c28daa24851ad201",
"parentHash": "0x1cabc93c2ece2353ff528807f4fd38f73ed3a12c8c6a27b646db9e842ef8944b",
"number": "0x24bcfb9",
"timestamp": "0x69296f6a",
"miner": "0x32ee0a75d937fff62f6bd8e9f00d1ee730001f25",
"gasLimit": "0xbebc200",
"gasUsed": "0xd878d7",
"baseFeePerGas": "0x174876e800",
"difficulty": "0x0",
"totalDifficulty": "0x0",
"size": "0x30f",
"transactions": [
{
"hash": "0x6c23e28e0f32b58695631acd9999dd2a89a14fe18ff58cbb659cbde14e025943",
"from": "0x6f49a8f621353f12378d0046e7d7e4b9b249dc9e",
"to": "0x0000000000000000000000000000000000001000",
"value": "0x15af1d78b58c40000",
"gas": "0x0",
"gasPrice": "0x0",
"nonce": "0x498455",
"blockNumber": "0x24bcfb9",
"transactionIndex": "0x0"
},
{
"hash": "0xdb84cc24bfb2ccc6e69a2f96b26ea2852966df86a7361efceadaa9c006d55fb8",
"from": "0x4427aeabe9a2e49d36b75427b981e88aad825754",
"to": "0x0d97dc33264bfc1c226207428a79b26757fb9dc3",
"value": "0x54b40b1f852bda00000",
"gas": "0xf4240",
"gasPrice": "0x2fd024af41",
"nonce": "0x377c",
"blockNumber": "0x24bcfb9",
"transactionIndex": "0x1"
}
// ... 11 more transactions (13 total)
],
"uncles": [],
"stateRoot": "0x99d87c6b6de854e133c37956f41eac76b27a2a06c0fc6b2af1d97c381705f2bf",
"transactionsRoot": "0x67ea99a2c88ef966ec9ee91115da863b04c4d5d407b3c63dfe733b28c42c1cc3",
"receiptsRoot": "0xc6f6a6dbafb36c8cd898b35ddd35083045b272a2397fa6bcb3176fb48d825daf",
"mixHash": "0x3a1d0344fffacf5ad4e7f924dda73680ca8514cd91d6debfbdd4f680369fba5d",
"nonce": "0x0000000000000000"
}
}
Key Monad-Specific Observations#
- Fast Block Times: Block
0x24bcfb9(38,666,169) demonstrates Monad's ~1 second block time - High Transaction Throughput: 13 transactions in a single block with various transaction types (Type 0, 1, and 2)
- EIP-1559 Support: Block includes
baseFeePerGasfield for dynamic fee market - Chain ID:
0x8f(143 in decimal) - Monad mainnet identifier