chain_subscribeFinalizedHeads
Subscribe to receive notifications when blocks are finalized on Astar. Finalized blocks are guaranteed to never be reverted, making this essential for applications requiring strong consistency.
Use Cases#
- Exchange deposits - Only credit funds after finalization for cross-chain DeFi, multi-VM smart contracts, and XCM-enabled interoperability with Ethereum and Cosmos
- Bridge operations - Wait for finality before cross-chain transfers
- Critical state changes - Ensure irreversibility for important transactions
Parameters#
This method takes no parameters.
Returns#
Returns a subscription ID. The subscription emits Header objects for each finalized 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 finalized heads
const unsubscribe = await api.rpc.chain.subscribeFinalizedHeads((header) => {
console.log(`Finalized block #${header.number}`);
console.log(` Hash: ${header.hash.toHex()}`);
// Safe to consider this block permanent
processConfirmedBlock(header);
});
// Later: unsubscribe()
import asyncio
import websockets
import json
async def subscribe_finalized():
uri = 'wss://api-astar.n.dwellir.com/YOUR_API_KEY'
async with websockets.connect(uri) as ws:
await ws.send(json.dumps({
'jsonrpc': '2.0',
'method': 'chain_subscribeFinalizedHeads',
'params': [],
'id': 1
}))
response = json.loads(await ws.recv())
sub_id = response['result']
print(f'Subscribed to finalized heads: {sub_id}')
while True:
message = json.loads(await ws.recv())
if 'params' in message:
header = message['params']['result']
block_num = int(header['number'], 16)
print(f"Finalized: #{block_num}")
asyncio.run(subscribe_finalized())
Finality Lag#
Finalized blocks typically lag behind the best block by a few blocks due to GRANDPA consensus requirements. This is normal and ensures Byzantine fault tolerance.
Related Methods#
chain_subscribeNewHeads- Subscribe to all new blocks (not just finalized)chain_getFinalizedHead- Get current finalized block hashgrandpa_roundState- Monitor GRANDPA consensus progress