Read the Latest Finalized Bittensor Block with JSON-RPC
Use Node.js to retrieve a finalized block hash and height from a Bittensor RPC endpoint, and handle common request failures.
To read Bittensor’s latest finalized block, call chain_getFinalizedHead, then pass the returned hash to chain_getHeader. The Node.js script below performs both calls against an RPC URL you supply. Start with the OnFinality Bittensor network page to check the available connection details.
Prepare an RPC connection
Install Node.js 18 or later and obtain an HTTP(S) Bittensor RPC URL from your chosen provider. Follow its instructions for any required authentication; do not commit credentials or a credential-bearing URL to source control.
Set BITTENSOR_RPC_URL in your shell, replacing the placeholder with your actual URL:
export BITTENSOR_RPC_URL='YOUR_HTTP_RPC_URL'The endpoint must accept the JSON-RPC methods used below. Check your provider’s documentation if a method is unavailable.
Fetch the finalized hash and header
Save this script as finalized-block.js and run it with node finalized-block.js. It uses the built-in Node.js fetch API, applies a timeout to each request, and exits with a nonzero status if either call fails.
const url = process.env.BITTENSOR_RPC_URL;
if (!url) {
console.error('Set BITTENSOR_RPC_URL to your HTTP(S) RPC URL.');
process.exit(1);
}
async function rpc(method, params = []) {
const response = await fetch(url, {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({ jsonrpc: '2.0', id: 1, method, params }),
signal: AbortSignal.timeout(10000)
});
if (!response.ok) {
throw new Error(`${method}: HTTP ${response.status}`);
}
let body;
try {
body = await response.json();
} catch {
throw new Error(`${method}: response was not valid JSON`);
}
if (body.error) {
throw new Error(`${method}: RPC error ${body.error.code}: ${body.error.message}`);
}
if (body.result == null) {
throw new Error(`${method}: missing result`);
}
return body.result;
}
async function main() {
const hash = await rpc('chain_getFinalizedHead');
if (typeof hash !== 'string' || !/^0x[0-9a-fA-F]{64}$/.test(hash)) {
throw new Error('Invalid finalized block hash');
}
const header = await rpc('chain_getHeader', [hash]);
if (typeof header.number !== 'string' || !/^0x[0-9a-fA-F]+$/.test(header.number)) {
throw new Error('Header has no valid hexadecimal block number');
}
console.log(JSON.stringify({
finalizedHash: hash,
finalizedHeight: BigInt(header.number).toString()
}, null, 2));
}
main().catch((error) => {
console.error('Failed to read finalized block:', error.message);
process.exitCode = 1;
});On success, expect a JSON object containing finalizedHash, a hexadecimal block hash, and finalizedHeight, the corresponding decimal height as a string. The values depend on the chain state at request time.
If the script reports an HTTP error, check the URL and authentication. For an RPC error, check that the endpoint supports the requested method. A timeout or network error warrants checking connectivity and retrying; avoid logging credential-bearing URLs while diagnosing the issue.
Decide when you need an index
These calls retrieve a point-in-time finalized hash and its header directly from RPC. They do not build a searchable history or provide application-specific queries across blocks.
For historical filtering or aggregations, an indexing workflow can process chain data into a queryable store. Check the indexer’s Bittensor compatibility and the RPC provider’s historical-data availability before designing that workflow.
For help exploring connection options, continue with the OnFinality RPC Assistant.