chain_subscribeNewHeads
Subscribe to receive notifications when new block headers are produced on Astar. This WebSocket subscription provides real-time updates for each new block.
Use Cases#
- Block monitoring - Track new blocks in real-time for cross-chain DeFi, multi-VM smart contracts, and XCM-enabled interoperability with Ethereum and Cosmos
- Event indexing - Trigger processing when new blocks arrive
- Chain synchronization - Keep external systems in sync with the chain
Parameters#
This method takes no parameters.
Returns#
Returns a subscription ID. The subscription emits Header objects for each new block:
| Field | Type | Description |
|---|---|---|
parentHash | Hash | Parent block hash |
number | BlockNumber | Block number |
stateRoot | Hash | State trie root hash |
extrinsicsRoot | Hash | Extrinsics trie root hash |
digest | Digest | Block digest with consensus logs |
Code Examples#
- JavaScript
- Python
import { ApiPromise, WsProvider } from '@polkadot/api';
const provider = new WsProvider('wss://api-astar.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()}`);
});
// Later: unsubscribe()
import asyncio
import websockets
import json
async def subscribe_new_heads():
uri = 'wss://api-astar.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']
print(f"Block #{int(header['number'], 16)}")
print(f" Hash: {header['parentHash']}")
asyncio.run(subscribe_new_heads())
Subscription vs Polling#
| Approach | Latency | Resource Usage | Use Case |
|---|---|---|---|
subscribeNewHeads | Immediate | Low (push-based) | Real-time monitoring |
Polling getHeader | Block time + poll interval | Higher (repeated requests) | Simple integrations |
Related Methods#
chain_subscribeFinalizedHeads- Subscribe to finalized blocks onlychain_getHeader- Get a specific block headerchain_getBlock- Get full block with extrinsics