Polkadot.js API for blockchain development (Part 2)

Reading Time: 3 minutes

Hello Readers!! In the previous blog, we read about what is Polkadot.js and how to install it, So now we will see how we can use it by creating its instance. So Lets start!

We have the API installed. We have an understanding of what will actually exposed. And how the API knows what to expose. So let’s create an actual API instance,

// Import
import { ApiPromise, WsProvider } from '@polkadot/api';

...
// Construct
const wsProvider = new WsProvider('wss://rpc.polkadot.io');
const api = await ApiPromise.create({ provider: wsProvider });

// Do something
console.log(api.genesisHash.toHex());
Polkadot and substrate

Providers

Focusing on the construction, any API requires a provider and we create one via the const wsProvider = new WsProvider(...). By default, if none is provided to the API it will construct a default WsProvider instance to connect to ws://127.0.0.1:9944.

We generally recommend always specifying the endpoint since in most cases we want to connect to an external node and even for local nodes, it is always better being explicit, less magic that can make you wonder in the future.

The WebSocket version is the only provider type that is fully supported by the API. Polkadot/Substrate really comes alive with possibilities once you have access to bi-directional RPCs such as what WebSockets provide.

API Instance

The API creation is done via the ApiPromise.create interface which is a shortcut version for calling new and then waiting until the API is connected. Without the async syntax, this would be,

ApiPromise
  .create({ provider: wsProvider }).isReady
  .then((api) =>
    console.log(api.genesisHash.toHex())
  );

In most cases we would suggest using the .create shortcut, which really just takes care of the following boilerplate that otherwise needs to be provided –

// Create the instance
const api = new ApiPromise({ provider: wsProvider });

// Wait until we are ready and connected
await api.isReady;

// Do something
console.log(api.genesisHash.toHex());

Failures

In all cases the API will handle reconnecting automatically. This means that when you connect and the endpoint is not (yet) ready, the promise will not resolve immediately, but rather when connected. The same applies to , The API will manage re-connections when connection is lost.

In cases where the API does not support the chain being connected to, such as it using an unknown metadata version. The ready promise will fail to resolve and instead reject.

Runtime constants

Constant queries will introduce you to the concepts behind the types and the interaction of the API with those types. The same concepts are implemented in the remainder of the API – the runtime constants is just the simplest starting point.

For some background: constants are values that are defined in the runtime and used as part of chain operations. These constants can be changed as part of an upgrade.

// Initialize the API as per previous sections
...

// The length of an epoch (session) in Babe
console.log(api.consts.babe.epochDuration.toNumber());

// The amount required to create a new account
console.log(api.consts.balances.existentialDeposit.toNumber());

// The amount required per byte on an extrinsic
console.log(api.consts.transactionPayment.transactionByteFee.toNumber());

Since these are constants and defined by the metadata, it is not a call, but rather the values immediately available – as you’ll see in subsequent sections, there is no need for await on these, it immediately returns the type and value for you to work with.

Thank You For Reading this blog, stay connected for more content on polkadot.js APIs.

If you want to read more content like this?  Subscribe to Rust Times Newsletter and receive insights and latest updates, bi-weekly, straight into your inbox. Subscribe to Rust Times Newsletter: https://bit.ly/2Vdlld7.


Knoldus-blog-footer-image

Written by 

Ayushi is a Software Developer having more than 1.5 year of experience in RUST. Her practice area is Rust and Go. She loves to solve daily coding challenges.

Discover more from Knoldus Blogs

Subscribe now to keep reading and get access to the full archive.

Continue reading