Skip to content
This repository has been 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);

Listen to balance changes

This example shows how to instantiate astar.js and use it to connect to a node and retrieve balance updates.

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

// Known account we want to use (available on dev chain, with funds)
const Alice = '5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY';

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

  // Retrieve the initial balance. Since the call has no callback, it is simply a promise
  // that resolves to the current on-chain value
  let { data: { free: previousFree }, nonce: previousNonce } = await api.query.system.account(Alice);

  console.log(`${Alice} has a balance of ${previousFree}, nonce ${previousNonce}`);
  console.log(`You may leave this example running and start example 06 or transfer any value to ${Alice}`);

  // Here we subscribe to any balance changes and update the on-screen value
  api.query.system.account(Alice, ({ data: { free: currentFree }, nonce: currentNonce }) => {
    // Calculate the delta
    const change = currentFree.sub(previousFree);

    // Only display positive value changes (Since we are pulling `previous` above already,
    // the initial balance change will also be zero)
    if (!change.isZero()) {
      console.log(`New balance change of ${change}, nonce ${currentNonce}`);

      previousFree = currentFree;
      previousNonce = currentNonce;
    }
  });
}

main().catch(console.error);
Clone this wiki locally