# chain_getHeader - FLOP RPC Method

Returns the block header for a given hash on FLOP. This is a lightweight alternative to `chain_getBlock` when you only need header metadata without extrinsic data.

> **Why FLOP?** Build on the Substrate Proof of Inference Layer 1 built for autonomous AI agents with Proof of Inference with TOPLOC activation commitments, full historical archive state from genesis, and JSON-RPC v2 archive and chainHead APIs.

## When to Use This Method

`chain_getHeader` is ideal for AI agent builders, FLOP miners, indexers, and Substrate developers:

- **Lightweight Queries** - Get block metadata without downloading full extrinsic data on FLOP
- **Chain Synchronization** - Track block production and monitor chain progress for Proof of Inference settlement, 1-second BABE blocks with AlephBFT finality, archive state queries, and HTLC atomic swaps
- **Parent Chain Navigation** - Follow `parentHash` links to traverse the chain backwards
- **State Verification** - Use `stateRoot` and `extrinsicsRoot` for Merkle proof verification

## Best Practices

- Headers are much smaller than full blocks -- use for quick verification without body data
- The `parentHash` field verifies chain continuity by linking to the previous block
- Digest logs contain consensus messages and seal data
- Cache headers for recent blocks to reduce repeated API calls

## Request Parameters

- `blockHash` (`String, optional`): Hex-encoded block hash. If omitted, returns the latest block header

## Request Example

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

## Response Fields

- `parentHash` (`Hash, required`): Hash of the parent block
- `number` (`BlockNumber, required`): Block number (hex-encoded)
- `stateRoot` (`Hash, required`): Merkle root of the state trie after this block
- `extrinsicsRoot` (`Hash, required`): Merkle root of the extrinsics trie
- `digest` (`Digest, required`): Block digest containing consensus engine logs

## Successful Response

```json
{
  "jsonrpc": "2.0",
  "id": 1,
  "result": {
    "parentHash": "0xa1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6e7f8a9b0c1d2e3f4a5b6c7d8e9f0a1b2",
    "number": "0xf4240",
    "stateRoot": "0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef",
    "extrinsicsRoot": "0xabcdef1234567890abcdef1234567890abcdef1234567890abcdef1234567890",
    "digest": {
      "logs": [
        "0x0642414245b50103..."
      ]
    }
  }
}
```

## Error Responses

### Error Response

- Code: `-32602`

```json
{
  "jsonrpc": "2.0",
  "id": 1,
  "error": {
    "code": -32602,
    "message": "Invalid block hash"
  }
}
```

## Code Examples

cURL
JavaScript
Python
Rust

```bash
# Get latest block header
curl -X POST https://api-flop-testnet.n.dwellir.com/YOUR_API_KEY \
  -H "Content-Type: application/json" \
  -d '{
    "jsonrpc": "2.0",
    "method": "chain_getHeader",
    "params": [],
    "id": 1
  }'

# Get header for a specific block hash
curl -X POST https://api-flop-testnet.n.dwellir.com/YOUR_API_KEY \
  -H "Content-Type: application/json" \
  -d '{
    "jsonrpc": "2.0",
    "method": "chain_getHeader",
    "params": ["0xYOUR_RECENT_BLOCK_HASH"],
    "id": 1
  }'
```

```javascript
import { ApiPromise, WsProvider } from '@polkadot/api';

const provider = new WsProvider('wss://api-flop-testnet.n.dwellir.com/YOUR_API_KEY');
const api = await ApiPromise.create({ provider });

// Get latest header
const header = await api.rpc.chain.getHeader();
console.log('Block number:', header.number.toNumber());
console.log('Parent hash:', header.parentHash.toHex());
console.log('State root:', header.stateRoot.toHex());
console.log('Extrinsics root:', header.extrinsicsRoot.toHex());

// Get header for a specific block hash
const blockHash = await api.rpc.chain.getBlockHash(1000000);
const historicalHeader = await api.rpc.chain.getHeader(blockHash);
console.log('Block #1000000 parent:', historicalHeader.parentHash.toHex());

await api.disconnect();
```

```python
import requests

def get_header(block_hash=None):
    url = 'https://api-flop-testnet.n.dwellir.com/YOUR_API_KEY'
    params = [block_hash] if block_hash else []

    payload = {
        'jsonrpc': '2.0',
        'method': 'chain_getHeader',
        'params': params,
        'id': 1
    }

    response = requests.post(url, json=payload)
    result = response.json()

    if 'error' in result:
        raise Exception(f"RPC Error: {result['error']}")

    return result['result']

# Get latest header
header = get_header()
block_number = int(header['number'], 16)
print(f'Block number: {block_number}')
print(f"Parent hash: {header['parentHash']}")
print(f"State root: {header['stateRoot']}")
print(f"Extrinsics root: {header['extrinsicsRoot']}")
```

```rust
use subxt::{OnlineClient, PolkadotConfig};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let api = OnlineClient::<PolkadotConfig>::from_url(
        "wss://api-flop-testnet.n.dwellir.com/YOUR_API_KEY"
    ).await?;

    // Get latest header
    let header = api.rpc()
        .chain_get_header(None)
        .await?
        .expect("Header should exist");

    println!("Block number: {}", header.number);
    println!("Parent hash: {:?}", header.parent_hash);
    println!("State root: {:?}", header.state_root);

    Ok(())
}
```

## Common Use Cases

### 1. Block Time Calculator

Estimate block production rate on FLOP:

```javascript
async function estimateBlockTime(api, sampleSize = 10) {
  const latestHeader = await api.rpc.chain.getHeader();
  const latestNumber = latestHeader.number.toNumber();

  const oldHash = await api.rpc.chain.getBlockHash(latestNumber - sampleSize);
  const oldHeader = await api.rpc.chain.getHeader(oldHash);

  // Use timestamp from block digests or timestamp pallet
  const latestTimestamp = await api.query.timestamp.now();
  const apiAt = await api.at(oldHash);
  const oldTimestamp = await apiAt.query.timestamp.now();

  const timeDiff = latestTimestamp.toNumber() - oldTimestamp.toNumber();
  const avgBlockTime = timeDiff / sampleSize;

  console.log(`Average block time: ${avgBlockTime / 1000}s over ${sampleSize} blocks`);
  return avgBlockTime;
}
```

### 2. Chain Traversal

Walk backwards through the FLOP chain using parent hashes:

```javascript
async function walkChain(api, startHash, depth = 5) {
  let currentHash = startHash || (await api.rpc.chain.getBlockHash());
  const headers = [];

  for (let i = 0; i < depth; i++) {
    const header = await api.rpc.chain.getHeader(currentHash);
    headers.push({
      number: header.number.toNumber(),
      hash: currentHash.toString(),
      parentHash: header.parentHash.toHex()
    });
    currentHash = header.parentHash;
  }

  return headers;
}
```

### 3. Lightweight Block Monitor

Monitor FLOP block production without downloading full blocks:

```javascript
async function monitorBlocks(api, callback) {
  let lastNumber = 0;

  setInterval(async () => {
    const header = await api.rpc.chain.getHeader();
    const number = header.number.toNumber();

    if (number > lastNumber) {
      console.log(`New block #${number}`);
      callback(header);
      lastNumber = number;
    }
  }, 3000);
}
```

## Related Methods

- [`chain_getBlock`](https://www.dwellir.com/docs/flop/chain_getBlock) - Get full block with extrinsics
- [`chain_getBlockHash`](https://www.dwellir.com/docs/flop/chain_getBlockHash) - Get block hash by number
- [`chain_subscribeNewHeads`](https://www.dwellir.com/docs/flop/chain_subscribeNewHeads) - Subscribe to new block headers in real time
- [`chain_subscribeFinalizedHeads`](https://www.dwellir.com/docs/flop/chain_subscribeFinalizedHeads) - Subscribe to finalized block headers
