# eth_getBlockByNumber - Moonbeam RPC Method

Returns information about a block by block number 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_getBlockByNumber` is essential for cross-chain dApp developers, Polkadot builders, and teams requiring multi-chain interoperability:

- **Block explorers and analytics dashboards**: Display comprehensive block data and chain metrics for end-user interfaces on Moonbeam
- **Transaction indexers processing block contents**: Extract and index every transaction within a block for data pipelines and search backends
- **Cross-chain bridges verifying block data**: Validate block headers and transaction proofs for cross-chain DeFi, multi-chain dApps, and Ethereum-to-Polkadot bridging via XCM, Axelar, LayerZero, and Wormhole
- **Timestamp-based logic**: Verify block age and enforce time-dependent contract logic on the cross-chain connected EVM platform on Polkadot with $65M+ TVL and 100+ projects

## Request Parameters

- `blockNumber` (`QUANTITY|TAG, required`): Block number in hex, or "latest", "earliest", "pending", "safe", "finalized"
- `fullTransactions` (`Boolean, required`): If true, returns full transaction objects; if false, returns transaction hashes

## Request Example

```json
{
  "jsonrpc": "2.0",
  "method": "eth_getBlockByNumber",
  "params": ["latest", false],
  "id": 1
}
```

## Response Fields

- `number` (`QUANTITY, required`): Block number
- `hash` (`DATA, required`): 32-byte block hash
- `parentHash` (`DATA, required`): 32-byte parent block hash
- `timestamp` (`QUANTITY, required`): Unix timestamp
- `gasUsed` (`QUANTITY, required`): Total gas used by all transactions
- `gasLimit` (`QUANTITY, required`): Maximum gas allowed in block
- `transactions` (`Array, required`): Array of transaction objects or hashes
- `baseFeePerGas` (`QUANTITY, required`): Base fee per gas (EIP-1559)

## Successful Response

```json
{
  "jsonrpc": "2.0",
  "id": 1,
  "result": {
    "number": "0x5BAD55",
    "hash": "0x4e3a3754410177e6937ef1f84bba68ea139e8d1a2258c5f85db9f1cd715a1bdd",
    "parentHash": "0x...",
    "timestamp": "0x64d8f6d0",
    "gasUsed": "0x1234",
    "gasLimit": "0x1c9c380",
    "transactions": [],
    "baseFeePerGas": "0x5f5e100"
  }
}
```

## Common Use Cases

### 1. Process All Transactions in the Latest Block

Fetch the latest block on Moonbeam with full transaction objects, then iterate through each transaction to extract sender, receiver, value, and gas data. This pattern powers indexers, analytics dashboards, and event backfill pipelines.

```javascript
import { JsonRpcProvider, formatEther } from 'ethers';

const provider = new JsonRpcProvider('https://api-moonbeam.n.dwellir.com/YOUR_API_KEY');

async function processLatestBlock() {
  const block = await provider.getBlock('latest', true);

  if (!block) return;

  console.log(`Block #${block.number}: ${block.transactions.length} transactions`);

  for (const tx of block.prefetchedTransactions) {
    console.log(`  ${tx.hash}`);
    console.log(`    From: ${tx.from}  To: ${tx.to}`);
    console.log(`    Value: ${formatEther(tx.value)}  Gas: ${tx.gasLimit.toString()}`);
  }
}

processLatestBlock();
```

### 2. Monitor New Blocks with a Polling Loop

Poll `eth_getBlockByNumber` at regular intervals to detect new blocks as they are produced on Moonbeam. This lightweight pattern is suitable for bots, watchers, and notification services that need near-real-time block awareness.

```python
from web3 import Web3
import time

w3 = Web3(Web3.HTTPProvider('https://api-moonbeam.n.dwellir.com/YOUR_API_KEY'))

last_block = w3.eth.block_number

print(f'Starting from block #{last_block}')

while True:
    current_block = w3.eth.block_number
    if current_block > last_block:
        for block_num in range(last_block + 1, current_block + 1):
            block = w3.eth.get_block(block_num)
            tx_count = len(block.transactions)
            print(f'New block #{block.number}: {tx_count} txns, '
                  f'gas used {block.gasUsed}')
        last_block = current_block
    time.sleep(2)
```

### 3. Verify Block Finality on L2 Chains

Layer 2 rollup chains on the cross-chain connected EVM platform on Polkadot with $65M+ TVL and 100+ projects expose additional block tags that indicate settlement confidence. Use `safe` or `finalized` tags alongside the base `latest` tag for use cases requiring strong finality guarantees.

```go
package main

import (
    "context"
    "fmt"
    "log"
    "math/big"

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

func main() {
    client, _ := ethclient.Dial("https://api-moonbeam.n.dwellir.com/YOUR_API_KEY")

    // Latest block (may be unconfirmed on L2)
    latest, _ := client.BlockByNumber(context.Background(), nil)
    fmt.Printf("Latest block: %d (timestamp: %d)\n",
        latest.Number().Uint64(), latest.Time())

    // Finalized block (settled on L1 for rollups)
    finalized, _ := client.BlockByNumber(context.Background(),
        big.NewInt(int64(RPCLatestBlockNumber-32))) // placeholder: use rpc.FinalizedBlockNumber
    if finalized != nil {
        fmt.Printf("Finalized block: %d\n", finalized.Number().Uint64())
    }
}
```

## Best Practices

- **Cache block data by block number**: Blocks are immutable once finalized, so cache results indefinitely keyed by block number to eliminate redundant API calls
- **Use `latest` tag for most use cases; avoid `pending` for production**: The `pending` tag returns speculative data that may never be included in the canonical chain
- **For L2 chains, check chain-specific finality tags**: Tags like `safe` and `finalized` provide settlement guarantees specific to each rollup's proof mechanism
- **Combine with `eth_getBlockReceipts` for efficient receipt scanning**: When you need both block headers and transaction outcomes, use `eth_getBlockReceipts` alongside this method rather than fetching receipts individually

## 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_getBlockByNumber",
    "params": ["latest", false],
    "id": 1
  }'
```

```javascript
import { JsonRpcProvider } from 'ethers';

const provider = new JsonRpcProvider('https://api-moonbeam.n.dwellir.com/YOUR_API_KEY');

// Get latest block
const block = await provider.getBlock('latest');
console.log('Block number:', block.number);
console.log('Timestamp:', new Date(block.timestamp * 1000));
console.log('Transactions:', block.transactions.length);

// Get block with full transactions
const blockWithTxs = await provider.getBlock('latest', true);
for (const tx of blockWithTxs.prefetchedTransactions) {
  console.log('Transaction:', tx.hash);
}
```

```python
from web3 import Web3

w3 = Web3(Web3.HTTPProvider('https://api-moonbeam.n.dwellir.com/YOUR_API_KEY'))

# Get latest block
block = w3.eth.get_block('latest')
print(f'Block number: {block.number}')
print(f'Timestamp: {block.timestamp}')
print(f'Transactions: {len(block.transactions)}')

# Get block with full transactions
block_full = w3.eth.get_block('latest', full_transactions=True)
for tx in block_full.transactions:
    print(f'Transaction: {tx.hash.hex()}')
```

```go
package main

import (
    "context"
    "fmt"
    "log"
    "math/big"

    "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)
    }

    // Get latest block
    block, err := client.BlockByNumber(context.Background(), nil)
    if err != nil {
        log.Fatal(err)
    }

    fmt.Printf("Block number: %d\n", block.Number().Uint64())
    fmt.Printf("Timestamp: %d\n", block.Time())
    fmt.Printf("Transactions: %d\n", len(block.Transactions()))
}
```

## Related Methods

- [`eth_blockNumber`](https://www.dwellir.com/docs/moonbeam/eth_blockNumber) - Get latest block number
- [`eth_getBlockByHash`](https://www.dwellir.com/docs/moonbeam/eth_getBlockByHash) - Get block by hash
- [`eth_getTransactionByHash`](https://www.dwellir.com/docs/moonbeam/eth_getTransactionByHash) - Get transaction details
