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

Interact with the blockchain using the API

Hoani Bryson edited this page Apr 24, 2020 · 9 revisions

Setup

Install Node.js (>=10.16.3) and Yarn (>= 1.19.0).

Clone the api template project and configure it

git clone https://github.com/plugblockchain/api-template.git
cd api-template
yarn install

Run your built node (see previous step if you haven't built a node yet)

../../target/debug/awesome-node --chain=dev --base-path=/tmp/awesome-test --validator --alice

Run the default script:

node index.js 

Should see output similar to:

Connecting to ws://localhost:9944
...
You are connected to chain Development using Awesome Node v2.0.0-alpha.5

Breaking down index.js

The API uses web sockets as a transport layer and relies heavily on javascript promises in order to handle asynchronous calls to the blockchain.

In the example script, we use the Promise interface to await and handle async functions.

// then() and catch() handle the outcomes of an async function 
run("ws://localhost:9944")
  .then(...)
  .catch(...);

The API itself is provided by a call to the blockchain. The types specify Pl^g specific types which are additional to the @polkadot/api library. In your application, you may develop new types for your runtime modules which will need to be included here.

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

The API is used to fetch a bunch of data using promises. In the case of Promise.all the values are not returned until all contained promises are resolved:

// Retrieve the chain & node information information via rpc calls
const [chain, nodeName, nodeVersion] = await Promise.all([
  api.rpc.system.chain(),
  api.rpc.system.name(),
  api.rpc.system.version(),
]);

Sending a transaction to the blockchain

Getting data from the blockchain

  • Use a query
  • Use an RPC call

PL^G


Getting Started


PL^G Component Guides


Advanced Topics


External Links

Clone this wiki locally