# eth_blockNumber - Moonbeam RPC Method

Returns the number of the most recent block on Moonbeam.

> **Why Moonbeam?** Build on the cross-chain connected EVM platform on Polkadot with $65M+ TVL and 100+ projects with full EVM compatibility on Polkadot, native XCM cross-chain messaging, 10K+ TPS, 24% staking APR, and $0.015 transaction costs.

## When to Use This Method

`eth_blockNumber` is fundamental for cross-chain dApp developers, Polkadot builders, and teams requiring multi-chain interoperability:

- **Syncing Applications** - Keep your dApp in sync with the latest Moonbeam blockchain state
- **Transaction Monitoring** - Verify confirmations by comparing block numbers
- **Event Filtering** - Set the correct block range for querying logs on cross-chain DeFi, multi-chain dApps, and Ethereum-to-Polkadot bridging via XCM, Axelar, LayerZero, and Wormhole
- **Health Checks** - Monitor node connectivity and sync status

## Request Parameters

This method accepts no parameters.

## Request Example

```json
{
  "jsonrpc": "2.0",
  "method": "eth_blockNumber",
  "params": [],
  "id": 1
}
```

## Response Fields

- `result` (`QUANTITY, required`): Hexadecimal string representing the current block number

## Successful Response

```json
{
  "jsonrpc": "2.0",
  "id": 1,
  "result": "0x5BAD55"
}
```

## Error Responses

### Error Response

- Code: `-32603`

```json
{
  "jsonrpc": "2.0",
  "id": 1,
  "error": {
    "code": -32603,
    "message": "Internal error"
  }
}
```

## Code Examples

cURL
JavaScript
Python
Go

```bash
curl -X POST https://api-moonbeam.n.dwellir.com/YOUR_API_KEY \
  -H "Content-Type: application/json" \
  -d '{
    "jsonrpc": "2.0",
    "method": "eth_blockNumber",
    "params": [],
    "id": 1
  }'
```

```javascript
// Using fetch
const response = await fetch('https://api-moonbeam.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 { result } = await response.json();
const blockNumber = parseInt(result, 16);
console.log('Moonbeam block:', blockNumber);

// Using ethers.js
import { JsonRpcProvider } from 'ethers';

const provider = new JsonRpcProvider('https://api-moonbeam.n.dwellir.com/YOUR_API_KEY');
const blockNumber = await provider.getBlockNumber();
console.log('Moonbeam block:', blockNumber);
```

```python
import requests

def get_block_number():
    response = requests.post(
        'https://api-moonbeam.n.dwellir.com/YOUR_API_KEY',
        json={
            'jsonrpc': '2.0',
            'method': 'eth_blockNumber',
            'params': [],
            'id': 1
        }
    )
    result = response.json()['result']
    return int(result, 16)

block_number = get_block_number()
print(f'Moonbeam block: {block_number}')

# Using web3.py
from web3 import Web3

w3 = Web3(Web3.HTTPProvider('https://api-moonbeam.n.dwellir.com/YOUR_API_KEY'))
print(f'Moonbeam block: {w3.eth.block_number}')
```

```go
package main

import (
    "context"
    "fmt"
    "log"

    "github.com/ethereum/go-ethereum/ethclient"
)

func main() {
    client, err := ethclient.Dial("https://api-moonbeam.n.dwellir.com/YOUR_API_KEY")
    if err != nil {
        log.Fatal(err)
    }

    blockNumber, err := client.BlockNumber(context.Background())
    if err != nil {
        log.Fatal(err)
    }

    fmt.Printf("Moonbeam block: %d\n", blockNumber)
}
```

## Common Use Cases

### 1. Block Confirmation Counter

Monitor transaction confirmations on Moonbeam:

```javascript
async function getConfirmations(provider, 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(provider, txHash, confirmations = 6) {
  let currentConfirmations = 0;

  while (currentConfirmations < confirmations) {
    currentConfirmations = await getConfirmations(provider, txHash);
    console.log(`Confirmations: ${currentConfirmations}/${confirmations}`);
    await new Promise(r => setTimeout(r, 2000));
  }

  return true;
}
```

### 2. Event Log Filtering

Query events from recent blocks on Moonbeam:

```javascript
async function getRecentEvents(provider, 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 Moonbeam node is synced:

```javascript
async function checkNodeHealth(provider) {
  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:

```javascript
class BlockNumberCache {
  constructor(ttl = 2000) {
    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:

```javascript
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-moonbeam.n.dwellir.com/YOUR_API_KEY', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify(batch)
});

const results = await response.json();
```

## Related Methods

- [`eth_getBlockByNumber`](https://www.dwellir.com/docs/moonbeam/eth_getBlockByNumber) - Get full block details by number
- [`eth_getBlockByHash`](https://www.dwellir.com/docs/moonbeam/eth_getBlockByHash) - Get block details by hash
- [`eth_syncing`](https://www.dwellir.com/docs/moonbeam/eth_syncing) - Check if node is still syncing
