Compare commits

..
24 Commits
Author SHA1 Message Date
Travis CI 957f3f404c [CI Skip] 0.92.1 2019-09-12 13:42:03 +00:00
Jaco Greeff d1105c899f 0.92 (#1390)
* Metadata for current Substrate master

* 0.92 doc updates

* @polkadot/util 1.4.1

* Update static polkadot metadata

* Version bump
2019-09-12 15:29:48 +02:00
Travis CI df97bc2bf8 [CI Skip] 0.92.0-beta.9 2019-09-12 10:26:07 +00:00
Jaco Greeff ebe77c25c7 FAQ for offline signing (#1388)
* FAQ for offline signing

* Shorten questions
2019-09-12 12:13:45 +02:00
Travis CI eed83fa5d9 [CI Skip] 0.92.0-beta.8 2019-09-12 09:34:51 +00:00
Jaco Greeff b62b1b248d Add specVersion to mini extraction (#1387) 2019-09-12 11:21:41 +02:00
Jaco Greeff 3b30f1fd43 Start FAQ (#1386)
* Start FAQ

* Update FAQ.md
2019-09-12 11:21:14 +02:00
Travis CI f28fff78b6 [CI Skip] 0.92.0-beta.7 2019-09-12 08:17:23 +00:00
Jaco Greeff 8b80ce7132 Expose keyring via @polkadot/api (#1385)
* Expose keyring via @polkadot/api

* typo, not -> now
2019-09-12 10:03:25 +02:00
Travis CI 8accd2945e [CI Skip] 0.92.0-beta.6 2019-09-11 16:03:32 +00:00
Jaco Greeff f8ec93adea Merge branch 'master' of github.com:polkadot-js/api 2019-09-11 17:51:30 +02:00
Jaco Greeff f4fc3589cc Docs sidebar depth 2019-09-11 17:51:26 +02:00
Travis CI 4e52a2ec02 [CI Skip] 0.92.0-beta.5 2019-09-11 15:44:52 +00:00
Jaco GreeffandThibaut Sardan 55fb391465 Things I wish I knew... (#1374)
* Make a start

* Intro

* Installation

* Flatten

* Move METHODS_*.md to substrate/*.md

* Basics

* Apply suggestions from code review

Co-Authored-By: Thibaut Sardan <33178835+Tbaut@users.noreply.github.com>

* Substrate links

* Create

* api.consts

* Typo

* Typo, ms -> md

* types.basics (SIP)

* Type basics

* api.consts jumps to api.query

* Start to api.query

* Basic queries

* Point starting to actual overview

* api.rpc

* Derive detour

* Query subs & query multi

* Apply suggestions from code review

Co-Authored-By: Thibaut Sardan <33178835+Tbaut@users.noreply.github.com>

* typo

* Query extras

* Basic transactions

* Misplaced ,

* keyring WIP

* Keyring wrap-up

* Subs SIP

* tx subs more WIP

* tx subs

* Small types cleanups

* Apply suggested changes from @JoshOrndorff

* Clarify naked await

* tx wrapping WIP

* Wrap api.wrap

* TS placeholder

* [WIP] markers for not-started

* Clarifying comments

* Additional clarifications

* types.extend... well, extended...

* Remove *nix

* Warp up TypeScript... it is it (for now)

* Some small text clarifications

* Some cleanups

* Cleanups, typos

* keyring cleanups

* Cleanups

* Wrap

* api.wrap wrapped... hopefully

* typos

* Registration typos

* typescript typos, hope I caught most...
2019-09-11 17:32:34 +02:00
Travis CI 3e417f4f94 [CI Skip] 0.92.0-beta.4 2019-09-11 11:02:56 +00:00
Jaco Greeff 158410011e Bump deps (#1384) 2019-09-11 12:51:00 +02:00
Travis CI 7383b1e1d7 [CI Skip] 0.92.0-beta.3 2019-09-10 18:37:45 +00:00
Jaco Greeff ad9d21cae2 Remove outdated blockNumber refs. in API docs (#1382)
* Remove outdated blockNumber refs

* ExtendedHeader

* Update subscribeNewHeads.ts
2019-09-10 20:23:37 +02:00
Travis CI 777007438c [CI Skip] 0.92.0-beta.2 2019-09-10 17:54:33 +00:00
Jaco Greeff a1a52fbdb6 Bump common (#1380) 2019-09-10 19:42:24 +02:00
Travis CI f9f5573abe [CI Skip] 0.92.0-beta.1 2019-09-10 16:07:03 +00:00
Jaco Greeff bdd0cb9d9a Remove ExtError from use (removed from util) 2019-09-10 17:55:02 +02:00
Travis CI 0096d17f2f [CI Skip] 0.92.0-beta.0 2019-09-09 15:43:23 +00:00
Jaco Greeff 3e3d03693a Set the ss58Format based on chain properties (#1378)
* Set the ss58Format based on chain properties

* Mock returns system_properties
2019-09-09 17:31:16 +02:00
61 changed files with 1829 additions and 625 deletions
+8
View File
@@ -1,3 +1,11 @@
# 0.92.1
- The API now correctly sets the ss58 prefix as retrieved from the chain properties via `ss58Format`
- Bump to `@polkadot/util` 1.4.1, removing use of `ExtError`
- The `Keyring` from `@polkadot/keyring` is now exposed on the API as well. You can do `import { Keyring } from '@polkadot/api'` - this alleviates the need for extra dependencies (apart from `@polkadot/api`), and since the keyring is critical for signing operations, aligns everything in one bundle
- Support the latest Polkadot & Substrate master branches (incl. metadata updates)
- Getting started documentation has been made available
# 0.91.1
- This release was focussed on stability, with a number of cleanups and bug-fixes
+32 -7
View File
@@ -22,11 +22,36 @@ module.exports = {
],
search: false,
sidebar: [
{
title: 'Getting started',
path: '/start/',
collapsable: false,
sidebarDepth: 0,
children: [
['start/install.md', 'Installation'],
['start/basics.md', 'Basics & Metadata'],
['start/create.md', 'Creating an instance'],
['start/api.consts.md', 'Runtime Constants'],
['start/api.query.md', 'State queries'],
['start/api.rpc.md', 'RPC calls'],
['start/api.query.subs.md', 'Query subscriptions'],
['start/api.query.multi.md', 'Multi queries'],
['start/api.query.other.md', 'Query extras'],
['start/api.tx.md', 'Transactions'],
['start/keyring.md', 'Keyring'],
['start/api.tx.subs.md', 'Transaction subscriptions'],
['start/api.tx.wrap.md', 'Complex transactions'],
['start/types.basics.md', 'Type basics'],
['start/types.extend.md', 'Extending types'],
['start/typescript.md', 'TypeScript interfaces'],
['start/FAQ.md', 'FAQ']
]
},
{
title: 'Examples (Promise API)',
path: '/examples/promise/',
collapsable: false,
sidebarDepth: 1,
sidebarDepth: 0,
children: [
['examples/promise/01_simple_connect/', 'Simple connect'],
['examples/promise/02_listen_to_blocks/', 'Listen to blocks'],
@@ -40,15 +65,15 @@ module.exports = {
]
},
{
title: 'Substrate interfaces',
title: 'Substrate defaults',
collapsable: false,
sidebarDepth: 0,
children: [
['/METHODS_RPC.md', 'Substrate RPC'],
['/METHODS_CONSTANTS.md', 'Constants (defaults)'],
['/METHODS_STORAGE.md', 'State storage (defaults)'],
['/METHODS_EXTRINSICS.md', 'Extrinsics (defaults)'],
['/METHODS_EVENTS.md', 'System events (defaults)']
['substrate/rpc.md', 'Substrate RPC'],
['substrate/constants.md', 'Constants'],
['substrate/storage.md', 'State storage'],
['substrate/extrinsics.md', 'Extrinsics'],
['substrate/events.md', 'System events']
]
},
['/api/', '@polkadot/api'],
+2 -2
View File
@@ -20,8 +20,8 @@ footer: Apache-2 Licensed | Copyright © 2017-2019 polkadot-js authors and contr
The API provides application developers the ability to query a node and interact with the Polkadot or Substrate chains using Javascript. Here you will find documentation and examples to get you started.
::: tip Examples
In a rush and just want examples? [Jump right in](/examples/promise/) and get a handle on using the API in your projects.
::: tip Getting started & Examples
[Jump right in](/start/) and get an overview on using the API in your projects, from installation all the way through to making it do magic. Already understand how things work and just want the examples? [The ApiPromise examples](/examples/promise/) provide some basic recipies.
:::
## Available packages
+27 -5
View File
@@ -1,3 +1,23 @@
## Getting started
- [Introduction](start/README.md)
- [Installation](start/install.md)
- [Basics](start/basics.md)
- [Creating](start/create.md)
- [Constant queries](start/api.consts.md)
- [State queries](start/api.query.md)
- [RPC queries](start/api.rpc.md)
- [State subscriptions](start/api.query.subs.md)
- [Multi state retrieval](start/api.query.multi.md)
- [State query utilities](start/api.query.other.md)
- [Transactions](start/api.tx.md)
- [Keyring](start/keyring.md)
- [Transaction subscriptions](start/api.tx.subs.md)
- [Complex transactions](start/api.tx.wrap.md)
- [Type basics](start/types.basics.md)
- [Type extension](start/types.extend.md)
- [TypeScript interfaces](start/typescript.md)
## Packages
- [api](api/README.md)
@@ -10,13 +30,15 @@
## Interfaces
- [RPC](METHODS_RPC.md)
- [Constants (runtime)](METHODS_CONSTANTS.md)
- [Chain state (runtime)](METHODS_STORAGE.md)
- [Extrinsics (runtime)](METHODS_EXTRINSICS.md)
- [Events (runtime)](METHODS_EVENTS.md)
- [Substrate](substrate/README.md)
- [RPC](substrate/rpc.md)
- [Constants (runtime)](substrate/constants.md)
- [Chain state (runtime)](substrate/storage.md)
- [Extrinsics (runtime)](substrate/extrinsics.md)
- [Events (runtime)](substrate/events.md)
## Examples
- [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)
@@ -37,8 +37,7 @@ async function main () {
// Do the transfer and track the actual status
api.tx.balances
.transfer(recipient, AMOUNT)
.sign(alicePair, { nonce })
.send(({ events = [], status }) => {
.signAndSend(alicePair, { nonce }, ({ events = [], status }) => {
console.log('Transaction status:', status.type);
if (status.isFinalized) {
+5
View File
@@ -0,0 +1,5 @@
... somewhere also need a signer injection section, something along the lines of the singlesigner or this https://github.com/polkadot-js/tools/blob/master/packages/signer-cli/src/cmdSubmit.ts#L12
... DoubleMap & LinkedMap examples
... api.derive
+19
View File
@@ -0,0 +1,19 @@
# FAQ
The list will be updated/expanded as questions come up, dealing with some common issues that API users find.
## I am getting a "Unknown types found, no types for ..." error
There are 2 caused for this, both related to the version of the API that you are using and the support of types. As explained in the elsewhere, types on Polkadot/Substrate are continuously evolving - the latest version of the API always tries to support types for the latest Polkadot networks, such as [Kusama](https://kusama.network/). So for Polkadot public chains, ensure that you are using the latest released API version.
If however you are running against a master branch of either Polkadot or Substrate, you may well be better suited running [a beta version, tracking master](install.md#betas). If you are connected to a customized chain, you would rather want to [register the types](types.extend.md) either on your own, or via packages that the chain vendor provides.
## I am getting a "Metadata:: failed on MagicNumber" error
Update your version of the API to the [latest version](install.md). Like types, the [metadata interfaces](basics.md) are continuously evolving. For instance with the Polkadot Alexander network, only metadata v3 is available. By the time Kusama launched, this has been bumped to v7. As these versions are added to the Polkadot/Substrate codebase, they are added to the API.
## I would like to sign transactions offline
The API itself is independent on where the signature comes from and how it is injected. Additionally it implements a signer interface, that can be used for external signing - an example of this is the [polkadot-js/apps](https://github.com/polkadot-js/apps) support for signing via extensions and even the [polkadot-js/extension](https://github.com/polkadot-js/extension) support for tools such as the [Parity Signer](https://github.com/paritytech/parity-signer).
As of this writing we don't have an explicit example of implementing the signer interface in these docs, although we do use one in [our tests](https://github.com/polkadot-js/api/blob/master/packages/api/test/util/SingleAccountSigner.ts). Additionally, the [polkadot-js/tools](https://github.com/polkadot-js/tools) has an implementation of [a very basic offline signer](https://github.com/polkadot-js/tools/tree/master/packages/signer-cli) where transactions are generated in one process and signatures in another non-connected process.
+15
View File
@@ -0,0 +1,15 @@
# Getting started
These sections should provide you with all the information needed to install the `@polkadot/api` package, understand the structure of the interfaces and allow you to start using it. For existing users this really should be titled "Things I wish I knew before I started using the api" - it really aims to close the gap to allow anybody to get to grips with using the packages.
## What this is not
This is not line-by-line documentation of all the extising function calls available, nor it is tied to a specific chain. (Although the examples do refer to the base Polkadot & Substrate chains). There will be some things in the API that are probably not covered, which brings us to the next point...
## Help us help others
If you spot gaps in the information provided, or are uncertain about any specific area, please do [log an issue](https://github.com/polkadot-js/api/issues) or if you are that way inclined, make a pull-request. We really want to have good documentation in these areas and allow people to be productive right from the start.
## Ready? Steady? Go!
If you already have a good grasp on the API and are just looking for a specific answer, you may want to take a look at the [Frequently Asked Questions](FAQ.md). With all that said, let's get started... [What should be installed, and how should we do it?](install.md)
+34
View File
@@ -0,0 +1,34 @@
# Runtime Constants
Constant queries will introduce you to the concepts behind the types and the interaction of the API with those types. The same concepts are implemented in the remainder of the API - the runtime constants is just the simplest starting point.
For some background: constants are values that are defined in the runtime and used as part of chain operations. These constants can be changed as part of an upgrade.
```js
// initialize the API as per previous sections
...
// the length of an epoch (session) in Babe
console.log(api.consts.babe.epochDuration.toNumber());
// the amount required to create a new account
console.log(api.consts.balances.creationFee.toNumber());
// the amount required per byte on an extrinsic
console.log(api.consts.balances.transactionByteFee.toNumber());
```
Since these are constants and defined by the metadata, it is not a call, but rather the values immediately available - as you'll see in subsequent sections, there is no need for `await` on these, it immediately returns the type and value for you to work with.
## The API and types
There is some magic applied by the API. For instance as the `createFee` result is returned, the API knows the expected type and makes a `Balance` object available, hence the `toNumber`. This result mapping is consistent in retrieving constants, making queries or even sending transactions:
- when values are passed to the API, the API will convert whatever is provided into the correct type as required by the call
- when a value is retrieved, the API will provide an object of the correct type that wraps this value
From the last point, this means that a `Balance` will be returned as a number object extending [bn.js](https://github.com/indutny/bn.js/). In a later section we will go through a breakdown of all the commonly-used types and all [the basics available on types](types.basics.md).
## Making queries
In the next section we will take an initial dive into [chain state and state queries](api.query.md), allowing the use of the API to retrieve information contained in the chain state.
+48
View File
@@ -0,0 +1,48 @@
# State queries
In previous sections, we initialized the API and retrieved runtime constants. This section will walk through the concepts behind making queries to the chain to retrieve current state. The `api.query.<module>.<method>` interfaces, as already described earlier, is populated from the metadata. The API uses the metadata information provided to construct queries based on the location and parameters provided to generate state keys, and then queries these via RPC.
## Basic queries
Let's dive right in, connect to a general chain and retrieve some information on the current state. Of interest may be retrieving the nonce of a particular account as well as the current balance, this can be achieved via -
```js
// initialize the API as in previous sections
...
// the actual address that we will use
const ADDR = '5DTestUPts3kjeXSTMyerHihn1uwMfLj8vU8sqF7qYrFabHE';
// retrieve the last timestamp
const now = await api.query.timestamp.now();
// retrieve the account nonce via the system module
const nonce = await api.query.system.accountNonce(ADDR);
// retrieve the account balance via the balances module
const balance = await api.query.balance.freeBalance(ADDR);
console.log(`${now}: balance of ${balance} and a nonce of ${nonce}`);
```
There have been some additions in the code above comparing with retrieving runtime constants. In these cases, since we are making a query to the actual chain, we use the `await` syntax to retrieve the information. Since the API is Promise-based, this means we can also rewrite the above to follow a Promise pattern,
```js
...
// retrieve last block timestamp, account nonce & balance
const [now, nonce, balance] = await Promise.all([
api.query.timestamp.now(),
api.query.system.accountNonce(ADDR),
api.query.balance.freeBalance(ADDR)
]);
```
## Parameters & return values
As indicated in previous sections, any return value is always an object with a consistent interface that reflects the type being returned. In the above example, the timestamp is a `Moment` (a `u64` value), the nonce is an `Index` (a `u32` value) and the `Balance` is an underlying `u128`.
Additionally we have provided some parameters for the query calls, specifically for the retrieval of the nonce and balance. It is important to note that the API will automatically convert any parameters into the correct type for encoding and making calls, in this case the `AccountId` parameter could be specified as a ss58 address (as it was), an actual `AccountId` (retrieved via another call) or just a plain `Uint8Array` (or even hex-string representation) for a publicKey.
## Exploring RPCs
Where all query functions use the underlying RPCs, together with metadata, to construct and retrieve information, the direct node RPCs can be seen as raw calls that enable these (slightly) higher-level operations. Next up we will take a dive into [making RPC calls via the API](api.rpc.md).
+60
View File
@@ -0,0 +1,60 @@
# Multi queries
In a number of applications, it is useful to monitor a number of like-queries at the same time. For instance, we may want to track the balances for a list of accounts we have. The `api.query` interfaces allows this via the `.multi` subscription call.
## Multi queries, same type
Where possible, the use of multi queries are encouraged since it tracks a number of state entries over a single RPC call, instead of making a call for each single item. In addition it allows you to have a single callback to track changes. For queries of the same type we can use `.multi`, for example to retrieve the balances of a number of accounts at once -
```js
...
// subscribe to balance changes for 2 accounts, ADDR1 & ADDR2 (already defined)
const unsub = await api.query.balances.freeBalance.multi([ADDR1, ADDR2], (balances) => {
const [balance1, balance2] = balances;
console.log(`The balances are ${balance1} and ${balance2}`);
});
```
A couple of items to note in the example above: we don't call `freeBalance` directly, but rather `freeBalance.multi`. We pass the addresses we want to query as an array, and the length thereof would depend on the number of addresses we want to query. As an extended example, we can track the balances of a list of validators,
```js
...
// retrieve a snapshot of the validators
const validators = await api.query.session.validators();
// subscribe to the balances for these accounts
const unsub = await api.query.balances.freeBalance.multi(validators, (balances) => {
console.log(`The balances are: ${balances}`);
});
```
The above example does not subscribe to the validators explicitly, but only gets a snapshot and uses this into the future. It should be trivially extendable to subscribe to the validators, track which one have entered or left and then subscribe to balances as they change through the next blocks.
## Multi queries, distinct types
The previous `.multi` examples assumes that we do queries for the same types, i.e. we retrieve the balances for a number of accounts. However, there is also a need to retrieve various distinct types, as an example we would like to track the block timestamp in addition to the nonce and balance of a specific account. To cater for this, the api has a specific `api.queryMulti` interface that can be used to perform this query -
```js
...
// subscribe to the timestamp, our index and balance
const unsub = await api.queryMulti([
api.query.timestamp.now,
[api.query.system.accountNonce, ADDR],
[api.query.balances.freeBalance, ADDR]
], ([now, nonce, balance]) => {
console.log(`${now}: balance of ${balance} and a nonce of ${nonce}`);
});
```
The above example certainly does not quite look as ergonomic and clean, but the API needs to understand (a) which are all the calls we need to make and (b) the calls and their params (if required). So breaking it down -
- `api.query.timestamp.now` - the timestamp is passed naked without any params. Also note that we do not call it while passing, but rather only provides a reference to the function, i.e. we do not have the expected `()` at the end. (This could also be of the form `[api.query.timestamp.now]`, aligning with subsequent entries)
- `[api.query.system.accountNonce, ADDR]` - the nonce query is passed as an array containing the function (once again naked), followed by the parameters that apply.
## Rounding out queries
To round out our query introduction, there are a [number of other utilities and calls available](api.query.other.md) that allows the `api.query` user to perform certain tasks, such as querying state at a specific block. These are covered in the next section.
+76
View File
@@ -0,0 +1,76 @@
# Query extras
In previous sections we took a walk through queries, showing how to use one-shot queries, how to subscribe to results and how to combine multiple queries into one. This section will aim to extend that knowledge showing some other features and utilities that are available on the `api.query` interfaces.
## State at a specific block
Quite often is is useful (taking pruning into account, more on this later) to retrieve the state at a specific block. For instance we may wish to retrieve the current balance as well as the balance at a previous block for a specific account -
```js
...
// retrieve the current block header
const lastHdr = await api.rpc.chain.getHeader();
// retrieve the balance at both the current and the parent hashes
const [balanceNow, balancePrev] = await Promise.all([
api.query.balances.freeBalance.at(lastHdr.hash, ADDR),
api.query.balances.freeBalance.at(lastHdr.parentHash, ADDR)
]);
// display the difference
console.log(`The delta was ${balanceNow.sub(balancePrev)}`);
```
In the above example, we introduce the `.at(<hash>[, ...params])` query. For all `.at` queries, the first parameter is always the block hash at which we want to make the query, in our example we use both the last retrieved block and the parent thereof. The params are optional as per the type of query made, for instance to retrieve the timestamp for a previous block, it would be -
```js
...
// retrieve the timestampt for the previous block
const momentPrev = await api.query.timestamp.now.at(lastHdr.parentHash);
```
The `.at` queries are all single-shot, i.e. there are no subscription option to these, since the state for a previous block should be static. (This is true to a certain extent, i.e. when blocks have been finalized).
An additional point to take care of (briefly mentioned above), is state pruning. By default a Polkadot/Substrate node will only keep state for the last 256 blocks, unless it is explicitly run in archive mode. This means that querying state further back than the pruning period will result in an error returned from the Node. (Generaly most public RPC nodes only run with default settings, which includes agressive state pruning)
## State entries
In addition to using `api.query` to make actual on-chain queries, it can also be used to retrieve some information on the state entries. For instance to retrieve both the hash and size of an existing entry, we can make the following calls -
```js
...
// retrieve the hash & size of the entry as stored on-chain
const [entryHash, entrySize] = await Promise.all([
api.query.freeBalance.hash(ADDR),
api.query.freeBalance.size(ADDR)
]);
// output the info
console.log(`The current size is ${entrySize} bytes with a hash of ${entryHash}`);
```
As per the previous examples, the params here apply explicitly to the actual needed values to identify an entry. As with `.at` queries, there are no subscription versions for these queries, rather they are seen as one-shot values at a specific point in time.
## Entry metadata
It has been explained that the `api.query` interfaces are decorated from the metadata. This also means that there is some information that we can gather from the entry, as decorated -
```js
// extract the info
const { meta, method, section } = api.query.balances.freeBalance;
// display some info on a specific entry
console.log(`${section}.${method}: ${meta.documentation.join(' ')}`);
console.log(`query key: ${api.query.balances.freeBalance.key(ADDR)}`);
```
The `section` & `method` is an indication of where it is exposed on the API. In addition the `meta` holds an array with the metadata documentation for the entry.
The `key` endpoint requires some explanation. In the chain state, the key values (identified by the module, method & params) are hashed and this is used as a lookup. So underlying a single-shot query would utilize the `api.rpc.state.getStorage` entry, passing the output of `key` (which is a hashed representation of the values). Apart from the hashing, the API also takes care of type formatting, handling optional values and merging results accross multiple subscriptions.
## Let's transact already!
At this point you are already burning to actually make some transactions. Making queries is cool, but just how do [you actually submit transactions on-chain](api.tx.md).
+37
View File
@@ -0,0 +1,37 @@
# Query subscriptions
Previously we explained the concepts between `api.query`. In this section we will expand on that knowledge to introduce subscriptions (akin to what we found in `api.rpc`) to stream results from the state, as it changes between blocks.
## Subcriptions
As in the case with `api.rpc` subscriptions, query subscriptions follow exactly the same form - an actual call is augmented with a callback to return the current state value that is updated as the underlying value changes. As an example, we can extend on what we had previously -
```js
...
// retrieve the current timestamp via subscription
const unsub = await api.query.timestamp.now((moment) => {
console.log(`The last block has a timestamp of ${moment}`);
});
```
The form is exactly the same as the subscriptions we have seen previously, instead of the `await` returning the actual once-off value, it returns a subscription `unsub()` function that can be used to stop the subscription and clear up any underlying RPC connections. The supplied callback will contain the value as it changes, streamed from the node.
## Subscriptions with params
If we had a query with parameters, i.e. where we wish to perform a query for a specific account, the form is exactly the same - the last parameter contains the actual callback, after all other parameters. To retrieve the balances for an account as it changes, we could do the following -
```js
...
// subscribe to balance changes for our account
const unsub = await api.query.balances.freeBalance(ADDR, (balance) => {
console.log(`Your account balance is ${balance}`);
});
```
By now this subscription form should be familiar to you, including the usage of `unsub`.
## Multiple queries
In most non-trivial applications, it is useful to optimize both our code in terms of callbacks as well as node resources, for instance by [performing multiple queries at once, over the same RPC call](api.query.multi.md).
+70
View File
@@ -0,0 +1,70 @@
# RPC queries
The RPC calls provide the backbone for the transmission of data to and from the node. This means that all API endpoints such as `api.query`, `api.tx` or `api.derive` just wrap RPC calls, providing information in the encoded format as expected by the node.
Since you are already familiar with the `api.query` interface, the `api.rpc` interface follows the same format, for instance -
```js
...
// retrieve the chain name
const chain = await api.rpc.system.chain();
// retrieve the latest header
const lastHeader = await api.rpc.chain.getHeader();
// log the information
console.log(`${chain}: last block #${lastHeader.number} has hash ${lastHeader.hash}`);
```
In this example, you will see the same pattern as with queries: each result is a promise and a simple `await` makes the query and resolves with the result.
## Subscriptions
The RPCs lend themselves to using subscriptions, for instance in the above case you would assume that once connected, the chain won't change, however new blocks will come in at intervals and we probably want to keep track of those. We can adapt the previous example to start using subscriptions -
```js
...
// subscribe to the new headers
await api.rpc.chain.subscribeNewHeads((lastHeader) => {
console.log(`${chain}: last block #${lastHeader.number} has hash ${lastHeader.hash}`);
});
```
Since we are dealing with a subscription, we now pass a callback into the `subscribeNewHeads` function, and this will be triggered on each header, as they are imported. The same pattern would apply to each of the `api.rpc.subscribe*` functions - as a last parameter a callback is to be provided that streams the latest data, as it becomes available.
In general, whenever we create a subscription, we would like to cleanup after ourselves and unsubscribe, so assuming we only want to log the first 10 headers, the above example can be adjusted in the following manner -
```js
...
let count = 0;
// subscribe to the new headers
const unsubHeads = await api.rpc.chain.subscribeNewHeads((lastHeader) => {
console.log(`${chain}: last block #${lastHeader.number} has hash ${lastHeader.hash}`);
if (++count === 10) {
unsubHeads();
}
});
```
Unlike single-shot queries, for subscriptions we are `await`-ing a function, taking no parameters (that also returns nothing) that can be used to unsubscribe for the subscription and clear the underlying RPC connection. So in the above example we set `unsubHeads` and then call it when we wish to cancel the subscription.
## Detour into derives
The `api.derive` interfaces will be covered in a follow-up section, but since the above example deals with new head subscriptions, a quick detour is warranted. The derives are just helpers that define certain functions and combine results from multiple sources. For new headers, the following information is useful in certain scenarios -
```js
...
const unsub = await api.derive.chain.subscribeNewHeads((lastHeader) => {
console.log(`#${lastHeader.number} was authored by ${lastHeader.author}`);
});
```
In the above case the `subscribeNewHeads` derive augments the header retrieved with an `.author` getter. This is done by parsing the actual header and logs received and filling in the author from the `api.query.session.validators` call.
## Extended Queries
As a next step, now that we have understood subscription and RPC basics, we will circle back to the `api.query` interface, [extending our queries with subscriptions](api.query.subs.md).
+40
View File
@@ -0,0 +1,40 @@
# Transactions
Transaction endpoints are exposed, as determined by the metadata, on the `api.tx` endpoint. These allow you to submit transactions for inclusion in blocks, be it transfers, setting information or anything else your chain supports.
## Simple transactions
To start off, let's make a balance transfer from Alice to Bob.
```js
...
// sign and send a transfer from Alice to Bob
const txHash = await api.tx.balances
.transfer(BOB, 12345)
.signAndSend(alice);
// show the hash
console.log(`Submitted with hash ${txHash}`);
```
We have already become familiar with the `Promise` syntax that is used throughout the API, in this case it is no different. We construct a transaction by calling `balances.transfer(<accountId>, <value>)` with the required params and then as a next step we submit it to the node.
As with all other API operations, the `to` params just needs to be "account-like" and the value params needs to be "number-like", the API will take care of encoding and conversion into the correct format.
The result for this call (we will deal with subscriptions in a short while), is the transaction hash. This is a hash of the data and receiving this does not mean that transaction has been included, but rather only that it has been accepted for propagation by the node. (It can still fail on execution, we will handle this in some of our follow-up sections.)
## Under the hood
Despite the single-line format of `signAndSend`, there is a lot hapenning under the hood (and all of this can be manually provided) -
- Based on the sender, the API will retrieve the `system.accountNonce` to determine the next nonce to use
- The API will retrieve the current block hash and use it to create a mortal transaction, i.e. the transaction will only be valid for a limited number of blocks (by default this is 5 mins at 6s blocktimes)
- It will construct a payload and sign this, this includes the `genesisHash`, the `blockHash` for the start of the mortal era as well as the current chain `specVersion`
- The transaction is submitted to the node
As suggested, you can override all of this, i.e. by retrieving the nonce yourself and passing that as an option, i.e. `signAndSend(alice, { nonce: aliceNonce })`, this could be useful when manually tracking and submitting transactions in bulk.
## Into the keyring we go
With the examples above, the variable `alice` seems to have appeared from thin air. To understand how transactions are signed, we will take a [brief diversion into the keyring](keyring.md) before returning to our regularly scheduled program.
+65
View File
@@ -0,0 +1,65 @@
# Transaction subscriptions
Previously we sent simple transactions using the `api.tx` endpoints, in this section we will extend that to monitor the actual transactions for inclusion and also extend the monitoring for transaction events.
## Transaction inclusion
To send a transaction and then waiting until it has been included in a block, we will use a subscription interface instead of just waiting for the transaction pool addition to yield the extrinsic hash. For the simplest form, we can do the following -
```js
...
// create alice (carry-over from the keyring section)
const alice = keyring.addFromUri('//Alice');
// make a transfer from Alice to BOB, waiting for inclusion
const unsub = await api.tx.balances
.transfer(BOB, 12345)
.signAndSend(alice, (result) => {
console.log(`Current status is ${result.status}`);
if (result.status.isFinalized) {
console.log(`Transaction included at blockHash ${result.status.asFinalized}`);
unsub();
}
});
```
As per all previous subscriptions, the transaction subscription returns in `unsub()` and the actual method has a subscription callback. The `result` object has 2 parts, `events` (to to covered in the next section) and the `status` enum.
When the `status` enum is in `Finalized` state (checked via `isFinalized`), the underlying value contains the block hash of the block where the transaction has been included. This does not mean the block is finalized, but rather applies to the transaction state, as no further updates will be received for this subscription.
## Transaction events
Any transaction will emit events, as a bare minimum this will always be either a `system.ExtrinsicSuccess` or `system.ExtrinsicFailed` event for the specific transaction. These provide the overall execution result for the transaction, i.e. execution has succeeded or failed.
Depending on the transaction sent, some other events may however be emitted, for instance for a `balances.transfer` this could include one or more of `Transfer`, `NewAccount` or `ReapedAccount`, as defined in the [substrate balances event defaults](../substrate/events.md#balances).
To display or act on these events, we can do the following -
```js
...
// make a transfer from Alice to BOB, waiting for inclusion
const unsub = await api.tx.balances
.transfer(BOB, 12345)
.signAndSend(alice, ({ events = [], status }) => {
console.log(`Current status is ${status.type}`);
if (status.isFinalized) {
console.log(`Transaction included at blockHash ${status.asFinalized}`);
// loop through Vec<EventRecord> to display all events
events.forEach(({ phase, event: { data, method, section } }) => {
console.log(`\t' ${phase}: ${section}.${method}:: ${data}`);
});
unsub();
}
});
```
Be aware that when a transaction status is `isFinalized`, it means it is included, but it may still have failed - for instance if you try to send a larger amount that you have free, the transaction is included in a block, however from a end-user perspective the transaction failed since the transfer did not occur. In these cases a `system.ExtrinsicFailed` event will be available in the events array.
## Complex transactions
In many cases transactions can carry quite complex information, be it for passing objects or proposing changes. In the next section we will take a dive [into complex transactions, including those wrapped for sudo](api.tx.wrap.md).
+44
View File
@@ -0,0 +1,44 @@
# Complex transactions
Up till now we have focussed on the base operation of transactions. There are however some more complex operations that deserve some more information, for instance when doing either democracy proposals or excuting sudo calls, in both these cases the transaction wraps a call or proposal to be evaluated.
## Sudo use
When running a development chain (Polkadot/Substrate with a `--dev` flag), or in certain testnets a sudo module is available - just like the sudo command found on some systems, it allows root-level access to perform actions. For instance, we can perform a `setBalance(<accountId>, <free>, <reserved>)` on an account -
```js
...
// get the current sudo key in the system
const sudoKey = await api.query.sudo.key();
// lookup from keyring (assuming we have added all, on --dev this would be `//Alice`)
const sudoPair = keyring.getPair(sudoKey);
// send the actual sudo transaction
const unsub = await api.tx.sudo
.sudo(
api.tx.balances.setBalance(ADDR, 12345, 678)
)
.signAndSend(sudoPair, (result) => { ... });
```
The above is really quite straight-forward, the `sudo.sudo(<call>)` call takes 1 parameter, which is a `Call`. We construct this via the `api.tx` and pass it through. The only difference is that the nested call has no actual `.signAndSend` on it, rather it is only used as a container for data.
Exactly the same would apply to the standard `democracy.propose(<proposal>, <value>)`, for instance we can just swap the above sudo wrapper with a proposal and add the correct fees for the proposal.
## Complex types
As indicated in previous sections (we will cover types in more detail next), the API will format the inputs into the actual type required for submission. For primitives such as numbers, this is quite understandable, but it is worth spending at least one example on cases where an object is provided as an input. For instance, making a call to validate -
```js
...
const txHash = await api.tx.staking.validate({
validatorPayment: 12345
});
```
In the above example, all we need to provide is a the fields for the `ValidatorPrefs` object. (Any fields not defined will be set to the default for that type, i.e. all zero). This object maps through to what is defined on the Polkadot/Substrate side, with the [@polkadot/types version](https://github.com/polkadot-js/api/blob/master/packages/types/src/interfaces/staking/definitions.ts) mapping all fields.
## Understanding types
As has been very apparent in all the preceding sections, the management of types is what allows the API to communicate with the node. Most values are in a [binary SCALE-encoded format](https://github.com/paritytech/parity-scale-codec) and it is the reponsibility of the API is to encode and decode these. In the next section we will [take a look at what interfaces the API provides around types](types.basics.md).
+34
View File
@@ -0,0 +1,34 @@
# Basics & Metadata
One of the most important things to understand about the `@polkadot/api` is that most interfaces are actually generated automatically when it connects to a running node. This is quite a departure from other APIs in projects where the interfaces are static. While sounding quite scary, it actually is a powerful concept that exists in both Polkadot and Substrate chains, and allows the API to be used in environments where the chain is customized.
To unpack this, we will start with the Metadata and explain what it actually provides, since it is critical for understanding how to interact with the API and any underlying chain.
## Metadata
When the API connects to a node, one of the first things it does is to retrieve the metadata. The metadata, effectively provides data in the form of `api.<type>.<module>.<section>` that fits into one of the following categories -
- [consts](../substrate/constants.md) - All runtime constants, e.g. `api.consts.balances.creationFee`. These are not functions, rather accessing the endpoint immediately yields the result as defined.
- [query](../substrate/storage.md) - All chain state, e.g. `api.query.balances.freeBalance(<accountId>)`.
- [tx](../substrate/extrinsics.md) - All extrinsics, e.g. `api.tx.balances.transfer(<accountId>, <value>)`.
Additionally the metadata also provides information on [events](../substrate/events.md), these are query-able via the `api.query.system.events()` interface and also appear on transactions... both these cases are detailed later.
## Types
The metadata defiends the calls with all the type names used in the various interfaces. At the moment (this is undergoing investigations and could improve in future versions of metadata), this also means that the types between the API and the node need to be aligned. For instance, by default Substrate defines a `BlockNumber` type as a `u32` and the API follows the Substrate defaults - if a chain has a different definitions, the API needs to be aware of this so it can actually decode (and encode) the type.
At this point just be aware of it, we will touch on types, custom chains and their impacts in a later section.
## Chain Defaults
In addition to the `api.[consts | query | tx]` detailed above, the API, upon connecting to a chain, fills in some information and makes it available directly on the API interface. These include -
- `api.genesisHash` - The genesisHash of the connected chain
- `api.runtimeMetadata` - The metadata as retrieved from the chain
- `api.runtimeVersion` - The chain runtime version (including spec/impl. versions and types)
- `api.libraryInfo` - The version of the API, i.e. `@polkadot/api v0.90.1`
## Let's do something!
Now that we have covered what the API actually exposes, it is time to [dive in and actually use what we installed earlier](create.md).
+79
View File
@@ -0,0 +1,79 @@
# Create an instance
We have the API installed, we have an understanding of what will actually be exposed and how the API knows what to expose. So down the rabbit hole we go - let's create an actual API instance, and then take it from there -
```js
// import
import { ApiPromise, WsProvider } from '@polkadot/api';
...
// construct
const wsProvider = new WsProvider('wss://poc-3.polkadot.io');
const api = await ApiPromise.create({ provider: wsProvider });
// do something
console.log(api.genesisHash.toHex());
```
We will have some explanation on the ES2015 syntax used next, but just a small note on the above - where other code is included (or just some previous boilerplate is used), you will see `...` in most of the examples. This is not due to lazyness, but rather just to keep things straight and to the point.
## ES2015 Usage and examples
Before we jump into an explanation of the above example, be aware that in all cases we are using ES2015, including using things like `async`/`await`, `import` and others. Depending on your environment, this may require some adjustments.
While we are using the `await` naked in all examples (this removes boilerplate), it will need to be wrapped in an `async` block, for we could warp all samples inside a `async function main () { ... }` and then just call `main()`.
In the case of Node.js you would change the `import` into `require`, i.e.
```js
// import
const { ApiPromise, WsProvider } = require('@polkadot/api');
...
```
We are basing all our examples on the [ApiPromise](../examples/promise/README.md) version of the API, however there is also an RxJS version available. Since Promises are a part of the ES2015 specification, it covers the greater amount of use and is the one that will be used in 95% of the cases and should be familiar to 100% of all developers. However if you are in an environment where RxJs is recommended or your have a great affinity ot it, you could take a look at the [RxJS examples](../examples/rx/README.md) once you are familiar with the base concepts introduced here.
For now... just ignore the various flavors and focus on understanding the concepts.
## Providers
Focusing on the construction, any API requires a provider and we create one via the `const wsProvider = new WsProvider(...)`. By default, if none is provided to the API it will construct a default `WsProvider` instance to connect to `ws://127.0.0.1:9944`.
We generally recommend always specifying the endpoint since in most cases we want to connect to an external node and even for local nodes, it is always better being explicit, less magic that can make you wonder in the future.
At this time the only provider type that is fully supported by the API is the WebSocket version. Polkadot/Substrate really comes alive with possibilities once you have access to bi-directional RPCs such as what WebSockets provide. (It is technically possible to have some limited capability via bare-HTTP, but at this point WebSockets is the only fully-operational and supported version - always remember that it is just "upgraded HTTP".)
## API Instance
The API creation is done via the `ApiPromise.create` interface which is a shortcut version for calling `new` and then waiting until the API is connected. Without the `async` syntax, this would be,
```js
ApiPromise
.create({ provider: wsProvider })
.then((api) =>
console.log(api.genesisHash.toHex())
);
```
In most cases we would suggest using the `.create` shortcut, which really just takes care of the following boilerplate that otherwise needs to be provided -
```js
// create the instance
const api = new ApiPromise({ provider: wsProvider });
// wait until we are ready and connected
await api.isReady;
// do something
console.log(api.genesisHash.toHex());
```
## Advanced creation
There are more advanced cases where you would prefer to use the longer version, for instance: if you want to explicitly listen to events emitted, you probably want to attach to the API even before connecting to the chain. All API instances implement an `EventEmitter` interface, with `on` handlers, which emit `connected`, `disconnected`, `ready` and `error` events, allowing you to listen to events on the transport layer.
In these cases, create via `new`, attach listeners and then wait for the `isReady`.
## Do something
Now that we have the API initialized, the next step would be to start using it to interact and extract data [starting with chain constants](api.consts.md).
+27
View File
@@ -0,0 +1,27 @@
# Installation
Yes, it really is as simple as [installing from npm](https://www.npmjs.com/package/@polkadot/api), so we are not going to waste too much time with the bare basics, just install the API via
`yarn add @polkadot/api`
And it will be added and ready for use. The above will always install the latest stable release, which should allow you to connect to testsnets and local nodes that are tracking versioned releases for [Polkadot](https://github.com/paritytech/polkadot) and [Substrate](https://github.com/paritytech/substrate).
## Betas
For users who have a slightly higher appetite for risk, or are using bleeding-edge master branches of either Polkadot/Substrate, we also publish a beta version as soon as anything is merged into the API master branch. This version really contains all the latest fixes and features and is the version we actually use inside the polkadot-js projects - eating our own dogfood.
To install a beta version, either to test or for support of a feature that is available in Substrate master (and has not yet made it to a stable api release), you can install it via the `@beta` tag, i.e.
`yarn add @polkadot/api@beta`
## Other dependencies
In most cases, you don't need to do anything else apart from just installing `@polkadot/api` above. It has dependencies such as `@polkadot/types` which are installed automatically alongside. When using `yarn` the dependencies are installed, flattened, available for use and you will never run into issues with mismatched versions.
This means that by simply installing `@polkadot/api`, you will have access to utilities (crypto and normal), types, providers and even higher-order (derived) API functions. (We will get to all of these in follow-up sections)
If you do however decide to explicitly install other packages (even though they are dependencies), please make sure that the versions inside the api package always match with your versions, i.e. if you installed `@polkadot/api` `0.91.0-beta.22` and you have your own version of `@polkadot/types`, ensure that it is also `0.91.0-beta.22`.
## API basics
So we have it installed. Before we jump into actual real-world usage, [let's understand what the API gives us](basics.md).
+102
View File
@@ -0,0 +1,102 @@
# Keyring
This section will give a quick introduction into the Keyring, including the addition of accounts, retrieving pairs and the signing of any data. Unlike the rest of the API, only the core concepts will be covered with the most-used-functions. However, what is covered is enough for 99.9 of the use-cases ... or rather, that is the aim.
## Installation
They [@polkadot/keyring](https://github.com/polkadot-js/common/tree/master/packages/keyring) keyring is included directly with the API as a dependency, so it is directly importable (since the 0.92 version) alongside the API.
If you do opt to install it seperately, ensure that the version of `@polkadot/util-crypto` that is included with the API matches with the version of `@polkadot/keyring` installed. So if the API depends on `util-crypto 1.4.1`, it would make sense to include `keyring 1.4.1` as the installed version. (This helps in making sure extra versions of the libraries are not included as duplicates, especially in the case where bundles are created. Additionally, this makes sure that weird side-effects in the WASM initialization is avoided.)
## Creating a keyring instance
Once installed, you can create an instance by just creating an instance of the `Keyring` class -
```js
// import the keyring as required
import { Keyring } from '@polkadot/api';
// initialize the API as we would normally do
...
// create a keyring instance
const keyring = new Keyring({ type: 'sr25519' });
```
In the above example, the import is self-explanatory. Upon creation we pass through a `type` which can have a value of either `ed25519` or `sr25519`, when not specified this would default to `ed25519`. This type parameter only applies to the default type of account created when no type is specified, it does not mean that the keyring can only store that type of account.
So effectively, when creating an account and not specifying a type, it will be `sr25519` by default based on the above construction params, however we can also add an `ed25519` account and use it transparently in the same keyring.
One "trick" that is done implictly in the above sample is that that keyring is only initialized after the API. In the case of `sr25519` the keyring relies on a [WASM build](https://github.com/polkadot-js/wasm) of the [schnorrkel libraries](https://github.com/w3f/schnorrkel). Since the API inlitialization is already async, it initializes the WASM libraries are part of the setup.
However, this initialization can also be done explicitly, mostly for more advances use-cases, or in cases where the API won't be attached until much later -
```js
// crypto promise, package used by keyring internally
import { cryptoWaitReady } from '@polkadot/util-crypto';
// wait for the promise to resolve, async WASM or `cryptoWaitReady().then(() => { ... })`
await cryptoWaitReady();
// create a keyring instance
const keyring = new Keyring({ type: 'sr25519' });
```
## Adding accounts
The recommended catch-all approach to adding accounts is via `.addFromUri(<suri>, [meta], [type])` function, where only the `suri` param is required. For instance to add an account via mnemonic, you would do the following -
```js
...
// some mnemonic phrase
const PHRASE = 'entire material egg meadow latin bargain dutch coral blood melt acoustic thought';
// add an account, straight menemonic
const newPair = keyring.addFromUri(PHRASE);
// (advanced) add an account with a derivation path (hard & soft)
const newDeri = keyring.addFromUri(`${PHRASE}//hard-derived/soft-derived`);
// (advanced, development-only) add with an implied dev seed and hard derivation
const alice = keyring.addFromUri('//Alice', { name: 'Alice default' });
```
The above additions cater for most of the usecases and aligns with the you would find in the Substrate `subkey`. Be very wary of the last "dev-seed" option, it is explicitly added for `subkey` compatibility and implies using the "known-everywhere" dev seed. It is however useful when running Polkadot/Substrate with a `--dev` flag.
## Working with pairs
In the previous examples we added a pair to the keyring (and we actually immediately got access to the pair). From this pair there is some information we can retrieve -
```js
...
// add our Alice dev account
const alice = keyring.addFromUri('//Alice', { name: 'Alice default' });
// log some info
console.log(`${alice.meta.name}: has address ${alice.address} with publicKey [${alice.publicKey}]`);
```
Additionally you can sign and verify using the pairs. This is the same internally to the API when constructing transactions -
```js
// some helper functions used here
import { stringToU8a, u8aToHex } from '@polkadot/util';
...
// convert message, sign and then verify
const message = stringToU8a('this is our message');
const signature = alice.sign(message);
const isValid = alice.verify(message, signature);
// log info
console.log(`The signature ${u8aToHex(signature)}, is ${isValid ? '' : 'in'}valid`);
```
This covers the keyring basics, however there are two additional functions here of interest, `keyring.getPairs()` to retrieve a list of all pairs in the keyring and `keyring.getPair(<address or publicKey>)` to retrieve a pair where we have an identifier.
## Back to transactions
Now that we have short introduction to the keyring, we can move back to API transactions and find out [how to subscribe and track events](api.tx.subs.md), taking our management of transactions to the next level.
+67
View File
@@ -0,0 +1,67 @@
# Type basics
We've touched upon types in most previous sections, i.e. that these are driven by metadata and that they are created and converted to/from automatically by the API. Since they appear in all results, we will divert a bit from the regularly scheduled program in explaining the API interfaces to giving some info on the base types.
## Everything is a type
Just to re-iterate from the above. Eveything returned by the API is a type and has a consistent interface. This means that a `Vec<u32>` (an array of `u32` values) as well as a `Struct` (an pre-defined object) or an `Enum` has the same consistent base interface. Specific types types will have values, based on the type - decorated and available.
As a minimum, anything returned by the API, be it a `Vec<...>`, `Option<...>`, `Struct` or any normal type will always have the following methods -
- `.eq(<other value>)` - checks for equality against the other value. In all cases, it will accept "like" values, i.e. in the case of a number you can pass a primitive (such as `1`), a hex value (such as `0x01`) or even an `Unit8Array`
- `toHex()` - returns a hex-base representation of the value, always prefixed by `0x`
- `toJSON()` - returns a JSON-like representation of the value, this is generally used when calling `JSON.stringify(...)` on the value
- `toString()` - returns a string representation, in some cases this performs additional encoding, i.e. for `Address`, `AccountId` and `AccountIndex` it will encode to the ss58 address
- `.toU8a()` - returns a `Uint8Array` representation of the encoded value (generally exactly as passed to the node, where values are SCALE encoded)
Additionally, the following getters and utilities are available -
- `.isEmpty` - `true` if the value is an all-empy value, i.e. `0` in for numbers, all-zero for Arrays (or anything `Uint8Array`), `false` is non-zero
- `.hash` - a `Hash` (once again with all the methods above) that is a `blake2-256` representation of the contained value
## Working with numbers
All numbers wrap and extend an instance of [bn.js](https://github.com/indutny/bn.js/). This means that in addition to the interfaces defined above, they have some additional methods -
- `.toNumber()` - a JS number (limited to 2^53 - 1). This does mean that for large values, e.g. `Balance` (a `u128` extension), this can cause overflows
- `.add(...)`, `.sub(...)`, ... - all the base methods available on the `BN` object
In cases where a `Compact` is returned, i.e. `Compact<Balance>`, the value is wrapped. This object should be `.unwrap()`-ed first to gain access to the underlying `Balance` object.
## Working with structures
All structures, a wrapping of an object containing a number of member variables, is an implementation of a standard JS `Map` object, so all the functions available on a `Map` such as `.entries()` are available. Additionally it is decorated with actual getters for the fields.
As an example, a `Header` will have getters for the `.parentHash`, `.number`, `.stateRoot`, `.extrinsicsRoot` and `.digest` fields. The same applies for all structures, as they are returned, each member will have an associated getter.
Be aware that in the JS version naming defaults to `camelCase` where names of fields in Substrate defaults to `snake_case`. (Each version aligning with conventions in the respective languages)
## Working with enums
Each enum has additional getters which are injected based on the fields wrapped. These take the form of `.is<Name>` and `.as<Name>` to allow you to check is the enum is a certain value or to retrieve the underlying value as a specific type.
As a real-world example, when an extrinsic is applied, the `Phase` enum has one of two states, `ApplyExtrinsic(u32)` or `Finalization`. In this case `.isApplyExtrinsic` would be `true` when an extrinsic is being applied, and `.asApplyExtrinsic` would return the value as a `u32` (which is the index of the extrinsic in the block, as it is being applied). When `isisApplyExtrinsic` is `false` and `asApplyExtrinsic` is called, the getter will throw.
## Working with Option&lt;Type&gt;
An `Option<Type>` attempts to mimic the Rust approach of having `None` and `Some` available. This means the following getters & methods are available on an `Option` -
- `.isNone` - is `true` if no underlying values is warpped, effectively the same as `.isEmpty`
- `.isSome` - this is `true` is a value is wrapped, i.e. if a `Option<u32>` has an actual underlying `u32`
- `.unwrap()` - when `isSome`, this will return the wrapped value, i.e. for `Option<u32>`, this would return the `u32`. When the value is `isNone`, this call will throw an exception.
- `.unwrapOr(<default value>)` - this extends `unwrap()`, returning the wrapped value when `isSome` and in the case of `isNone` it will return the `<default value>` passed.
## Working with Tuples
A tuple is defined in the form of `(u32, AccountId)`. To access the individual values, you can access t via the index, i.e.
```js
// assuming a tuple defined as `(32, AccountId)`
const [count, accountId] = tuple;
console.log(`${accountId} has ${count.toNumber()} values`);
```
## Extending types
For customized chains, the need exists to register types so the API is aware of how to decode values for those types. The next section will provide a [walk-through for the definition of custom types](types.extend.md) allowing the definition or re-definition of any type the API is aware of.
+142
View File
@@ -0,0 +1,142 @@
# Extending types
Circling back to metadata, by default the metadata information (at this point in time), only returns the type names as they apply to any section, be it a call, event or query. As an example, this means that transfers are defined as `balances.transfer(AccountId, Balance)` with no details as to the mapping of the `Balance` type to a `u128`. (The underlying Polkadot/Substrate default)
Therefore to cater for all types, a mapping in done on the [@polkadot/types library](https://github.com/polkadot-js/api/tree/master/packages/types/src/interfaces) to define each of the types and align with their underlying structures as it maps to a default Polkadot or Substrate chain.
Additionally, the API contains some logic for chain type detection, for instance in the case of Substrate 1.x based chains, it will define `BlockNumber` & `Index` (nonce) as a `u64`, while for current-generation chains, these will be defined as `u32`. Some of the work in maintaining the API for Polkadot/Substrate is the addition of types as they appear and gets used in the Rust codebases.
There is a the [recommentation](install.md#betas) to use a `@polkadot/api@beta` should you wish to track the master branches of Polkadot or Substrate, since master changes for the addition of new types do not make it into a stable release immediately.
## Extension
As a blockchain toolkit, Substrate makes it easy to add your own modules and types. In most non-trivial implementations, this would mean that developers are adding specific types for their implementation as well. The API will get to know the names of these types via the metadata, however it won't understand what they are, which means it cannot encode or decode them.
To close this gap, the API allows for the injection of types, i.e. you can explicitly define (or override) types for the node/chain you are connecting to. In the simplest example, assuming you have a chain where your `Balance` type is a `u64` (as opposed to the default `u128`), you need to let the API know -
```js
...
const api = await ApiPromise.create({
provider: wsProvider,
types: {
Balance: 'u64'
}
});
```
The above introduces the `types` registry, effectively allowing overrides and the definition of new types. The override above would mean that immediately the API will treat all occurences of `Balance` not as the default, but rather as the defined size.
## User-defined types
Registration also applies to any type that can be found on a specific chain, i.e. we can add any types that is available on a specific node -
```js
...
const api = await ApiPromise.create({
...,
types: {
TransactionInput: {
parentOutput: 'Hash',
signature: 'Signature'
},
TransactionOutput: {
value: 'u128',
pubkey: 'Hash',
sale: 'u32'
},
Transaction: {
inputs: 'Vec<TransactionInput>',
outputs: 'Vec<TransactionOutput>'
}
}
})
```
The example above defines non-primitive types (as found in the specific implementation) as structs. Additionally it also shows the user-defined types can depend on other user-defined types with `Transaction` referencing both `TransactionInput` and `TransactionOutput`. Here you can reference any known types, i.e. in the above we have referenced primitives such as `u32` and `Signature` (itself an alias for `H512`).
One form of types that appear regularly is enums, these can be defined as follow -
```js
...
const api = await ApiPromise.create({
...,
types: {
CLikeEnum: {
_enum: ['One', 'Two', 'Three']
},
TypedEnum: {
_enum: {
One: 'Compact<u32>',
Two: 'u64',
Three: 'Option<Balance>',
Four: null
}
}
}
});
```
As seen in these examples, types are built up in terms of primitives and aligns with the Rust-type definition model with `Compact`, `Option` and `Vec`.
## Node and chain-specific types
There are cases where a single API object can be used to connect to different types of nodes or chains, each including their own specific types. For these cases the `typesChain` and `typesSpec` injectors are made available.
As a real-world example, the [polkadot-js/apps UI](https://github.com/polkadot-js/apps) can connect to a variety of chains. To support [Edgeware](https://edgewa.re/) by default, the following node-type (`specName` as per the runtime version) overrides are made -
```js
import { IdentityTypes } from 'edgeware-node-types/dist/identity';
import { SignalingTypes } from 'edgeware-node-types/dist/signaling';
import { VotingTypes } from 'edgeware-node-types/dist/voting';
...
const api = await ApiPromise.create({
...,
typesSpec: {
edgeware: {
...IdentityTypes,
...SignalingTypes,
...VotingTypes
}
}
});
```
In the same way `typesChain` can be used to match on the actual chain name, i.e. for a chain such as Kusama, the following overrides can be made (as per example only - Kusama uses the Polkadot defaults, so no overrides are needed) -
```js
...
const api = await ApiPromise.create({
...,
typesChain: {
'Kusama CC1': {
BlockNumber: 'u32',
Index: 'u32'
}
}
});
```
The `types`, `typesChain` and `typesSpec` overrides are all optional and all are applied, as applicable to a specific connection. From the options `types` are registered first, followed by `typesSpec` for node-specific overrides and finally `typesChain` for chain-specific overrides. The would mean is you have the following (contrived) example,
```js
...
const api = await ApiPromise.create({
...,
types: {
Balance: 'u32',
}
typesChain: {
Balance: 'u128'
},
typesSpec: {
Balance: 'u64',
}
});
```
`Balance` would be defined as an `u128` at the end. Effectively based on the flow it is first registered as a `u32`, then overridden as a `u64` and finally overridden once more as a `u128` by the chain types.
## Using with TypeScript
The API is built with TypeScript (as are all projects in the [polkadot-js organization](https://github.com/polkadot-js/)) and as such allows developers using TS to have access to all the type interfaces defined on the chain, as well as having access to typings on interacting with the `api.*` namespaces. In the next section we will provide an overview of [what is available in terms of types and TypeScript](typescript.md).
+56
View File
@@ -0,0 +1,56 @@
# TypeScript interfaces
The API is written in TypeScript, and as such definitions for all actual exposed interfaces are available. In general terms, care has been taken to expose types via a `@polkadot/<package>/types` interface, for instance the `ApiOptions` type which is passed through on the `.create` interface is available under `@polkadot/api/types`.
## RPC interfaces
Before getting to the "hard things", i.e. methods as decorated based on metadata interfaces, let's take a look at more "static" interfaces such as RPC. (Be aware though that these can be customized on a per-chain basis as well - for now this functionality is not reflected in the API itself).
```js
import { Header } from '@polkadot/types/interfaces';
...
const firstHead = api.rpc.chain.getHeader();
api.rpc.chain.subscribeNewHeads((lastHead: Header): void => {
console.log('current header:', JSON.stringify(header));
});
```
In the above example a couple of things are introduced - most of the chain definitions (the default types for both Polkadot & Substrate) can be imported as interfaces from the `@polkadot/types/interfaces` endpoint. These are not classes (since they are [generated from definitions](https://github.com/polkadot-js/api/tree/master/packages/types/src/interfaces)) but rather a combination of TypeScript `interfaces` (where structures are involved) and `type`, i.e. `type Balance = u128`.
In the subscription example, we explicitly define `lastHead: Header`, although the same definition is missing for `firstHead`. However, in both these cases the definitions for the `api.rpc` sections are such that TypeScript understands that `firstHead` and `lastHead` are of type `Header`. The `: Header` here is rather for our own understanding (and could be needed based on your eslint/tslint config).
As indicated, most of the Polkadot/Substrate default types are available via `types/interfaces`. However, for primitives types where there is an actual implementation, these are made available via `@polkadot/types` directly. For instance, `import { u32 } from '@polkadot/types` is valid in this context.
## Metadata injected
For any interface injected by metadata, the types are not available by default (although it may be in the future for default interfaces), but rather what the API understands is that all results need to comply to the `Codec` interface. (The bas of all out types)
However, to make this sane from a developer perspective the injected methods are generic, effectively making the following possible -
```js
import { Balance, Index } from '@polkadot/types/interfaces';
...
const nonce = await api.query.system.accountNonce<Index>(ADDR);
const balance = await api.query.balances.freeBalance<Balance>(ADDR);
```
In both these case we can instruct the TypeScript compiler that the type we are expecting in `Index` and `Balance` respectively, not just pure `Codec`. This means that functions like `.toNumber()` is available on both these types - as opposed to just the [general type defaults](types.basics.md#everything-is-a-type) with `.toHex()` and friends.
## Future work
As of this writing, there are still some gray areas to type detection, specifically around the following interfaces -
- `.at` & `.multi` on `api.query` does not (yet) have a `<TypeOverride>` interface. This means `as <TypeOverride>` casts are presently needed for these results
- `api.queryMulti` does not (yet) allow you to provide a hint to the types returned, this ties to the previous point
In additiont to expanding the type covereage, we wish to make the actual generation script for the types from `@polkadot/types/interfaces` available in 2 ways -
- allowing you to point to a folder of types and auto-generate the TypeScript typings from those. (Which is akin to what we do internally). This would allow a reduction in type classes explicitly written and injected.
- once the metadata itself supports full type definitions, the script can be used to generate interface definitions specifically tailored for a chain
## And it is a wrap
This brings us to the end of our overview and jump through the API. While the documentation is still very much and ever evolving item, we can encourage you to try out what you have learned with some [examples](../examples). As we [indicated right at the start of this journey](README.md#help-us-help-others), if there are areas for improvement, let us know.
+3
View File
@@ -0,0 +1,3 @@
# Substrate
As part of a running node, some information is exposed as part of the metadata.
@@ -1,6 +1,8 @@
## Constants
_The following sections contain the module constants, also known as parameter types.
The following sections contain the module constants, also known as parameter types. These can only be changed as part of a runtime upgrade. On the api, these are exposed via `api.consts.<module>.<method>`.
(NOTE: These were generated from a static/snapshot view of a recent Substrate master node. Some items may not be available in older nodes, or in any customized implementations.)
- **[babe](#babe)**
- **[balances](#balances)**
@@ -1,6 +1,8 @@
## Events
Events are emitted for certain operations on the runtime. The following sections describe the events that are part of the default Substrate runtime.
Events are emitted for certain operations on the runtime. The following sections describe the events that are part of the default Substrate runtime.
(NOTE: These were generated from a static/snapshot view of a recent Substrate master node. Some items may not be available in older nodes, or in any customized implementations.)
- **[balances](#balances)**
- **[contracts](#contracts)**
@@ -1,6 +1,8 @@
## Extrinsics
_The following sections contain Extrinsics methods are part of the default Substrate runtime._
The following sections contain Extrinsics methods are part of the default Substrate runtime. On the api, these are exposed via `api.tx.<module>.<method>`.
(NOTE: These were generated from a static/snapshot view of a recent Substrate master node. Some items may not be available in older nodes, or in any customized implementations.)
- **[authorship](#authorship)**
- **[babe](#babe)**
@@ -1,6 +1,7 @@
## JSON-RPC
_The following sections contain RPC methods that are Remote Calls available by default and allow you to interact with the actual node, query, and submit. The RPCs are provided by Substrate itself._
The following sections contain RPC methods that are Remote Calls available by default and allow you to interact with the actual node, query, and submit.
- **[author](#author)**
- **[chain](#chain)**
@@ -1,6 +1,8 @@
## Storage
_The following sections contain Storage methods are part of the default Substrate runtime._
The following sections contain Storage methods are part of the default Substrate runtime. On the api, these are exposed via `api.query.<module>.<method>`.
(NOTE: These were generated from a static/snapshot view of a recent Substrate master node. Some items may not be available in older nodes, or in any customized implementations.)
- **[authorship](#authorship)**
- **[babe](#babe)**
@@ -367,7 +369,7 @@ ___
▸ **currentEra**(): `EraIndex`
- **summary**: The current era index.
▸ **currentEraRewards**(): `EraRewards`
▸ **currentEraPointsEarned**(): `EraPoints`
- **summary**: Rewards for the current era. Using indices of current elected set.
▸ **currentEraStart**(): `MomentOf`
+1 -1
View File
@@ -9,5 +9,5 @@
"packages": [
"packages/*"
],
"version": "0.91.1"
"version": "0.92.1"
}
+7 -7
View File
@@ -1,5 +1,5 @@
{
"version": "0.91.1",
"version": "0.92.1",
"private": true,
"engines": {
"yarn": "^1.10.1"
@@ -9,7 +9,7 @@
],
"resolutions": {
"babel-core": "^7.0.0-bridge.0",
"typescript": "^3.6.2"
"typescript": "^3.6.3"
},
"scripts": {
"build": "yarn build:interfaces && polkadot-dev-build-ts && yarn run build:methodsdoc && polkadot-dev-build-docs",
@@ -30,11 +30,11 @@
"test:watch": "jest --coverage --watch"
},
"devDependencies": {
"@babel/core": "^7.5.5",
"@babel/register": "^7.5.5",
"@babel/runtime": "^7.5.5",
"@polkadot/dev": "^0.31.0-beta.7",
"@polkadot/ts": "^0.1.71",
"@babel/core": "^7.6.0",
"@babel/register": "^7.6.0",
"@babel/runtime": "^7.6.0",
"@polkadot/dev": "^0.31.0-beta.8",
"@polkadot/ts": "^0.1.72",
"gh-pages": "^2.1.1"
}
}
+3 -3
View File
@@ -1,6 +1,6 @@
{
"name": "@polkadot/api-contract",
"version": "0.91.1",
"version": "0.92.1",
"description": "Interfaces for interacting with contracts and contract ABIs",
"main": "index.js",
"keywords": [
@@ -26,7 +26,7 @@
},
"homepage": "https://github.com/polkadot-js/api/tree/master/packages/api-contract#readme",
"dependencies": {
"@babel/runtime": "^7.5.5",
"@polkadot/types": "^0.91.1"
"@babel/runtime": "^7.6.0",
"@polkadot/types": "^0.92.1"
}
}
+5 -5
View File
@@ -1,6 +1,6 @@
{
"name": "@polkadot/api-derive",
"version": "0.91.1",
"version": "0.92.1",
"description": "Common functions used across Polkadot, derived from RPC calls and storage queries.",
"main": "index.js",
"keywords": [
@@ -27,11 +27,11 @@
},
"homepage": "https://github.com/polkadot-js/api/tree/master/packages/api-derive#readme",
"dependencies": {
"@babel/runtime": "^7.5.5",
"@polkadot/api": "^0.91.1",
"@polkadot/types": "^0.91.1"
"@babel/runtime": "^7.6.0",
"@polkadot/api": "^0.92.1",
"@polkadot/types": "^0.92.1"
},
"devDependencies": {
"@polkadot/keyring": "^1.2.1"
"@polkadot/keyring": "^1.4.1"
}
}
@@ -21,8 +21,8 @@ export type HeaderAndValidators = [Header, AccountId[]];
* <BR>
*
* ```javascript
* api.derive.chain.subscribeNewHeads(({ author, blockNumber }) => {
* console.log(`block #${blockNumber} was authored by ${author}`);
* api.derive.chain.subscribeNewHeads((header) => {
* console.log(`block #${header.number} was authored by ${header.author}`);
* });
* ```
*/
+6 -6
View File
@@ -1,6 +1,6 @@
{
"name": "@polkadot/api-metadata",
"version": "0.91.1",
"version": "0.92.1",
"description": "Helpers to extract information from runtime metadata",
"main": "index.js",
"publishConfig": {
@@ -26,12 +26,12 @@
},
"homepage": "https://github.com/polkadot-js/api/tree/master/packages/type-metadata#readme",
"dependencies": {
"@babel/runtime": "^7.5.5",
"@polkadot/types": "^0.91.1",
"@polkadot/util": "^1.2.1",
"@polkadot/util-crypto": "^1.2.1"
"@babel/runtime": "^7.6.0",
"@polkadot/types": "^0.92.1",
"@polkadot/util": "^1.4.1",
"@polkadot/util-crypto": "^1.4.1"
},
"devDependencies": {
"@polkadot/keyring": "^1.2.1"
"@polkadot/keyring": "^1.4.1"
}
}
+6 -6
View File
@@ -7,13 +7,13 @@ The API wrappers provide a standard interface for use -
- A static `.create(<optional ApiOptions>)` that returns an API instance when connected, decorated and ready-to use. ApiOptions can include an optional WsProvider and optional custom type definitions `{ provider: <Optional WsProvider>, types: <Optional RegistryTypes> }`.
- The above is just a wrapper for `new Api(<optional ApiOptions>) `, exposing the `isReady` getter
- `api.rpc.<section>.<method>` provides access to actual RPC calls, be it for queries, submission or retrieving chain information
- [RPC (node interface)](../METHODS_RPC.md)
- [RPC (node interface)](../substrate/rpc.md)
- `api.query.<section>.<method>` provides access to chain state queries. These are dynamically populated based on what the runtime provides
- [Storage chain state (runtime node interface)](../METHODS_STORAGE.md)
- [Storage chain state (runtime node interface)](../substrate/storage.md)
- `api.tx.<section>.<method>` provides the ability to create a transaction, like chain state, this list is populated from a runtime query
- [Extrinsics (runtime node interface)](../METHODS_EXTRINSICS.md)
- [Extrinsics (runtime node interface)](../substrate/extrinsics.md)
- `api.consts.<section>.<constant>` provides access to the module constants (parameter types).
- [Constants (runtime node interface)](../METHODS_CONSTANTS.md)
- [Constants (runtime node interface)](../substrate/constants.md)
## API Selection
@@ -46,7 +46,7 @@ const api = await ApiPromise.create();
// make a call to retrieve the current network head
api.rpc.chain.subscribeNewHeads((header) => {
console.log(`Chain is at #${header.blockNumber}`);
console.log(`Chain is at #${header.number}`);
});
```
@@ -60,7 +60,7 @@ const api = await ApiRx.create().toPromise();
// make a call to retrieve the current network head
api.rpc.chain.subscribeNewHeads().subscribe((header) => {
console.log(`Chain is at #${header.blockNumber}`);
console.log(`Chain is at #${header.number}`);
});
```
+10 -9
View File
@@ -1,6 +1,6 @@
{
"name": "@polkadot/api",
"version": "0.91.1",
"version": "0.92.1",
"description": "Promise and RxJS wrappers around the Polkadot JS RPC",
"main": "index.js",
"keywords": [
@@ -26,15 +26,16 @@
},
"homepage": "https://github.com/polkadot-js/api/tree/master/packages/api#readme",
"dependencies": {
"@babel/runtime": "^7.5.5",
"@polkadot/api-derive": "^0.91.1",
"@polkadot/api-metadata": "^0.91.1",
"@polkadot/rpc-core": "^0.91.1",
"@polkadot/rpc-provider": "^0.91.1",
"@polkadot/types": "^0.91.1",
"@polkadot/util-crypto": "^1.2.1"
"@babel/runtime": "^7.6.0",
"@polkadot/api-derive": "^0.92.1",
"@polkadot/api-metadata": "^0.92.1",
"@polkadot/keyring": "^1.4.1",
"@polkadot/rpc-core": "^0.92.1",
"@polkadot/rpc-provider": "^0.92.1",
"@polkadot/types": "^0.92.1",
"@polkadot/util-crypto": "^1.4.1"
},
"devDependencies": {
"@polkadot/keyring": "^1.2.1"
"@polkadot/keyring": "^1.4.1"
}
}
+11 -4
View File
@@ -2,6 +2,7 @@
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { Prefix } from '@polkadot/util-crypto/address/types';
import { SignedBlock } from '@polkadot/types/interfaces';
import { RegistryTypes } from '@polkadot/types/types';
import { ApiInterfaceRx, ApiOptions, ApiTypes, DecorateMethod } from '../types';
@@ -9,14 +10,16 @@ import { ApiInterfaceRx, ApiOptions, ApiTypes, DecorateMethod } from '../types';
import constantsFromMeta from '@polkadot/api-metadata/consts/fromMetadata';
import extrinsicsFromMeta from '@polkadot/api-metadata/extrinsics/fromMetadata';
import storageFromMeta from '@polkadot/api-metadata/storage/fromMetadata';
import { GenericCall, GenericEvent, Metadata } from '@polkadot/types';
import { GenericCall, GenericEvent, Metadata, u32 as U32 } from '@polkadot/types';
import { LATEST_VERSION as EXTRINSIC_LATEST_VERSION } from '@polkadot/types/primitive/Extrinsic/constants';
import { assert, logger } from '@polkadot/util';
import { cryptoWaitReady } from '@polkadot/util-crypto';
import { cryptoWaitReady, setSS58Format } from '@polkadot/util-crypto';
import addressDefaults from '@polkadot/util-crypto/address/defaults';
import Decorate from './Decorate';
const KEEPALIVE_INTERVAL = 15000;
const DEFAULT_SS58 = new U32(addressDefaults.prefix);
// these are override types for polkadot chains
// NOTE The SessionKeys definition for Polkadot and Substrate (OpaqueKeys
@@ -90,10 +93,11 @@ export default abstract class Init<ApiType> extends Decorate<ApiType> {
private async metaFromChain (optMetadata: Record<string, string>): Promise<Metadata> {
const { typesChain = {}, typesSpec = {} } = this._options;
const [genesisHash, runtimeVersion, chain] = await Promise.all([
const [genesisHash, runtimeVersion, chain, chainProps] = await Promise.all([
this._rpcCore.chain.getBlockHash(0).toPromise(),
this._rpcCore.state.getRuntimeVersion().toPromise(),
this._rpcCore.system.chain().toPromise()
this._rpcCore.system.chain().toPromise(),
this._rpcCore.system.properties().toPromise()
]);
const specName = runtimeVersion.specName.toString();
@@ -114,6 +118,9 @@ export default abstract class Init<ApiType> extends Decorate<ApiType> {
this._genesisHash = genesisHash;
this._runtimeVersion = runtimeVersion;
// set the global ss58Format as detected by the chain
setSS58Format(chainProps.ss58Format.unwrapOr(DEFAULT_SS58).toNumber() as Prefix);
// get unique types & validate
metadata.getUniqTypes(false);
+1 -1
View File
@@ -88,7 +88,7 @@ export default abstract class ApiBase<ApiType> extends Init<ApiType> {
}
/**
* @description Returns th version of extrinsics in-use on this chain
* @description Returns the version of extrinsics in-use on this chain
*/
public get extrinsicVersion (): number {
return this._extrinsicType;
+1
View File
@@ -6,6 +6,7 @@ import { assertSingletonPackage } from '@polkadot/util';
assertSingletonPackage('@polkadot/api');
export { Keyring } from '@polkadot/keyring';
export { WsProvider } from '@polkadot/rpc-provider';
export { default as ApiPromise } from './promise';
+2 -2
View File
@@ -43,7 +43,7 @@ rpc.chain
)
.subscribe(
(header) => {
console.log(`best #${header.blockNumber.toString()}`);
console.log(`best #${header.number.toString()}`);
console.log(`parentHash: ${header.parentHash.toString()}`);
console.log(`stateRoot: ${header.stateRoot.toString()}`);
console.log(`extrinsicsRoot: ${header.extrinsicsRoot.toString()}`);
@@ -63,7 +63,7 @@ rpc
.subscribeNewHeads()
.subscribe(
(header) => {
console.log(`best #${header.blockNumber}`);
console.log(`best #${header.number}`);
},
(error) => {
console.error('error subscribing:', error);
+6 -6
View File
@@ -1,6 +1,6 @@
{
"name": "@polkadot/rpc-core",
"version": "0.91.1",
"version": "0.92.1",
"description": "A JavaScript wrapper for the Polkadot JsonRPC interface",
"main": "index.js",
"keywords": [
@@ -26,11 +26,11 @@
},
"homepage": "https://github.com/polkadot-js/api/tree/master/packages/rpc-core#readme",
"dependencies": {
"@babel/runtime": "^7.5.5",
"@polkadot/jsonrpc": "^0.91.1",
"@polkadot/rpc-provider": "^0.91.1",
"@polkadot/types": "^0.91.1",
"@polkadot/util": "^1.2.1",
"@babel/runtime": "^7.6.0",
"@polkadot/jsonrpc": "^0.92.1",
"@polkadot/rpc-provider": "^0.92.1",
"@polkadot/types": "^0.92.1",
"@polkadot/util": "^1.4.1",
"rxjs": "^6.5.3"
}
}
+3 -3
View File
@@ -15,7 +15,7 @@ import { catchError, map, publishReplay, refCount, switchMap } from 'rxjs/operat
import interfaces from '@polkadot/jsonrpc';
import { ClassOf, Option, StorageData, StorageKey, Vec, createClass } from '@polkadot/types';
import { createTypeUnsafe } from '@polkadot/types/codec';
import { ExtError, assert, isFunction, isNull, isNumber, logger } from '@polkadot/util';
import { assert, isFunction, isNull, isNumber, logger } from '@polkadot/util';
const l = logger('rpc-core');
@@ -163,7 +163,7 @@ export default class Rpc implements RpcInterface {
l.error(message);
return throwError(new ExtError(message, (error as ExtError).code, undefined));
return throwError(new Error(message));
}),
publishReplay(1), // create a Replay(1)
refCount() // Unsubcribe WS when there are no more subscribers
@@ -191,7 +191,7 @@ export default class Rpc implements RpcInterface {
l.error(message);
observer.error(new ExtError(message, (error as ExtError).code, undefined));
observer.error(new Error(message));
};
try {
+7 -7
View File
@@ -1,6 +1,6 @@
{
"name": "@polkadot/rpc-provider",
"version": "0.91.1",
"version": "0.92.1",
"description": "Transport providers for the API",
"main": "index.js",
"keywords": [
@@ -26,18 +26,18 @@
},
"homepage": "https://github.com/polkadot-js/api/tree/master/packages/rpc-provider#readme",
"dependencies": {
"@babel/runtime": "^7.5.5",
"@polkadot/api-metadata": "^0.91.1",
"@polkadot/util": "^1.2.1",
"@polkadot/util-crypto": "^1.2.1",
"@babel/runtime": "^7.6.0",
"@polkadot/api-metadata": "^0.92.1",
"@polkadot/util": "^1.4.1",
"@polkadot/util-crypto": "^1.4.1",
"@types/nock": "^10.0.3",
"eventemitter3": "^4.0.0",
"isomorphic-fetch": "^2.2.1",
"websocket": "^1.0.29"
},
"devDependencies": {
"@polkadot/keyring": "^1.2.1",
"@polkadot/keyring": "^1.4.1",
"mock-socket": "^9.0.0",
"nock": "^11.3.1"
"nock": "^11.3.3"
}
}
+2 -1
View File
@@ -48,7 +48,7 @@ export default class Mock implements ProviderInterface {
public isUpdating = true;
private requests: Record<string, (...params: any[]) => string> = {
private requests: Record<string, (...params: any[]) => any> = {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
chain_getBlock: (hash: string): any => createType('SignedBlock', rpcSignedBlock.result).toJSON(),
// eslint-disable-next-line @typescript-eslint/no-unused-vars
@@ -62,6 +62,7 @@ export default class Mock implements ProviderInterface {
system_chain: (): string => 'mockChain',
state_getMetadata: (): string => rpcMetadata,
system_name: (): string => 'mockClient',
system_properties: (): Record<string, number | string> => ({ ss58Format: 42 }),
system_version: (): string => '9.8.7'
};
+1 -1
View File
@@ -2,7 +2,7 @@
A definition of all the methods exposed in a general Polkadot client application. These are used not only to provide a comprehensive code-generated document of the available methods, but are also used in the API to auto-generate endpoints with the required type-checking.
For a list of currently exposed methods, see the [method documentation](docs/METHODS_RPC.md).
For a list of currently exposed methods, see the [method documentation](docs/substrate/rpc.md).
## Usage
+2 -2
View File
@@ -1,6 +1,6 @@
{
"name": "@polkadot/jsonrpc",
"version": "0.91.1",
"version": "0.92.1",
"description": "Method definitions for the Polkadot RPC layer",
"main": "index.js",
"publishConfig": {
@@ -26,6 +26,6 @@
},
"homepage": "https://github.com/polkadot-js/api/tree/master/packages/type-jsonrpc#readme",
"dependencies": {
"@babel/runtime": "^7.5.5"
"@babel/runtime": "^7.6.0"
}
}
+6 -6
View File
@@ -1,6 +1,6 @@
{
"name": "@polkadot/types",
"version": "0.91.1",
"version": "0.92.1",
"description": "Implementation of the Parity codec",
"main": "index.js",
"keywords": [
@@ -26,13 +26,13 @@
},
"homepage": "https://github.com/polkadot-js/api/tree/master/packages/types#readme",
"dependencies": {
"@babel/runtime": "^7.5.5",
"@polkadot/util": "^1.2.1",
"@polkadot/util-crypto": "^1.2.1",
"@types/memoizee": "^0.4.2",
"@babel/runtime": "^7.6.0",
"@polkadot/util": "^1.4.1",
"@polkadot/util-crypto": "^1.4.1",
"@types/memoizee": "^0.4.3",
"memoizee": "^0.4.14"
},
"devDependencies": {
"@polkadot/keyring": "^1.2.1"
"@polkadot/keyring": "^1.4.1"
}
}
@@ -289,7 +289,9 @@
},
{
"name": "ExtrinsicFailed",
"args": [],
"args": [
"DispatchError"
],
"documentation": [
" An extrinsic failed."
]
@@ -471,7 +473,7 @@
{
"name": "EpochDuration",
"type": "u64",
"value": "0x5802000000000000",
"value": "0x6009000000000000",
"documentation": [
" The number of **slots** that an epoch takes. We couple sessions to",
" epochs, i.e. we start a new session once the new epoch begins."
@@ -480,7 +482,7 @@
{
"name": "ExpectedBlockTime",
"type": "Moment",
"value": "0xe803000000000000",
"value": "0x7017000000000000",
"documentation": [
" The expected average block time at which BABE should be creating",
" blocks. Since BABE is probabilistic it is not trivial to figure out",
@@ -547,7 +549,7 @@
{
"name": "MinimumPeriod",
"type": "Moment",
"value": "0xf401000000000000",
"value": "0xb80b000000000000",
"documentation": [
" The minimum period between blocks. Beware that this is different to the *expected* period",
" that the block production apparatus provides. Your chosen consensus system will generally",
@@ -781,6 +783,27 @@
" - Contains a limited number of reads and writes.",
" # </weight>"
]
},
{
"name": "force_transfer",
"args": [
{
"name": "source",
"type": "Address"
},
{
"name": "dest",
"type": "Address"
},
{
"name": "value",
"type": "Compact<Balance>"
}
],
"documentation": [
" Exactly as `transfer`, except the origin must be root and the source account may be",
" specified."
]
}
],
"events": [
@@ -943,28 +966,6 @@
" Minimum number of staking participants before emergency conditions are imposed."
]
},
{
"name": "OfflineSlash",
"modifier": 1,
"type": {
"Type": "Perbill"
},
"fallback": "0x40420f00",
"documentation": [
" Slash, per validator that is taken for the first time they are found to be offline."
]
},
{
"name": "OfflineSlashGrace",
"modifier": 1,
"type": {
"Type": "u32"
},
"fallback": "0x00000000",
"documentation": [
" Number of instances of offline reports before slashing begins for validators."
]
},
{
"name": "Invulnerables",
"modifier": 1,
@@ -1037,7 +1038,7 @@
"linked": true
}
},
"fallback": "0x0c00",
"fallback": "0x00",
"documentation": [
" The map from (wannabe) validator stash key to the preferences of that validator."
]
@@ -1145,35 +1146,6 @@
" This is used to derive rewards and punishments."
]
},
{
"name": "SlashCount",
"modifier": 1,
"type": {
"Map": {
"hasher": "Blake2_256",
"key": "AccountId",
"value": "u32",
"linked": false
}
},
"fallback": "0x00000000",
"documentation": [
" The number of times a given validator has been reported offline. This gets decremented",
" by one each era that passes."
]
},
{
"name": "RecentlyOffline",
"modifier": 1,
"type": {
"Type": "Vec<(AccountId,BlockNumber,u32)>"
},
"fallback": "0x00",
"documentation": [
" Most recent `RECENT_OFFLINE_COUNT` instances. (Who it was, when it was reported, how",
" many instances they were offline for)."
]
},
{
"name": "ForceEra",
"modifier": 1,
@@ -1185,6 +1157,19 @@
" True if the next session change will be a new era regardless of index."
]
},
{
"name": "SlashRewardFraction",
"modifier": 1,
"type": {
"Type": "Perbill"
},
"fallback": "0x00000000",
"documentation": [
" The percentage of the slash that is distributed to reporters.",
"",
" The rest of the slashed value is handled by the `Slash`."
]
},
{
"name": "BondedEras",
"modifier": 1,
@@ -1195,6 +1180,22 @@
"documentation": [
" A mapping from still-bonded eras to the first session index of that era."
]
},
{
"name": "EraSlashJournal",
"modifier": 1,
"type": {
"Map": {
"hasher": "Blake2_256",
"key": "EraIndex",
"value": "Vec<SlashJournalEntry>",
"linked": false
}
},
"fallback": "0x00",
"documentation": [
" All slashes that have occurred in a given era."
]
}
]
},
@@ -1219,7 +1220,7 @@
" Take the origin account as a stash and lock up `value` of its balance. `controller` will",
" be the account that controls it.",
"",
" `value` must be more than the `existential_deposit` defined in the Balances module.",
" `value` must be more than the `minimum_balance` specified by `T::Currency`.",
"",
" The dispatch origin for this call must be _Signed_ by the stash account.",
"",
@@ -1269,7 +1270,7 @@
"documentation": [
" Schedule a portion of the stash to be unlocked ready for transfer out after the bond",
" period ends. If this leaves an amount actively bonded less than",
" T::Currency::existential_deposit(), then it is increased to the full amount.",
" T::Currency::minimum_balance(), then it is increased to the full amount.",
"",
" Once the unlock period is done, you can call `withdraw_unbonded` to actually move",
" the funds out of management ready for transfer.",
@@ -1454,18 +1455,6 @@
" # </weight>"
]
},
{
"name": "set_offline_slash_grace",
"args": [
{
"name": "new",
"type": "Compact<u32>"
}
],
"documentation": [
" Set the offline slash grace period."
]
},
{
"name": "set_invulnerables",
"args": [
@@ -1490,18 +1479,7 @@
]
},
{
"name": "OfflineWarning",
"args": [
"AccountId",
"u32"
],
"documentation": [
" One validator (and its nominators) has been given an offline-warning (it is still",
" within its grace). The accrued number of slashes is recorded, too."
]
},
{
"name": "OfflineSlash",
"name": "Slash",
"args": [
"AccountId",
"Balance"
@@ -1509,6 +1487,16 @@
"documentation": [
" One validator (and its nominators) has been slashed by the given amount."
]
},
{
"name": "OldSlashingReportDiscarded",
"args": [
"SessionIndex"
],
"documentation": [
" An old slashing report from a prior era was discarded because it could",
" not be processed."
]
}
],
"constants": [
@@ -1523,13 +1511,90 @@
{
"name": "BondingDuration",
"type": "EraIndex",
"value": "0xa0020000",
"value": "0x1c000000",
"documentation": [
" Number of eras that staked funds must remain bonded for."
]
}
]
},
{
"name": "Offences",
"storage": {
"prefix": "Offences",
"items": [
{
"name": "Reports",
"modifier": 0,
"type": {
"Map": {
"hasher": "Blake2_256",
"key": "ReportIdOf",
"value": "OffenceDetails",
"linked": false
}
},
"fallback": "0x00",
"documentation": [
" The primary structure that holds all offence records keyed by report identifiers."
]
},
{
"name": "ConcurrentReportsIndex",
"modifier": 1,
"type": {
"DoubleMap": {
"hasher": "Blake2_256",
"key1": "Kind",
"key2": "OpaqueTimeSlot",
"value": "Vec<ReportIdOf>",
"key2Hasher": "Blake2_256"
}
},
"fallback": "0x00",
"documentation": [
" A vector of reports of the same kind that happened at the same time slot."
]
},
{
"name": "ReportsByKindIndex",
"modifier": 1,
"type": {
"Map": {
"hasher": "Blake2_256",
"key": "Kind",
"value": "Bytes",
"linked": false
}
},
"fallback": "0x00",
"documentation": [
" Enumerates all reports of a kind along with the time they happened.",
"",
" All reports are sorted by the time of offence.",
"",
" Note that the actual type of this mapping is `Vec<u8>`, this is because values of",
" different types are not supported at the moment so we are doing the manual serialization."
]
}
]
},
"calls": [],
"events": [
{
"name": "Offence",
"args": [
"Kind",
"OpaqueTimeSlot"
],
"documentation": [
" There is an offence reported of the given `kind` happened at the `session_index` and",
" (kind-specific) time slot. This event is not deposited for duplicate slashes."
]
}
],
"constants": []
},
{
"name": "Session",
"storage": {
@@ -1557,17 +1622,6 @@
" Current index of the session."
]
},
{
"name": "Changed",
"modifier": 1,
"type": {
"Type": "bool"
},
"fallback": "0x00",
"documentation": [
" True if anything has changed in this session."
]
},
{
"name": "QueuedChanged",
"modifier": 1,
@@ -1576,7 +1630,8 @@
},
"fallback": "0x00",
"documentation": [
" Queued keys changed."
" True if the underlying economic identities or weighting behind the validators",
" has changed in the queued validator set."
]
},
{
@@ -1781,6 +1836,34 @@
"documentation": [
" `true` if we are currently stalled."
]
},
{
"name": "CurrentSetId",
"modifier": 1,
"type": {
"Type": "SetId"
},
"fallback": "0x0000000000000000",
"documentation": [
" The number of changes (both in terms of keys and underlying economic responsibilities)",
" in the \"set\" of Grandpa validators from genesis."
]
},
{
"name": "SetIdSession",
"modifier": 0,
"type": {
"Map": {
"hasher": "Blake2_256",
"key": "SetId",
"value": "SessionIndex",
"linked": false
}
},
"fallback": "0x00",
"documentation": [
" A mapping from grandpa set ID to the index of the *most recent* session for which its members were responsible."
]
}
]
},
@@ -1802,7 +1885,7 @@
{
"name": "NewAuthorities",
"args": [
"Vec<(AuthorityId,u64)>"
"Vec<(AuthorityId,AuthorityWeight)>"
],
"documentation": [
" New authority set has been applied."
@@ -1882,7 +1965,7 @@
},
{
"name": "signature",
"type": "AuthoritySignature"
"type": "Signature"
}
],
"documentation": []
@@ -2503,7 +2586,7 @@
{
"name": "EnactmentPeriod",
"type": "BlockNumber",
"value": "0x008d2700",
"value": "0x80970600",
"documentation": [
" The minimum period of locking and the period between a proposal being approved and enacted.",
"",
@@ -2515,7 +2598,7 @@
{
"name": "LaunchPeriod",
"type": "BlockNumber",
"value": "0x00ea2400",
"value": "0x00270600",
"documentation": [
" How often (in blocks) new public referenda are launched."
]
@@ -2523,7 +2606,7 @@
{
"name": "VotingPeriod",
"type": "BlockNumber",
"value": "0x00ea2400",
"value": "0x00270600",
"documentation": [
" How often (in blocks) to check for new votes."
]
@@ -2539,7 +2622,7 @@
{
"name": "EmergencyVotingPeriod",
"type": "BlockNumber",
"value": "0x80f40300",
"value": "0xc0a80000",
"documentation": [
" Minimum voting period allowed for an emergency referendum."
]
@@ -2547,7 +2630,7 @@
{
"name": "CooloffPeriod",
"type": "BlockNumber",
"value": "0x00ea2400",
"value": "0x00270600",
"documentation": [
" Period in blocks where an external proposal may not be re-submitted after being vetoed."
]
@@ -3530,7 +3613,7 @@
{
"name": "VotingPeriod",
"type": "BlockNumber",
"value": "0x00a30200",
"value": "0x80700000",
"documentation": [
" How often (in blocks) to check for new votes. A reasonable default value",
" is 1000."
@@ -3858,7 +3941,7 @@
{
"name": "ProposalBondMinimum",
"type": "BalanceOf",
"value": "0x00e40b54020000000000000000000000",
"value": "0x0010a5d4e80000000000000000000000",
"documentation": [
" Minimum amount of funds that should be placed in a deposit for making a proposal."
]
@@ -3866,7 +3949,7 @@
{
"name": "SpendPeriod",
"type": "BlockNumber",
"value": "0x80510100",
"value": "0x00460500",
"documentation": [
" Period between successive spends."
]
@@ -3874,7 +3957,7 @@
{
"name": "Burn",
"type": "Permill",
"value": "0x20a10700",
"value": "0x50c30000",
"documentation": [
" Percentage of spare funds (if any) that are burnt per spend period."
]
@@ -3953,88 +4036,6 @@
}
]
},
{
"name": "Sudo",
"storage": {
"prefix": "Sudo",
"items": [
{
"name": "Key",
"modifier": 1,
"type": {
"Type": "AccountId"
},
"fallback": "0x0000000000000000000000000000000000000000000000000000000000000000",
"documentation": [
" The `AccountId` of the sudo key."
]
}
]
},
"calls": [
{
"name": "sudo",
"args": [
{
"name": "proposal",
"type": "Proposal"
}
],
"documentation": [
" Authenticates the sudo key and dispatches a function call with `Root` origin.",
"",
" The dispatch origin for this call must be _Signed_.",
"",
" # <weight>",
" - O(1).",
" - Limited storage reads.",
" - No DB writes.",
" # </weight>"
]
},
{
"name": "set_key",
"args": [
{
"name": "new",
"type": "Address"
}
],
"documentation": [
" Authenticates the current sudo key and sets the given AccountId (`new`) as the new sudo key.",
"",
" The dispatch origin for this call must be _Signed_.",
"",
" # <weight>",
" - O(1).",
" - Limited storage reads.",
" - One DB change.",
" # </weight>"
]
}
],
"events": [
{
"name": "Sudid",
"args": [
"bool"
],
"documentation": [
" A sudo just took place."
]
},
{
"name": "KeyChanged",
"args": [
"AccountId"
],
"documentation": [
" The sudoer just switched identity; the old key is supplied."
]
}
],
"constants": []
},
{
"name": "Parachains",
"storage": {
@@ -4723,6 +4724,88 @@
}
],
"constants": []
},
{
"name": "Sudo",
"storage": {
"prefix": "Sudo",
"items": [
{
"name": "Key",
"modifier": 1,
"type": {
"Type": "AccountId"
},
"fallback": "0x0000000000000000000000000000000000000000000000000000000000000000",
"documentation": [
" The `AccountId` of the sudo key."
]
}
]
},
"calls": [
{
"name": "sudo",
"args": [
{
"name": "proposal",
"type": "Proposal"
}
],
"documentation": [
" Authenticates the sudo key and dispatches a function call with `Root` origin.",
"",
" The dispatch origin for this call must be _Signed_.",
"",
" # <weight>",
" - O(1).",
" - Limited storage reads.",
" - No DB writes.",
" # </weight>"
]
},
{
"name": "set_key",
"args": [
{
"name": "new",
"type": "Address"
}
],
"documentation": [
" Authenticates the current sudo key and sets the given AccountId (`new`) as the new sudo key.",
"",
" The dispatch origin for this call must be _Signed_.",
"",
" # <weight>",
" - O(1).",
" - Limited storage reads.",
" - One DB change.",
" # </weight>"
]
}
],
"events": [
{
"name": "Sudid",
"args": [
"bool"
],
"documentation": [
" A sudo just took place."
]
},
{
"name": "KeyChanged",
"args": [
"AccountId"
],
"documentation": [
" The sudoer just switched identity; the old key is supplied."
]
}
],
"constants": []
}
]
}
@@ -1123,10 +1123,10 @@
]
},
{
"name": "CurrentEraRewards",
"name": "CurrentEraPointsEarned",
"modifier": 1,
"type": {
"Type": "EraRewards"
"Type": "EraPoints"
},
"fallback": "0x0000000000",
"documentation": [
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+8 -1
View File
@@ -19,7 +19,7 @@ import { AuthorityWeight, NextAuthority, PendingPause, PendingResume, SetId, Sto
import { AuthIndex, AuthoritySignature, Heartbeat, OpaqueMultiaddr, OpaqueNetworkState, OpaquePeerId } from './interfaces/imOnline';
import { Kind, OffenceDetails, Offender, OpaqueTimeSlot, ReportIdOf, Reporter } from './interfaces/offences';
import { FullIdentification, IdentificationTuple, Keys, SessionIndex, SessionKeysPolkadot, SessionKeysSubstrate } from './interfaces/session';
import { EraIndex, EraRewards, Exposure, Forcing, IndividualExposure, MomentOf, RewardDestination, SlashJournalEntry, StakingLedger, UnlockChunk, ValidatorPrefs, ValidatorPrefs0to145 } from './interfaces/staking';
import { EraIndex, EraPoints, EraRewards, Exposure, Forcing, IndividualExposure, MomentOf, Points, RewardDestination, SlashJournalEntry, StakingLedger, UnlockChunk, ValidatorPrefs, ValidatorPrefs0to145 } from './interfaces/staking';
import { DigestOf, DispatchError, Event, EventId, EventIndex, EventRecord, EventRecord0to76, Key, Phase } from './interfaces/system';
import { TreasuryProposal } from './interfaces/treasury';
import { BlockAttestations, IncludedBlocks, MoreAttestations } from './interfaces/attestations';
@@ -533,6 +533,9 @@ export interface InterfaceRegistry {
'Compact<EraIndex>': Compact<EraIndex>;
'Option<EraIndex>': Option<EraIndex>;
'Vec<EraIndex>': Vec<EraIndex>;
EraPoints: EraPoints;
'Option<EraPoints>': Option<EraPoints>;
'Vec<EraPoints>': Vec<EraPoints>;
EraRewards: EraRewards;
'Option<EraRewards>': Option<EraRewards>;
'Vec<EraRewards>': Vec<EraRewards>;
@@ -548,6 +551,10 @@ export interface InterfaceRegistry {
MomentOf: MomentOf;
'Option<MomentOf>': Option<MomentOf>;
'Vec<MomentOf>': Vec<MomentOf>;
Points: Points;
'Compact<Points>': Compact<Points>;
'Option<Points>': Option<Points>;
'Vec<Points>': Vec<Points>;
RewardDestination: RewardDestination;
'Option<RewardDestination>': Option<RewardDestination>;
'Vec<RewardDestination>': Vec<RewardDestination>;
@@ -5,6 +5,10 @@
export default {
types: {
EraIndex: 'u32',
EraPoints: {
total: 'Points',
individual: 'Vec<Points>'
},
EraRewards: {
total: 'u32',
rewards: 'Vec<u32>'
@@ -26,6 +30,7 @@ export default {
value: 'Compact<Balance>'
},
MomentOf: 'Moment',
Points: 'u32',
RewardDestination: {
_enum: [
'Staked',
@@ -8,6 +8,14 @@ import { AccountId, Balance, BlockNumber, Moment } from '../runtime';
/** u32 */
export type EraIndex = u32;
/** Struct */
export interface EraPoints extends Struct {
/** Points */
readonly total: Points;
/** Vec<Points> */
readonly individual: Vec<Points>;
}
/** Struct */
export interface EraRewards extends Struct {
/** u32 */
@@ -47,6 +55,9 @@ export interface IndividualExposure extends Struct {
/** Moment */
export type MomentOf = Moment;
/** u32 */
export type Points = u32;
/** Enum */
export interface RewardDestination extends Enum {
/** 0:: Staked */
@@ -4,7 +4,7 @@
import '../../injector';
import { setAddressPrefix } from '@polkadot/util-crypto';
import { setSS58Format } from '@polkadot/util-crypto';
import { createType } from '../../codec/create';
import U8a from '../../codec/U8a';
@@ -84,7 +84,7 @@ describe('AccountId', (): void => {
describe('storage decoding', (): void => {
it('has the correct entries', (): void => {
setAddressPrefix(68);
setSS58Format(68);
const data = createType('StorageData', jsonVec.params.result.changes[0][1]);
const list = createType('Vec<AccountId>', data).map((accountId): string => accountId.toString());
+13 -11
View File
@@ -16,11 +16,13 @@ import MetadataV7, { ModuleMetadataV7 } from '../Metadata/v7';
const ANCHOR_TOP = '';
const LINK_BACK_TO_TOP = '';
const DESC_CONSTANTS = '\n\n_The following sections contain the module constants, also known as parameter types.\n';
const DESC_EXTRINSICS = '\n\n_The following sections contain Extrinsics methods are part of the default Substrate runtime._\n';
const DESC_EVENTS = '\n\nEvents are emitted for certain operations on the runtime. The following sections describe the events that are part of the default Substrate runtime.\n';
const DESC_RPC = '\n\n_The following sections contain RPC methods that are Remote Calls available by default and allow you to interact with the actual node, query, and submit. The RPCs are provided by Substrate itself._';
const DESC_STORAGE = '\n\n_The following sections contain Storage methods are part of the default Substrate runtime._\n';
const STATIC_TEXT = '\n\n(NOTE: These were generated from a static/snapshot view of a recent Substrate master node. Some items may not be available in older nodes, or in any customized implementations.)';
const DESC_CONSTANTS = `\n\nThe following sections contain the module constants, also known as parameter types. These can only be changed as part of a runtime upgrade. On the api, these are exposed via \`api.consts.<module>.<method>\`. ${STATIC_TEXT}\n`;
const DESC_EXTRINSICS = `\n\nThe following sections contain Extrinsics methods are part of the default Substrate runtime. On the api, these are exposed via \`api.tx.<module>.<method>\`. ${STATIC_TEXT}\n`;
const DESC_EVENTS = `\n\nEvents are emitted for certain operations on the runtime. The following sections describe the events that are part of the default Substrate runtime. ${STATIC_TEXT}\n`;
const DESC_RPC = '\n\nThe following sections contain RPC methods that are Remote Calls available by default and allow you to interact with the actual node, query, and submit.\n';
const DESC_STORAGE = `\n\nThe following sections contain Storage methods are part of the default Substrate runtime. On the api, these are exposed via \`api.query.<module>.<method>\`. ${STATIC_TEXT}\n`;
function sectionLink (sectionName: string): string {
return `- **[${stringCamelCase(sectionName)}](#${stringCamelCase(sectionName)})**\n\n`;
@@ -219,26 +221,26 @@ function writeFile (name: string, ...chunks: any[]): void {
}
function writeToRpcMd (): void {
writeFile('docs/METHODS_RPC.md', addRpc());
writeFile('docs/substrate/rpc.md', addRpc());
}
function writeToConstantsMd (metadata: MetadataV7): void {
writeFile('docs/METHODS_CONSTANTS.md', addConstants(metadata));
writeFile('docs/substrate/constants.md', addConstants(metadata));
}
function writeToStorageMd (metadata: MetadataV7): void {
const options = { flags: 'r', encoding: 'utf8' };
const data = fs.readFileSync('packages/types/src/scripts/METHODS_STORAGE_SUBSTRATE.md', options);
const data = fs.readFileSync('docs/substrate/storage-known.md', options);
writeFile('docs/METHODS_STORAGE.md', addStorage(metadata), data);
writeFile('docs/substrate/storage.md', addStorage(metadata), data);
}
function writeToExtrinsicsMd (metadata: MetadataV7): void {
writeFile('docs/METHODS_EXTRINSICS.md', addExtrinsics(metadata));
writeFile('docs/substrate/extrinsics.md', addExtrinsics(metadata));
}
function writeToEventsMd (metadata: MetadataV7): void {
writeFile('docs/METHODS_EVENTS.md', addEvents(metadata));
writeFile('docs/substrate/events.md', addEvents(metadata));
}
const metadata = new Metadata(rpcdata).asLatest;
+3 -3
View File
@@ -25,15 +25,15 @@ const { argv: { ws } } = yargs
async function main (): Promise<void> {
const provider = new WsProvider(ws);
const api = await ApiPromise.create({ provider });
const chain = await api.rpc.system.chain();
const props = await api.rpc.system.properties();
const meta = await api.rpc.state.getMetadata();
// output the chain info, for easy re-use
console.error(`export default { chain: '${chain.toString()}', genesisHash: '${api.genesisHash.toHex()}', ss58Format: ${props.ss58Format.unwrapOr(42)}, tokenDecimals: ${props.tokenDecimals.unwrapOr(0)}, tokenSymbol: '${props.tokenSymbol.unwrapOr('UNIT')}', metaCalls: '${Buffer.from(meta.asCallsOnly.toU8a()).toString('base64')}' };`);
console.error(`export default { chain: '${chain.toString()}', genesisHash: '${api.genesisHash.toHex()}', specVersion: ${api.runtimeVersion.specVersion.toNumber()}, ss58Format: ${props.ss58Format.unwrapOr(42)}, tokenDecimals: ${props.tokenDecimals.unwrapOr(0)}, tokenSymbol: '${props.tokenSymbol.unwrapOr('UNIT')}', metaCalls: '${Buffer.from(api.runtimeMetadata.asCallsOnly.toU8a()).toString('base64')}' };`);
// show any missing types
meta.getUniqTypes(false);
api.runtimeMetadata.getUniqTypes(false);
}
main()
+322 -322
View File
File diff suppressed because it is too large Load Diff