Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Round out ApiPromise examples #263

Merged
merged 5 commits into from
Oct 12, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 3 additions & 5 deletions docs/SUMMARY.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,6 @@
- [ApiPromise](examples/promise/README.md)
- [Simple connect](examples/promise/01_simple_connect/README.md)
- [Listen to blocks](examples/promise/02_listen_to_blocks/README.md)
- [Listen to balance change](examples/deprecated-rpc/03_listen_to_balance_change/README.md)
- [Generate Accounts](examples/deprecated-rpc/04_generate_account/README.md)
- [Read Storage](examples/deprecated-rpc/05_read_storage/README.md)
- [Craft Extrinsic](examples/deprecated-rpc/06_craft_extrinsic/README.md)
- [Transfer DOTs](examples/deprecated-rpc/07_transfer_dots/README.md)
- [Listen to balance change](examples/promise/03_listen_to_balance_change/README.md)
- [Read chain state](examples/promise/05_read_storage/README.md)
- [Make a transfer](examples/promise/07_transfer_dots/README.md)
10 changes: 7 additions & 3 deletions docs/examples/promise/01_simple_connect/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,14 @@ async function main () {
// create the API and wait until ready
const api = await ApiPromise.create(provider);

// retrieve the chain information (rpc call)
const chain = await api.rpc.system.chain();
// 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}`);
console.log(`You are connected to chain ${chain} using ${nodeName} v${nodeVersion}`);
}

main().catch(console.error).finally(() => process.exit());
6 changes: 3 additions & 3 deletions docs/examples/promise/01_simple_connect/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "01_simple_connect",
"version": "0.1.0",
"version": "0.2.0",
"description": "Example showing how to connect using a WebSocket",
"main": "index.js",
"author": "chevdor",
Expand All @@ -11,8 +11,8 @@
},

"dependencies": {
"@polkadot/api": "^0.31.15",
"@polkadot/rpc-provider": "^0.31.15"
"@polkadot/api": "^0.31.18",
"@polkadot/rpc-provider": "^0.31.18"
},
"devDependencies": {
"rimraf": "^2.6.2"
Expand Down
4 changes: 2 additions & 2 deletions docs/examples/promise/02_listen_to_blocks/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,13 @@ 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 new ApiPromise().isReady;
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 subsciptionId = await api.rpc.chain.newHead((header) => {
console.log(`best #${header.blockNumber.toString()}`);
console.log(`best #${header.blockNumber}`);
});

// id for the subscription, we can cleanup and unsubscribe via
Expand Down
4 changes: 2 additions & 2 deletions docs/examples/promise/02_listen_to_blocks/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "02_listen_to_blocks",
"version": "0.1.0",
"version": "0.2.0",
"description": "Example showing how to use subscriptions",
"main": "index.js",
"author": "chevdor",
Expand All @@ -10,7 +10,7 @@
"start": "node index.js"
},
"dependencies": {
"@polkadot/api": "^0.31.15"
"@polkadot/api": "^0.31.18"
},
"devDependencies": {
"rimraf": "^2.6.2"
Expand Down
5 changes: 5 additions & 0 deletions docs/examples/promise/03_listen_to_balance_change/README.md
Original file line number Diff line number Diff line change
@@ -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.

[include](index.js)
35 changes: 35 additions & 0 deletions docs/examples/promise/03_listen_to_balance_change/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
// import the Api
const { ApiPromise } = require('@polkadot/api');

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

async function main () {
// Create an wait for the API
const api = await ApiPromise.create();

// Retrieve the initial balance. Since the call has no callback, it is simply a promise
// the resolves to the current on-chain value
let previous = await api.st.balances.freeBalance(Alice);

console.log(`${Alice} has an ${previous} balance`);
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 updates the on-screen value
api.st.balances.freeBalance(Alice, (current) => {
// Calculate the delta
const change = current.sub(previous);

// Only display positive value changes (Since we are pulling previous above already,
// the intiial balance change will also be zero)
if (change.isZero()) {
return;
}

previous = current;

console.log(`Balance of ${Alice}: ${current}, ${change} change`);
});
}

main().catch(console.error);
18 changes: 18 additions & 0 deletions docs/examples/promise/03_listen_to_balance_change/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
{
"name": "03_listen_to_balance_change",
"version": "0.2.0",
"description": "Example showing how to subscribe to balance change",
"main": "index.js",
"author": "chevdor",
"license": "MIT",
"scripts": {
"clean": "rimraf node_modules",
"start": "node index.js"
},
"dependencies": {
"@polkadot/api": "^0.31.18"
},
"devDependencies": {
"rimraf": "^2.6.2"
}
}
5 changes: 5 additions & 0 deletions docs/examples/promise/05_read_storage/README.md
Original file line number Diff line number Diff line change
@@ -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.

[include](index.js)
34 changes: 34 additions & 0 deletions docs/examples/promise/05_read_storage/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
// Import the ApiPromise
const { ApiPromise } = require('@polkadot/api');

// Our address for Alice on the dev chain
const Alice = '5GoKvZWG5ZPYL1WUovuHW3zJBWBP5eT8CbqjdRY4Q6iMaDtZ';

async function main () {
// Create out API with a default connection to the local node
const api = await ApiPromise.create();

// Make our basic chain state/storage queries, all in one go
const [accountNonce, blockPeriod, validators] = await Promise.all([
api.st.system.accountNonce(Alice),
api.st.timestamp.blockPeriod(),
api.st.session.validators()
]);

console.log(`accountNonce(${Alice}) ${accountNonce}`);
console.log(`blockPeriod ${blockPeriod.toNumber()} seconds`);

// get the balances for all validators
const validatorBalances = await Promise.all(
validators.map((authorityId) =>
api.st.balances.freeBalance(authorityId)
)
);

console.log('validators', validators.map((authorityId, index) => ({
address: authorityId.toString(),
balance: validatorBalances[index].toString()
})));
}

main().catch(console.error).finally(_ => process.exit());
18 changes: 18 additions & 0 deletions docs/examples/promise/05_read_storage/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
{
"name": "04_read_storage",
"version": "0.2.0",
"description": "Example showing how to transfer DOTs",
"main": "index.js",
"author": "chevdor",
"license": "MIT",
"scripts": {
"clean": "rimraf node_modules",
"start": "node index.js"
},
"dependencies": {
"@polkadot/api": "^0.31.18"
},
"devDependencies": {
"rimraf": "2.6.2"
}
}
5 changes: 5 additions & 0 deletions docs/examples/promise/07_transfer_dots/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
# Tranfer DOTs

This sample shows how to create a transaction to make a transfer from one an account to another.

[include](index.js)
36 changes: 36 additions & 0 deletions docs/examples/promise/07_transfer_dots/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
// Import our API, Keyring and some utility functions
const { ApiPromise } = require('@polkadot/api');
const Keyring = require('@polkadot/util-keyring').default;
const u8aFromUtf8 = require('@polkadot/util/u8a/fromUtf8').default;

const ALICE_SEED = 'Alice'.padEnd(32, ' ');
const BOB_ADDR = '5Gw3s7q4QLkSWwknsiPtjujPv3XM4Trxi5d4PgKMMk3gfGTE';

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(u8aFromUtf8(ALICE_SEED));

// instantiate the API
const api = await ApiPromise.create();

// retrieve the nonce for Alice, used to sign the transaction
const aliceNonce = await api.st.system.accountNonce(alice.address());

// Create a extrinsic, transferring 12345 units to Bob. We can also create,
// sign and send in one operation (as per the samples in the Api documentation),
// here we split it out for the sake of readability
const transfer = api.tx.balances.transfer(BOB_ADDR, 12345);

// sign the transaction using our account
transfer.sign(alice, aliceNonce);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe sign should already take care of nonce? Not sure if it should go here, on in the combined api-observable.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It it does return a promise, yes. Currently it just returns the observable. We had this chat a couple of days ago, not sure which way is best - I would love it to be optional as well. For now, not yet...


// send the transaction and retrieve the resulting Hash
const hash = await transfer.send();

console.log(`transfer 12345 to Bob with hash ${hash}`);
}

main().catch(console.error).finally(_ => process.exit());
18 changes: 18 additions & 0 deletions docs/examples/promise/07_transfer_dots/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
{
"name": "07_transfer_dots",
"version": "0.2.0",
"description": "Example showing how to transfer DOTs",
"main": "index.js",
"author": "chevdor",
"license": "MIT",
"scripts": {
"clean": "rimraf node_modules",
"start": "node index.js"
},
"dependencies": {
"@polkadot/api": "^0.31.18"
},
"devDependencies": {
"rimraf": "2.6.2"
}
}