docs: add examples from polkadot

This commit is contained in:
ian.he
2019-04-12 17:40:12 +12:00
parent f103863fdd
commit c14a071b74
59 changed files with 462 additions and 74 deletions
@@ -0,0 +1,5 @@
# Simple Connect
The following example shows how to instantiate a Polkadot API object and use it to connect to a node using ApiPromise.
<<< @/docs/examples/promise/01_simple_connect/index.js
+22
View File
@@ -0,0 +1,22 @@
// @ts-check
// Required imports
const { ApiPromise, WsProvider } = require('@polkadot/api');
async function main () {
// Initialise the provider to connect to the local node
const provider = new WsProvider('ws://127.0.0.1:9944');
// Create the API and wait until ready
const api = await ApiPromise.create(provider);
// 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()
]);
console.log(`You are connected to chain ${chain} using ${nodeName} v${nodeVersion}`);
}
main().catch(console.error).finally(() => process.exit());
@@ -11,7 +11,7 @@
},
"dependencies": {
"@polkadot/api": "^0.45.14"
"@polkadot/api": "^0.53.1"
},
"devDependencies": {
"rimraf": "^2.6.2"
@@ -0,0 +1,8 @@
# 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
<<< @/docs/examples/promise/02_listen_to_blocks/index.js
+19
View File
@@ -0,0 +1,19 @@
// @ts-check
// Import the API
const { ApiPromise } = require('@polkadot/api');
async function main () {
// Here we don't pass the (optional) provider, connecting directly to the default
// node/port, i.e. `ws://127.0.0.1:9944`. Await for the isReady promise to ensure
// the API has connected to the node and completed the initialisation process
const api = await ApiPromise.create();
// 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.subscribeNewHead((header) => {
console.log(`Chain is at block: #${header.blockNumber}`);
});
}
main().catch(console.error);
@@ -0,0 +1,18 @@
{
"name": "02_listen_to_blocks",
"version": "0.2.0",
"description": "Example showing how to use subscriptions",
"main": "index.js",
"author": "chevdor",
"license": "MIT",
"scripts": {
"clean": "rimraf node_modules",
"start": "node index.js"
},
"dependencies": {
"@polkadot/api": "^0.45.14"
},
"devDependencies": {
"rimraf": "^2.6.2"
}
}
@@ -0,0 +1,5 @@
# Listen to balance changes
This example shows how to instantiate a Polkadot API object and use it to connect to a node and retrieve balance updates.
<<< @/docs/examples/promise/03_listen_to_balance_change/index.js
@@ -3,7 +3,7 @@
const { ApiPromise } = require('@polkadot/api');
// Known account we want to use (available on dev chain, with funds)
const Alice = '5GoKvZWG5ZPYL1WUovuHW3zJBWBP5eT8CbqjdRY4Q6iMaDtZ';
const Alice = '5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY';
async function main () {
// Create an await for the API
@@ -10,7 +10,7 @@
"start": "node index.js"
},
"dependencies": {
"@polkadot/api": "^0.45.14"
"@polkadot/api": "^0.53.1"
},
"devDependencies": {
"rimraf": "^2.6.2"
@@ -0,0 +1,7 @@
# Unsubscribe from listening to updates
This example shows how to subscribe to and later unsubscribe from listening to block updates.
In this example we're calling the built-in unsubscribe() function after a timeOut of 20s to cleanup and unsubscribe from listening to updates.
<<< @/docs/examples/promise/04_unsubscribe/index.js
@@ -0,0 +1,23 @@
// @ts-check
// Import the API
const { ApiPromise } = require('@polkadot/api');
async function main () {
// Create a new instance of the api
const api = await ApiPromise.create();
// Subscribe to chain updates and log the current block number on update.
const unsubscribe = await api.rpc.chain.subscribeNewHead((header) => {
console.log(`Chain is at block: #${header.blockNumber}`);
});
// In this example we're calling the unsubscribe() function that is being
// returned by the api call function after 20s.
setTimeout(() => {
unsubscribe();
console.log('Unsubscribed')
}, 20000);
}
main().catch(console.error);
@@ -0,0 +1,18 @@
{
"name": "04_unsubscribe",
"version": "0.2.0",
"description": "Example showing how to unsubscribe from a subscription",
"main": "index.js",
"author": "Stefie",
"license": "MIT",
"scripts": {
"clean": "rimraf node_modules",
"start": "node index.js"
},
"dependencies": {
"@polkadot/api": "^0.45.14"
},
"devDependencies": {
"rimraf": "^2.6.2"
}
}
@@ -0,0 +1,5 @@
# Read storage
Many important variables are available through the storage API. This example shows how to call a few of those APIs.
<<< @/docs/examples/promise/05_read_storage/index.js
@@ -3,7 +3,7 @@
const { ApiPromise } = require('@polkadot/api');
// Our address for Alice on the dev chain
const Alice = '5GoKvZWG5ZPYL1WUovuHW3zJBWBP5eT8CbqjdRY4Q6iMaDtZ';
const Alice = '5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY';
async function main () {
// Create our API with a default connection to the local node
@@ -10,7 +10,7 @@
"start": "node index.js"
},
"dependencies": {
"@polkadot/api": "^0.45.14"
"@polkadot/api": "^0.53.1"
},
"devDependencies": {
"rimraf": "^2.6.2"
@@ -0,0 +1,5 @@
# Make a simple transfer
This sample shows how to create a transaction to make a transfer from one an account to another.
<<< @/docs/examples/promise/06_make_transfer/index.js
@@ -2,25 +2,21 @@
// Import the API, Keyring and some utility functions
const { ApiPromise } = require('@polkadot/api');
const { Keyring } = require('@polkadot/keyring');
const { stringToU8a } = require('@polkadot/util');
// Important to note that we pad the seed to a length of 32 bytes using ' '
// The underlying seed needs to be exactly 32 bytes in length
const ALICE_SEED = 'Alice'.padEnd(32, ' ');
const BOB_ADDR = '5Gw3s7q4QLkSWwknsiPtjujPv3XM4Trxi5d4PgKMMk3gfGTE';
const BOB = '5FHneW46xGXgs5mUiveU4sbTyGBzmstUspZC92UhjJM694ty';
async function main () {
// Create an instance of the keyring
const keyring = new Keyring();
// Add Alice to our keyring (with the known seed for the account)
const alice = keyring.addFromSeed(stringToU8a(ALICE_SEED));
// Instantiate the API
const api = await ApiPromise.create();
// Constuct the keying after the API (crypto has an async init)
const keyring = new Keyring({ type: 'sr25519' });
// Add alice to our keyring with a hard-deived path (empty phrase, so uses dev)
const alice = keyring.addFromUri('//Alice');
// Create a extrinsic, transferring 12345 units to Bob
const transfer = api.tx.balances.transfer(BOB_ADDR, 12345);
const transfer = api.tx.balances.transfer(BOB, 12345);
// Sign and send the transaction using our account
const hash = await transfer.signAndSend(alice);
@@ -10,7 +10,7 @@
"start": "node index.js"
},
"dependencies": {
"@polkadot/api": "^0.45.14"
"@polkadot/api": "^0.53.1"
},
"devDependencies": {
"rimraf": "^2.6.2"
@@ -0,0 +1,5 @@
# Traverse events
Query the system events and extract information from them. This example runs until exited via Ctrl-C
<<< @/docs/examples/promise/08_system_events/index.js
+34
View File
@@ -0,0 +1,34 @@
// @ts-check
// Import the API
const { ApiPromise } = require('@polkadot/api');
async function main () {
// Create our API with a default connection to the local node
const api = await ApiPromise.create();
// subscribe to system events via storage
api.query.system.events((events) => {
console.log(`\nReceived ${events.length} events:`);
// loop through the Vec<EventRecord>
events.forEach((record) => {
// extract the phase, event and the event types
const { event, phase } = record;
const types = event.typeDef;
// show what we are busy with
console.log(`\t${event.section}:${event.method}:: (phase=${phase.toString()})`);
console.log(`\t\t${event.meta.documentation.toString()}`);
// loop through each of the parameters, displaying the type and data
event.data.forEach((data, index) => {
console.log(`\t\t\t${types[index].type}: ${data.toString()}`);
});
});
});
}
main().catch((error) => {
console.error(error);
process.exit(-1);
});
@@ -10,7 +10,7 @@
"start": "node index.js"
},
"dependencies": {
"@polkadot/api": "^0.45.14"
"@polkadot/api": "^0.53.1"
},
"devDependencies": {
"rimraf": "^2.6.2"
@@ -0,0 +1,5 @@
# Transfer events
Display the events that occur during a transfer by sending a value to a random account
<<< @/docs/examples/promise/09_transfer_events/index.js
@@ -9,18 +9,18 @@ const testKeyring = require('@polkadot/keyring/testing');
const { randomAsU8a } = require('@polkadot/util-crypto');
// some constants we are using in this sample
const ALICE = '5GoKvZWG5ZPYL1WUovuHW3zJBWBP5eT8CbqjdRY4Q6iMaDtZ';
const ALICE = '5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY';
const AMOUNT = 10000;
async function main () {
// create an instance of our testign keyring
// Create the API and wait until ready
const api = await ApiPromise.create();
// create an instance of our testing keyring
// If you're using ES6 module imports instead of require, just change this line to:
// const keyring = testKeyring();
const keyring = testKeyring.default();
// Create the API and wait until ready
const api = await ApiPromise.create();
// get the nonce for the admin key
const nonce = await api.query.system.accountNonce(ALICE);
@@ -36,11 +36,11 @@ async function main () {
api.tx.balances
.transfer(recipient, AMOUNT)
.sign(alicePair, { nonce })
.send(({ events = [], status, type }) => {
console.log('Transaction status:', type);
.send(({ events = [], status }) => {
console.log('Transaction status:', status.type);
if (type === 'Finalised') {
console.log('Completed at block hash', status.asFinalised.toHex());
if (status.isFinalized) {
console.log('Completed at block hash', status.asFinalized.toHex());
console.log('Events:');
events.forEach(({ phase, event: { data, method, section } }) => {
@@ -10,7 +10,7 @@
"start": "node index.js"
},
"dependencies": {
"@polkadot/api": "^0.45.14"
"@polkadot/api": "^0.53.1"
},
"devDependencies": {
"rimraf": "^2.6.2"
@@ -0,0 +1,5 @@
# Chain upgrade
Performs a chain upgrade using the `sudo` module. This may brick your chain, so us it as an educational sample. (use `substrate --dev purge-chain` to remove DB and recover).
<<< @/docs/examples/promise/10_upgrade_chain/index.js
@@ -32,13 +32,13 @@ async function main () {
// preform the actual chain upgrade via the sudo module
api.tx.sudo
.sudo(proposal)
.signAndSend(adminPair, ({ events = [], status, type }) => {
console.log('Proposal status:', type);
.signAndSend(adminPair, ({ events = [], status }) => {
console.log('Proposal status:', status.type);
if (type === 'Finalised') {
if (status.isFinalized) {
console.error('You have just upgraded your chain');
console.log('Completed at block hash', status.asFinalised.toHex());
console.log('Completed at block hash', status.asFinalized.toHex());
console.log('Events:');
events.forEach(({ phase, event: { data, method, section } }) => {
@@ -10,7 +10,7 @@
"start": "node index.js"
},
"dependencies": {
"@polkadot/api": "^0.45.14"
"@polkadot/api": "^0.53.1"
},
"devDependencies": {
"rimraf": "^2.6.2"
Binary file not shown.
+26
View File
@@ -0,0 +1,26 @@
# ApiPromise Examples
Here you will find a list of examples that takes you through the basics of connecting to a local 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. It is usually convenient testing with:
```
substrate --dev
```
## Running the examples
From each folder, run `yarn` to install the required dependencies and then run `yarn start` to execute the example against the running node.
## Development accounts
Some of the examples use the following accounts:
- Alice: `5GoKvZWG5ZPYL1WUovuHW3zJBWBP5eT8CbqjdRY4Q6iMaDtZ`
- Bob: `5Gw3s7q4QLkSWwknsiPtjujPv3XM4Trxi5d4PgKMMk3gfGTE`
Those accounts are easy to add if you don't have/see them. The seed of Alice's account is `Alice␣␣␣␣␣␣␣␣␣␣␣␣␣␣␣␣␣␣␣␣␣␣␣␣␣␣␣` and the seed of Bob is... well you guess...
NOTE: Note the spaces padding Alice's key up to 32 chars.