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

Interact with the blockchain using the API

Jordan edited this page Sep 23, 2020 · 9 revisions

Installation and Setup

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

Clone the api template project and configure it

git clone -b 1.0.0-rc4.2 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). This time, we will add the arguments --unsafe-ws-external --ws-port=9944 --rpc-cors=all which ensures that we can access the full API. This is not recommended for validator nodes on a full distributed blockchain; but it is fine for testing.

../../target/debug/awesome-node --chain=dev --base-path=/tmp/awesome-test --validator --alice --unsafe-ws-external --ws-port=9944 --rpc-cors=all

If you want to know more about these parameters use:

../../target/debug/awesome-node --help

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

A brief tour of 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(),
]);

Using the API

Sending a transaction to the blockchain

Add the following to the end of the run() function:

// Get the testing pairs
const keyring = testingPairs.default({ type: 'sr25519'});

console.log(`Alice is transferring 1_500_000_000 to Bob`);

// Sign and send a transfer from Alice to Bob
const txHash = await api.tx.balances
  .transfer(keyring.bob.address, 1_500_000_000)
  .signAndSend(keyring.alice);

// Show the hash
console.log(`Transaction submitted with hash ${txHash}`);

If you run it, you will see the following on the console:

Transaction submitted with hash <Some Hash>

That means that a transaction has been submitted to the blockchain and state data will be updated when it is processed.

We are using the keyring.alice and keyring.bob test accounts which are immediately available on a develop blockchain.

Next, we want to confirm the transfer actually happens, so we will check the account balances before and after the transfer.

Getting data from the blockchain

Put the following code directly after the definition of const keyring:

let [alice_balance, bob_balance] = await Promise.all([
  api.query.balances.account(keyring.alice.address),
  api.query.balances.account(keyring.bob.address),
]);

console.log(`Alice's balance (before): ${alice_balance.free}`);
console.log(`Bob's   balance (before): ${bob_balance.free}`);

Put the following code at the end of the run() function:

[alice_balance, bob_balance] = await Promise.all([
  api.query.balances.account(keyring.alice.address),
  api.query.balances.account(keyring.bob.address),
]);

console.log(`Alice's balance (after):  ${alice_balance.free}`);
console.log(`Bob's   balance (after):  ${bob_balance.free}`);

If we run this code (node index.js), we should see something similar to:

...
Alice's balance (before): 1152921504606846976
Bob's   balance (before): 1152921504606846976
Transaction submitted with hash <Some Hash>
Alice's balance (after):  1152921503007886676
Bob's   balance (after):  1152921506106846976

Alice and Bob are very rich, so even a transfer of 1.5 trillion doesn't affect their accounts much.

For more information on using the API: