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
1291 changed files with 56480 additions and 297401 deletions
+1 -36
View File
@@ -1,36 +1 @@
33
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
5
+1
View File
@@ -0,0 +1 @@
module.exports = require('./babel.config.js');
-12
View File
@@ -1,12 +0,0 @@
exclude_patterns:
- "**/*.spec.js"
- "**/*.spec.ts"
- "**/*.test.js"
- "**/*.test.ts"
- "docs/**/*.js"
- "docs/**/*.ts"
- "packages/api/src/augment/"
- "packages/typegen/scripts"
- "packages/typegen/src"
- "packages/types/src/interfaces/"
- "packages/types/src/augment/"
-30
View File
@@ -1,30 +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: [
'.eslintrc.js',
'.github/**',
'.vscode/**',
'.yarn/**',
'**/build/*',
'**/coverage/*',
'**/node_modules/*'
],
parserOptions: {
...base.parserOptions,
project: [
'./tsconfig.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: '30 1/2 * * *'
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: '30 2/2 * * *'
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
-7
View File
@@ -3,7 +3,6 @@ build/
build-docs/
coverage/
docs/.vuepress/dist/
docs/substrate/*.md
node_modules/
tmp/
.DS_Store
@@ -12,12 +11,6 @@ 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*
+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 -2271
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>
-20
View File
@@ -1,20 +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-(contract|derive)(.*)$': '<rootDir>/packages/api-$1/src/$2',
// eslint-disable-next-line sort-keys
'@polkadot/api(.*)$': '<rootDir>/packages/api/src/$1',
'@polkadot/metadata(.*)$': '<rootDir>/packages/metadata/src/$1',
'@polkadot/rpc-(core|provider)(.*)$': '<rootDir>/packages/rpc-$1/src/$2',
'@polkadot/typegen(.*)$': '<rootDir>/packages/typegen/src/$1',
'@polkadot/types-(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 -29
View File
@@ -1,40 +1,33 @@
{
"repository": "https://github.com/polkadot-js/api",
"author": "Jaco Greeff <jacogr@gmail.com>",
"license": "Apache-2",
"version": "0.0.0",
"private": true,
"type": "commonjs",
"engines": {
"node": ">=10.13.0",
"yarn": "^1.10.1"
},
"workspaces": [
"packages/*"
],
"resolutions": {
"typescript": "^4.4.3"
"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",
"docs:metadata": "polkadot-types-internal-metadata",
"chain:info": "polkadot-types-chain-info",
"lint": "polkadot-dev-run-lint",
"clean": "polkadot-dev-clean-build",
"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.15.5",
"@babel/register": "^7.15.3",
"@babel/runtime": "^7.15.4",
"@polkadot/dev": "^0.62.67",
"@polkadot/ts": "^0.4.8",
"@polkadot/typegen": "workspace:packages/typegen",
"@types/jest": "^27.0.1",
"copyfiles": "^2.4.1"
},
"version": "6.0.5",
"packageManager": "yarn@3.0.1"
"@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"
}
}
-16
View File
@@ -1,16 +0,0 @@
# @polkadot/api-contract
Interfaces to allow for the encoding and decoding of Substrate contract ABIs.
```js
import {ApiPromise, WsProvider } from '@polkadot/api';
import { Abi } from '@polkadot/api-contract';
const wsProvider = new WsProvider(<...Node Url...>);
const api = await ApiPromise.create({ provider: wsProvider });
const abi = new Abi(<...JSON ABI...>, api.registry.getChainProperties());
api.tx.contracts
.call(<contract addr>, <value>, <max gas>, abi.messages.<method name>(<...params...>))
.signAndSend(<keyring pair>, (result: SubmittableResult) => { ... });
```
-28
View File
@@ -1,28 +0,0 @@
{
"name": "@polkadot/api-contract",
"version": "6.0.5",
"type": "module",
"description": "Interfaces for interacting with contracts and contract ABIs",
"main": "index.js",
"sideEffects": [
"./detectPackage.js",
"./detectPackage.cjs"
],
"engines": {
"node": ">=14.0.0"
},
"author": "Jaco Greeff <jacogr@gmail.com>",
"maintainers": [],
"contributors": [],
"license": "Apache-2.0",
"repository": "github:polkadot-js/api",
"bugs": "https://github.com/polkadot-js/api/issues",
"homepage": "https://github.com/polkadot-js/api/tree/master/packages/api-contract#readme",
"dependencies": {
"@babel/runtime": "^7.15.4",
"@polkadot/api": "6.0.5",
"@polkadot/types": "6.0.5",
"@polkadot/util": "^7.4.1",
"rxjs": "^7.3.0"
}
}
-52
View File
@@ -1,52 +0,0 @@
// Copyright 2017-2021 @polkadot/api-contract authors & contributors
// SPDX-License-Identifier: Apache-2.0
import { blake2AsHex } from '@polkadot/util-crypto';
import abis from '../test/contracts';
import { Abi } from '.';
interface JSONAbi {
source: {
compiler: string,
hash: string,
language: string,
wasm: string
},
spec: {
messages: {
name: string[] | string
}[]
}
}
describe('Abi', (): void => {
Object.entries(abis).forEach(([abiName, abi]) => {
it(`initializes from a contract ABI (${abiName})`, (): void => {
try {
const messageIds = (abi as JSONAbi).spec.messages.map(({ name }) => Array.isArray(name) ? name[0] : name);
const inkAbi = new Abi(abis[abiName]);
expect(inkAbi.messages.map(({ identifier }) => identifier)).toEqual(messageIds);
} catch (error) {
console.error(error);
throw error;
}
});
});
it('has the correct hash for the source', (): void => {
const bundle = abis.ink_flipperBundle as JSONAbi;
const abi = new Abi(bundle as any);
// manual
expect(bundle.source.hash).toEqual(blake2AsHex(bundle.source.wasm));
// the Codec hash
expect(bundle.source.hash).toEqual(abi.project.source.wasm.hash.toHex());
// the hash as per the actual Abi
expect(bundle.source.hash).toEqual(abi.project.source.wasmHash.toHex());
});
});
-198
View File
@@ -1,198 +0,0 @@
// Copyright 2017-2021 @polkadot/api-contract authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { Bytes } from '@polkadot/types';
import type { ChainProperties, ContractConstructorSpec, ContractEventSpec, ContractMessageParamSpec, ContractMessageSpec, ContractProject } from '@polkadot/types/interfaces';
import type { AnyJson, Codec } from '@polkadot/types/types';
import type { AbiConstructor, AbiEvent, AbiMessage, AbiParam, DecodedEvent, DecodedMessage } from './types';
import { assert, assertReturn, compactAddLength, compactStripLength, isNumber, isObject, isString, logger, stringCamelCase, stringify, u8aConcat, u8aToHex } from '@polkadot/util';
import { MetaRegistry } from './MetaRegistry';
const l = logger('Abi');
function findMessage <T extends AbiMessage> (list: T[], messageOrId: T | string | number): T {
const message = isNumber(messageOrId)
? list[messageOrId]
: isString(messageOrId)
? list.find(({ identifier }) => [identifier, stringCamelCase(identifier)].includes(messageOrId.toString()))
: messageOrId;
return assertReturn(message, () => `Attempted to call an invalid contract interface, ${stringify(messageOrId)}`);
}
export class Abi {
readonly #events: AbiEvent[];
public readonly constructors: AbiConstructor[];
public readonly json: AnyJson;
public readonly messages: AbiMessage[];
public readonly project: ContractProject;
public readonly registry: MetaRegistry;
constructor (abiJson: AnyJson, chainProperties?: ChainProperties) {
const json = isString(abiJson)
? JSON.parse(abiJson) as AnyJson
: abiJson;
assert(isObject(json) && !Array.isArray(json) && json.metadataVersion && isObject(json.spec) && !Array.isArray(json.spec) && Array.isArray(json.spec.constructors) && Array.isArray(json.spec.messages), 'Invalid JSON ABI structure supplied, expected a recent metadata version');
this.json = json;
this.registry = new MetaRegistry(json.metadataVersion as string, chainProperties);
this.project = this.registry.createType('ContractProject', json);
this.registry.setMetaTypes(this.project.types);
this.project.types.forEach((_, index) =>
this.registry.getMetaTypeDef({ type: this.registry.createType('Si0LookupTypeId', index + this.registry.typeOffset) })
);
this.constructors = this.project.spec.constructors.map((spec: ContractConstructorSpec, index) =>
this.#createMessage(spec, index, {
isConstructor: true
})
);
this.#events = this.project.spec.events.map((spec: ContractEventSpec, index) =>
this.#createEvent(spec, index)
);
this.messages = this.project.spec.messages.map((spec: ContractMessageSpec, index): AbiMessage => {
const typeSpec = spec.returnType.unwrapOr(null);
return this.#createMessage(spec, index, {
isMutating: spec.mutates.isTrue,
isPayable: spec.payable.isTrue,
returnType: typeSpec
? this.registry.getMetaTypeDef(typeSpec)
: null
});
});
}
/**
* Warning: Unstable API, bound to change
*/
public decodeEvent (data: Bytes | Uint8Array): DecodedEvent {
const index = data[0];
const event = this.#events[index];
assert(event, () => `Unable to find event with index ${index}`);
return event.fromU8a(data.subarray(1));
}
/**
* Warning: Unstable API, bound to change
*/
public decodeConstructor (data: Uint8Array): DecodedMessage {
return this.#decodeMessage('message', this.constructors, data);
}
/**
* Warning: Unstable API, bound to change
*/
public decodeMessage (data: Uint8Array): DecodedMessage {
return this.#decodeMessage('message', this.messages, data);
}
public findConstructor (constructorOrId: AbiConstructor | string | number): AbiConstructor {
return findMessage(this.constructors, constructorOrId);
}
public findMessage (messageOrId: AbiMessage | string | number): AbiMessage {
return findMessage(this.messages, messageOrId);
}
#createArgs = (args: ContractMessageParamSpec[], spec: unknown): AbiParam[] => {
return args.map((arg, index): AbiParam => {
try {
assert(isObject(arg.type), 'Invalid type definition found');
return {
name: stringCamelCase(arg.name),
type: this.registry.getMetaTypeDef(arg.type)
};
} catch (error) {
l.error(`Error expanding argument ${index} in ${stringify(spec)}`);
throw error;
}
});
}
#createEvent = (spec: ContractEventSpec, index: number): AbiEvent => {
const args = this.#createArgs(spec.args, spec);
const event = {
args,
docs: spec.docs.map((d) => d.toString()),
fromU8a: (data: Uint8Array): DecodedEvent => ({
args: this.#decodeArgs(args, data),
event
}),
identifier: spec.name.toString(),
index
};
return event;
}
#createMessage = (spec: ContractMessageSpec | ContractConstructorSpec, index: number, add: Partial<AbiMessage> = {}): AbiMessage => {
const args = this.#createArgs(spec.args, spec);
const identifier = spec.name.toString();
const message = {
...add,
args,
docs: spec.docs.map((d) => d.toString()),
fromU8a: (data: Uint8Array): DecodedMessage => ({
args: this.#decodeArgs(args, data),
message
}),
identifier,
index,
method: stringCamelCase(identifier),
selector: spec.selector,
toU8a: (params: unknown[]) =>
this.#encodeArgs(spec, args, params)
};
return message;
}
#decodeArgs = (args: AbiParam[], data: Uint8Array): Codec[] => {
// for decoding we expect the input to be just the arg data, no selectors
// no length added (this allows use with events as well)
let offset = 0;
return args.map(({ type }): Codec => {
const value = this.registry.createType(type.type as 'Text', data.subarray(offset));
offset += value.encodedLength;
return value;
});
}
#decodeMessage = (type: 'constructor' | 'message', list: AbiMessage[], data: Uint8Array): DecodedMessage => {
const [, trimmed] = compactStripLength(data);
const selector = trimmed.subarray(0, 4);
const message = list.find((m) => m.selector.eq(selector));
assert(message, `Unable to find ${type} with selector ${u8aToHex(selector)}`);
return message.fromU8a(trimmed.subarray(4));
}
#encodeArgs = ({ name, selector }: ContractMessageSpec | ContractConstructorSpec, args: AbiParam[], data: unknown[]): Uint8Array => {
assert(data.length === args.length, () => `Expected ${args.length} arguments to contract message '${name.toString()}', found ${data.length}`);
return compactAddLength(
u8aConcat(
this.registry.createType('ContractSelector', selector).toU8a(),
...args.map(({ type }, index) => this.registry.createType(type.type as 'Text', data[index]).toU8a())
)
);
}
}
@@ -1,43 +0,0 @@
// Copyright 2017-2021 @polkadot/api-contract authors & contributors
// SPDX-License-Identifier: Apache-2.0
import fs from 'fs';
import path from 'path';
import { TypeDefInfo } from '@polkadot/types/types';
import abis from '../test/contracts';
import { Abi } from '.';
function stringifyInfo (key: string, value: unknown): unknown {
return key === 'info'
? TypeDefInfo[value as number]
: value;
}
describe('MetaRegistry', (): void => {
Object.keys(abis).forEach((abiName) => {
it(`initializes from a contract ABI (${abiName})`, (): void => {
const abi = new Abi(abis[abiName]);
const json = JSON.stringify(abi.registry.metaTypeDefs, stringifyInfo, 2);
const cmpPath = path.join(__dirname, `../test/compare/${abiName}.test.json`);
try {
// eslint-disable-next-line @typescript-eslint/no-var-requires
expect(JSON.parse(json)).toEqual(require(cmpPath));
} catch (error) {
if (process.env.GITHUB_REPOSITORY) {
console.error(JSON.stringify(abi.registry.metaTypeDefs, stringifyInfo));
throw error;
}
fs.writeFileSync(cmpPath, json, { flag: 'w' });
}
});
});
it('stores base project as JSON', (): void => {
expect(new Abi(abis.ink_dns).json).toEqual(abis.ink_dns);
});
});
-252
View File
@@ -1,252 +0,0 @@
// Copyright 2017-2021 @polkadot/api-contract authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { ChainProperties, ContractDisplayName, Si0Field, Si0LookupTypeId, Si0Type, Si0TypeDefArray, Si0TypeDefSequence, Si0TypeDefTuple, Si0TypeDefVariant, Si0Variant } from '@polkadot/types/interfaces';
import type { InterfaceTypes, TypeDef } from '@polkadot/types/types';
import { TypeDefInfo, TypeRegistry, withTypeString } from '@polkadot/types';
import { assert, isUndefined } from '@polkadot/util';
interface PartialTypeSpec {
readonly type: Si0LookupTypeId;
readonly displayName?: ContractDisplayName;
}
// convert the offset into project-specific, index-1
export function getRegistryOffset (id: Si0LookupTypeId, typeOffset: number): number {
return id.toNumber() - typeOffset;
}
const PRIMITIVE_ALIAS: Record<string, keyof InterfaceTypes> = {
Char: 'u32', // Rust char is 4-bytes
Str: 'Text'
};
const PRIMITIVE_ALWAYS = ['AccountId', 'AccountIndex', 'Address', 'Balance'];
// TODO Replace usages with PortableRegistry
export class MetaRegistry extends TypeRegistry {
public readonly metaTypeDefs: TypeDef[] = [];
public readonly typeOffset;
#siTypes: Si0Type[] = [];
constructor (metadataVersion: string, chainProperties?: ChainProperties) {
super();
const [major, minor] = metadataVersion.split('.').map((n) => parseInt(n, 10));
// type indexes are 1-based pre 0.7 and 0-based post
this.typeOffset = (major === 0 && minor < 7) ? 1 : 0;
if (chainProperties) {
this.setChainProperties(chainProperties);
}
}
public setMetaTypes (metaTypes: Si0Type[]): void {
this.#siTypes = metaTypes;
}
public getMetaTypeDef (typeSpec: PartialTypeSpec): TypeDef {
const offset = getRegistryOffset(typeSpec.type, this.typeOffset);
let typeDef = this.metaTypeDefs[offset];
if (!typeDef) {
typeDef = this.#extract(this.#getMetaType(typeSpec.type), typeSpec.type);
this.metaTypeDefs[offset] = typeDef;
}
if (typeSpec.displayName && typeSpec.displayName.length) {
const displayName = typeSpec.displayName[typeSpec.displayName.length - 1].toString();
if (!typeDef.type.startsWith(displayName)) {
typeDef = {
...typeDef,
displayName,
type: PRIMITIVE_ALWAYS.includes(displayName)
? displayName
: typeDef.type
};
}
}
// Here we protect against the following cases
// - No displayName present, these are generally known primitives
// - displayName === type, these generate circular references
// - displayName Option & type Option<...something...>
if (typeDef.displayName && !this.hasType(typeDef.displayName) && !(typeDef.type === typeDef.displayName || typeDef.type.startsWith(`${typeDef.displayName}<`))) {
this.register({ [typeDef.displayName]: typeDef.type });
}
return typeDef;
}
#getMetaType = (id: Si0LookupTypeId): Si0Type => {
const type = this.#siTypes[getRegistryOffset(id, this.typeOffset)];
assert(!isUndefined(type), () => `getMetaType:: Unable to find ${id.toNumber()} in type values`);
return this.createType('Si0Type', type);
}
#extract = (type: Si0Type, id: Si0LookupTypeId): TypeDef => {
const path = [...type.path];
const isPrimitivePath = !!path.length && (
(path.length > 2 && path[0].eq('ink_env') && path[1].eq('types')) ||
PRIMITIVE_ALWAYS.includes(path[path.length - 1].toString())
);
let typeDef: Omit<TypeDef, 'type'>;
if (isPrimitivePath) {
typeDef = this.#extractPrimitivePath(type);
} else if (type.def.isPrimitive) {
typeDef = this.#extractPrimitive(type);
} else if (type.def.isComposite) {
typeDef = this.#extractFields(type.def.asComposite.fields);
} else if (type.def.isVariant) {
typeDef = this.#extractVariant(type.def.asVariant, id);
} else if (type.def.isArray) {
typeDef = this.#extractArray(type.def.asArray);
} else if (type.def.isSequence) {
typeDef = this.#extractSequence(type.def.asSequence, id);
} else if (type.def.isTuple) {
typeDef = this.#extractTuple(type.def.asTuple);
} else {
throw new Error(`Invalid ink! type at index ${id.toString()}`);
}
const displayName = path.pop()?.toString();
return withTypeString(this, {
...(displayName
? { displayName }
: {}
),
...(path.length > 1
? { namespace: path.map((s) => s.toString()).join('::') }
: {}
),
...(type.params.length > 0
? { sub: type.params.map((type) => this.getMetaTypeDef({ type })) }
: {}
),
...typeDef
});
}
#extractArray = ({ len: length, type }: Si0TypeDefArray): Omit<TypeDef, 'type'> => {
assert(!length || length.toNumber() <= 256, 'MetaRegistry: Only support for [Type; <length>], where length <= 256');
return {
info: TypeDefInfo.VecFixed,
length: length.toNumber(),
sub: this.getMetaTypeDef({ type })
};
}
#extractFields = (fields: Si0Field[]): Omit<TypeDef, 'type'> => {
const [isStruct, isTuple] = fields.reduce(([isAllNamed, isAllUnnamed], { name }) => ([
isAllNamed && name.isSome,
isAllUnnamed && name.isNone
]),
[true, true]);
assert(isTuple || isStruct, 'Invalid fields type detected, expected either Tuple or Struct');
const sub = fields.map(({ name, type }) => ({
...this.getMetaTypeDef({ type }),
...(name.isSome
? { name: name.unwrap().toString() }
: {}
)
}));
return isTuple && sub.length === 1
? sub[0]
: {
// check for tuple first (no fields may be available)
info: isTuple
? TypeDefInfo.Tuple
: TypeDefInfo.Struct,
sub
};
}
#extractPrimitive = (type: Si0Type): TypeDef => {
const typeStr = type.def.asPrimitive.type.toString();
return {
info: TypeDefInfo.Plain,
type: PRIMITIVE_ALIAS[typeStr] || typeStr.toLowerCase()
};
}
#extractPrimitivePath = (type: Si0Type): TypeDef => {
return {
info: TypeDefInfo.Plain,
type: type.path[type.path.length - 1].toString()
};
}
#extractSequence = ({ type }: Si0TypeDefSequence, id: Si0LookupTypeId): Omit<TypeDef, 'type'> => {
assert(!!type, () => `ContractRegistry: Invalid sequence type found at id ${id.toString()}`);
return {
info: TypeDefInfo.Vec,
sub: this.getMetaTypeDef({ type })
};
}
#extractTuple = (ids: Si0TypeDefTuple): Omit<TypeDef, 'type'> => {
return ids.length === 1
? this.getMetaTypeDef({ type: ids[0] })
: {
info: TypeDefInfo.Tuple,
sub: ids.map((type) => this.getMetaTypeDef({ type }))
};
}
#extractVariant = ({ variants }: Si0TypeDefVariant, id: Si0LookupTypeId): Omit<TypeDef, 'type'> => {
const { params, path } = this.#getMetaType(id);
const specialVariant = path[0].toString();
return specialVariant === 'Option'
? {
info: TypeDefInfo.Option,
sub: this.getMetaTypeDef({ type: params[0] })
}
: specialVariant === 'Result'
? {
info: TypeDefInfo.Result,
sub: params.map((type, index) => ({
name: ['Ok', 'Error'][index],
...this.getMetaTypeDef({ type })
}))
}
: {
info: TypeDefInfo.Enum,
sub: this.#extractVariantSub(variants)
};
}
#extractVariantSub = (variants: Si0Variant[]): TypeDef[] => {
return variants.every(({ fields }) => fields.length === 0)
? variants.map(({ discriminant, name }) => ({
...(
discriminant.isSome
? { ext: { discriminant: discriminant.unwrap().toNumber() } }
: {}
),
info: TypeDefInfo.Plain,
name: name.toString(),
type: 'Null'
}))
: variants.map(({ fields, name }) => withTypeString(this, {
...this.#extractFields(fields),
name: name.toString()
}));
}
}
-32
View File
@@ -1,32 +0,0 @@
// Copyright 2017-2021 @polkadot/api authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { ApiTypes, DecorateMethod } from '@polkadot/api/types';
import type { AnyJson, Registry } from '@polkadot/types/types';
import { ApiBase } from '@polkadot/api/base';
import { assert, isFunction } from '@polkadot/util';
import { Abi } from '../Abi';
export abstract class Base<ApiType extends ApiTypes> {
public readonly abi: Abi;
public readonly api: ApiBase<ApiType>;
public readonly registry: Registry;
protected readonly _decorateMethod: DecorateMethod<ApiType>;
constructor (api: ApiBase<ApiType>, abi: AnyJson | Abi, decorateMethod: DecorateMethod<ApiType>) {
this.abi = abi instanceof Abi
? abi
: new Abi(abi, api.registry.getChainProperties());
this.api = api;
this.registry = this.abi.registry;
this._decorateMethod = decorateMethod;
assert(!!(api && api.isConnected && api.tx && api.tx.contracts && Object.keys(api.tx.contracts).length), 'Your API has not been initialized correctly and it not decorated with the runtime interfaces for contracts as retrieved from the on-chain runtime');
assert(isFunction(api.tx.contracts.instantiateWithCode), 'You need to connect to a chain with a runtime with a V3 contracts module. The runtime does not expose api.tx.contracts.instantiateWithCode');
}
}
@@ -1,70 +0,0 @@
// Copyright 2017-2021 @polkadot/api-contract authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { SubmittableExtrinsic } from '@polkadot/api/submittable/types';
import type { ApiTypes, DecorateMethod } from '@polkadot/api/types';
import type { AccountId, EventRecord, Hash } from '@polkadot/types/interfaces';
import type { AnyJson, ISubmittableResult } from '@polkadot/types/types';
import type { AbiConstructor, BlueprintOptions } from '../types';
import type { MapConstructorExec } from './types';
import { SubmittableResult } from '@polkadot/api';
import { ApiBase } from '@polkadot/api/base';
import { BN_ZERO, isUndefined } from '@polkadot/util';
import { Abi } from '../Abi';
import { applyOnEvent } from '../util';
import { Base } from './Base';
import { Contract } from './Contract';
import { createBluePrintTx, encodeSalt } from './util';
export class BlueprintSubmittableResult<ApiType extends ApiTypes> extends SubmittableResult {
public readonly contract?: Contract<ApiType>;
constructor (result: ISubmittableResult, contract?: Contract<ApiType>) {
super(result);
this.contract = contract;
}
}
export class Blueprint<ApiType extends ApiTypes> extends Base<ApiType> {
/**
* @description The on-chain code hash for this blueprint
*/
public readonly codeHash: Hash;
readonly #tx: MapConstructorExec<ApiType> = {};
constructor (api: ApiBase<ApiType>, abi: AnyJson | Abi, codeHash: string | Hash | Uint8Array, decorateMethod: DecorateMethod<ApiType>) {
super(api, abi, decorateMethod);
this.codeHash = this.registry.createType('Hash', codeHash);
this.abi.constructors.forEach((c): void => {
if (isUndefined(this.#tx[c.method])) {
this.#tx[c.method] = createBluePrintTx((o, p) => this.#deploy(c, o, p));
}
});
}
public get tx (): MapConstructorExec<ApiType> {
return this.#tx;
}
#deploy = (constructorOrId: AbiConstructor | string | number, { gasLimit = BN_ZERO, salt, value = BN_ZERO }: BlueprintOptions, params: unknown[]): SubmittableExtrinsic<ApiType, BlueprintSubmittableResult<ApiType>> => {
return this.api.tx.contracts
.instantiate(
value,
gasLimit,
this.codeHash,
this.abi.findConstructor(constructorOrId).toU8a(params),
encodeSalt(salt)
)
.withResultTransform((result: ISubmittableResult) =>
new BlueprintSubmittableResult(result, applyOnEvent(result, ['Instantiated'], ([record]: EventRecord[]) =>
new Contract<ApiType>(this.api, this.abi, record.event.data[1] as AccountId, this._decorateMethod)
))
);
}
}

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