Skip to content
This repository was archived by the owner on Oct 30, 2024. It is now read-only.

Examples

Nikhil Ranjan edited this page Sep 22, 2022 · 9 revisions

Here you will find a list of examples that takes you through the basics of connecting to a node, retrieving data from the Node and chain and execute transactions on the chain. It uses the ApiPromise interface.

Prerequisites

For the following examples, you need a local node. Compile astar-collator at https://github.com/AstarNetwork/astar. It is usually convenient testing with local dev node:

target/release/astar-collator --dev

Development accounts

Some of the examples use the following accounts:

  • Alice
  • Bob

Those accounts are easy to add if you don't have/see them. The seed of Alice's account is //Alice (via keyring.addUri(...), dev seed implied) and the seed of Bob is... well you guess...

Listen to new blocks

This example shows how to subscribe to new blocks.

It displays the block number every time a new block is seen by the node you are connected to.

NOTE: The example runs until you stop it with CTRL+C

// Import the API
import { ApiPromise } from '@polkadot/api';
import { WsProvider } from '@polkadot/rpc-provider';
import { options } from '@astar-network/astar-api';

async function main () {
  const provider = new WsProvider('ws://localhost:9944');
  const api = new ApiPromise(options({ provider }));
  await api.isReady;

  // We only display a couple, then unsubscribe
  let count = 0;

  // Subscribe to the new headers on-chain. The callback is fired when new headers
  // are found, the call itself returns a promise with a subscription that can be
  // used to unsubscribe from the newHead subscription
  const unsubscribe = await api.rpc.chain.subscribeNewHeads((header) => {
    console.log(`Chain is at block: #${header.number}`);

    if (++count === 256) {
      unsubscribe();
      process.exit(0);
    }
  });
}

main().catch(console.error);

Clone this wiki locally