Compare commits

..
51 Commits
Author SHA1 Message Date
ian.he 4e6b533539 v0.78.103 2019-06-06 14:02:54 +12:00
ian.he 224803f4c4 fix: derive generated is empty 2019-06-06 13:53:53 +12:00
ian.he 9fbf4bf478 v0.78.102 2019-06-06 12:50:29 +12:00
ian.he 385150bd81 fix: lock typescript to 3.4.5 until merge upstream 2019-06-06 12:40:16 +12:00
ian.he 14216a42a3 0.78.101 2019-06-05 10:04:08 +12:00
Alex Wang 0055cb594f fix: clean code (#1) 2019-06-05 10:04:08 +12:00
Jaco Greeff 63e08d8357 Fix ContractAbi assert name (#951) 2019-06-04 17:01:39 +12:00
ian.he c9f9e2ec8a docs: include statement and link of upstream project 2019-05-27 15:55:12 +12:00
ian.he 019f1f761f rebase upstream and bump to 0.78.100 2019-05-27 15:46:59 +12:00
Jaco Greeff c91e72b60b 0.78.1 (#884)
* update CHANGELOG

* Bump common

* Bump to 0.78
2019-05-27 15:46:31 +12:00
Amaury Martiny e4cf97d71e Linked map in v0 (#886) 2019-05-27 15:46:31 +12:00
Jaco Greeff dcdbd2ca40 Fix bug in metadata conversion (return converted) (#880)
* Fix bug in metadata conversion (return converted)

* v2 -> v3
2019-05-27 15:46:31 +12:00
Jaco Greeff 13ae360c7a assert type on all asXxx getters (#879)
* assert type on all asXxx getters

* Convert via built-in asVx

* Implicit index

* Re-add V0 (not dropped here, but dropped somewhere)

* MetadataDeprectated -> MetadataDeprecated
2019-05-27 15:46:31 +12:00
Jaco Greeff 6c0d683235 Add contract fees (#875) 2019-05-27 15:46:31 +12:00
Amaury Martiny 6fc35d641a Fix linked maps (#878)
* Fix linked maps

* Line breaks
2019-05-27 15:46:31 +12:00
Jaco Greeff d79c0ea28d Update to latest metadata (with ContractInfo) (#874)
* Update to latest metadata (with ContractInfo)

* isAlive/isTomstone

* typo
2019-05-27 15:46:30 +12:00
Jaco Greeff 486412d051 Fix struct keys, log additional decoding error info (#872)
* Re-create test cases for failures

* Fix cloberring of keys

* Add logging to pinpoint decoding failures
2019-05-27 15:46:30 +12:00
Jaco Greeff f3f1807013 Bump dev (& fix indents) (#870)
* Bump dev (& fix indents)

* Bump common
2019-05-27 15:46:30 +12:00
Jaco Greeff d9e581fbdc Basic same-type multi queries (#866)
* Basic same-type multi queries

* Remove extra map, straight to switchMap
2019-05-27 15:46:30 +12:00
Xiliang Chen 89ebae9d78 Update WithdrawReasons to match substrate (#865)
* Update WithdrawReasons to match substrate

* Linting, comment alignment
2019-05-27 15:46:30 +12:00
Jaco Greeff 071d872adf USize -> U32 (#839)
- Possibly a fix for https://github.com/polkadot-js/api/issues/838
2019-05-27 15:46:30 +12:00
Jaco Greeff 1b6d6d970c rm -rf cc-test-reporter 2019-05-27 15:46:30 +12:00
Jaco Greeff 9f5be747e7 Bump deps (#861)
* Bump deps

* Align with published common

* Fix rxjs to 6.4.0 (false deprecations on 6.5.1)
2019-05-27 15:46:30 +12:00
Amaury Martiny 86cb0962bc Update Changelog (#859) 2019-05-27 15:46:29 +12:00
ian.he 75884d22a3 0.77.102 2019-05-27 15:46:29 +12:00
ian.he a4d09f799d fix: import for Api.spec.ts 2019-05-27 15:46:29 +12:00
Karishma Bothara 85a29de479 Api pre-bundled metadata (#850)
(cherry picked from commit 19eb484a29)

Approved-by: Ian He <ian-he@outlook.com>
2019-05-27 15:46:29 +12:00
Alex Wang ed2e44ac93 v0.77.101 2019-05-27 15:46:29 +12:00
Alex Wang c88d284a5c fix: storageNames in metadata v4 to support DoubleMap
Merged in polkadot_v77_1 (pull request #4)

Approved-by: Ian He <ian-he@outlook.com>
2019-05-27 15:46:29 +12:00
ian.he daaa16523d v0.77.100 2019-05-27 15:46:27 +12:00
Travis CI 116714a8f9 upstream upgrade(v0.77.1)
release v0.77.100
2019-05-27 15:46:19 +12:00
Amaury Martiny 5c1f7fb527 Use custom hasher for Map (#857)
* Use blake2 instead of two_x

* Add v4

* Update to new v4 static

* Update json

* Revert

* Use hasher enum

* Fix metadata v4 test

* Fix metadata v4 test

* Fix versioned metadata

* refactor & clean

* Use consistent naming

* Make jsons consistent

* Add backward compat

* Fix tests

* Start working on type-storage

* Fix output

* Grumble

* Update to latest static

* Clean code

* Fix imports

* Remove useless imports

* Fix tests

* Use prettier output for toJSON in metadata

* Implement different hashers

* Remove generic storageKey

* Bump version

* Add backwards-compat

* Fix hashing function, use Twox128

* Grumbles

* Add tests
2019-05-27 15:46:19 +12:00
Stefanie Doll 8a69bc4458 Fix the md table formatting (#855)
* Last attempt

* Poke Travis
2019-05-27 15:46:18 +12:00
Stefanie Doll a8dd059097 Type definitions formatting fix (#851)
* attempt to fix vuepress falsy markdown interpretation

* Linebreak fix

* Roll-back yarn.lock
2019-05-27 15:46:16 +12:00
Stefanie Doll 1204ac37f6 Add short description to all types on overview page (#849)
* Smaller typos/ wording

* Grammar An - A

* Add short description to each type on overview page WIP

* Removed 'Derived types' section because HeaderExtended was the only derived method left

* Commit current state

* Description completed

* Removed empty row placeholder

* Fixed Typo in LockPeriods

* Spell out Little Endian

* Fixed accidentaly removed space character
2019-05-27 15:46:09 +12:00
Jaco Greeff b2f03e500e Remove contract encoding debug (confirmed working) (#836)
* Remove contract encoding debug (confirmed working)

* Remove (now-unused) import
2019-05-27 15:46:09 +12:00
Jaco Greeff de90242456 Bumps (#834) 2019-05-27 15:46:06 +12:00
Jaco Greeff a7ffe44ae6 AbstractArray base & VectorAny (no types in constructor) (#833)
* AbstractArray base & VectorAny (no  types in constrctor)

* Remove noInheritDoc from Tuple, Vector* (already on abstract)
2019-05-27 15:45:51 +12:00
Jaco Greeff ac5bfeda39 Contract ABI (extended) 2019-05-27 15:45:50 +12:00
Jaco Greeff 73a184ec7d Expand Digest for asAura, use in HeaderExtended (#832) 2019-05-27 15:45:50 +12:00
Jaco Greeff e4371684b6 Properly map indexes (swapped in balances -> indices change) (#831)
* Properly map indexes (swapped in balances -> indices change)

* Typos
2019-05-27 15:45:50 +12:00
Jaco Greeff 382e903b8f TreasuryProposal (#825) 2019-05-27 15:45:50 +12:00
ian.he 6b6b7fe145 chore: rebranding to @plugnet 2019-04-26 16:43:32 +12:00
ian.he 1f4e7638d5 v0.76.102 2019-04-16 16:37:21 +12:00
Alex Wang 4d95d622a9 fix: fix double map
Merged in check (pull request #2)

Approved-by: Ian He <ian-he@outlook.com>
2019-04-16 04:36:17 +00:00
ian.he 327c20ddea v0.76.101 2019-04-16 14:55:50 +12:00
Alex Wang 04f6d352d9 feat: adding double map support
Merged in double-map (pull request #1)

Approved-by: Ian He <ian-he@outlook.com>
2019-04-16 02:53:30 +00:00
ian.he c14a071b74 docs: add examples from polkadot 2019-04-12 17:40:12 +12:00
ian.he f103863fdd docs: add examples from polkadot 2019-04-12 17:33:55 +12:00
ian.he 3c7c79f18f merge v0.76.1 2019-04-12 11:26:54 +12:00
ian.he 4e30fab9d6 init 2019-04-11 13:42:06 +12:00
1465 changed files with 58088 additions and 333569 deletions
+1 -48
View File
@@ -1,48 +1 @@
39
1.4.2
1.6.2
1.11.2
1.12.2
1.17.2
1.31.2
2.8.2
3.2.2
3.2.3
3.3.2
3.6.2
3.6.3
3.6.4
3.7.2
3.7.3
3.9.2
3.9.3
3.10.2
4.0.2
4.0.3
4.6.2
4.7.2
4.9.2
4.11.2
4.16.2
5.3.2
5.5.2
5.8.2
5.8.3
6.0.2
6.0.3
6.0.4
6.0.5
6.1.2
6.4.2
6.5.2
6.7.2
6.9.2
6.10.2
6.10.3
5
+1
View File
@@ -0,0 +1 @@
module.exports = require('./babel.config.js');
-26
View File
@@ -1,26 +0,0 @@
checks:
argument-count:
config:
threshold: 5
method-complexity:
config:
threshold: 7
method-count:
config:
threshold: 25
method-lines:
config:
threshold: 30
exclude_patterns:
- "**/*.spec.js"
- "**/*.spec.ts"
- "**/*.test.js"
- "**/*.test.ts"
- "docs/**/*.js"
- "docs/**/*.ts"
- "packages/*-augment/"
- "packages/typegen/scripts"
- "packages/typegen/src"
- "packages/types/src/interfaces/"
- "packages/types/src/augment/"
-24
View File
@@ -1,24 +0,0 @@
// Copyright 2017-2021 @polkadot/api authors & contributors
// SPDX-License-Identifier: Apache-2.0
const base = require('@polkadot/dev/config/eslint.cjs');
module.exports = {
...base,
ignorePatterns: [
...base.ignorePatterns
],
parserOptions: {
...base.parserOptions,
project: [
'./tsconfig.eslint.json'
]
},
rules: {
...base.rules,
// add override for any (a metric ton of them, initial conversion)
'@typescript-eslint/no-explicit-any': 'off',
// this seems very broken atm, false positives
'@typescript-eslint/unbound-method': 'off'
}
};
-23
View File
@@ -1,23 +0,0 @@
name: 'Lock Threads'
on:
schedule:
- cron: '10 1/3 * * *'
jobs:
lock:
runs-on: ubuntu-latest
steps:
- uses: dessant/lock-threads@v2
with:
github-token: ${{ secrets.GH_PAT_BOT }}
issue-lock-inactive-days: '7'
issue-lock-comment: >
This thread has been automatically locked since there has not been
any recent activity after it was closed. Please open a new issue
if you think you have a related problem or query.
pr-lock-inactive-days: '2'
pr-lock-comment: >
This pull request has been automatically locked since there
has not been any recent activity after it was closed.
Please open a new issue for related bugs.
-16
View File
@@ -1,16 +0,0 @@
name: PR
on: [pull_request]
jobs:
pr:
strategy:
matrix:
step: ['lint', 'test', 'build']
name: ${{ matrix.step }}
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: ${{ matrix.step }}
run: |
yarn install --immutable | grep -v 'YN0013'
yarn ${{ matrix.step }}
-27
View File
@@ -1,27 +0,0 @@
name: Master
on:
push:
branches:
- master
jobs:
master:
if: "! startsWith(github.event.head_commit.message, '[CI Skip]')"
strategy:
matrix:
step: ['build:release']
name: ${{ matrix.step }}
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
with:
token: ${{ secrets.GH_PAT }}
- name: ${{ matrix.step }}
env:
CC_TEST_REPORTER_ID: ${{ secrets.CC_TEST_REPORTER_ID }}
GH_PAT: ${{ secrets.GH_PAT }}
GH_RELEASE_GITHUB_API_TOKEN: ${{ secrets.GH_PAT }}
NPM_TOKEN: ${{ secrets.NPM_TOKEN }}
run: |
yarn install --immutable | grep -v 'YN0013'
yarn ${{ matrix.step }}
-18
View File
@@ -1,18 +0,0 @@
name: Semgrep
on:
pull_request: {}
push:
branches:
- master
jobs:
check:
if: "! startsWith(github.event.head_commit.message, '[CI Skip]') && (!github.event.pull_request || github.event.pull_request.head.repo.full_name == github.repository)"
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: returntocorp/semgrep-action@v1
with:
auditOn: push
publishToken: ${{ secrets.SEMGREP_APP_TOKEN }}
publishDeployment: 1395
-17
View File
@@ -1,17 +0,0 @@
name: 'Close stale issues and PRs'
on:
schedule:
- cron: '55 1/3 * * *'
jobs:
stale:
runs-on: ubuntu-latest
steps:
- uses: actions/stale@v3
with:
repo-token: ${{ secrets.GH_PAT_BOT }}
stale-issue-message: 'This issue has been open for 21 days with no activity and is not labelled as an enhancement. It will be closed in 7 days.'
stale-issue-label: 'stale'
exempt-issue-labels: '-size-l,-size-m,-size-s,-size-xl,-size-xs,[bug]'
days-before-stale: 21
days-before-close: 7
+1 -9
View File
@@ -3,7 +3,6 @@ build/
build-docs/
coverage/
docs/.vuepress/dist/
docs/substrate/*.md
node_modules/
tmp/
.DS_Store
@@ -12,16 +11,9 @@ tmp/
.env.test.local
.env.production.local
.npmrc
.rpt2_cache
.yarn/*
!.yarn/releases
!.yarn/plugins
.pnp.*
.vscode/
cc-test-reporter
lerna-debug.log*
npm-debug.log*
package-lock.json
tsconfig*buildinfo
yarn-debug.log*
yarn-error.log*
package-lock.json
+1 -1
View File
@@ -1 +1 @@
14
10
-3
View File
@@ -1,3 +0,0 @@
build
coverage
packages
-4
View File
@@ -1,4 +0,0 @@
// Copyright 2017-2021 @polkadot/api authors & contributors
// SPDX-License-Identifier: Apache-2.0
module.exports = require('@polkadot/dev/config/prettier.cjs');
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
-631
View File
File diff suppressed because one or more lines are too long
-13
View File
@@ -1,13 +0,0 @@
enableImmutableInstalls: false
enableProgressBars: false
nodeLinker: node-modules
plugins:
- path: .yarn/plugins/@yarnpkg/plugin-interactive-tools.cjs
spec: "@yarnpkg/plugin-interactive-tools"
- path: .yarn/plugins/@yarnpkg/plugin-version.cjs
spec: "@yarnpkg/plugin-version"
yarnPath: .yarn/releases/yarn-3.0.1.cjs
+34 -2568
View File
File diff suppressed because it is too large Load Diff
+30 -18
View File
@@ -1,30 +1,42 @@
[![polkadotjs](https://img.shields.io/badge/polkadot-js-orange?style=flat-square)](https://polkadot.js.org)
![license](https://img.shields.io/badge/License-Apache%202.0-blue?logo=apache&style=flat-square)
[![npm](https://img.shields.io/npm/v/@polkadot/api?logo=npm&style=flat-square)](https://www.npmjs.com/package/@polkadot/api)
[![beta](https://img.shields.io/npm/v/@polkadot/api/beta?label=beta&logo=npm&&style=flat-square)](https://www.npmjs.com/package/@polkadot/api)
[![maintainability](https://img.shields.io/codeclimate/maintainability-percentage/polkadot-js/api?logo=code-climate&style=flat-square)](https://codeclimate.com/github/polkadot-js/api)
[![coverage](https://img.shields.io/codeclimate/coverage/polkadot-js/api?logo=code-climate&style=flat-square)](https://codeclimate.com/github/polkadot-js/api)
# @plugnet/api
# @polkadot/api
_This repo is a fork of [@polkadot/api](https://github.com/polkadot-js/api), up to the version which works with current plug-node_
This library provides a clean wrapper around all the methods exposed by a Polkadot/Substrate network client and defines all the types exposed by a node. For complete documentation around the classes, interfaces and their use, visit the [documentation portal](https://polkadot.js.org/docs/api/).
If you are an existing user, please be sure to track the [CHANGELOG](CHANGELOG.md) and [UPGRADING](UPGRADING.md) guides when changing versions.
This library provides a clean wrapper around all the methods exposed by a Plugnet/Subtrate network client and defines all the types exposed by a node. For complete documentation around the classes, interfaces and their use, visit the [documentation portal](https://www.poweredbyplug.com/).
## tutorials
Looking for tutorials to get started? Look at [examples](https://polkadot.js.org/docs/api/examples/promise/) for guides on how to use the API to make queries and submit transactions.
Looking for tutorials to get started? Look at [examples](https://www.poweredbyplug.com/) for guides on how to use the API to make queries and submit transactions.
## overview
The API is split up into a number of internal packages -
- [@polkadot/api](packages/api/) The API library, providing both Promise and RxJS Observable-based interfaces. This is the main user-facing entry point.
- [@polkadot/api-derive](packages/api-derive/) Derived results that are injected into the API, allowing for combinations of various query results (only used internally and exposed on the Api instances via `api.derive.*`)
- [@polkadot/metadata](packages/metadata/) Base extrinsic, storage and constant injectors for injection
- [@polkadot/rpc-core](packages/rpc-core/) Wrapper around all [JSON-RPC methods](https://polkadot.js.org/docs/substrate/rpc) exposed by a Polkadot network client
- [@polkadot/rpc-provider](packages/rpc-provider/) Providers for connecting to nodes, including WebSockets and Http
- [@plugnet/api](packages/api/) The API library, providing both Promise and RxJS Observable-based interfaces. This is the main user-facing entry point.
- [@plugnet/api-derive](packages/api-derive/) Derived results that are injected into the API, allowing for combinations of various query results (only used internally and exposed on the Api instances via `api.derive.*`)
- [@plugnet/rpc-core](packages/rpc-core/) Wrapper around all [JSON-RPC methods](https://www.poweredbyplug.com/) exposed by a Plugnet network client
- [@plugnet/rpc-provider](packages/rpc-provider/) Providers for connecting to nodes, including WebSockets and Http
- [@plugnet/rpc-rx](packages/rpc-rx/) A RxJs Observable wrapper around [@plugnet/rpc-provider](packages/rpc-provider)
Type definitions for interfaces as exposed by Polkadot & Substrate clients -
Type definitions for interfaces as exposed by Plugnet & Substrate clients -
- [@polkadot/types](packages/types/) Codecs for all Polkadot and Substrate primitives
- [@plugnet/extrinsics](packages/type-extrinsics/) Base extrinsic definitions & codecs
- [@plugnet/jsonrpc](packages/type-jsonrpc/) Definitions for JSONRPC endpoints
- [@plugnet/storage](packages/type-storage/) Definitions for storage entries
- [@plugnet/types](packages/types/) Codecs for all Plugnet primitives
## development
Contributions are welcome!
To start off, this repo (along with others in the [@plugnet](https://github.com/plugblockchain/) family) uses yarn workspaces to organise the code. As such, after cloning, its dependencies _should_ be installed via `yarn`, not via npm; the latter will result in broken dependencies.
To get started -
1. Clone the repo locally, via `git clone https://github.com/plugblockchain/api.js <optional local path>`
2. Ensure that you have a recent version of Node.js, for development purposes [Node 10](https://nodejs.org/en/) is recommended.
3. Ensure that you have a recent version of Yarn, for development purposes [Yarn >=1.10.1](https://yarnpkg.com/docs/install) is required.
4. Install the dependencies by running `yarn`
5. Build the everything via `yarn run build`
6. You can also launch the API Docs, via `yarn vuepress dev docs`
7. Access the docs via [http://localhost:8080](http://localhost:8080)
-201
View File
@@ -1,201 +0,0 @@
# Upgrade guide
This is an upgrade guide for users of the API. It does not attempt to detail each version (the [CHANGELOG](CHANGELOG.md) has all the changes between versions), but rather tries to explain the rationale behind major breaking changes and how users of the API should handle this.
While we try to keep the user-facing interfaces as stable as possible, sometimes you just need to make additions to move forward and improve things down the road, as painful as they may be. Like you, we are also users of the API, and eat our own dog food - and as such, feel any pains introduced first.
## 0.97.1 (and newer)
The 0.97 series lays the groundwork to allow type registration to be ties to a specific chain and a specific Api instance. In the past, 2 Api instances in the same process would share types, which mean that you could not connect to 2 independent chains with different types. This is very problematic for Polkadot chains, where the idea is to connect to multiple chains.
When using the Api, a new `Registry` will be created on using `new Api(...)` or `Api.create(...)` and this will be transparently passed when creating types. In the cases where you create type instances explicitly or create type classes for injection, you would need to make adjustments.
### Type classes
In a number of instances, developers are creating classes and making these available for interacting with their chains. For instance, an example of a custom type could be -
```js
import { Struct, Text, u32 } from '@polkadot/types';
export class Preferences extends Struct {
constructor (value?: ahy) {
super({
name: Text,
id: u32
}, value);
}
...
}
```
In the current iteration, the underlying `@polkadot/types` bases structures now require a `Registry` to be passed as the first parameter. This means that the above signature would be adjusted to -
```js
// the next import is only required for TypeScript
import { Registry } from '@polkadot/types/types';
import { Struct, Text, u32 } from '@polkadot/types';
export class Preferences extends Struct {
constructor (registry: Registry, value?: ahy) {
super(registry, {
name: Text,
id: u32
}, value);
}
...
}
```
Where the type is used or returned from the API, the `Registry` will be automatically passed to class creation.
### createType
Previously, when creating a type instance such as `BlockNumber`, you would do `api.createType('BlockNumber', <initValue>)`, this is unchanged. In the cases where you directly import from `@polkadot/types`, the following pattern is required -
```js
import { createType } from '@polkadot/types';
...
const blockNumber = createType(api.registry, 'BlockNumber', 12345);
```
In some cases, you would want to explicitly pass a `Registry` interface to the API, instead of relying on it explicitly. This is generally applicable in the cases where you want to use the `createType` independently from the API -
```js
import { ApiPromise } from '@polkadot/api';
import { TypeRegistry, createType } from '@polkadot/types';
...
const registry = new TypeRegistry();
const blockNumber = createType(registry, 'BlockNumber', 12345);
const api = await ApiPromise.create({ registry });
```
### Extrinsic metadata
In some applications, the undocumented `findFunction` has been used to determine the Api has the metadata for a specific extrinsic. The has been exposed on top of `GenericCall`, and it typically used in applications such as signers. Along with the compulsory registry, the above functions have been moved to the `Registry` itself, so if you previously had -
```js
const { meta, method, section } = GenericCall.findFunction(extrinsic.callIndex);
```
You need to change it to -
```js
const { meta, method, section } = registry.findMetaCall(extrinsic.callIndex);
```
## 0.90.1 (and newer), from 0.81.1 (and older)
The 0.90.1 release caters for the [Kusama network](https://kusama.network/) and pulls in all the changes to support [Substrate 2.x](https://github.com/paritytech/substrate), all while maintaining backwards compatibility to allow operation on networks such as [Polkadot's Alexander](https://polkadot.network/).
To support the network and the new transaction formats, a number of changes were made to how extrinsics are handled and signed. In addition, as support for ongoing work where type definitions are to be supplied by the actual node metadata, the foundation has been laid to move to type definitions as opposed to classes for runtime types.
### Modules
The first thing to be aware of is breakages when connecting to any new network, here older networks such as Alex are unaffected - the node metadata defines exactly what is available to the chain, so endpoints that worked yesterday still works today.
There will no doubt be breakages in using calls to now non-existent endpoints (as populated by the metadata) if you are upgrading your nodes to Substrate 2.x. Substrate 2.x has had a number of internal changes, where new modules and features are introduced (such as `babe` and `technicalCommittee`), some modules have been renamed (such as `contract` -> `contracts`) and modules such as `session` has been reworked to a large degree.
To cater for both 1.x and 2.x support, the [@polkadot/api-derive](packages/api-derive) endpoints, do feature detection for the node type and should continue working as-is. Additionally, a number of new derives have been added, specifically around elections.
### Type renames
To better align with the actual types from the metadata, and avoid (too much) context switching, some types from the `@polkadot/types` have been renamed. These include -
- `Vector` -> `Vec`
- `U{8|16|32|64|128|256}` have been removed, only the lowercase version of these remain, i.e. `u32`.
### Type usage
The [@polkadot/api](packages/api) has always handled the conversion of types for parameters when making calls or queries. For example, when making a transfer to `BOB` (address), any of the following is valid -
- `api.tx.balances.transfer(BOB, 12345)` - value specified as a number
- `api.tx.balances.transfer(BOB, '12345')` - value specified as a string
- `api.tx.balances.transfer(BOB, '0x3039')` - value specified as a hex
- `api.tx.balances.transfer(BOB, new BN(12345))` - value specified as a [BN](https://github.com/indutny/bn.js/)
Internally the API will take the input and convert the value into a `Balance`, serialize it using the SCALE codec and transfer it to the node. In some cases users would construct the `Balance` type manually, by importing the class and calling `new` on it. This last approach has now been removed, and where classes are still available (limited reach), discouraged.
First the rationale behind this - in all cases Substrate is very flexible, so while Polkadot (and the Substrate base), define `type Balance = u128`, this can be different between chains. (This also applies to the majority of built-in supported types). As such, type construction should be done via the actual registered types.
```js
// this is applicable everywhere, import the type creator, using the registry
import { createType } from '@polkadot/types';
// construct the Balance, of type Balance (type is inferred and available with TS)
const value = createType('Balance', 12345);
// use value here as you normally would
...
```
The impact of this will be noticeable, if you have been importing the old-style type classes from `@polkadot/types`, those imports are not available anymore. For creation, just pass everything through the `createType`.
If a TypeScript user, you can find the updated type (it is a type definition only, not a class), under `@polkadot/types/interfaces`. To do type casting, using interfaces -
```js
// import the TypeScript runtime interfaces we wish to use
import { Balance, Hash } from '@polkadot/types/interfaces';
// import the primitives we wish to use
import { createType, Compact, Vec, u32 } from '@polkadot/types';
// define an interface we want to use inside our code
interface MyProps {
balance: Compact<Balance>;
changes: Vec<Hash>;
counter?: u32;
}
// assign something to this structure
const props = {
balance: createType('Compact<Balance>', 12345),
changes: createType('Vec<Hash>', []) // empty for now
};
```
### Type definitions
One of the major pain points in working with a custom Substrate node is the definition of types to cater for chains. There are 2 approaches: defining types via a JSON format or extending your own classes in TypeScript (or JS) and injecting these. For the latter category, there are some impacts in the way you define these.
If using JSON definitions, nothing changes, your types are still defined as -
```json
{
"MyStruct": {
"balance": "Compact<Balance>",
"values": "Vec<AccountId>",
"counter": "u32"
}
}
```
For the definition of any structures using the Substrate specific types as classes, some adjustments are needed. Since the base modules types are now not available in classes, however it is needed for definitions, the following approach is encouraged -
```js
// import the ClassOf, it works the same as `createType` (along with type detection)
// and acts as a replacement for the direct import and use of specific classes
import { ClassOf, Struct, u32 } from '@polkadot/types';
export class MyStruct extends Struct {
constructor (value?: any) {
super({
balance: ClassOf('Compact<Balance>'),
values: ClassOf('Vec<AccountId>'),
counter: u32
}, value);
}
}
```
Internally the [@polkadot/types](packages/types) package now only defines classes where there are specific encoding logic applied. For all other types, the definitions are done via a JSON-like format and then the TypeScript definitions are generated from these. (In a world where nodes inject types and the type definitions are not needed, this functionality will be useful to allow TS developers to auto-generate type definitions based on what the node defines.)
### Signing transactions (Signer interface)
For users of the API signer interfaces (such as extensions and mobile signers), the interfaces have undergone some changes to cater for the extrinsic v2 format as defined by Substrate. If you are only supporting current chains (e.g. Alexander), no changes are required, however the old `sign` interface does not support chains such as Kusama, so all users are encouraged to upgrade to the new `signPayload` interface.
This has already been implemented in both the [polkadot-js extension](https://github.com/polkadot-js/extension/blob/5f22f67d558655c605eb6f6beecef6826ed6c159/packages/extension/src/page/Signer.ts#L16v) as well as the [simple single signer](https://github.com/polkadot-js/api/blob/d56905d1b566be6f17eb570ac01448378fc91b67/packages/api/test/util/SingleAccountSigner.ts#L37).
-4
View File
@@ -1,4 +0,0 @@
// Copyright 2017-2021 @polkadot/api authors & contributors
// SPDX-License-Identifier: Apache-2.0
module.exports = require('@polkadot/dev/config/babel-config-cjs.cjs');
+3
View File
@@ -0,0 +1,3 @@
module.exports = {
extends: '@plugnet/dev/config/babel'
};
View File
-12
View File
@@ -1,12 +0,0 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="initial-scale=0.5, maximum-scale=1">
<meta http-equiv="refresh" content="0;URL='https://polkadot.js.org/docs/api/'" />
<title>Redirecting to https://polkadot.js.org/docs/api/</title>
</head>
<body>
Redirecting to <a href="https://polkadot.js.org/docs/api/">https://polkadot.js.org/docs/api/</a>
</body>
</html>
+214
View File
@@ -0,0 +1,214 @@
## Events
Events are emitted for certain operations on the runtime. The following sections describe the events that are part of the default Substrate runtime.
- **[balances](#balances)**
- **[contract](#contract)**
- **[council](#council)**
- **[councilMotions](#councilMotions)**
- **[councilVoting](#councilVoting)**
- **[democracy](#democracy)**
- **[grandpa](#grandpa)**
- **[indices](#indices)**
- **[session](#session)**
- **[staking](#staking)**
- **[sudo](#sudo)**
- **[system](#system)**
- **[treasury](#treasury)**
___
### balances
**NewAccount**(`AccountId`, `Balance`)
- **summary**: A new account was created.
**ReapedAccount**(`AccountId`)
- **summary**: An account was reaped.
**Transfer**(`AccountId`, `AccountId`, `Balance`, `Balance`)
- **summary**: Transfer succeeded (from, to, value, fees).
___
### contract
**CodeStored**(`Hash`)
- **summary**: Code with the specified hash has been stored.
**Dispatched**(`AccountId`, `bool`)
- **summary**: A call was dispatched from the given account. The bool signals whether it was successful execution or not.
**Instantiated**(`AccountId`, `AccountId`)
- **summary**: Contract deployed by address at the specified address.
**ScheduleUpdated**(`u32`)
- **summary**: Triggered when the current schedule is updated.
**Transfer**(`AccountId`, `AccountId`, `Balance`)
- **summary**: Transfer happened `from` to `to` with given `value` as part of a `call` or `create`.
___
### council
**BadReaperSlashed**(`AccountId`)
- **summary**: slashed reaper
**TallyFinalized**(`Vec<AccountId>`, `Vec<AccountId>`)
- **summary**: A tally (for approval votes of council seat(s)) has ended (with one or more new members).
**TallyStarted**(`u32`)
- **summary**: A tally (for approval votes of council seat(s)) has started.
**VoterReaped**(`AccountId`, `AccountId`)
- **summary**: reaped voter, reaper
___
### councilMotions
**Approved**(`Hash`)
- **summary**: A motion was approved by the required threshold.
**Disapproved**(`Hash`)
- **summary**: A motion was not approved by the required threshold.
**Executed**(`Hash`, `bool`)
- **summary**: A motion was executed; `bool` is true if returned without error.
**Proposed**(`AccountId`, `ProposalIndex`, `Hash`, `u32`)
- **summary**: A motion (given hash) has been proposed (by given account) with a threshold (given u32).
**Voted**(`AccountId`, `Hash`, `bool`, `u32`, `u32`)
- **summary**: A motion (given hash) has been voted on by given account, leaving a tally (yes votes and no votes given as u32s respectively).
___
### councilVoting
**TallyCancelation**(`Hash`, `u32`, `u32`, `u32`)
- **summary**: A voting tally has happened for a referendum cancellation vote. Last three are yes, no, abstain counts.
**TallyReferendum**(`Hash`, `u32`, `u32`, `u32`)
- **summary**: A voting tally has happened for a referendum vote. Last three are yes, no, abstain counts.
___
### democracy
**Cancelled**(`ReferendumIndex`)
**Delegated**(`AccountId`, `AccountId`)
**Executed**(`ReferendumIndex`, `bool`)
**NotPassed**(`ReferendumIndex`)
**Passed**(`ReferendumIndex`)
**Proposed**(`PropIndex`, `Balance`)
**Started**(`ReferendumIndex`, `VoteThreshold`)
**Tabled**(`PropIndex`, `Balance`, `Vec<AccountId>`)
**Undelegated**(`AccountId`)
___
### grandpa
**NewAuthorities**(`Vec<(SessionKey,u64)>`)
- **summary**: New authority set has been applied.
___
### indices
**NewAccountIndex**(`AccountId`, `AccountIndex`)
- **summary**: A new account index was assigned. This event is not triggered when an existing index is reassigned to another `AccountId`.
___
### session
**NewSession**(`BlockNumber`)
- **summary**: New session has happened. Note that the argument is the session index, not the block number as the type might suggest.
___
### staking
**OfflineSlash**(`AccountId`, `Balance`)
- **summary**: One validator (and their nominators) has been slashed by the given amount.
**OfflineWarning**(`AccountId`, `u32`)
- **summary**: One validator (and their nominators) has been given a offline-warning (they're still within their grace). The accrued number of slashes is recorded, too.
**Reward**(`Balance`)
- **summary**: All validators have been rewarded by the given balance.
___
### sudo
**KeyChanged**(`AccountId`)
- **summary**: The sudoer just switched identity; the old key is supplied.
**Sudid**(`bool`)
- **summary**: A sudo just took place.
___
### system
**ExtrinsicFailed**()
- **summary**: An extrinsic failed.
**ExtrinsicSuccess**()
- **summary**: An extrinsic completed successfully.
___
### treasury
**Awarded**(`ProposalIndex`, `Balance`, `AccountId`)
- **summary**: Some funds have been allocated.
**Burnt**(`Balance`)
- **summary**: Some of our funds have been burnt.
**Proposed**(`ProposalIndex`)
- **summary**: New proposal.
**Rollover**(`Balance`)
- **summary**: Spending has finished; this is the amount that rolls over until next spend.
**Spending**(`Balance`)
- **summary**: We have ended a spend period and will now allocate funds.
+287
View File
@@ -0,0 +1,287 @@
## Extrinsics
_The following sections contain Extrinsics methods are part of the default Substrate runtime._
- **[balances](#balances)**
- **[consensus](#consensus)**
- **[contract](#contract)**
- **[council](#council)**
- **[councilMotions](#councilMotions)**
- **[councilVoting](#councilVoting)**
- **[democracy](#democracy)**
- **[finalityTracker](#finalityTracker)**
- **[grandpa](#grandpa)**
- **[session](#session)**
- **[staking](#staking)**
- **[sudo](#sudo)**
- **[timestamp](#timestamp)**
- **[treasury](#treasury)**
___
### balances
**setBalance**(who: `Address`, free: `Compact<Balance>`, reserved: `Compact<Balance>`)
- **summary**: Set the balances of a given account. This will alter `FreeBalance` and `ReservedBalance` in storage. If the new free or reserved balance is below the existential deposit, it will also decrease the total issuance of the system (`TotalIssuance`) and reset the account nonce (`system::AccountNonce`). The dispatch origin for this call is `root`.
**transfer**(dest: `Address`, value: `Compact<Balance>`)
- **summary**: Transfer some liquid free balance to another account. `transfer` will set the `FreeBalance` of the sender and receiver. It will decrease the total issuance of the system by the `TransferFee`. If the sender's account is below the existential deposit as a result of the transfer, the account will be reaped. The dispatch origin for this call must be `Signed` by the transactor.
___
### consensus
**killStorage**(keys: `Vec<Key>`)
- **summary**: Kill some items from storage.
**noteOffline**(offline: `InherentOfflineReport`)
- **summary**: Note the previous block's validator missed their opportunity to propose a block.
**remark**(_remark: `Bytes`)
- **summary**: Make some on-chain remark.
**reportMisbehavior**(_report: `Bytes`)
- **summary**: Report some misbehavior.
**setCode**(new: `Bytes`)
- **summary**: Set the new code.
**setHeapPages**(pages: `u64`)
- **summary**: Set the number of pages in the WebAssembly environment's heap.
**setStorage**(items: `Vec<KeyValue>`)
- **summary**: Set some items of storage.
___
### contract
**call**(dest: `Address`, value: `Compact<BalanceOf>`, gas_limit: `Compact<Gas>`, data: `Bytes`)
- **summary**: Makes a call to an account, optionally transferring some balance. * If the account is a smart-contract account, the associated code will be executed and any value will be transferred. * If the account is a regular account, any value will be transferred. * If no account exists and the call value is not less than `existential_deposit`, a regular account will be created and any value will be transferred.
**create**(endowment: `Compact<BalanceOf>`, gas_limit: `Compact<Gas>`, code_hash: `CodeHash`, data: `Bytes`)
- **summary**: Creates a new contract from the `codehash` generated by `put_code`, optionally transferring some balance. Creation is executed as follows: - the destination address is computed based on the sender and hash of the code. - the smart-contract account is created at the computed address. - the `ctor_code` is executed in the context of the newly created account. Buffer returned after the execution is saved as the `code` of the account. That code will be invoked upon any call received by this account. - The contract is initialized.
**putCode**(gas_limit: `Compact<Gas>`, code: `Bytes`)
- **summary**: Stores the given binary Wasm code into the chains storage and returns its `codehash`. You can instantiate contracts only with stored code.
**updateSchedule**(schedule: `Schedule`)
- **summary**: Updates the schedule for metering contracts. The schedule must have a greater version than the stored schedule.
___
### council
**presentWinner**(candidate: `Address`, total: `Compact<BalanceOf>`, index: `Compact<VoteIndex>`)
- **summary**: Claim that `signed` is one of the top Self::carry_count() + current_vote().1 candidates. Only works if the `block_number >= current_vote().0` and `< current_vote().0 + presentation_duration()`` `signed` should have at least
**reapInactiveVoter**(reporter_index: `Compact<u32>`, who: `Address`, who_index: `Compact<u32>`, assumed_vote_index: `Compact<VoteIndex>`)
- **summary**: Remove a voter. For it not to be a bond-consuming no-op, all approved candidate indices must now be either unregistered or registered to a candidate that registered the slot after the voter gave their last approval set. May be called by anyone. Returns the voter deposit to `signed`.
**removeMember**(who: `Address`)
- **summary**: Remove a particular member. A tally will happen instantly (if not already in a presentation period) to fill the seat if removal means that the desired members are not met. This is effective immediately.
**retractVoter**(index: `Compact<u32>`)
- **summary**: Remove a voter. All votes are cancelled and the voter deposit is returned.
**setApprovals**(votes: `Vec<bool>`, index: `Compact<VoteIndex>`)
- **summary**: Set candidate approvals. Approval slots stay valid as long as candidates in those slots are registered.
**setDesiredSeats**(count: `Compact<u32>`)
- **summary**: Set the desired member count; if lower than the current count, then seats will not be up election when they expire. If more, then a new vote will be started if one is not already in progress.
**setPresentationDuration**(count: `Compact<BlockNumber>`)
- **summary**: Set the presentation duration. If there is currently a vote being presented for, will invoke `finalize_vote`.
**setTermDuration**(count: `Compact<BlockNumber>`)
- **summary**: Set the presentation duration. If there is current a vote being presented for, will invoke `finalize_vote`.
**submitCandidacy**(slot: `Compact<u32>`)
- **summary**: Submit oneself for candidacy. Account must have enough transferrable funds in it to pay the bond.
___
### councilMotions
**propose**(threshold: `Compact<u32>`, proposal: `Proposal`)
**vote**(proposal: `Hash`, index: `Compact<ProposalIndex>`, approve: `bool`)
___
### councilVoting
**propose**(proposal: `Proposal`)
**setCooloffPeriod**(blocks: `Compact<BlockNumber>`)
**setVotingPeriod**(blocks: `Compact<BlockNumber>`)
**veto**(proposal_hash: `Hash`)
**vote**(proposal: `Hash`, approve: `bool`)
___
### democracy
**cancelQueued**(when: `Compact<BlockNumber>`, which: `Compact<u32>`)
- **summary**: Cancel a proposal queued for enactment.
**cancelReferendum**(ref_index: `Compact<ReferendumIndex>`)
- **summary**: Remove a referendum.
**delegate**(to: `AccountId`, lock_periods: `LockPeriods`)
- **summary**: Delegate vote.
**propose**(proposal: `Proposal`, value: `Compact<BalanceOf>`)
- **summary**: Propose a sensitive action to be taken.
**second**(proposal: `Compact<PropIndex>`)
- **summary**: Propose a sensitive action to be taken.
**startReferendum**(proposal: `Proposal`, threshold: `VoteThreshold`, delay: `BlockNumber`)
- **summary**: Start a referendum.
**undelegate**()
- **summary**: Undelegate vote.
**vote**(ref_index: `Compact<ReferendumIndex>`, vote: `Vote`)
- **summary**: Vote in a referendum. If `vote.is_aye()`, the vote is to enact the proposal; otherwise it is a vote to keep the status quo.
___
### finalityTracker
**finalHint**(hint: `Compact<BlockNumber>`)
- **summary**: Hint that the author of this block thinks the best finalized block is the given number.
___
### grandpa
**reportMisbehavior**(_report: `Bytes`)
- **summary**: Report some misbehavior.
___
### session
**forceNewSession**(apply_rewards: `bool`)
- **summary**: Forces a new session.
**setKey**(key: `SessionKey`)
- **summary**: Sets the session key of `_validator` to `_key`. This doesn't take effect until the next session.
**setLength**(new: `Compact<BlockNumber>`)
- **summary**: Set a new session length. Won't kick in until the next session change (at current length).
___
### staking
**bond**(controller: `Address`, value: `Compact<BalanceOf>`, payee: `RewardDestination`)
- **summary**: Take the origin account as a stash and lock up `value` of its balance. `controller` will be the account that controls it. The dispatch origin for this call must be _Signed_.
**bondExtra**(max_additional: `Compact<BalanceOf>`)
- **summary**: Add some extra amount that have appeared in the stash `free_balance` into the balance up for staking. Use this if there are additional funds in your stash account that you wish to bond. The dispatch origin for this call must be _Signed_ by the stash, not the controller.
**chill**()
- **summary**: Declare no desire to either validate or nominate. Effects will be felt at the beginning of the next era. The dispatch origin for this call must be _Signed_ by the controller, not the stash.
**forceNewEra**(apply_rewards: `bool`)
- **summary**: Force there to be a new era. This also forces a new session immediately after. `apply_rewards` should be true for validators to get the session reward.
**nominate**(targets: `Vec<Address>`)
- **summary**: Declare the desire to nominate `targets` for the origin controller. Effects will be felt at the beginning of the next era. The dispatch origin for this call must be _Signed_ by the controller, not the stash.
**setBondingDuration**(new: `Compact<BlockNumber>`)
- **summary**: The length of the bonding duration in eras.
**setController**(controller: `Address`)
- **summary**: (Re-)set the payment target for a controller. Effects will be felt at the beginning of the next era. The dispatch origin for this call must be _Signed_ by the stash, not the controller.
**setInvulnerables**(validators: `Vec<AccountId>`)
- **summary**: Set the validators who cannot be slashed (if any).
**setOfflineSlashGrace**(new: `Compact<u32>`)
- **summary**: Set the offline slash grace period.
**setPayee**(payee: `RewardDestination`)
- **summary**: (Re-)set the payment target for a controller. Effects will be felt at the beginning of the next era. The dispatch origin for this call must be _Signed_ by the controller, not the stash.
**setSessionsPerEra**(new: `Compact<BlockNumber>`)
- **summary**: Set the number of sessions in an era.
**setValidatorCount**(new: `Compact<u32>`)
- **summary**: The ideal number of validators.
**unbond**(value: `Compact<BalanceOf>`)
- **summary**: 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. Once the unlock period is done, you can call `withdraw_unbonded` to actually move the funds out of management ready for transfer. The dispatch origin for this call must be _Signed_ by the controller, not the stash. See also [`Call::withdraw_unbonded`].
**validate**(prefs: `ValidatorPrefs`)
- **summary**: Declare the desire to validate for the origin controller. Effects will be felt at the beginning of the next era. The dispatch origin for this call must be _Signed_ by the controller, not the stash.
**withdrawUnbonded**()
- **summary**: Remove any unlocked chunks from the `unlocking` queue from our management. This essentially frees up that balance to be used by the stash account to do whatever it wants. The dispatch origin for this call must be _Signed_ by the controller, not the stash. See also [`Call::unbond`].
___
### sudo
**setKey**(new: `Address`)
**sudo**(proposal: `Proposal`)
___
### timestamp
**set**(now: `Compact<Moment>`)
- **summary**: Set the current time. This call should be invoked exactly once per block. It will panic at the finalization phase, if this call hasn't been invoked by that time. The timestamp should be greater than the previous one by the amount specified by `minimum_period`. The dispatch origin for this call must be `Inherent`.
___
### treasury
**approveProposal**(proposal_id: `Compact<ProposalIndex>`)
- **summary**: Approve a proposal. At a later time, the proposal will be allocated to the beneficiary and the original deposit will be returned.
**configure**(proposal_bond: `Compact<Permill>`, proposal_bond_minimum: `Compact<BalanceOf>`, spend_period: `Compact<BlockNumber>`, burn: `Compact<Permill>`)
- **summary**: (Re-)configure this module.
**proposeSpend**(value: `Compact<BalanceOf>`, beneficiary: `Address`)
- **summary**: Put forward a suggestion for spending. A deposit proportional to the value is reserved and slashed if the proposal is rejected. It is returned once the proposal is awarded.
**rejectProposal**(proposal_id: `Compact<ProposalIndex>`)
- **summary**: Reject a proposed spend. The original deposit will be slashed.
**setPot**(new_pot: `Compact<BalanceOf>`)
- **summary**: Set the balance of funds available to spend.
+117
View File
@@ -0,0 +1,117 @@
## 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._
- **[author](#author)**
- **[chain](#chain)**
- **[state](#state)**
- **[system](#system)**
___
### author
_Authoring of network items_
**pendingExtrinsics**(): `PendingExtrinsics`
- **summary**: Returns all pending extrinsics, potentially grouped by sender
**submitAndWatchExtrinsic**(extrinsic: `Extrinsic`): `ExtrinsicStatus`
- **summary**: Subscribe and watch an extrinsic until unsubscribed
**submitExtrinsic**(extrinsic: `Extrinsic`): `Hash`
- **summary**: Submit a fully formatted extrinsic for block inclusion
___
### chain
_Retrieval of chain data_
**getBlock**(hash?: `Hash`): `SignedBlock`
- **summary**: Get header and body of a relay chain block
**getBlockHash**(blockNumber?: `BlockNumber`): `Hash`
- **summary**: Get the block hash for a specific block
**getFinalizedHead**(): `Hash`
- **summary**: Get hash of the last finalised block in the canon chain
**getHeader**(hash?: `Hash`): `Header`
- **summary**: Retrieves the header for a specific block
**getRuntimeVersion**(hash?: `Hash`): `RuntimeVersion`
- **summary**: Get the runtime version (alias of state_getRuntimeVersion)
**subscribeFinalizedHeads**(): `Header`
- **summary**: Retrieves the best finalized header via subscription
**subscribeNewHead**(): `Header`
- **summary**: Retrieves the best header via subscription
**subscribeRuntimeVersion**(): `RuntimeVersion`
- **summary**: Retrieves the runtime version via subscription
___
### state
_Query of state_
**call**(method: `Text`, data: `Bytes`, block?: `Hash`): `Bytes`
- **summary**: Perform a call to a builtin on the chain
**getMetadata**(block?: `Hash`): `Metadata`
- **summary**: Returns the runtime metadata
**getRuntimeVersion**(hash?: `Hash`): `RuntimeVersion`
- **summary**: Get the runtime version
**getStorage**(key: `StorageKey`, block?: `Hash`): `StorageData`
- **summary**: Retrieves the storage for a key
**getStorageHash**(key: `StorageKey`, block?: `Hash`): `Hash`
- **summary**: Retrieves the storage hash
**getStorageSize**(key: `StorageKey`, block?: `Hash`): `u64`
- **summary**: Retrieves the storage size
**queryStorage**(keys: `Vec<StorageKey>`, startBlock: `Hash`, block?: `Hash`): `Vec<StorageChangeSet>`
- **summary**: Query historical storage entries (by key) starting from a start block
**subscribeStorage**(keys: `Vec<StorageKey>`): `StorageChangeSet`
- **summary**: Subscribes to storage changes for the provided keys
___
### system
_Methods to retrieve system info_
**chain**(): `Text`
- **summary**: Retrieves the chain
**health**(): `Health`
- **summary**: Return health status of the node
**name**(): `Text`
- **summary**: Retrieves the node name
**networkState**(): `NetworkState`
- **summary**: Returns current state of the network
**peers**(): `Vec<PeerInfo>`
- **summary**: Returns the currently connected peers
**properties**(): `ChainProperties`
- **summary**: Get a custom set of properties as a JSON object, defined in the chain spec
**version**(): `Text`
- **summary**: Retrieves the version of the node
+529
View File
@@ -0,0 +1,529 @@
## Storage
_The following sections contain Storage methods are part of the default Substrate runtime._
- **[balances](#balances)**
- **[consensus](#consensus)**
- **[contract](#contract)**
- **[council](#council)**
- **[councilMotions](#councilMotions)**
- **[councilVoting](#councilVoting)**
- **[democracy](#democracy)**
- **[grandpaFinality](#grandpaFinality)**
- **[indices](#indices)**
- **[session](#session)**
- **[staking](#staking)**
- **[sudo](#sudo)**
- **[system](#system)**
- **[timestamp](#timestamp)**
- **[treasury](#treasury)**
- **[substrate](#substrate)**
___
### balances
**creationFee**(): `Balance`
- **summary**: The fee required to create an account.
**existentialDeposit**(): `Balance`
- **summary**: The minimum amount required to keep an account open.
**freeBalance**(`AccountId`): `Balance`
- **summary**: The 'free' balance of a given account. This is the only balance that matters in terms of most operations on tokens. It alone is used to determine the balance when in the contract execution environment. When this balance falls below the value of `ExistentialDeposit`, then the 'current account' is deleted: specifically `FreeBalance`. Further, the `OnFreeBalanceZero` callback is invoked, giving a chance to external modules to clean up data associated with the deleted account. `system::AccountNonce` is also deleted if `ReservedBalance` is also zero (it also gets collapsed to zero if it ever becomes less than `ExistentialDeposit`.
**locks**(`AccountId`): `Vec<BalanceLock>`
- **summary**: Any liquidity locks on some account balances.
**reservedBalance**(`AccountId`): `Balance`
- **summary**: The amount of the balance of a given account that is externally reserved; this can still get slashed, but gets slashed last of all. This balance is a 'reserve' balance that other subsystems use in order to set aside tokens that are still 'owned' by the account holder, but which are suspendable. When this balance falls below the value of `ExistentialDeposit`, then this 'reserve account' is deleted: specifically, `ReservedBalance`. `system::AccountNonce` is also deleted if `FreeBalance` is also zero (it also gets collapsed to zero if it ever becomes less than `ExistentialDeposit`.)
**totalIssuance**(): `Balance`
- **summary**: The total units issued in the system.
**transactionBaseFee**(): `Balance`
- **summary**: The fee to be paid for making a transaction; the base.
**transactionByteFee**(): `Balance`
- **summary**: The fee to be paid for making a transaction; the per-byte portion.
**transferFee**(): `Balance`
- **summary**: The fee required to make a transfer.
**vesting**(`AccountId`): `Option<VestingSchedule>`
- **summary**: Information regarding the vesting of a given account.
___
### consensus
**originalAuthorities**(): `Option<Vec<SessionKey>>`
___
### contract
**accountCounter**(): `u64`
- **summary**: The subtrie counter
**accountInfoOf**(`AccountId`): `Option<AccountInfo>`
- **summary**: The code associated with a given account.
**blockGasLimit**(): `Gas`
- **summary**: The maximum amount of gas that could be expended per block.
**callBaseFee**(): `Gas`
- **summary**: The base fee charged for calling into a contract.
**codeHashOf**(`AccountId`): `Option<CodeHash>`
- **summary**: The code associated with a given account.
**codeStorage**(`CodeHash`): `Option<PrefabWasmModule>`
- **summary**: A mapping between an original code hash and instrumented wasm code, ready for the execution.
**contractFee**(): `BalanceOf`
- **summary**: The fee required to create a contract instance.
**createBaseFee**(): `Gas`
- **summary**: The base fee charged for creating a contract.
**creationFee**(): `BalanceOf`
- **summary**: The fee required to create an account.
**currentSchedule**(): `Schedule`
- **summary**: Current cost schedule for contracts.
**gasPrice**(): `BalanceOf`
- **summary**: The price of one unit of gas.
**gasSpent**(): `Gas`
- **summary**: Gas spent so far in this block.
**maxDepth**(): `u32`
- **summary**: The maximum nesting level of a call/create stack.
**pristineCode**(`CodeHash`): `Option<Bytes>`
- **summary**: A mapping from an original code hash to the original code, untouched by instrumentation.
**transactionBaseFee**(): `BalanceOf`
- **summary**: The fee to be paid for making a transaction; the base.
**transactionByteFee**(): `BalanceOf`
- **summary**: The fee to be paid for making a transaction; the per-byte portion.
**transferFee**(): `BalanceOf`
- **summary**: The fee required to make a transfer.
___
### council
**activeCouncil**(): `Vec<(AccountId,BlockNumber)>`
- **summary**: The current council. When there's a vote going on, this should still be used for executive matters. The block number (second element in the tuple) is the block that their position is active until (calculated by the sum of the block number when the council member was elected and their term duration).
**approvalsOf**(`AccountId`): `Vec<bool>`
- **summary**: A list of votes for each voter, respecting the last cleared vote index that this voter was last active at.
**candidacyBond**(): `BalanceOf`
- **summary**: How much should be locked up in order to submit one's candidacy.
**candidateCount**(): `u32`
**candidates**(): `Vec<AccountId>`
- **summary**: The present candidate list.
**carryCount**(): `u32`
- **summary**: How many runners-up should have their approvals persist until the next vote.
**desiredSeats**(): `u32`
- **summary**: Number of accounts that should be sitting on the council.
**inactiveGracePeriod**(): `VoteIndex`
- **summary**: How many vote indexes need to go by after a target voter's last vote before they can be reaped if their approvals are moot.
**lastActiveOf**(`AccountId`): `Option<VoteIndex>`
- **summary**: The last cleared vote index that this voter was last active at.
**leaderboard**(): `Option<Vec<(BalanceOf,AccountId)>>`
- **summary**: Get the leaderboard if we;re in the presentation phase.
**nextFinalize**(): `Option<(BlockNumber,u32,Vec<AccountId>)>`
- **summary**: The accounts holding the seats that will become free on the next tally.
**presentSlashPerVoter**(): `BalanceOf`
- **summary**: The punishment, per voter, if you provide an invalid presentation.
**presentationDuration**(): `BlockNumber`
- **summary**: How long to give each top candidate to present themselves after the vote ends.
**registerInfoOf**(`AccountId`): `Option<(VoteIndex,u32)>`
- **summary**: The vote index and list slot that the candidate `who` was registered or `None` if they are not currently registered.
**snapshotedStakes**(): `Vec<BalanceOf>`
- **summary**: The stakes as they were at the point that the vote ended.
**termDuration**(): `BlockNumber`
- **summary**: How long each position is active for.
**voteCount**(): `VoteIndex`
- **summary**: The total number of votes that have happened or are in progress.
**voters**(): `Vec<AccountId>`
- **summary**: The present voter list.
**votingBond**(): `BalanceOf`
- **summary**: How much should be locked up in order to be able to submit votes.
**votingPeriod**(): `BlockNumber`
- **summary**: How often (in blocks) to check for new votes.
___
### councilMotions
**proposalCount**(): `u32`
- **summary**: Proposals so far.
**proposalOf**(`Hash`): `Option<Proposal>`
- **summary**: Actual proposal for a given hash, if it's current.
**proposals**(): `Vec<Hash>`
- **summary**: The (hashes of) the active proposals.
**voting**(`Hash`): `Option<(ProposalIndex,u32,Vec<AccountId>,Vec<AccountId>)>`
- **summary**: Votes for a given proposal: (required_yes_votes, yes_voters, no_voters).
___
### councilVoting
**cooloffPeriod**(): `BlockNumber`
**councilVoteOf**(`(Hash,AccountId)`): `Option<bool>`
**enactDelayPeriod**(): `BlockNumber`
- **summary**: Number of blocks by which to delay enactment of successful, non-unanimous-council-instigated referendum proposals.
**proposalOf**(`Hash`): `Option<Proposal>`
**proposalVoters**(`Hash`): `Vec<AccountId>`
**proposals**(): `Vec<(BlockNumber,Hash)>`
**vetoedProposal**(`Hash`): `Option<(BlockNumber,Vec<AccountId>)>`
**votingPeriod**(): `BlockNumber`
___
### democracy
**delegations**(`AccountId`): `((AccountId,LockPeriods), Linkage<AccountId>)`
- **summary**: Get the account (and lock periods) to which another account is delegating vote.
**depositOf**(`PropIndex`): `Option<(BalanceOf,Vec<AccountId>)>`
- **summary**: Those who have locked a deposit.
**dispatchQueue**(`BlockNumber`): `Vec<Option<(Proposal,ReferendumIndex)>>`
- **summary**: Queue of successful referenda to be dispatched.
**launchPeriod**(): `BlockNumber`
- **summary**: How often (in blocks) new public referenda are launched.
**maxLockPeriods**(): `LockPeriods`
- **summary**: The maximum number of additional lock periods a voter may offer to strengthen their vote. Multiples of `PublicDelay`.
**minimumDeposit**(): `BalanceOf`
- **summary**: The minimum amount to be used as a deposit for a public referendum proposal.
**nextTally**(): `ReferendumIndex`
- **summary**: The next referendum index that should be tallied.
**publicDelay**(): `BlockNumber`
- **summary**: The delay before enactment for all public referenda.
**publicPropCount**(): `PropIndex`
- **summary**: The number of (public) proposals that have been made so far.
**publicProps**(): `Vec<(PropIndex,Proposal,AccountId)>`
- **summary**: The public proposals. Unsorted.
**referendumCount**(): `ReferendumIndex`
- **summary**: The next free referendum index, aka the number of referendums started so far.
**referendumInfoOf**(`ReferendumIndex`): `Option<ReferendumInfo>`
- **summary**: Information concerning any given referendum.
**voteOf**(`(ReferendumIndex,AccountId)`): `Vote`
- **summary**: Get the vote in a given referendum of a particular voter. The result is meaningful only if `voters_for` includes the voter when called with the referendum (you'll get the default `Vote` value otherwise). If you don't want to check `voters_for`, then you can also check for simple existence with `VoteOf::exists` first.
**votersFor**(`ReferendumIndex`): `Vec<AccountId>`
- **summary**: Get the voters for the current proposal.
**votingPeriod**(): `BlockNumber`
- **summary**: How often (in blocks) to check for new votes.
___
### grandpaFinality
**nextForced**(): `Option<BlockNumber>`
**pendingChange**(): `Option<StoredPendingChange>`
___
### indices
**enumSet**(`AccountIndex`): `Vec<AccountId>`
- **summary**: The enumeration sets.
**nextEnumSet**(): `AccountIndex`
- **summary**: The next free enumeration set.
___
### session
**currentIndex**(): `BlockNumber`
- **summary**: Current index of the session.
**currentStart**(): `Moment`
- **summary**: Timestamp when current session started.
**forcingNewSession**(): `Option<bool>`
- **summary**: New session is being forced is this entry exists; in which case, the boolean value is whether the new session should be considered a normal rotation (rewardable) or exceptional (slashable).
**lastLengthChange**(): `Option<BlockNumber>`
- **summary**: Block at which the session length last changed.
**nextKeyFor**(`AccountId`): `Option<SessionKey>`
- **summary**: The next key for a given validator.
**nextSessionLength**(): `Option<BlockNumber>`
- **summary**: The next session length.
**sessionLength**(): `BlockNumber`
- **summary**: Current length of the session.
**validators**(): `Vec<AccountId>`
- **summary**: The current set of validators.
___
### staking
**bonded**(`AccountId`): `Option<AccountId>`
- **summary**: Map from all locked "stash" accounts to the controller account.
**bondingDuration**(): `BlockNumber`
- **summary**: The length of the bonding duration in blocks.
**currentElected**(): `Vec<AccountId>`
- **summary**: The currently elected validator set keyed by stash account ID.
**currentEra**(): `BlockNumber`
- **summary**: The current era index.
**currentEraReward**(): `BalanceOf`
- **summary**: The accumulated reward for the current era. Reset to zero at the beginning of the era and increased for every successfully finished session.
**currentSessionReward**(): `BalanceOf`
- **summary**: Maximum reward, per validator, that is provided per acceptable session.
**forcingNewEra**(): `Option<Null>`
- **summary**: We are forcing a new era.
**invulnerables**(): `Vec<AccountId>`
- **summary**: Any validators that may never be slashed or forcibly kicked. It's a Vec since they're easy to initialize and the performance hit is minimal (we expect no more than four invulnerables) and restricted to testnets.
**lastEraLengthChange**(): `BlockNumber`
- **summary**: The session index at which the era length last changed.
**ledger**(`AccountId`): `Option<StakingLedger>`
- **summary**: Map from all (unlocked) "controller" accounts to the info regarding the staking.
**minimumValidatorCount**(): `u32`
- **summary**: Minimum number of staking participants before emergency conditions are imposed.
**nextSessionsPerEra**(): `Option<BlockNumber>`
- **summary**: The next value of sessions per era.
**nominators**(`AccountId`): `(Vec<AccountId>, Linkage<AccountId>)`
- **summary**: The map from nominator stash key to the set of stash keys of all validators to nominate.
**offlineSlash**(): `Perbill`
- **summary**: Slash, per validator that is taken for the first time they are found to be offline.
**offlineSlashGrace**(): `u32`
- **summary**: Number of instances of offline reports before slashing begins for validators.
**payee**(`AccountId`): `RewardDestination`
- **summary**: Where the reward payment should be made. Keyed by stash.
**recentlyOffline**(): `Vec<(AccountId,BlockNumber,u32)>`
- **summary**: Most recent `RECENT_OFFLINE_COUNT` instances. (who it was, when it was reported, how many instances they were offline for).
**sessionReward**(): `Perbill`
- **summary**: Maximum reward, per validator, that is provided per acceptable session.
**sessionsPerEra**(): `BlockNumber`
- **summary**: The length of a staking era in sessions.
**slashCount**(`AccountId`): `u32`
- **summary**: The number of times a given validator has been reported offline. This gets decremented by one each era that passes.
**slotStake**(): `BalanceOf`
- **summary**: The amount of balance actively at stake for each validator slot, currently. This is used to derive rewards and punishments.
**stakers**(`AccountId`): `Exposure`
- **summary**: Nominators for a particular account that is in action right now. You can't iterate through validators here, but you can find them in the `sessions` module. This is keyed by the stash account.
**validatorCount**(): `u32`
- **summary**: The ideal number of staking participants.
**validators**(`AccountId`): `(ValidatorPrefs, Linkage<AccountId>)`
- **summary**: The map from (wannabe) validator stash key to the preferences of that validator.
___
### sudo
**key**(): `AccountId`
___
### system
**accountNonce**(`AccountId`): `Index`
- **summary**: Extrinsics nonce for accounts.
**allExtrinsicsLen**(): `Option<u32>`
- **summary**: Total length in bytes for all extrinsics put together, for the current block.
**blockHash**(`BlockNumber`): `Hash`
- **summary**: Map of block numbers to block hashes.
**digest**(): `Digest`
- **summary**: Digest of the current block, also part of the block header.
**events**(): `Vec<EventRecord>`
- **summary**: Events deposited for the current block.
**extrinsicCount**(): `Option<u32>`
- **summary**: Total extrinsics count for the current block.
**extrinsicData**(`u32`): `Bytes`
- **summary**: Extrinsics data for the current block (maps extrinsic's index to its data).
**extrinsicsRoot**(): `Hash`
- **summary**: Extrinsics root of the current block, also part of the block header.
**number**(): `BlockNumber`
- **summary**: The current block number being processed. Set by `execute_block`.
**parentHash**(): `Hash`
- **summary**: Hash of the previous block.
**randomSeed**(): `Hash`
- **summary**: Random seed of the current block.
___
### timestamp
**blockPeriod**(): `Option<Moment>`
- **summary**: Old storage item provided for compatibility. Remove after all networks upgraded.
**didUpdate**(): `bool`
- **summary**: Did the timestamp get updated in this block?
**minimumPeriod**(): `Moment`
- **summary**: 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 work with this to determine a sensible block time. e.g. For Aura, it will be double this period on default settings.
**now**(): `Moment`
- **summary**: Current time for the current block.
___
### treasury
**approvals**(): `Vec<ProposalIndex>`
- **summary**: Proposal indices that have been approved but not yet awarded.
**burn**(): `Permill`
- **summary**: Percentage of spare funds (if any) that are burnt per spend period.
**pot**(): `BalanceOf`
- **summary**: Total funds available to this module for spending.
**proposalBond**(): `Permill`
- **summary**: Proportion of funds that should be bonded in order to place a proposal. An accepted proposal gets these back. A rejected proposal doesn't.
**proposalBondMinimum**(): `BalanceOf`
- **summary**: Minimum amount of funds that should be placed in a deposit for making a proposal.
**proposalCount**(): `ProposalIndex`
- **summary**: Number of proposals that have been made.
**proposals**(`ProposalIndex`): `Option<TreasuryProposal>`
- **summary**: Proposals that have been made.
**spendPeriod**(): `BlockNumber`
- **summary**: Period between successive spends.
---
### substrate
_These are keys that are always available to the runtime implementation_
**authorityCount**(): `u32`
- **summary**: Number of authorities.
**authorityPrefix**(): `u32`
- **summary**: Prefix under which authorities are stored.
**changesTrieConfig**(): `u32`
- **summary**: Changes trie configuration is stored under this key.
**code**(): `Bytes`
- **summary**: Wasm code of the runtime.
**extrinsicIndex**(): `u32`
- **summary**: Current extrinsic index (u32) is stored under this key.
**heapPages**(): `u64`
- **summary**: Number of wasm linear memory pages required for execution of the runtime.
---
+1
View File
@@ -0,0 +1 @@
yarn.lock
@@ -0,0 +1,5 @@
# Simple Connect
The following example shows how to instantiate a Plugnet API object and use it to connect to a node using ApiPromise.
<<< @/docs/examples/promise/01_simple_connect/index.js
+22
View File
@@ -0,0 +1,22 @@
// @ts-check
// Required imports
const { ApiPromise, WsProvider } = require('@plugnet/api');
async function main () {
// Initialise the provider to connect to the local node
const provider = new WsProvider('ws://127.0.0.1:9944');
// Create the API and wait until ready
const api = await ApiPromise.create(provider);
// Retrieve the chain & node information information via rpc calls
const [chain, nodeName, nodeVersion] = await Promise.all([
api.rpc.system.chain(),
api.rpc.system.name(),
api.rpc.system.version()
]);
console.log(`You are connected to chain ${chain} using ${nodeName} v${nodeVersion}`);
}
main().catch(console.error).finally(() => process.exit());
@@ -0,0 +1,19 @@
{
"name": "01_simple_connect",
"version": "0.2.0",
"description": "Example showing how to connect using a WebSocket",
"main": "index.js",
"author": "chevdor",
"license": "MIT",
"scripts": {
"clean": "rimraf node_modules",
"start": "node index.js"
},
"dependencies": {
"@plugnet/api": "^0.76.102"
},
"devDependencies": {
"rimraf": "^2.6.2"
}
}
@@ -0,0 +1,8 @@
# Listen to new blocks
This example shows how to subscribe to new blocks.
It displays the block number every time a new block is seen by the node you are connected to.
NOTE: The example runs until you stop it with CTRL+C
<<< @/docs/examples/promise/02_listen_to_blocks/index.js
+19
View File
@@ -0,0 +1,19 @@
// @ts-check
// Import the API
const { ApiPromise } = require('@plugnet/api');
async function main () {
// Here we don't pass the (optional) provider, connecting directly to the default
// node/port, i.e. `ws://127.0.0.1:9944`. Await for the isReady promise to ensure
// the API has connected to the node and completed the initialisation process
const api = await ApiPromise.create();
// Subscribe to the new headers on-chain. The callback is fired when new headers
// are found, the call itself returns a promise with a subscription that can be
// used to unsubscribe from the newHead subscription
const unsubscribe = await api.rpc.chain.subscribeNewHead((header) => {
console.log(`Chain is at block: #${header.blockNumber}`);
});
}
main().catch(console.error);
@@ -0,0 +1,18 @@
{
"name": "02_listen_to_blocks",
"version": "0.2.0",
"description": "Example showing how to use subscriptions",
"main": "index.js",
"author": "chevdor",
"license": "MIT",
"scripts": {
"clean": "rimraf node_modules",
"start": "node index.js"
},
"dependencies": {
"@plugnet/api": "^0.76.102"
},
"devDependencies": {
"rimraf": "^2.6.2"
}
}
@@ -0,0 +1,5 @@
# Listen to balance changes
This example shows how to instantiate a Plugnet API object and use it to connect to a node and retrieve balance updates.
<<< @/docs/examples/promise/03_listen_to_balance_change/index.js
+33
View File
@@ -0,0 +1,33 @@
// @ts-check
// Import the API
const { ApiPromise } = require('@plugnet/api');
// Known account we want to use (available on dev chain, with funds)
const Alice = '5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY';
async function main () {
// Create an await for the API
const api = await ApiPromise.create();
// Retrieve the initial balance. Since the call has no callback, it is simply a promise
// that resolves to the current on-chain value
let previous = await api.query.balances.freeBalance(Alice);
console.log(`${Alice} has a balance of ${previous}`);
console.log(`You may leave this example running and start example 06 or transfer any value to ${Alice}`);
// Here we subscribe to any balance changes and update the on-screen value
api.query.balances.freeBalance(Alice, (current) => {
// Calculate the delta
const change = current.sub(previous);
// Only display positive value changes (Since we are pulling `previous` above already,
// the initial balance change will also be zero)
if (!change.isZero()) {
previous = current;
console.log(`New balance change of: ${change}`);
}
});
}
main().catch(console.error);
@@ -0,0 +1,18 @@
{
"name": "03_listen_to_balance_change",
"version": "0.2.0",
"description": "Example showing how to subscribe to balance change",
"main": "index.js",
"author": "chevdor",
"license": "MIT",
"scripts": {
"clean": "rimraf node_modules",
"start": "node index.js"
},
"dependencies": {
"@plugnet/api": "^0.76.102"
},
"devDependencies": {
"rimraf": "^2.6.2"
}
}
@@ -0,0 +1,7 @@
# Unsubscribe from listening to updates
This example shows how to subscribe to and later unsubscribe from listening to block updates.
In this example we're calling the built-in unsubscribe() function after a timeOut of 20s to cleanup and unsubscribe from listening to updates.
<<< @/docs/examples/promise/04_unsubscribe/index.js
@@ -0,0 +1,23 @@
// @ts-check
// Import the API
const { ApiPromise } = require('@plugnet/api');
async function main () {
// Create a new instance of the api
const api = await ApiPromise.create();
// Subscribe to chain updates and log the current block number on update.
const unsubscribe = await api.rpc.chain.subscribeNewHead((header) => {
console.log(`Chain is at block: #${header.blockNumber}`);
});
// In this example we're calling the unsubscribe() function that is being
// returned by the api call function after 20s.
setTimeout(() => {
unsubscribe();
console.log('Unsubscribed')
}, 20000);
}
main().catch(console.error);
@@ -0,0 +1,18 @@
{
"name": "04_unsubscribe",
"version": "0.2.0",
"description": "Example showing how to unsubscribe from a subscription",
"main": "index.js",
"author": "Stefie",
"license": "MIT",
"scripts": {
"clean": "rimraf node_modules",
"start": "node index.js"
},
"dependencies": {
"@plugnet/api": "^0.76.102"
},
"devDependencies": {
"rimraf": "^2.6.2"
}
}
@@ -0,0 +1,5 @@
# Read storage
Many important variables are available through the storage API. This example shows how to call a few of those APIs.
<<< @/docs/examples/promise/05_read_storage/index.js
+38
View File
@@ -0,0 +1,38 @@
// @ts-check
// Import the API
const { ApiPromise } = require('@plugnet/api');
// Our address for Alice on the dev chain
const Alice = '5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY';
async function main () {
// Create our API with a default connection to the local node
const api = await ApiPromise.create();
// Make our basic chain state/storage queries, all in one go
const [accountNonce, blockPeriod, validators] = await Promise.all([
api.query.system.accountNonce(Alice),
api.query.timestamp.blockPeriod(),
api.query.session.validators()
]);
console.log(`accountNonce(${Alice}) ${accountNonce}`);
console.log(`blockPeriod ${blockPeriod.toNumber()} seconds`);
if (validators && validators.length > 0) {
// Retrieve the balances for all validators
const validatorBalances = await Promise.all(
validators.map(authorityId =>
api.query.balances.freeBalance(authorityId)
)
);
// Print out the authorityIds and balances of all validators
console.log('validators', validators.map((authorityId, index) => ({
address: authorityId.toString(),
balance: validatorBalances[index].toString()
})));
}
}
main().catch(console.error).finally(_ => process.exit());
@@ -0,0 +1,18 @@
{
"name": "05_read_storage",
"version": "0.2.0",
"description": "Example showing how to query storage",
"main": "index.js",
"author": "chevdor",
"license": "MIT",
"scripts": {
"clean": "rimraf node_modules",
"start": "node index.js"
},
"dependencies": {
"@plugnet/api": "^0.76.102"
},
"devDependencies": {
"rimraf": "^2.6.2"
}
}
@@ -0,0 +1,5 @@
# Make a simple transfer
This sample shows how to create a transaction to make a transfer from one an account to another.
<<< @/docs/examples/promise/06_make_transfer/index.js
+27
View File
@@ -0,0 +1,27 @@
// @ts-check
// Import the API, Keyring and some utility functions
const { ApiPromise } = require('@plugnet/api');
const { Keyring } = require('@plugnet/keyring');
const BOB = '5FHneW46xGXgs5mUiveU4sbTyGBzmstUspZC92UhjJM694ty';
async function main () {
// Instantiate the API
const api = await ApiPromise.create();
// Constuct the keying after the API (crypto has an async init)
const keyring = new Keyring({ type: 'sr25519' });
// Add alice to our keyring with a hard-deived path (empty phrase, so uses dev)
const alice = keyring.addFromUri('//Alice');
// Create a extrinsic, transferring 12345 units to Bob
const transfer = api.tx.balances.transfer(BOB, 12345);
// Sign and send the transaction using our account
const hash = await transfer.signAndSend(alice);
console.log('Transfer sent with hash', hash.toHex());
}
main().catch(console.error).finally(() => process.exit());
@@ -0,0 +1,18 @@
{
"name": "06_make_transfer",
"version": "0.2.0",
"description": "Example showing how to make a transfer",
"main": "index.js",
"author": "chevdor",
"license": "MIT",
"scripts": {
"clean": "rimraf node_modules",
"start": "node index.js"
},
"dependencies": {
"@plugnet/api": "^0.76.102"
},
"devDependencies": {
"rimraf": "^2.6.2"
}
}
@@ -0,0 +1,5 @@
# Traverse events
Query the system events and extract information from them. This example runs until exited via Ctrl-C
<<< @/docs/examples/promise/08_system_events/index.js
+34
View File
@@ -0,0 +1,34 @@
// @ts-check
// Import the API
const { ApiPromise } = require('@plugnet/api');
async function main () {
// Create our API with a default connection to the local node
const api = await ApiPromise.create();
// subscribe to system events via storage
api.query.system.events((events) => {
console.log(`\nReceived ${events.length} events:`);
// loop through the Vec<EventRecord>
events.forEach((record) => {
// extract the phase, event and the event types
const { event, phase } = record;
const types = event.typeDef;
// show what we are busy with
console.log(`\t${event.section}:${event.method}:: (phase=${phase.toString()})`);
console.log(`\t\t${event.meta.documentation.toString()}`);
// loop through each of the parameters, displaying the type and data
event.data.forEach((data, index) => {
console.log(`\t\t\t${types[index].type}: ${data.toString()}`);
});
});
});
}
main().catch((error) => {
console.error(error);
process.exit(-1);
});
@@ -0,0 +1,18 @@
{
"name": "08_system_events",
"version": "0.1.0",
"description": "Example showing how to query and parse events",
"main": "index.js",
"author": "Jaco Greeff <jacogr@gmail.com>",
"license": "MIT",
"scripts": {
"clean": "rimraf node_modules",
"start": "node index.js"
},
"dependencies": {
"@plugnet/api": "^0.76.102"
},
"devDependencies": {
"rimraf": "^2.6.2"
}
}
@@ -0,0 +1,5 @@
# Transfer events
Display the events that occur during a transfer by sending a value to a random account
<<< @/docs/examples/promise/09_transfer_events/index.js
+55
View File
@@ -0,0 +1,55 @@
// @ts-check
// Import the API & Provider and some utility functions
const { ApiPromise } = require('@plugnet/api');
// import the test keyring (already has dev keys for Alice, Bob, Charlie, Eve & Ferdie)
const testKeyring = require('@plugnet/keyring/testing');
// utility function for random values
const { randomAsU8a } = require('@plugnet/util-crypto');
// some constants we are using in this sample
const ALICE = '5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY';
const AMOUNT = 10000;
async function main () {
// Create the API and wait until ready
const api = await ApiPromise.create();
// create an instance of our testing keyring
// If you're using ES6 module imports instead of require, just change this line to:
// const keyring = testKeyring();
const keyring = testKeyring.default();
// get the nonce for the admin key
const nonce = await api.query.system.accountNonce(ALICE);
// find the actual keypair in the keyring
const alicePair = keyring.getPair(ALICE);
// create a new random recipient
const recipient = keyring.addFromSeed(randomAsU8a(32)).address();
console.log('Sending', AMOUNT, 'from', alicePair.address(), 'to', recipient, 'with nonce', nonce.toString());
// Do the transfer and track the actual status
api.tx.balances
.transfer(recipient, AMOUNT)
.sign(alicePair, { nonce })
.send(({ events = [], status }) => {
console.log('Transaction status:', status.type);
if (status.isFinalized) {
console.log('Completed at block hash', status.asFinalized.toHex());
console.log('Events:');
events.forEach(({ phase, event: { data, method, section } }) => {
console.log('\t', phase.toString(), `: ${section}.${method}`, data.toString());
});
process.exit(0);
}
});
}
main().catch(console.error);
@@ -0,0 +1,18 @@
{
"name": "09_transfer_events",
"version": "0.1.0",
"description": "Example showing how to transfer DOTs (with events)",
"main": "index.js",
"author": "Jaco Greeff <jacogr@gmail.com>",
"license": "MIT",
"scripts": {
"clean": "rimraf node_modules",
"start": "node index.js"
},
"dependencies": {
"@plugnet/api": "^0.76.102"
},
"devDependencies": {
"rimraf": "^2.6.2"
}
}
@@ -0,0 +1,5 @@
# Chain upgrade
Performs a chain upgrade using the `sudo` module. This may brick your chain, so us it as an educational sample. (use `substrate --dev purge-chain` to remove DB and recover).
<<< @/docs/examples/promise/10_upgrade_chain/index.js
+56
View File
@@ -0,0 +1,56 @@
// @ts-check
// Import the API & Provider and some utility functions
const { ApiPromise, WsProvider } = require('@plugnet/api');
// import the test keyring (already has dev keys for Alice, Bob, Charlie, Eve & Ferdie)
const testKeyring = require('@plugnet/keyring/testing');
const fs = require('fs');
async function main () {
// Initialise the provider to connect to the local node
const provider = new WsProvider('ws://127.0.0.1:9944');
// Create the API and wait until ready (optional provider passed through)
const api = await ApiPromise.create(provider);
// retrieve the upgrade key from the chain state
const adminId = await api.query.sudo.key();
// find the actual keypair in the keyring (if this is an changed value, the key
// needs to be added to the keyring before - this assumes we have defaults, i.e.
// Alice as the key - and this already exists on the test keyring)
const keyring = testKeyring.default();
const adminPair = keyring.getPair(adminId.toString());
// retrieve the runtime to upgrade to
const code = fs.readFileSync('./test.wasm').toString('hex');
const proposal = api.tx.consensus.setCode(`0x${code}`);
console.log(`Upgrading from ${adminId}, ${code.length / 2} bytes`);
// preform the actual chain upgrade via the sudo module
api.tx.sudo
.sudo(proposal)
.signAndSend(adminPair, ({ events = [], status }) => {
console.log('Proposal status:', status.type);
if (status.isFinalized) {
console.error('You have just upgraded your chain');
console.log('Completed at block hash', status.asFinalized.toHex());
console.log('Events:');
events.forEach(({ phase, event: { data, method, section } }) => {
console.log('\t', phase.toString(), `: ${section}.${method}`, data.toString());
});
process.exit(0);
}
});
}
main().catch((error) => {
console.error(error);
process.exit(-1);
});
@@ -0,0 +1,18 @@
{
"name": "10_upgrade_chain",
"version": "0.2.0",
"description": "Example showing how to upgrade via upgradeKey",
"main": "index.js",
"author": "Jaco Greeff <jacogr@gmail.com>",
"license": "MIT",
"scripts": {
"clean": "rimraf node_modules",
"start": "node index.js"
},
"dependencies": {
"@plugnet/api": "^0.76.102"
},
"devDependencies": {
"rimraf": "^2.6.2"
}
}
Binary file not shown.
+26
View File
@@ -0,0 +1,26 @@
# ApiPromise Examples
Here you will find a list of examples that takes you through the basics of connecting to a local node, retrieving data from the Node and chain and execute transactions on the chain. It uses the [[ApiPromise]] interface.
## Prerequisites
For the following examples, you need a local node. It is usually convenient testing with:
```
substrate --dev
```
## Running the examples
From each folder, run `yarn` to install the required dependencies and then run `yarn start` to execute the example against the running node.
## Development accounts
Some of the examples use the following accounts:
- Alice: `5GoKvZWG5ZPYL1WUovuHW3zJBWBP5eT8CbqjdRY4Q6iMaDtZ`
- Bob: `5Gw3s7q4QLkSWwknsiPtjujPv3XM4Trxi5d4PgKMMk3gfGTE`
Those accounts are easy to add if you don't have/see them. The seed of Alice's account is `Alice␣␣␣␣␣␣␣␣␣␣␣␣␣␣␣␣␣␣␣␣␣␣␣␣␣␣␣` and the seed of Bob is... well you guess...
NOTE: Note the spaces padding Alice's key up to 32 chars.
@@ -0,0 +1,5 @@
# Simple Connect
The following example shows how to instantiate a Plugnet API object and use it to connect to a node using ApiRx.
<<< @/docs/examples/rx/01_simple_connect/index.js
@@ -0,0 +1,26 @@
// Required imports
const { zip } = require('rxjs');
const { ApiRx } = require('@plugnet/api');
const { WsProvider } = require('@plugnet/rpc-provider');
function main () {
// Initialise the provider to connect to the local node
const provider = new WsProvider('ws://127.0.0.1:9944');
// Create the API and wait until ready
const api = await ApiRx.create(provider).toPromise();
// We're using RxJs 'zip()' combination operator to get the emitted values
// of multiple observables as an array
zip(
api.rpc.system.chain(),
api.rpc.system.name(),
api.rpc.system.version()
)
// Then we subscribe to the result
.subscribe(([chain, nodeName, nodeVersion]) => {
console.log(`You are connected to chain ${chain} using ${nodeName} v${nodeVersion}`);
});
}
main().catch(console.error).finally(() => process.exit());
@@ -0,0 +1,19 @@
{
"name": "rx_01_simple_connect",
"version": "0.2.0",
"description": "Example showing how to connect using a WebSocket",
"main": "index.js",
"author": "Stefie",
"license": "MIT",
"scripts": {
"clean": "rimraf node_modules",
"start": "node index.js"
},
"dependencies": {
"@plugnet/api": "^0.76.102"
},
"devDependencies": {
"rimraf": "^2.6.2"
}
}
@@ -0,0 +1,9 @@
# Listen to new blocks
This example shows how to subscribe to new blocks.
It displays the block number every time a new block is seen by the node you are connected to.
NOTE: The example runs until you stop it with CTRL+C
<<< @/docs/examples/rx/02_listen_to_blocks/index.js
@@ -0,0 +1,19 @@
// Import the API
const { ApiRx } = require('@plugnet/api');
const { switchMap } = require('rxjs/operators');
async function main () {
// Here we don't pass the (optional) provider, connecting directly to the default
// node/port, i.e. `ws://127.0.0.1:9944`. Await for the isReady promise to ensure
// the API has connected to the node and completed the initialisation process
new ApiRx().isReady
.pipe(
switchMap((api) =>
api.rpc.chain.subscribeNewHead()
))
.subscribe((header) => {
console.log(`Chain is at block: #${header.blockNumber}`);
});
}
main().catch(console.error);
@@ -0,0 +1,18 @@
{
"name": "rx_02_listen_to_blocks",
"version": "0.2.0",
"description": "Example showing how to use subscriptions",
"main": "index.js",
"author": "Stefie",
"license": "MIT",
"scripts": {
"clean": "rimraf node_modules",
"start": "node index.js"
},
"dependencies": {
"@plugnet/api": "^0.76.102"
},
"devDependencies": {
"rimraf": "^2.6.2"
}
}
@@ -0,0 +1,5 @@
# Listen to balance changes
This example shows how to instantiate a Plugnet API object and use it to connect to a node and retrieve balance updates.
<<< @/docs/examples/rx/03_listent_to_balance_change/index.js
@@ -0,0 +1,38 @@
// Import the API and operators from RxJs
const { ApiRx } = require('@plugnet/api');
const { pairwise, startWith } = require('rxjs/operators');
// Known account we want to use (available on dev chain, with funds)
const Alice = '5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY';
async function main () {
// Create an await for the API
const api = await ApiRx.create().toPromise();
// Here we subscribe to any balance changes and update the on-screen value.
// We're using RxJs pairwise() operator to get the previous and current values as an array.
api.query.balances.freeBalance(Alice)
.pipe(
// since pairwise only starts emitting values on the second emission, we prepend an
// initial value with the startWith() operator to be able to also receive the first value
startWith('first'),
pairwise()
)
.subscribe((balance) => {
if (balance[0] === 'first') {
// Now we know that if the previous value emitted as balance[0] is `first`,
// then balance[1] is the initial value of Alice account.
console.log(`Alice ${Alice} has a balance of ${balance[1]}`);
console.log('You may leave this example running and start the "Make a transfer" example or transfer any value to Alice address');
return;
}
const change = balance[1].sub(balance[0]);
// Only display value changes
if (!change.isZero()) {
console.log(`New balance change of: ${change}`);
}
});
}
main().catch(console.error);
@@ -0,0 +1,18 @@
{
"name": "rx_03_listen_to_balance_change",
"version": "0.2.0",
"description": "Example showing how to subscribe to balance change",
"main": "index.js",
"author": "Stefie",
"license": "MIT",
"scripts": {
"clean": "rimraf node_modules",
"start": "node index.js"
},
"dependencies": {
"@plugnet/api": "^0.76.102"
},
"devDependencies": {
"rimraf": "^2.6.2"
}
}
@@ -0,0 +1,7 @@
# Unsubscribe from listening to updates
This example shows how to subscribe to and later unsubscribe from listening to block updates.
In this example we're calling the built-in unsubscribe() function after a timeOut of 20s to cleanup and unsubscribe from listening to updates.
<<< @/docs/examples/rx/04_unsubscribe/index.js
+25
View File
@@ -0,0 +1,25 @@
// Import the API
const { ApiRx } = require('@plugnet/api');
const { switchMap } = require('rxjs/operators');
async function main () {
// Create a new instance of the api
// Subscribe to chain updates and log the current block number on update.
const subscription = new ApiRx().isReady
.pipe(
switchMap((api) =>
api.rpc.chain.subscribeNewHead()
))
.subscribe((header) => {
console.log(`Chain is at block: #${header.blockNumber}`);
});
// In this example we're calling the Overvables unsubscribe() //
// function after 20s.
setTimeout(() => {
subscription.unsubscribe();
console.log('Unsubscribed');
}, 20000);
}
main().catch(console.error);
@@ -0,0 +1,18 @@
{
"name": "rx_04_unsubscribe",
"version": "0.2.0",
"description": "Example showing how to unsubscribe from a subscription",
"main": "index.js",
"author": "Stefie",
"license": "MIT",
"scripts": {
"clean": "rimraf node_modules",
"start": "node index.js"
},
"dependencies": {
"@plugnet/api": "^0.76.102"
},
"devDependencies": {
"rimraf": "^2.6.2"
}
}
@@ -0,0 +1,5 @@
# Read storage
Many important variables are available through the storage API. This example shows how to call a few of those APIs.
<<< @/docs/examples/rx/05_read_storage/index.js
+51
View File
@@ -0,0 +1,51 @@
// Import the API
const { ApiRx } = require('@plugnet/api');
// Import dependencies from RxJs
const { combineLatest, of } = require('rxjs');
const { first, switchMap } = require('rxjs/operators');
// Our address for Alice on the dev chain
const Alice = '5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY';
function main () {
// Create our API with a default connection to the local node
new ApiRx(provider).isReady
.pipe(
// Here we ake our basic chain state/storage queries
switchMap((api) => combineLatest(
of(api),
api.query.session.validators().pipe(first())
)),
switchMap(([api, validators]) => {
// In the next step, we're checking if the node has active validators.
// If it does, we're making another call to the api to get the balances for all validators
const balances = (validators && validators.length > 0)
? combineLatest(validators.map(authorityId => api.query.balances.freeBalance(authorityId).pipe(first())))
: of(null);
// We're combining the results together with the emitted value 'validators',
// which we're turning back into an observable using of()
return combineLatest(
api.query.system.accountNonce(Alice).pipe(first()),
api.query.timestamp.blockPeriod().pipe(first()),
of(validators),
balances
);
})
)
// Then we're subscribing to the emitted results
.subscribe(([accountNonce, blockPeriod, validators, validatorBalances]) => {
console.log(`accountNonce(${Alice}) ${accountNonce}`);
console.log(`blockPeriod ${blockPeriod.toNumber()} seconds`);
if (validatorBalances) {
// And lastly we print out the authorityIds and balances of all validators
console.log('validators', validators.map((authorityId, index) => ({
address: authorityId.toString(),
balance: validatorBalances[index].toString()
})));
}
});
}
main().catch(console.error).finally(_ => process.exit());
@@ -0,0 +1,18 @@
{
"name": "rx_05_read_storage",
"version": "0.2.0",
"description": "Example showing how to query storage",
"main": "index.js",
"author": "Stefie",
"license": "MIT",
"scripts": {
"clean": "rimraf node_modules",
"start": "node index.js"
},
"dependencies": {
"@plugnet/api": "^0.76.102"
},
"devDependencies": {
"rimraf": "^2.6.2"
}
}
@@ -0,0 +1,5 @@
# Make a simple transfer
This sample shows how to create a transaction to make a transfer from one an account to another.
<<< @/docs/examples/rx/06_make_transfer/index.js
@@ -0,0 +1,33 @@
// Import the API, Keyring and some utility functions
const { ApiRx } = require('@plugnet/api');
const { Keyring } = require('@plugnet/keyring');
const BOB = '5FHneW46xGXgs5mUiveU4sbTyGBzmstUspZC92UhjJM694ty';
async function main () {
// Instantiate the API
const api = await ApiRx.create().toPromise();
// Create an instance of the keyring
const keyring = new Keyring({ type: 's25519' });
// Add Alice to our keyring (with the known seed for the account)
const alice = keyring.addFomUri('//Alice');
// Create a extrinsic, transferring 12345 units to Bob.
api.tx.balances
// create transfer
.transfer(BOB, randomAmount)
// Sign and send the transcation
.signAndSend(alice)
// Subscribe to the status updates of the transfer
.subscribe(({ status }) => {
if (status.isFinalized) {
console.log(`Successful transfer of 12345 from Alice to Bob with hash ${status.asFinalized.toHex()}`);
} else {
console.log(`Staus of transfer: ${status.type}`);
}
});
}
main().catch(console.error).finally(_ => process.exit());
@@ -0,0 +1,18 @@
{
"name": "rx_06_make_transfer",
"version": "0.2.0",
"description": "Example showing how to make a transfer",
"main": "index.js",
"author": "Stefie",
"license": "MIT",
"scripts": {
"clean": "rimraf node_modules",
"start": "node index.js"
},
"dependencies": {
"@plugnet/api": "^0.76.102"
},
"devDependencies": {
"rimraf": "^2.6.2"
}
}
@@ -0,0 +1,5 @@
# Traverse events
Query the system events and extract information from them. This example runs until exited via Ctrl-C
<<< @/docs/examples/rx/08_system_events/index.js
@@ -0,0 +1,37 @@
// Import the API and selected RxJs operators
const { switchMap } = require('rxjs/operators');
const { ApiRx } = require('@plugnet/api');
async function main () {
// Create our API with a default connection to the local node
ApiRx.create()
.pipe(
switchMap((api) =>
// subscribe to system events via storage
api.query.system.events()
))
// Then we're subscribing to the emitted results
.subscribe((events) => {
console.log(`\nReceived ${events.length} events:`);
// loop through the Vec<EventRecord>
events.forEach((record) => {
// extract the phase, event and the event types
const { event, phase } = record;
const types = event.typeDef;
// show what we are busy with
console.log(`\t${event.section}:${event.method}:: (phase=${phase.toString()})`);
console.log(`\t\t${event.meta.documentation.toString()}`);
// loop through each of the parameters, displaying the type and data
event.data.forEach((data, index) => {
console.log(`\t\t\t${types[index].type}: ${data.toString()}`);
});
});
});
};
main().catch((error) => {
console.error(error);
process.exit(-1);
});
@@ -0,0 +1,18 @@
{
"name": "rx_08_system_events",
"version": "0.1.0",
"description": "Example showing how to query and parse events",
"main": "index.js",
"author": "Stefie",
"license": "MIT",
"scripts": {
"clean": "rimraf node_modules",
"start": "node index.js"
},
"dependencies": {
"@plugnet/api": "^0.76.102"
},
"devDependencies": {
"rimraf": "^2.6.2"
}
}
@@ -0,0 +1,5 @@
# Transfer events
Display the events that occur during a transfer by sending a value to a random account
<<< @/docs/examples/rx/09_transfer_events/index.js
@@ -0,0 +1,55 @@
// Import the API and some utility functions
const { ApiRx } = require('@plugnet/api');
// import the test keyring (already has dev keys for Alice, Bob, Charlie, Eve & Ferdie)
const testKeyring = require('@plugnet/keyring/testing');
// utility function for random values
const { randomAsU8a } = require('@plugnet/util-crypto');
// some constants we are using in this sample
const ALICE = '5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY';
const AMOUNT = 10000;
async function main () {
// Create our API with a connection to the node
const api = await ApiRx.create().toPromise();
// create an instance of our testign keyring
// If you're using ES6 module imports instead of require, just change this line to:
// const keyring = testKeyring();
const keyring = testKeyring.default();
// find the actual keypair in the keyring
const alicePair = keyring.getPair(ALICE);
// create a new random recipient
const recipient = keyring.addFromSeed(randomAsU8a(32)).address();
console.log('Sending', AMOUNT, 'from', alicePair.address(), 'to', recipient);
// get the nonce for the admin key
// Create a extrinsic, transferring 12345 units to Bob.
api.tx.balances
// Do the transfer
.transfer(recipient, AMOUNT)
// Sign and send it
.signAndSend(alicePair)
// And subscribe to the actual status
.subscribe(({ events = [], status }) => {
// Log transfer events
console.log('Transfer status:', status.type);
// Log system events once the transfer is finalised
if (status.isFinalized) {
console.log('Completed at block hash', status.asFinalized.toHex());
console.log('Events:');
events.forEach(({ phase, event: { data, method, section } }) => {
console.log('\t', phase.toString(), `: ${section}.${method}`, data.toString());
});
}
});
}
main().catch(console.error);
@@ -0,0 +1,18 @@
{
"name": "rx_09_transfer_events",
"version": "0.1.0",
"description": "Example showing how to transfer DOTs (with events)",
"main": "index.js",
"author": "Stefie",
"license": "MIT",
"scripts": {
"clean": "rimraf node_modules",
"start": "node index.js"
},
"dependencies": {
"@plugnet/api": "^0.76.102"
},
"devDependencies": {
"rimraf": "^2.6.2"
}
}
@@ -0,0 +1,5 @@
# Chain upgrade
Performs a chain upgrade using the `sudo` module. This may brick your chain, so us it as an educational sample. (use `substrate --dev purge-chain` to remove DB and recover).
<<< @/docs/examples/rx/10_upgrade_chain/index.js
@@ -0,0 +1,58 @@
// Import the API & Provider and some utility functions
const { ApiRx, WsPovider } = require('@plugnet/api');
// import the test keyring (already has dev keys for Alice, Bob, Charlie, Eve & Ferdie)
const testKeyring = require('@plugnet/keyring/testing');
const fs = require('fs');
async function main () {
// Initialise the provider to connect to the local node
const provider = new WsProvider('ws://127.0.0.1:9944');
// Create the API and wait until ready (optional provider passed through)
const api = await ApiRx.create(provider).toPromise();
// retrieve the upgrade key from the chain state
const adminId = await api.query.sudo.key().toPromise();
// find the actual keypair in the keyring (if this is an changed value, the key
// needs to be added to the keyring before - this assumes we have defaults, i.e.
// Alice as the key - and this already exists on the test keyring)
const keyring = testKeyring.default();
const adminPair = keyring.getPair(adminId.toString());
// retrieve the runtime to upgrade to
const code = fs.readFileSync('./test.wasm').toString('hex');
const proposal = api.tx.consensus.setCode(`0x${code}`);
console.log(`Upgrading chain runtime from ${adminId}`);
api.tx.sudo
// preform the actual chain upgrade via the sudo module
.sudo(proposal)
// sign and send the proposal
.signAndSend(adminPair)
// subscribe to overall result
.subscribe(({ events = [], status }) => {
// Log transfer events
console.log('Proposal status:', status.type);
if (status.isFinalized) {
console.error('You have just upgraded your chain');
console.log('Completed at block hash', status.asFinalized.toHex());
console.log('Events:');
// Log system events once the chain update is finalised
events.forEach(({ phase, event: { data, method, section } }) => {
console.log('\t', phase.toString(), `: ${section}.${method}`, data.toString());
});
process.exit(0);
}
});
}
main().catch((error) => {
console.error(error);
process.exit(-1);
});
@@ -0,0 +1,18 @@
{
"name": "rx_10_upgrade_chain",
"version": "0.2.0",
"description": "Example showing how to upgrade via upgradeKey",
"main": "index.js",
"author": "Stefie",
"license": "MIT",
"scripts": {
"clean": "rimraf node_modules",
"start": "node index.js"
},
"dependencies": {
"@plugnet/api": "^0.76.102"
},
"devDependencies": {
"rimraf": "^2.6.2"
}
}
Binary file not shown.
+26
View File
@@ -0,0 +1,26 @@
# ApiRx Examples
Here you will find a list of examples that takes you through the basics of connecting to a local node, retrieving data from the Node and chain and execute transactions on the chain. It uses the [[ApiRx]] interface.
## Prerequisites
For the following examples, you need a local node. It is usually convenient testing with:
```
substrate --dev
```
## Running the examples
From each folder, run `yarn` to install the required dependencies and then run `yarn start` to execute the example against the running node.
## Development accounts
Some of the examples use the following accounts:
- Alice: `5GoKvZWG5ZPYL1WUovuHW3zJBWBP5eT8CbqjdRY4Q6iMaDtZ`
- Bob: `5Gw3s7q4QLkSWwknsiPtjujPv3XM4Trxi5d4PgKMMk3gfGTE`
Those accounts are easy to add if you don't have/see them. The seed of Alice's account is `Alice␣␣␣␣␣␣␣␣␣␣␣␣␣␣␣␣␣␣␣␣␣␣␣␣␣␣␣` and the seed of Bob is... well you guess...
NOTE: Note the spaces padding Alice's key up to 32 chars.
-12
View File
@@ -1,12 +0,0 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="initial-scale=0.5, maximum-scale=1">
<meta http-equiv="refresh" content="0;URL='https://polkadot.js.org/docs/api/'" />
<title>Redirecting to https://polkadot.js.org/docs/api/</title>
</head>
<body>
Redirecting to <a href="https://polkadot.js.org/docs/api/">https://polkadot.js.org/docs/api/</a>
</body>
</html>
-19
View File
@@ -1,19 +0,0 @@
// Copyright 2017-2021 @polkadot/api authors & contributors
// SPDX-License-Identifier: Apache-2.0
const config = require('@polkadot/dev/config/jest.cjs');
module.exports = {
...config,
moduleNameMapper: {
'@polkadot/api-(augment|base|contract|derive)(.*)$': '<rootDir>/packages/api-$1/src/$2',
// eslint-disable-next-line sort-keys
'@polkadot/api(.*)$': '<rootDir>/packages/api/src/$1',
'@polkadot/rpc-(augment|core|provider)(.*)$': '<rootDir>/packages/rpc-$1/src/$2',
'@polkadot/typegen(.*)$': '<rootDir>/packages/typegen/src/$1',
'@polkadot/types-(augment|codec|create|known|support)(.*)$': '<rootDir>/packages/types-$1/src/$2',
// eslint-disable-next-line sort-keys
'@polkadot/types(.*)$': '<rootDir>/packages/types/src/$1'
},
testTimeout: 30000
};
+24
View File
@@ -0,0 +1,24 @@
const config = require('@plugnet/dev/config/jest');
module.exports = Object.assign({}, config, {
moduleNameMapper: {
'@plugnet/api-derive(.*)$': '<rootDir>/packages/api-derive/src/$1',
'@plugnet/api(.*)$': '<rootDir>/packages/api/src/$1',
'@plugnet/rpc-(core|provider|rx)(.*)$': '<rootDir>/packages/rpc-$1/src/$2',
'@plugnet/extrinsics(.*)$': '<rootDir>/packages/type-extrinsics/src/$1',
'@plugnet/jsonrpc(.*)$': '<rootDir>/packages/type-jsonrpc/src/$1',
'@plugnet/storage(.*)$': '<rootDir>/packages/type-storage/src/$1',
'@plugnet/types(.*)$': '<rootDir>/packages/types/src/$1'
},
modulePathIgnorePatterns: [
'<rootDir>/packages/api/build',
'<rootDir>/packages/api-derive/build',
'<rootDir>/packages/rpc-core/build',
'<rootDir>/packages/rpc-provider/build',
'<rootDir>/packages/rpc-rx/build',
'<rootDir>/packages/type-extrinsics/build',
'<rootDir>/packages/type-jsonrpc/build',
'<rootDir>/packages/type-storage/build/',
'<rootDir>/packages/types/build'
]
});
+13
View File
@@ -0,0 +1,13 @@
{
"npmClient": "yarn",
"useWorkspaces": true,
"command": {
"publish": {
"allowBranch": "master"
}
},
"packages": [
"packages/*"
],
"version": "0.78.103"
}
+22 -35
View File
@@ -1,46 +1,33 @@
{
"author": "Jaco Greeff <jacogr@gmail.com>",
"bugs": "https://github.com/polkadot-js/api/issues",
"homepage": "https://github.com/polkadot-js/api#readme",
"license": "Apache-2",
"packageManager": "yarn@3.0.1",
"version": "0.0.0",
"private": true,
"repository": {
"type": "git",
"url": "https://github.com/polkadot-js/api.git"
"engines": {
"node": ">=10.13.0",
"yarn": "^1.10.1"
},
"sideEffects": false,
"type": "commonjs",
"version": "7.0.1",
"workspaces": [
"packages/*"
],
"resolutions": {
"babel-core": "^7.0.0-bridge.0",
"typescript": "~3.4.5"
},
"scripts": {
"build": "yarn build:interfaces && polkadot-dev-build-ts",
"build:extra": "(cd packages/typegen && copyfiles scripts/* build)",
"build:interfaces": "polkadot-types-internal-interfaces",
"build:release": "polkadot-ci-ghact-build",
"build:rollup": "polkadot-exec-rollup --config",
"chain:info": "polkadot-types-chain-info",
"clean": "polkadot-dev-clean-build",
"docs:metadata": "polkadot-types-internal-metadata",
"lint": "polkadot-dev-run-lint",
"postinstall": "polkadot-dev-yarn-only",
"test": "polkadot-dev-run-test --coverage --forceExit --runInBand --testPathIgnorePatterns e2e",
"test:one": "polkadot-dev-run-test --detectOpenHandles --forceExit",
"test:watch": "polkadot-dev-run-test --watch"
"build": "plugnet-dev-build-ts && yarn run build:methodsdoc",
"build:htmldoc": "yarn clean && typedoc --theme default --out docs/html",
"build:methodsdoc": "node packages/types/src/scripts/MetadataMdWrapper.js",
"check": "yarn lint",
"lint": "tslint --project . && tsc --noEmit --pretty",
"clean": "plugnet-dev-clean-build",
"postinstall": "plugnet-dev-yarn-only",
"test": "jest --coverage"
},
"devDependencies": {
"@babel/core": "^7.16.5",
"@babel/register": "^7.16.5",
"@babel/runtime": "^7.16.5",
"@polkadot/dev": "^0.64.8",
"@polkadot/ts": "^0.4.20",
"@polkadot/typegen": "workspace:packages/typegen",
"@types/jest": "^27.0.3",
"copyfiles": "^2.4.1"
},
"resolutions": {
"typescript": "^4.5.3"
"@babel/core": "^7.4.4",
"@babel/register": "^7.4.4",
"@babel/runtime": "^7.4.4",
"@plugnet/dev": "^0.30.4",
"@polkadot/ts": "^0.1.56",
"gh-pages": "^2.0.1"
}
}
-3
View File
@@ -1,3 +0,0 @@
# @polkadot/api-augment
Generated augmentation.
-34
View File
@@ -1,34 +0,0 @@
{
"author": "Jaco Greeff <jacogr@gmail.com>",
"bugs": "https://github.com/polkadot-js/api/issues",
"contributors": [],
"description": "API generated augmentation",
"engines": {
"node": ">=14.0.0"
},
"homepage": "https://github.com/polkadot-js/api/tree/master/packages/api-augment#readme",
"license": "Apache-2.0",
"maintainers": [],
"name": "@polkadot/api-augment",
"repository": {
"directory": "packages/api-augment",
"type": "git",
"url": "https://github.com/polkadot-js/api.git"
},
"sideEffects": [
"./detectPackage.js",
"./detectPackage.cjs"
],
"type": "module",
"version": "7.0.1",
"main": "index.js",
"dependencies": {
"@babel/runtime": "^7.16.5",
"@polkadot/api-base": "7.0.1",
"@polkadot/rpc-augment": "7.0.1",
"@polkadot/types": "7.0.1",
"@polkadot/types-augment": "7.0.1",
"@polkadot/types-codec": "7.0.1",
"@polkadot/util": "^8.2.2"
}
}
-954
View File
@@ -1,954 +0,0 @@
// Auto-generated via `yarn polkadot-types-from-chain`, do not edit
/* eslint-disable */
import type { ApiTypes } from '@polkadot/api-base/types';
import type { U8aFixed, Vec, bool, u128, u16, u32, u64, u8 } from '@polkadot/types-codec';
import type { Codec } from '@polkadot/types-codec/types';
import type { Perbill, Percent, Permill } from '@polkadot/types/interfaces/runtime';
import type { FrameSupportPalletId, FrameSupportWeightsRuntimeDbWeight, FrameSupportWeightsWeightToFeeCoefficient, FrameSystemLimitsBlockLength, FrameSystemLimitsBlockWeights, PalletContractsSchedule, SpVersionRuntimeVersion } from '@polkadot/types/lookup';
declare module '@polkadot/api-base/types/consts' {
export interface AugmentedConsts<ApiType extends ApiTypes> {
assets: {
/**
* The amount of funds that must be reserved when creating a new approval.
**/
approvalDeposit: u128 & AugmentedConst<ApiType>;
/**
* The basic amount of funds that must be reserved for an asset.
**/
assetDeposit: u128 & AugmentedConst<ApiType>;
/**
* The basic amount of funds that must be reserved when adding metadata to your asset.
**/
metadataDepositBase: u128 & AugmentedConst<ApiType>;
/**
* The additional funds that must be reserved for the number of bytes you store in your
* metadata.
**/
metadataDepositPerByte: u128 & AugmentedConst<ApiType>;
/**
* The maximum length of a name or symbol stored on-chain.
**/
stringLimit: u32 & AugmentedConst<ApiType>;
/**
* Generic const
**/
[key: string]: Codec;
};
authorship: {
/**
* The number of blocks back we should accept uncles.
* This means that we will deal with uncle-parents that are
* `UncleGenerations + 1` before `now`.
**/
uncleGenerations: u32 & AugmentedConst<ApiType>;
/**
* Generic const
**/
[key: string]: Codec;
};
babe: {
/**
* The amount of time, in slots, that each epoch should last.
* NOTE: Currently it is not possible to change the epoch duration after
* the chain has started. Attempting to do so will brick block production.
**/
epochDuration: u64 & AugmentedConst<ApiType>;
/**
* The expected average block time at which BABE should be creating
* blocks. Since BABE is probabilistic it is not trivial to figure out
* what the expected average block time should be based on the slot
* duration and the security parameter `c` (where `1 - c` represents
* the probability of a slot being empty).
**/
expectedBlockTime: u64 & AugmentedConst<ApiType>;
/**
* Max number of authorities allowed
**/
maxAuthorities: u32 & AugmentedConst<ApiType>;
/**
* Generic const
**/
[key: string]: Codec;
};
bagsList: {
/**
* The list of thresholds separating the various bags.
*
* Ids are separated into unsorted bags according to their vote weight. This specifies the
* thresholds separating the bags. An id's bag is the largest bag for which the id's weight
* is less than or equal to its upper threshold.
*
* When ids are iterated, higher bags are iterated completely before lower bags. This means
* that iteration is _semi-sorted_: ids of higher weight tend to come before ids of lower
* weight, but peer ids within a particular bag are sorted in insertion order.
*
* # Expressing the constant
*
* This constant must be sorted in strictly increasing order. Duplicate items are not
* permitted.
*
* There is an implied upper limit of `VoteWeight::MAX`; that value does not need to be
* specified within the bag. For any two threshold lists, if one ends with
* `VoteWeight::MAX`, the other one does not, and they are otherwise equal, the two lists
* will behave identically.
*
* # Calculation
*
* It is recommended to generate the set of thresholds in a geometric series, such that
* there exists some constant ratio such that `threshold[k + 1] == (threshold[k] *
* constant_ratio).max(threshold[k] + 1)` for all `k`.
*
* The helpers in the `/utils/frame/generate-bags` module can simplify this calculation.
*
* # Examples
*
* - If `BagThresholds::get().is_empty()`, then all ids are put into the same bag, and
* iteration is strictly in insertion order.
* - If `BagThresholds::get().len() == 64`, and the thresholds are determined according to
* the procedure given above, then the constant ratio is equal to 2.
* - If `BagThresholds::get().len() == 200`, and the thresholds are determined according to
* the procedure given above, then the constant ratio is approximately equal to 1.248.
* - If the threshold list begins `[1, 2, 3, ...]`, then an id with weight 0 or 1 will fall
* into bag 0, an id with weight 2 will fall into bag 1, etc.
*
* # Migration
*
* In the event that this list ever changes, a copy of the old bags list must be retained.
* With that `List::migrate` can be called, which will perform the appropriate migration.
**/
bagThresholds: Vec<u64> & AugmentedConst<ApiType>;
/**
* Generic const
**/
[key: string]: Codec;
};
balances: {
/**
* The minimum amount required to keep an account open.
**/
existentialDeposit: u128 & AugmentedConst<ApiType>;
/**
* The maximum number of locks that should exist on an account.
* Not strictly enforced, but used for weight estimation.
**/
maxLocks: u32 & AugmentedConst<ApiType>;
/**
* The maximum number of named reserves that can exist on an account.
**/
maxReserves: u32 & AugmentedConst<ApiType>;
/**
* Generic const
**/
[key: string]: Codec;
};
bounties: {
/**
* Percentage of the curator fee that will be reserved upfront as deposit for bounty
* curator.
**/
bountyCuratorDeposit: Permill & AugmentedConst<ApiType>;
/**
* The amount held on deposit for placing a bounty proposal.
**/
bountyDepositBase: u128 & AugmentedConst<ApiType>;
/**
* The delay period for which a bounty beneficiary need to wait before claim the payout.
**/
bountyDepositPayoutDelay: u32 & AugmentedConst<ApiType>;
/**
* Bounty duration in blocks.
**/
bountyUpdatePeriod: u32 & AugmentedConst<ApiType>;
/**
* Minimum value for a bounty.
**/
bountyValueMinimum: u128 & AugmentedConst<ApiType>;
/**
* The amount held on deposit per byte within the tip report reason or bounty description.
**/
dataDepositPerByte: u128 & AugmentedConst<ApiType>;
/**
* Maximum acceptable reason length.
*
* Benchmarks depend on this value, be sure to update weights file when changing this value
**/
maximumReasonLength: u32 & AugmentedConst<ApiType>;
/**
* Generic const
**/
[key: string]: Codec;
};
childBounties: {
/**
* Percentage of child-bounty value to be reserved as curator deposit
* when curator fee is zero.
**/
childBountyCuratorDepositBase: Permill & AugmentedConst<ApiType>;
/**
* Minimum value for a child-bounty.
**/
childBountyValueMinimum: u128 & AugmentedConst<ApiType>;
/**
* Maximum number of child-bounties that can be added to a parent bounty.
**/
maxActiveChildBountyCount: u32 & AugmentedConst<ApiType>;
/**
* Generic const
**/
[key: string]: Codec;
};
contracts: {
/**
* The maximum number of tries that can be queued for deletion.
**/
deletionQueueDepth: u32 & AugmentedConst<ApiType>;
/**
* The maximum amount of weight that can be consumed per block for lazy trie removal.
**/
deletionWeightLimit: u64 & AugmentedConst<ApiType>;
/**
* The amount of balance a caller has to pay for each byte of storage.
*
* # Note
*
* Changing this value for an existing chain might need a storage migration.
**/
depositPerByte: u128 & AugmentedConst<ApiType>;
/**
* The amount of balance a caller has to pay for each storage item.
* # Note
*
* Changing this value for an existing chain might need a storage migration.
**/
depositPerItem: u128 & AugmentedConst<ApiType>;
/**
* Cost schedule and limits.
**/
schedule: PalletContractsSchedule & AugmentedConst<ApiType>;
/**
* Generic const
**/
[key: string]: Codec;
};
democracy: {
/**
* Period in blocks where an external proposal may not be re-submitted after being vetoed.
**/
cooloffPeriod: u32 & AugmentedConst<ApiType>;
/**
* The period between a proposal being approved and enacted.
*
* It should generally be a little more than the unstake period to ensure that
* voting stakers have an opportunity to remove themselves from the system in the case
* where they are on the losing side of a vote.
**/
enactmentPeriod: u32 & AugmentedConst<ApiType>;
/**
* Minimum voting period allowed for a fast-track referendum.
**/
fastTrackVotingPeriod: u32 & AugmentedConst<ApiType>;
/**
* Indicator for whether an emergency origin is even allowed to happen. Some chains may
* want to set this permanently to `false`, others may want to condition it on things such
* as an upgrade having happened recently.
**/
instantAllowed: bool & AugmentedConst<ApiType>;
/**
* How often (in blocks) new public referenda are launched.
**/
launchPeriod: u32 & AugmentedConst<ApiType>;
/**
* The maximum number of public proposals that can exist at any time.
**/
maxProposals: u32 & AugmentedConst<ApiType>;
/**
* The maximum number of votes for an account.
*
* Also used to compute weight, an overly big value can
* lead to extrinsic with very big weight: see `delegate` for instance.
**/
maxVotes: u32 & AugmentedConst<ApiType>;
/**
* The minimum amount to be used as a deposit for a public referendum proposal.
**/
minimumDeposit: u128 & AugmentedConst<ApiType>;
/**
* The amount of balance that must be deposited per byte of preimage stored.
**/
preimageByteDeposit: u128 & AugmentedConst<ApiType>;
/**
* The minimum period of vote locking.
*
* It should be no shorter than enactment period to ensure that in the case of an approval,
* those successful voters are locked into the consequences that their votes entail.
**/
voteLockingPeriod: u32 & AugmentedConst<ApiType>;
/**
* How often (in blocks) to check for new votes.
**/
votingPeriod: u32 & AugmentedConst<ApiType>;
/**
* Generic const
**/
[key: string]: Codec;
};
electionProviderMultiPhase: {
/**
* Maximum length (bytes) that the mined solution should consume.
*
* The miner will ensure that the total length of the unsigned solution will not exceed
* this value.
**/
minerMaxLength: u32 & AugmentedConst<ApiType>;
/**
* Maximum weight that the miner should consume.
*
* The miner will ensure that the total weight of the unsigned solution will not exceed
* this value, based on [`WeightInfo::submit_unsigned`].
**/
minerMaxWeight: u64 & AugmentedConst<ApiType>;
/**
* The priority of the unsigned transaction submitted in the unsigned-phase
**/
minerTxPriority: u64 & AugmentedConst<ApiType>;
/**
* The repeat threshold of the offchain worker.
*
* For example, if it is 5, that means that at least 5 blocks will elapse between attempts
* to submit the worker's solution.
**/
offchainRepeat: u32 & AugmentedConst<ApiType>;
/**
* Base deposit for a signed solution.
**/
signedDepositBase: u128 & AugmentedConst<ApiType>;
/**
* Per-byte deposit for a signed solution.
**/
signedDepositByte: u128 & AugmentedConst<ApiType>;
/**
* Per-weight deposit for a signed solution.
**/
signedDepositWeight: u128 & AugmentedConst<ApiType>;
/**
* Maximum number of signed submissions that can be queued.
*
* It is best to avoid adjusting this during an election, as it impacts downstream data
* structures. In particular, `SignedSubmissionIndices<T>` is bounded on this value. If you
* update this value during an election, you _must_ ensure that
* `SignedSubmissionIndices.len()` is less than or equal to the new value. Otherwise,
* attempts to submit new solutions may cause a runtime panic.
**/
signedMaxSubmissions: u32 & AugmentedConst<ApiType>;
/**
* Maximum weight of a signed solution.
*
* This should probably be similar to [`Config::MinerMaxWeight`].
**/
signedMaxWeight: u64 & AugmentedConst<ApiType>;
/**
* Duration of the signed phase.
**/
signedPhase: u32 & AugmentedConst<ApiType>;
/**
* Base reward for a signed solution
**/
signedRewardBase: u128 & AugmentedConst<ApiType>;
/**
* The minimum amount of improvement to the solution score that defines a solution as
* "better" (in any phase).
**/
solutionImprovementThreshold: Perbill & AugmentedConst<ApiType>;
/**
* Duration of the unsigned phase.
**/
unsignedPhase: u32 & AugmentedConst<ApiType>;
/**
* The maximum number of voters to put in the snapshot. At the moment, snapshots are only
* over a single block, but once multi-block elections are introduced they will take place
* over multiple blocks.
*
* Also, note the data type: If the voters are represented by a `u32` in `type
* CompactSolution`, the same `u32` is used here to ensure bounds are respected.
**/
voterSnapshotPerBlock: u32 & AugmentedConst<ApiType>;
/**
* Generic const
**/
[key: string]: Codec;
};
elections: {
/**
* How much should be locked up in order to submit one's candidacy.
**/
candidacyBond: u128 & AugmentedConst<ApiType>;
/**
* Number of members to elect.
**/
desiredMembers: u32 & AugmentedConst<ApiType>;
/**
* Number of runners_up to keep.
**/
desiredRunnersUp: u32 & AugmentedConst<ApiType>;
/**
* Identifier for the elections-phragmen pallet's lock
**/
palletId: U8aFixed & AugmentedConst<ApiType>;
/**
* How long each seat is kept. This defines the next block number at which an election
* round will happen. If set to zero, no elections are ever triggered and the module will
* be in passive mode.
**/
termDuration: u32 & AugmentedConst<ApiType>;
/**
* Base deposit associated with voting.
*
* This should be sensibly high to economically ensure the pallet cannot be attacked by
* creating a gigantic number of votes.
**/
votingBondBase: u128 & AugmentedConst<ApiType>;
/**
* The amount of bond that need to be locked for each vote (32 bytes).
**/
votingBondFactor: u128 & AugmentedConst<ApiType>;
/**
* Generic const
**/
[key: string]: Codec;
};
gilt: {
/**
* Portion of the queue which is free from ordering and just a FIFO.
*
* Must be no greater than `MaxQueueLen`.
**/
fifoQueueLen: u32 & AugmentedConst<ApiType>;
/**
* The number of blocks between consecutive attempts to issue more gilts in an effort to
* get to the target amount to be frozen.
*
* A larger value results in fewer storage hits each block, but a slower period to get to
* the target.
**/
intakePeriod: u32 & AugmentedConst<ApiType>;
/**
* The maximum amount of bids that can be turned into issued gilts each block. A larger
* value here means less of the block available for transactions should there be a glut of
* bids to make into gilts to reach the target.
**/
maxIntakeBids: u32 & AugmentedConst<ApiType>;
/**
* Maximum number of items that may be in each duration queue.
**/
maxQueueLen: u32 & AugmentedConst<ApiType>;
/**
* The minimum amount of funds that may be offered to freeze for a gilt. Note that this
* does not actually limit the amount which may be frozen in a gilt since gilts may be
* split up in order to satisfy the desired amount of funds under gilts.
*
* It should be at least big enough to ensure that there is no possible storage spam attack
* or queue-filling attack.
**/
minFreeze: u128 & AugmentedConst<ApiType>;
/**
* The base period for the duration queues. This is the common multiple across all
* supported freezing durations that can be bid upon.
**/
period: u32 & AugmentedConst<ApiType>;
/**
* Number of duration queues in total. This sets the maximum duration supported, which is
* this value multiplied by `Period`.
**/
queueCount: u32 & AugmentedConst<ApiType>;
/**
* Generic const
**/
[key: string]: Codec;
};
grandpa: {
/**
* Max Authorities in use
**/
maxAuthorities: u32 & AugmentedConst<ApiType>;
/**
* Generic const
**/
[key: string]: Codec;
};
identity: {
/**
* The amount held on deposit for a registered identity
**/
basicDeposit: u128 & AugmentedConst<ApiType>;
/**
* The amount held on deposit per additional field for a registered identity.
**/
fieldDeposit: u128 & AugmentedConst<ApiType>;
/**
* Maximum number of additional fields that may be stored in an ID. Needed to bound the I/O
* required to access an identity, but can be pretty high.
**/
maxAdditionalFields: u32 & AugmentedConst<ApiType>;
/**
* Maxmimum number of registrars allowed in the system. Needed to bound the complexity
* of, e.g., updating judgements.
**/
maxRegistrars: u32 & AugmentedConst<ApiType>;
/**
* The maximum number of sub-accounts allowed per identified account.
**/
maxSubAccounts: u32 & AugmentedConst<ApiType>;
/**
* The amount held on deposit for a registered subaccount. This should account for the fact
* that one storage item's value will increase by the size of an account ID, and there will
* be another trie item whose value is the size of an account ID plus 32 bytes.
**/
subAccountDeposit: u128 & AugmentedConst<ApiType>;
/**
* Generic const
**/
[key: string]: Codec;
};
imOnline: {
/**
* A configuration for base priority of unsigned transactions.
*
* This is exposed so that it can be tuned for particular runtime, when
* multiple pallets send unsigned transactions.
**/
unsignedPriority: u64 & AugmentedConst<ApiType>;
/**
* Generic const
**/
[key: string]: Codec;
};
indices: {
/**
* The deposit needed for reserving an index.
**/
deposit: u128 & AugmentedConst<ApiType>;
/**
* Generic const
**/
[key: string]: Codec;
};
lottery: {
/**
* The max number of calls available in a single lottery.
**/
maxCalls: u32 & AugmentedConst<ApiType>;
/**
* Number of time we should try to generate a random number that has no modulo bias.
* The larger this number, the more potential computation is used for picking the winner,
* but also the more likely that the chosen winner is done fairly.
**/
maxGenerateRandom: u32 & AugmentedConst<ApiType>;
/**
* The Lottery's pallet id
**/
palletId: FrameSupportPalletId & AugmentedConst<ApiType>;
/**
* Generic const
**/
[key: string]: Codec;
};
multisig: {
/**
* The base amount of currency needed to reserve for creating a multisig execution or to
* store a dispatch call for later.
*
* This is held for an additional storage item whose value size is
* `4 + sizeof((BlockNumber, Balance, AccountId))` bytes and whose key size is
* `32 + sizeof(AccountId)` bytes.
**/
depositBase: u128 & AugmentedConst<ApiType>;
/**
* The amount of currency needed per unit threshold when creating a multisig execution.
*
* This is held for adding 32 bytes more into a pre-existing storage value.
**/
depositFactor: u128 & AugmentedConst<ApiType>;
/**
* The maximum amount of signatories allowed in the multisig.
**/
maxSignatories: u16 & AugmentedConst<ApiType>;
/**
* Generic const
**/
[key: string]: Codec;
};
proxy: {
/**
* The base amount of currency needed to reserve for creating an announcement.
*
* This is held when a new storage item holding a `Balance` is created (typically 16
* bytes).
**/
announcementDepositBase: u128 & AugmentedConst<ApiType>;
/**
* The amount of currency needed per announcement made.
*
* This is held for adding an `AccountId`, `Hash` and `BlockNumber` (typically 68 bytes)
* into a pre-existing storage value.
**/
announcementDepositFactor: u128 & AugmentedConst<ApiType>;
/**
* The maximum amount of time-delayed announcements that are allowed to be pending.
**/
maxPending: u32 & AugmentedConst<ApiType>;
/**
* The maximum amount of proxies allowed for a single account.
**/
maxProxies: u32 & AugmentedConst<ApiType>;
/**
* The base amount of currency needed to reserve for creating a proxy.
*
* This is held for an additional storage item whose value size is
* `sizeof(Balance)` bytes and whose key size is `sizeof(AccountId)` bytes.
**/
proxyDepositBase: u128 & AugmentedConst<ApiType>;
/**
* The amount of currency needed per proxy added.
*
* This is held for adding 32 bytes plus an instance of `ProxyType` more into a
* pre-existing storage value. Thus, when configuring `ProxyDepositFactor` one should take
* into account `32 + proxy_type.encode().len()` bytes of data.
**/
proxyDepositFactor: u128 & AugmentedConst<ApiType>;
/**
* Generic const
**/
[key: string]: Codec;
};
recovery: {
/**
* The base amount of currency needed to reserve for creating a recovery configuration.
*
* This is held for an additional storage item whose value size is
* `2 + sizeof(BlockNumber, Balance)` bytes.
**/
configDepositBase: u128 & AugmentedConst<ApiType>;
/**
* The amount of currency needed per additional user when creating a recovery
* configuration.
*
* This is held for adding `sizeof(AccountId)` bytes more into a pre-existing storage
* value.
**/
friendDepositFactor: u128 & AugmentedConst<ApiType>;
/**
* The maximum amount of friends allowed in a recovery configuration.
**/
maxFriends: u16 & AugmentedConst<ApiType>;
/**
* The base amount of currency needed to reserve for starting a recovery.
*
* This is primarily held for deterring malicious recovery attempts, and should
* have a value large enough that a bad actor would choose not to place this
* deposit. It also acts to fund additional storage item whose value size is
* `sizeof(BlockNumber, Balance + T * AccountId)` bytes. Where T is a configurable
* threshold.
**/
recoveryDeposit: u128 & AugmentedConst<ApiType>;
/**
* Generic const
**/
[key: string]: Codec;
};
scheduler: {
/**
* The maximum weight that may be scheduled per block for any dispatchables of less
* priority than `schedule::HARD_DEADLINE`.
**/
maximumWeight: u64 & AugmentedConst<ApiType>;
/**
* The maximum number of scheduled calls in the queue for a single block.
* Not strictly enforced, but used for weight estimation.
**/
maxScheduledPerBlock: u32 & AugmentedConst<ApiType>;
/**
* Generic const
**/
[key: string]: Codec;
};
society: {
/**
* The minimum amount of a deposit required for a bid to be made.
**/
candidateDeposit: u128 & AugmentedConst<ApiType>;
/**
* The number of blocks between membership challenges.
**/
challengePeriod: u32 & AugmentedConst<ApiType>;
/**
* The maximum number of candidates that we accept per round.
**/
maxCandidateIntake: u32 & AugmentedConst<ApiType>;
/**
* The maximum duration of the payout lock.
**/
maxLockDuration: u32 & AugmentedConst<ApiType>;
/**
* The number of times a member may vote the wrong way (or not at all, when they are a
* skeptic) before they become suspended.
**/
maxStrikes: u32 & AugmentedConst<ApiType>;
/**
* The societies's pallet id
**/
palletId: FrameSupportPalletId & AugmentedConst<ApiType>;
/**
* The amount of incentive paid within each period. Doesn't include VoterTip.
**/
periodSpend: u128 & AugmentedConst<ApiType>;
/**
* The number of blocks between candidate/membership rotation periods.
**/
rotationPeriod: u32 & AugmentedConst<ApiType>;
/**
* The amount of the unpaid reward that gets deducted in the case that either a skeptic
* doesn't vote or someone votes in the wrong way.
**/
wrongSideDeduction: u128 & AugmentedConst<ApiType>;
/**
* Generic const
**/
[key: string]: Codec;
};
staking: {
/**
* Number of eras that staked funds must remain bonded for.
**/
bondingDuration: u32 & AugmentedConst<ApiType>;
maxNominations: u32 & AugmentedConst<ApiType>;
/**
* The maximum number of nominators rewarded for each validator.
*
* For each validator only the `$MaxNominatorRewardedPerValidator` biggest stakers can
* claim their reward. This used to limit the i/o cost for the nominator payout.
**/
maxNominatorRewardedPerValidator: u32 & AugmentedConst<ApiType>;
/**
* Number of sessions per era.
**/
sessionsPerEra: u32 & AugmentedConst<ApiType>;
/**
* Number of eras that slashes are deferred by, after computation.
*
* This should be less than the bonding duration. Set to 0 if slashes
* should be applied immediately, without opportunity for intervention.
**/
slashDeferDuration: u32 & AugmentedConst<ApiType>;
/**
* Generic const
**/
[key: string]: Codec;
};
system: {
/**
* Maximum number of block number to block hash mappings to keep (oldest pruned first).
**/
blockHashCount: u32 & AugmentedConst<ApiType>;
/**
* The maximum length of a block (in bytes).
**/
blockLength: FrameSystemLimitsBlockLength & AugmentedConst<ApiType>;
/**
* Block & extrinsics weights: base values and limits.
**/
blockWeights: FrameSystemLimitsBlockWeights & AugmentedConst<ApiType>;
/**
* The weight of runtime database operations the runtime can invoke.
**/
dbWeight: FrameSupportWeightsRuntimeDbWeight & AugmentedConst<ApiType>;
/**
* The designated SS85 prefix of this chain.
*
* This replaces the "ss58Format" property declared in the chain spec. Reason is
* that the runtime should know about the prefix in order to make use of it as
* an identifier of the chain.
**/
ss58Prefix: u16 & AugmentedConst<ApiType>;
/**
* Get the chain's current version.
**/
version: SpVersionRuntimeVersion & AugmentedConst<ApiType>;
/**
* Generic const
**/
[key: string]: Codec;
};
timestamp: {
/**
* 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 work with this to determine a sensible block time. e.g. For Aura, it will be
* double this period on default settings.
**/
minimumPeriod: u64 & AugmentedConst<ApiType>;
/**
* Generic const
**/
[key: string]: Codec;
};
tips: {
/**
* The amount held on deposit per byte within the tip report reason or bounty description.
**/
dataDepositPerByte: u128 & AugmentedConst<ApiType>;
/**
* Maximum acceptable reason length.
*
* Benchmarks depend on this value, be sure to update weights file when changing this value
**/
maximumReasonLength: u32 & AugmentedConst<ApiType>;
/**
* The period for which a tip remains open after is has achieved threshold tippers.
**/
tipCountdown: u32 & AugmentedConst<ApiType>;
/**
* The percent of the final tip which goes to the original reporter of the tip.
**/
tipFindersFee: Percent & AugmentedConst<ApiType>;
/**
* The amount held on deposit for placing a tip report.
**/
tipReportDepositBase: u128 & AugmentedConst<ApiType>;
/**
* Generic const
**/
[key: string]: Codec;
};
transactionPayment: {
/**
* A fee mulitplier for `Operational` extrinsics to compute "virtual tip" to boost their
* `priority`
*
* This value is multipled by the `final_fee` to obtain a "virtual tip" that is later
* added to a tip component in regular `priority` calculations.
* It means that a `Normal` transaction can front-run a similarly-sized `Operational`
* extrinsic (with no tip), by including a tip value greater than the virtual tip.
*
* ```rust,ignore
* // For `Normal`
* let priority = priority_calc(tip);
*
* // For `Operational`
* let virtual_tip = (inclusion_fee + tip) * OperationalFeeMultiplier;
* let priority = priority_calc(tip + virtual_tip);
* ```
*
* Note that since we use `final_fee` the multiplier applies also to the regular `tip`
* sent with the transaction. So, not only does the transaction get a priority bump based
* on the `inclusion_fee`, but we also amplify the impact of tips applied to `Operational`
* transactions.
**/
operationalFeeMultiplier: u8 & AugmentedConst<ApiType>;
/**
* The fee to be paid for making a transaction; the per-byte portion.
**/
transactionByteFee: u128 & AugmentedConst<ApiType>;
/**
* The polynomial that is applied in order to derive fee from weight.
**/
weightToFee: Vec<FrameSupportWeightsWeightToFeeCoefficient> & AugmentedConst<ApiType>;
/**
* Generic const
**/
[key: string]: Codec;
};
treasury: {
/**
* Percentage of spare funds (if any) that are burnt per spend period.
**/
burn: Permill & AugmentedConst<ApiType>;
/**
* The maximum number of approvals that can wait in the spending queue.
**/
maxApprovals: u32 & AugmentedConst<ApiType>;
/**
* The treasury's pallet id, used for deriving its sovereign account ID.
**/
palletId: FrameSupportPalletId & AugmentedConst<ApiType>;
/**
* Fraction of a proposal's value that should be bonded in order to place the proposal.
* An accepted proposal gets these back. A rejected proposal does not.
**/
proposalBond: Permill & AugmentedConst<ApiType>;
/**
* Minimum amount of funds that should be placed in a deposit for making a proposal.
**/
proposalBondMinimum: u128 & AugmentedConst<ApiType>;
/**
* Period between successive spends.
**/
spendPeriod: u32 & AugmentedConst<ApiType>;
/**
* Generic const
**/
[key: string]: Codec;
};
uniques: {
/**
* The basic amount of funds that must be reserved when adding an attribute to an asset.
**/
attributeDepositBase: u128 & AugmentedConst<ApiType>;
/**
* The basic amount of funds that must be reserved for an asset class.
**/
classDeposit: u128 & AugmentedConst<ApiType>;
/**
* The additional funds that must be reserved for the number of bytes store in metadata,
* either "normal" metadata or attribute metadata.
**/
depositPerByte: u128 & AugmentedConst<ApiType>;
/**
* The basic amount of funds that must be reserved for an asset instance.
**/
instanceDeposit: u128 & AugmentedConst<ApiType>;
/**
* The maximum length of an attribute key.
**/
keyLimit: u32 & AugmentedConst<ApiType>;
/**
* The basic amount of funds that must be reserved when adding metadata to your asset.
**/
metadataDepositBase: u128 & AugmentedConst<ApiType>;
/**
* The maximum length of data stored on-chain.
**/
stringLimit: u32 & AugmentedConst<ApiType>;
/**
* The maximum length of an attribute value.
**/
valueLimit: u32 & AugmentedConst<ApiType>;
/**
* Generic const
**/
[key: string]: Codec;
};
utility: {
/**
* The limit on the number of batched calls.
**/
batchedCallsLimit: u32 & AugmentedConst<ApiType>;
/**
* Generic const
**/
[key: string]: Codec;
};
vesting: {
maxVestingSchedules: u32 & AugmentedConst<ApiType>;
/**
* The minimum amount transferred to call `vested_transfer`.
**/
minVestedTransfer: u128 & AugmentedConst<ApiType>;
/**
* Generic const
**/
[key: string]: Codec;
};
} // AugmentedConsts
} // declare module
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
-12
View File
@@ -1,12 +0,0 @@
// Copyright 2017-2021 @polkadot/api-augment authors & contributors
// SPDX-License-Identifier: Apache-2.0
// for the API, we decorate not only the endpoints, but all types
import '@polkadot/rpc-augment';
import '@polkadot/types-augment';
// the augmentated types (on top of @polkadot/api-base)
import './consts';
import './errors';
import './events';
import './query';
import './tx';
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff

Some files were not shown because too many files have changed in this diff Show More