Skip to content
This repository has been archived by the owner on Jul 4, 2022. It is now read-only.

Javascript API Reference

Roy Sirui Yang edited this page Apr 28, 2020 · 14 revisions

Introduction to JS API

As you develop new features for your own blockchain, you will want to add additional functions and interfaces that allow new interaction to your chain. This can be done by:

  1. Creating and defining your own JS API packages, then
  2. Import your packages into your JS script and use them to interacts with your blockchain.

Creating a new JS API package

Your JS API library can be injected into an API session from @polkadot/api in order to connect and transact with a Plug chain.

As an example, the "Plug types" contains additional data types required to use Doughnut. The codebase can be found here:Plug API types

The package is defined in package.json:

{
  "name": "@plugnet/plug-api-types",
  "version": "0.0.0",
  "description": "SDK type definitions for the Plug runtime",
  "main": "dist/index.js",
  ....
}

Importing and using your package

To add your API as a dependency, add it to the package.json in your JS script:

// package.json
{ 
  "dependencies": {
    "@plugnet/plug-api-types": "git+https://github.com/plugblockchain/plug-api-types.git#1.0.0-rc2"
  }
}

In your JS script, you can now initialize and use your API:

import {ApiPromise, WsProvider} from '@polkadot/api';
import PlugRuntimeTypes from '@plugnet/plug-api-types';

async function main() {
  const provider = new WsProvider('ws://example.com:9944');
  const api = await ApiPromise.create({ 
    provider,
    types: PlugRuntimeTypes,
  });

  //...

}

Now you can make calls to your API library using the api object.

const [chain, nodeName, nodeVersion] = await Promise.all([
    api.rpc.system.chain(),
    api.rpc.system.name(),
    api.rpc.system.version(),
  ]);

Example: Plug-Doughnut

Creating Doughnuts

You can create a signed and encoded doughnut:

const Doughnut = require('plug-doughnut').Doughnut;
const domain = 'awesome_node';

const doughnut = Doughnut
    .new(issuer, holder, expiry, not_before)
    .add_domain(domain, 0x00)
    .sign(issuer_secrect_key)
    .encode();

Attaching Doughnuts to Extrinsic calls

You can add the encoded doughnut to the extrinsic call. This example creates a normal balance transfer with the encoded doughnut added in the option parameter.

// Create the API and wait until ready
const provider = new WsProvider("ws://localhost:9944");
const types = PlugRuntimeTypes.default;
const api = await ApiPromise.create({ provider, types });

// Send transfer extrinsic with doughnut
const options = { doughnut: doughnut.encode() };
const txHash = await api.tx.balances
  .transfer(keyring.bob.address, "1_500_000_000")
  .signAndSend(keyring.alice, options);

Reference:

Using Doughnut with Plug

Polkadot API reference

PL^G


Getting Started


PL^G Component Guides


Advanced Topics


External Links

Clone this wiki locally