# chain_getFinalizedHead - FLOP RPC Method

Returns the hash of the last finalized block on FLOP. Finalized blocks have been confirmed by the GRANDPA finality gadget and are guaranteed to never be reverted.

> **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_getFinalizedHead` is critical for AI agent builders, FLOP miners, indexers, and Substrate developers:

- **Exchange Deposits** - Only credit user funds after the block has been finalized on FLOP
- **Transaction Confirmation** - Verify transactions have achieved irreversible finality for Proof of Inference settlement, 1-second BABE blocks with AlephBFT finality, archive state queries, and HTLC atomic swaps
- **Safe Checkpoints** - Use finalized blocks as safe anchors for indexing and state queries
- **Bridge Operations** - Confirm source-chain finality before executing cross-chain transfers

## Best Practices

- FLOP finalizes blocks with AlephBFT rather than GRANDPA or BEEFY. Do not call `grandpa_roundState` or `beefy_getFinalizedHead` on FLOP nodes.
- Finalized blocks are irreversible and safe for all settlement, indexing, and deposit checks.
- Combine with `chain_getBlock` or `chain_getHeader` for full block data, or call `archive_v1_finalizedHeight` for the finalized block number directly.
- Use `chain_subscribeFinalizedHeads` or `chainHead_v1_follow` over WebSocket instead of polling 1-second blocks over HTTP.

## Request Parameters

This method accepts no parameters.

## Request Example

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

## Response Fields

- `result` (`Hash, required`): Hex-encoded 32-byte hash of the latest finalized block

## Successful Response

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

## Error Responses

### Error Response

- Code: `-32603`

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

## Code Examples

cURL
JavaScript
Python
Rust

```bash
curl -X POST https://api-flop-testnet.n.dwellir.com/YOUR_API_KEY \
  -H "Content-Type: application/json" \
  -d '{
    "jsonrpc": "2.0",
    "method": "chain_getFinalizedHead",
    "params": [],
    "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 finalized block hash
const finalizedHash = await api.rpc.chain.getFinalizedHead();
console.log('Finalized block hash:', finalizedHash.toHex());

// Get finalized block details
const block = await api.rpc.chain.getBlock(finalizedHash);
const blockNumber = block.block.header.number.toNumber();
console.log('Finalized block number:', blockNumber);

// Compare with best block to see finality lag
const bestHeader = await api.rpc.chain.getHeader();
const lag = bestHeader.number.toNumber() - blockNumber;
console.log(`Finality lag: ${lag} blocks`);

await api.disconnect();
```

```python
import requests

def get_finalized_head():
    url = 'https://api-flop-testnet.n.dwellir.com/YOUR_API_KEY'

    payload = {
        'jsonrpc': '2.0',
        'method': 'chain_getFinalizedHead',
        'params': [],
        'id': 1
    }

    response = requests.post(url, json=payload)
    return response.json()['result']

finalized_hash = get_finalized_head()
print(f'Finalized block hash: {finalized_hash}')

# Fetch finalized block details
payload = {
    'jsonrpc': '2.0',
    'method': 'chain_getBlock',
    'params': [finalized_hash],
    'id': 2
}

response = requests.post('https://api-flop-testnet.n.dwellir.com/YOUR_API_KEY', json=payload)
block = response.json()['result']
block_number = int(block['block']['header']['number'], 16)
print(f'Finalized block number: {block_number}')
```

```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?;

    let finalized_hash = api.rpc()
        .chain_get_finalized_head()
        .await?;

    println!("Finalized block hash: {:?}", finalized_hash);

    let block = api.rpc()
        .chain_get_block(Some(finalized_hash))
        .await?
        .expect("Finalized block should exist");

    println!("Finalized block number: {}", block.block.header.number);

    Ok(())
}
```

## Common Use Cases

### 1. Exchange Deposit Confirmation

Wait for finality before crediting deposits on FLOP:

```javascript
async function waitForFinality(api, txBlockHash) {
  return new Promise((resolve) => {
    const unsub = api.rpc.chain.subscribeFinalizedHeads(async (header) => {
      const finalizedHash = await api.rpc.chain.getBlockHash(header.number);

      // Check if the transaction block has been finalized
      const finalizedNumber = header.number.toNumber();
      const txBlock = await api.rpc.chain.getBlock(txBlockHash);
      const txNumber = txBlock.block.header.number.toNumber();

      if (finalizedNumber >= txNumber) {
        console.log(`Transaction finalized at block #${txNumber}`);
        unsub();
        resolve(txBlockHash);
      }
    });
  });
}
```

### 2. Safe State Queries

Query chain state at the finalized block to avoid reading data that could be reverted:

```javascript
async function getSafeBalance(api, address) {
  const finalizedHash = await api.rpc.chain.getFinalizedHead();
  const apiAt = await api.at(finalizedHash);
  const account = await apiAt.query.system.account(address);

  return {
    free: account.data.free.toString(),
    reserved: account.data.reserved.toString(),
    finalizedAt: finalizedHash.toHex()
  };
}
```

### 3. Finality Lag Monitor

Track the gap between best and finalized blocks for health monitoring:

```javascript
async function monitorFinalityLag(api, threshold = 10) {
  const bestHeader = await api.rpc.chain.getHeader();
  const finalizedHash = await api.rpc.chain.getFinalizedHead();
  const finalizedHeader = await api.rpc.chain.getHeader(finalizedHash);

  const lag = bestHeader.number.toNumber() - finalizedHeader.number.toNumber();
  console.log(`Finality lag: ${lag} blocks`);

  if (lag > threshold) {
    console.warn(`WARNING: Finality lag (${lag}) exceeds threshold (${threshold})`);
  }

  return lag;
}
```

## Related Methods

- [`chain_getBlock`](https://www.dwellir.com/docs/flop/chain_getBlock) - Get full block data by hash
- [`chain_getBlockHash`](https://www.dwellir.com/docs/flop/chain_getBlockHash) - Get block hash by number
- [`chain_subscribeFinalizedHeads`](https://www.dwellir.com/docs/flop/chain_subscribeFinalizedHeads) - Subscribe to finalized block headers
- `grandpa_roundState` - Monitor GRANDPA finality progress
