To query the chainspec of a blockchain from an RPC, you can use the following code:
import polkadot from 'polkadot-js';
const client = polkadot.createClient();
const chainspec = await client.rpc.chainSpec();
const name = chainspec.name;
const paraId = chainspec.paraId;
console.log(The chain name is ${name});
console.log(The para chain ID is ${paraId});
This code will first create a client object for the Polkadot network. Then, it will call the rpc.chainSpec() method to get the chainspec for the current chain. Finally, it will print the name and para chain ID of the chain to the console.
For example, if you are running this code on the Polkadot mainnet, the name of the chain will be "Polkadot" and the para chain ID will be 0.
Here is a breakdown of the code:
The import polkadot from 'polkadot-js'; line imports the Polkadot JavaScript library.
The const client = polkadot.createClient(); line creates a client object for the Polkadot network.
The const chainspec = await client.rpc.chainSpec(); line calls the rpc.chainSpec() method to get the chainspec for the current chain.
The const name = chainspec.name; line gets the name of the chain from the chainspec.
The const paraId = chainspec.paraId; line gets the para chain ID of the chain from the chainspec.
The console.log(The chain name is ${name}); line prints the name of the chain to the console.
The console.log(The para chain ID is ${paraId}); line prints the para chain ID of the chain to the console.