# chain_subscribeNewHeads - FLOP RPC Method

Subscribe to receive notifications when new block headers are produced on FLOP. This WebSocket subscription provides real-time, push-based updates for each new block, making it more efficient than polling.

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

- **Block Monitoring** - Track new blocks in real time on FLOP for Proof of Inference settlement, 1-second BABE blocks with AlephBFT finality, archive state queries, and HTLC atomic swaps
- **Event Indexing** - Trigger processing pipelines when new blocks arrive
- **Chain Synchronization** - Keep external databases and systems in sync with the chain
- **Dashboard Updates** - Push live block data to monitoring dashboards

## Best Practices

- Requires a WebSocket connection at `wss://api-flop-testnet.n.dwellir.com/YOUR_API_KEY`
- Unsubscribe when monitoring is no longer needed to free node resources
- Headers arrive faster than full blocks -- use `chain_getBlock` for full data when needed
- For consensus-critical applications, prefer `chain_subscribeFinalizedHeads`

## Request Parameters

This method accepts no parameters.

## Request Example

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

## Response Fields

- `parentHash` (`Hash, required`): Parent block hash
- `number` (`BlockNumber, required`): Block number (hex-encoded)
- `stateRoot` (`Hash, required`): State trie root hash after this block
- `extrinsicsRoot` (`Hash, required`): Extrinsics trie root hash
- `digest` (`Digest, required`): Block digest with consensus engine logs

## Successful Response

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

## Code Examples

cURL
JavaScript
Python
Rust

```bash
# WebSocket subscription (requires wscat or similar tool)
wscat -c wss://api-flop-testnet.n.dwellir.com/YOUR_API_KEY -x '{
  "jsonrpc": "2.0",
  "method": "chain_subscribeNewHeads",
  "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 });

// Subscribe to new heads
const unsubscribe = await api.rpc.chain.subscribeNewHeads((header) => {
  console.log(`New block #${header.number}`);
  console.log(`  Hash: ${header.hash.toHex()}`);
  console.log(`  Parent: ${header.parentHash.toHex()}`);
  console.log(`  State root: ${header.stateRoot.toHex()}`);
  console.log(`  Extrinsics root: ${header.extrinsicsRoot.toHex()}`);
});

// Unsubscribe after 60 seconds
setTimeout(() => {
  unsubscribe();
  api.disconnect();
}, 60000);
```

```python
import asyncio
import websockets
import json

async def subscribe_new_heads():
    uri = 'wss://api-flop-testnet.n.dwellir.com/YOUR_API_KEY'

    async with websockets.connect(uri) as ws:
        # Subscribe to new heads
        await ws.send(json.dumps({
            'jsonrpc': '2.0',
            'method': 'chain_subscribeNewHeads',
            'params': [],
            'id': 1
        }))

        # Get subscription ID
        response = json.loads(await ws.recv())
        sub_id = response['result']
        print(f'Subscribed with ID: {sub_id}')

        # Listen for new headers
        while True:
            message = json.loads(await ws.recv())
            if 'params' in message:
                header = message['params']['result']
                block_num = int(header['number'], 16)
                print(f"Block #{block_num}")
                print(f"  Parent: {header['parentHash']}")
                print(f"  State root: {header['stateRoot']}")

asyncio.run(subscribe_new_heads())
```

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

#[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 mut new_heads = api.rpc()
        .subscribe_all_block_headers()
        .await?;

    while let Some(Ok(header)) = new_heads.next().await {
        println!(
            "New block #{}: {:?}",
            header.number,
            header.hash()
        );
    }

    Ok(())
}
```

## Common Use Cases

### 1. Real-Time Block Indexer

Index new blocks and their events on FLOP as they arrive:

```javascript
async function indexBlocks(api, onBlock) {
  const unsub = await api.rpc.chain.subscribeNewHeads(async (header) => {
    const blockHash = header.hash;
    const [block, events] = await Promise.all([
      api.rpc.chain.getBlock(blockHash),
      api.query.system.events.at(blockHash)
    ]);

    const blockData = {
      number: header.number.toNumber(),
      hash: blockHash.toHex(),
      parentHash: header.parentHash.toHex(),
      extrinsicCount: block.block.extrinsics.length,
      eventCount: events.length,
      timestamp: Date.now()
    };

    await onBlock(blockData);
  });

  return unsub;
}
```

### 2. Block Production Monitor

Detect block production delays on FLOP:

```javascript
async function monitorBlockProduction(api, expectedBlockTimeMs = 6000) {
  let lastBlockTime = Date.now();
  const threshold = expectedBlockTimeMs * 3;

  const unsub = await api.rpc.chain.subscribeNewHeads((header) => {
    const now = Date.now();
    const elapsed = now - lastBlockTime;

    if (elapsed > threshold) {
      console.warn(
        `Block #${header.number}: ${elapsed}ms since last block (expected ~${expectedBlockTimeMs}ms)`
      );
    } else {
      console.log(`Block #${header.number}: ${elapsed}ms`);
    }

    lastBlockTime = now;
  });

  return unsub;
}
```

### 3. Live Dashboard Feed

Stream block data to a WebSocket-connected frontend:

```javascript
async function streamToClients(api, wss) {
  const unsub = await api.rpc.chain.subscribeNewHeads(async (header) => {
    const message = JSON.stringify({
      type: 'new_block',
      number: header.number.toNumber(),
      hash: header.hash.toHex(),
      parentHash: header.parentHash.toHex(),
      stateRoot: header.stateRoot.toHex()
    });

    wss.clients.forEach((client) => {
      if (client.readyState === 1) {
        client.send(message);
      }
    });
  });

  return unsub;
}
```

## Subscription vs Polling

| Approach            | Latency                    | Resource Usage             | Use Case                       |
| ------------------- | -------------------------- | -------------------------- | ------------------------------ |
| `subscribeNewHeads` | Immediate                  | Low (push-based)           | Real-time monitoring, indexing |
| Polling `getHeader` | Block time + poll interval | Higher (repeated requests) | Simple integrations, HTTP-only |

## Related Methods

- [`chain_subscribeFinalizedHeads`](https://www.dwellir.com/docs/flop/chain_subscribeFinalizedHeads) - Subscribe to finalized blocks only (for irreversible state)
- [`chain_getHeader`](https://www.dwellir.com/docs/flop/chain_getHeader) - Get a specific block header by hash
- [`chain_getBlock`](https://www.dwellir.com/docs/flop/chain_getBlock) - Get full block data with extrinsics
- `chain_unsubscribeNewHeads` - Unsubscribe from new heads
