Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4e6b533539 | ||
|
|
224803f4c4 | ||
|
|
9fbf4bf478 | ||
|
|
385150bd81 | ||
|
|
14216a42a3 | ||
|
|
0055cb594f | ||
|
|
63e08d8357 | ||
|
|
c9f9e2ec8a | ||
|
|
019f1f761f | ||
|
|
c91e72b60b | ||
|
|
e4cf97d71e | ||
|
|
dcdbd2ca40 | ||
|
|
13ae360c7a | ||
|
|
6c0d683235 | ||
|
|
6fc35d641a | ||
|
|
d79c0ea28d | ||
|
|
486412d051 | ||
|
|
f3f1807013 | ||
|
|
d9e581fbdc | ||
|
|
89ebae9d78 | ||
|
|
071d872adf | ||
|
|
1b6d6d970c | ||
|
|
9f5be747e7 | ||
|
|
86cb0962bc | ||
|
|
75884d22a3 | ||
|
|
a4d09f799d | ||
|
|
85a29de479 | ||
|
|
ed2e44ac93 | ||
|
|
c88d284a5c | ||
|
|
daaa16523d | ||
|
|
116714a8f9 | ||
|
|
5c1f7fb527 | ||
|
|
8a69bc4458 | ||
|
|
a8dd059097 | ||
|
|
1204ac37f6 | ||
|
|
b2f03e500e | ||
|
|
de90242456 | ||
|
|
a7ffe44ae6 | ||
|
|
ac5bfeda39 | ||
|
|
73a184ec7d | ||
|
|
e4371684b6 | ||
|
|
382e903b8f | ||
|
|
6b6b7fe145 | ||
|
|
1f4e7638d5 | ||
|
|
4d95d622a9 | ||
|
|
327c20ddea | ||
|
|
04f6d352d9 | ||
|
|
c14a071b74 | ||
|
|
f103863fdd | ||
|
|
3c7c79f18f | ||
|
|
4e30fab9d6 |
+1
-3
@@ -1,3 +1 @@
|
||||
20
|
||||
1.4.2
|
||||
1.6.2
|
||||
5
|
||||
|
||||
@@ -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/"
|
||||
@@ -1,4 +0,0 @@
|
||||
**/build/*
|
||||
**/coverage/*
|
||||
**/node_modules/*
|
||||
docs/examples/promise/90_typegen/*
|
||||
@@ -1,18 +0,0 @@
|
||||
const base = require('@polkadot/dev/config/eslint');
|
||||
|
||||
module.exports = {
|
||||
...base,
|
||||
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',
|
||||
// these should be removed, there are 8 of them as errors
|
||||
'@typescript-eslint/no-non-null-assertion': 'off'
|
||||
}
|
||||
};
|
||||
@@ -1,19 +0,0 @@
|
||||
name: PR
|
||||
on: [pull_request]
|
||||
|
||||
jobs:
|
||||
pr:
|
||||
strategy:
|
||||
matrix:
|
||||
step: ['lint', 'test', 'build', 'docs']
|
||||
name: ${{ matrix.step }}
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v1
|
||||
- uses: actions/setup-node@v1
|
||||
with:
|
||||
node-version: '12.x'
|
||||
- name: ${{ matrix.step }}
|
||||
run: |
|
||||
yarn install --immutable | grep -v 'YN0013'
|
||||
yarn ${{ matrix.step }}
|
||||
@@ -1,41 +0,0 @@
|
||||
name: Master
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- master
|
||||
|
||||
jobs:
|
||||
master:
|
||||
strategy:
|
||||
matrix:
|
||||
step: ['build:release', 'docs:release']
|
||||
name: ${{ matrix.step }}
|
||||
if: "! contains(github.event.head_commit.message, '[CI Skip]')"
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v1
|
||||
with:
|
||||
token: ${{ secrets.GH_PAT }}
|
||||
- uses: actions/setup-node@v1
|
||||
with:
|
||||
node-version: '12.x'
|
||||
- name: ${{ matrix.step }}
|
||||
env:
|
||||
CC_TEST_REPORTER_ID: ${{ secrets.CC_TEST_REPORTER_ID }}
|
||||
GH_PAGES_SRC: build-docs
|
||||
GH_PAT: ${{ secrets.GH_PAT }}
|
||||
GH_TOKEN: ${{ secrets.GH_PAT }}
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
NPM_TOKEN: ${{ secrets.NPM_TOKEN }}
|
||||
run: |
|
||||
yarn install --immutable | grep -v 'YN0013'
|
||||
yarn ${{ matrix.step }}
|
||||
|
||||
dummy:
|
||||
name: Dummy
|
||||
if: "contains(github.event.head_commit.message, '[CI Skip]')"
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: dummy
|
||||
run: |
|
||||
echo "Dummy skip step"
|
||||
@@ -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*
|
||||
|
||||
File diff suppressed because one or more lines are too long
Vendored
-50
File diff suppressed because one or more lines are too long
-11
@@ -1,11 +0,0 @@
|
||||
enableImmutableInstalls: false
|
||||
|
||||
enableProgressBars: false
|
||||
|
||||
nodeLinker: node-modules
|
||||
|
||||
plugins:
|
||||
- path: .yarn/plugins/@yarnpkg/plugin-interactive-tools.js
|
||||
spec: "@yarnpkg/plugin-interactive-tools"
|
||||
|
||||
yarnPath: .yarn/releases/yarn-rc.js
|
||||
+34
-424
@@ -1,329 +1,4 @@
|
||||
# 1.7.1 Mar 17, 2020
|
||||
|
||||
- **Important** Current versions of Polkadot/Substrate have dropped support for linked maps on storage entries. If you are using these queries to retriev all entries, for instance `staking.{nominators,validators}()` and using an upgraded chain, you need to swap to retrieving entries via `.entries()` or `.keys()` for the keys.
|
||||
- Pull in support and types for latest Polkadot/Substrate
|
||||
- Add support for the new Substrate `state_getKeysPaged` RPC, including use in storage keys
|
||||
- Move `derive.staking.controllers` to `derive.staking.stashes`, reflecting actual content
|
||||
- Cater for adjusted storage (non-linked mapped) for `derive.staking.stashes` queries (with old-compat)
|
||||
- Expanded `derive.staking.*` derives, including addition of `derive.staking.own*`
|
||||
- Re-add fixed (with tests) checks for query args, previously disabled in 1.6.2
|
||||
|
||||
# 1.6.2 Mar 12, 2020
|
||||
|
||||
- Revert checks for query args, not working on `.at()` queries (proper fix in next version)
|
||||
|
||||
# 1.6.1 Mar 12, 2020
|
||||
|
||||
- **Breaking change** `api.rpc.state.queryStorage(...)` now fully decodes the `Vec<StorageChangeSet>` and returns a decoded `[Hash, Codec[]][]` when using this RPC.
|
||||
- `StorageKey` now has an `.args` property, decoded from meta where `twox64_concat` or `blake128_concat` are used on maps
|
||||
- Fix `api.query.*.*.entries` type conversions to return exact types (not `Option` in some cases)
|
||||
- Add `api.query.*.*.keys` to retrieve only the storage keys, similar to `.entries`
|
||||
- Full linked map retrievals will now use direct getStorage queries for faster operation
|
||||
- Underlying rpc-core interfaces now unwraps `Error("...")` when found in responses
|
||||
- Added `derive.eras*` interfaces for queries to new Substrate staking interfaces
|
||||
- Update `derive.account` to cater for new indices module storage (detected with fallbacks)
|
||||
- Adjust derive queries for session without module prefix (DoubleMap -> Map), detected on use
|
||||
- Add runtime validation for map arguments to `api.query.*`
|
||||
- TypeScript interfaces for linked maps now correctly generates as `[Type, Linkage<Next>]`
|
||||
|
||||
# 1.5.1 Mar 06, 2020
|
||||
|
||||
- **Important** Substrate master has updated staking, on older chains supply `StakingLedger: 'StakingLedgerTo223'`
|
||||
- **Important** Substrate master has updated collective, on older chains supply `Votes: 'VotesTo230'`
|
||||
- Add proper support for type generation with an Enum containing an Tuple (Thanks to https://github.com/monitz87)
|
||||
- Fix storage parsing not resulting in rejected Promises (Fix from https://github.com/aniiantt applied)
|
||||
- Remove use of deprecated `Observable.create` (Thanks to https://github.com/Himself65)
|
||||
- Add types & metadata for the latest Polkadot/Substrate runtime versions (master branches)
|
||||
- Type extraction will now allow the same sub-module name across packages, i.e. `@polkadot/types/interfaces/runtime` & `@mine/interfaces/runtime` will be valid
|
||||
- Add `.range([from, to]: [Hash, Hash?], ...args: any[]): [Hash, Codec][]` on all storage entries
|
||||
- Add `.raw(...args: any[]): Promise<Uint8Array & Codec>` to all RPC calls, returning the un-encoded result
|
||||
- Allow pre-module type aliasing with `typesAlias: { <moduleName>: { <meta-type>: <alias-type> } }` in API construction options
|
||||
- Allow `BTreeMap` to be initialized with a `Record<string, any>` object (in addition to `Map`)
|
||||
- Allow for `HashMap<KeyType, ValueType>` definitions
|
||||
- `Bool` will now correctly return `isEmpty` on false/default values
|
||||
- Refresh the `NetworkState` types as returned by the `rpc.system.networkState()` call to current
|
||||
- Expose `registry.createClass(<typeName>)` to allow for creating type classes. If you are using `createClass` or `ClassOf` in your code, it is recommended to swap to this instance.
|
||||
- Add additional derives to `api.derive.staking` to handle lazy-payout retrievals
|
||||
- Update `@polkadot/{util, util-crypto, keyring}` to 1.6.1 & `@polkadot/wasm` to 1.2.1
|
||||
|
||||
# 1.4.2 Feb 27, 2020
|
||||
|
||||
- Fix `api.tx(<extrinsic>): Submittable` decoration (non-working in 1.4.1, now with proper test)
|
||||
|
||||
# 1.4.1 Feb 26, 2020
|
||||
|
||||
- **Breaking change** (TypeScript only) The `*.d.ts` files now contain TypeScript 3.8 features (specifically `#private`), which is not usable in TS versions < 3.8
|
||||
- **Breaking change** - `api.derive.staking.*` has updated result types and detects support for lazy payouts queries
|
||||
- Rework type generation for `api.{query, tx}` to properly handle complex type inputs (Thanks to https://github.com/monitz87)
|
||||
- Rework metadata `--strict` mode to effectively decorate chain metadata (Thanks to https://github.com/monitz87)
|
||||
- Add `api.rpc.chain.subscribeAllHeads` (not just best) (Thanks to https://github.com/jak-pan)
|
||||
- Add `api.rpc.engine.*` for manual seal support
|
||||
- Add `api.injectMetadata(metadata)` to initialize API with a specific metadata version
|
||||
- The api now checks for runtime upgrades, augmenting the interfaces with new metadata when found
|
||||
- Support types & interfaces required for lazy reaping, lazy payouts & offchain phragmen
|
||||
- `Option` types now has an `.unwrapOrDefault` as an complement to `.unwrap` & `.unwrapOr`
|
||||
- Support JS `BigInt` inputs in any derived `UInt` and `Int` object, e.g. `api.tx.balances.transfer(..., 9876543210123456789n)`
|
||||
- `UInt` & `Int` now does source bitLength checks upon construction
|
||||
- Registry now exposes `.createType(<type>, ...args)` as an additional helper (like the API)
|
||||
- Expand `.toHuman` on `ExtrinsicEra`, `SubmittableResult` & `Vote`
|
||||
- Move `DigestItem`, `Fixed64`, `H160`, `H256` & `H512` to interfaces in `@polkadot/types/interfaces`
|
||||
- Align construction of unknown types in `registry.get` consistently warn on detection, throw on use
|
||||
- Support for arbitrary `u*`` types via `UInt<bitLength>` type definitions
|
||||
- Expose static `.with` on `UInt`, `Int` & `U8aFixed` classes with optional type name override
|
||||
- Remove [11 Jan 2019](https://github.com/polkadot-js/api/issues/574) extrinsic length hack
|
||||
- Use ES `#field` on private class fields as applicable
|
||||
- Move `types/primitive/{extrinsics, generic}` to `types/{extrinsics, generic}`
|
||||
- Cleanup augmentation and generation scripts for type definitions, aligning with api augmentation
|
||||
- Bump to `@polkadot/{util, util-crypto, keyring}` 2.5.1
|
||||
|
||||
# 1.3.1 Feb 18, 2020
|
||||
|
||||
- Add `@types/bn.js` as a normal dependency, exposed in `*.d.ts` (Thanks to https://github.com/monitz87)
|
||||
- Type generation scripts (including `polkadot-types-from-{chain,defs}`) has been moved to the `@polkadot/typegen` package
|
||||
- The `@polkadot/types/codec/create` has been moved to `@polkadot/types/create`, imports from `@polkadot/types` are unaffected
|
||||
- Expose chain properties on registry (and use for API type formatting)
|
||||
- Add `toHuman(isExtended?: boolean)` to all codec types, formatting into a human-readable structure
|
||||
|
||||
# 1.2.1 Feb 16, 2020
|
||||
|
||||
- **Important** Update RPC status codes (latest Substrate 2), with the `isInBlock` (`isFinalized` now indicates finality)
|
||||
- Storage `.entries(arg?: any)` now has the correct argument type for DoubleMap (Thanks to https://github.com/monitz87)
|
||||
- Swap Kusama and Polkadot aliases for `Address` to `AccountId` (future update)
|
||||
- Add `LookupSource` and `LookupTarget` types instead of mapping these directly for aliasing
|
||||
- Add `BitVec` type primitive
|
||||
- Add support for `system.account` for balance & nonce queries in derives as well as Submittables (Substrate composites)
|
||||
- Add `rpc.author.hasKey` and `rpc.author.hasSessionKeys` RPCs
|
||||
- Add derives for the parachains interfaces
|
||||
- Applied the latest types for Polkadot parachains
|
||||
- `registry.findMetaError` now can take in a `DispatchErrorModule` object for error lookups (from `asModule` in `DispatchError`)
|
||||
- Metadata now correctly serializes to the original input data via `toHex()` & `toU8a()`
|
||||
- Metadata documentation generation rework, including the output of errors from metadata
|
||||
- Update all examples and comments to use latest `system.account` queries (instead of `system.accountNonce` and `balances.freeBalance`/`balances.reservedBalance`)
|
||||
- Cleanup `codec/Date` tests to make it run properly on all timezones
|
||||
- Add explicit dependencies to all packages and move TypeScript `@types/*` to dev deps
|
||||
|
||||
# 1.1.1 Feb 06, 2020
|
||||
|
||||
- **Important** Chains without `balances.account` or `system.account` should supply `"BalanceLock": "BalanceLockTo212"` to their types to use the previous-generation `BalanceLock` (when querying locks)
|
||||
- Add support for `balances.account` in all applicable derives (incl. `vesting` module)
|
||||
- Inject and use SignedExtensions by name from V11 metadata (V4 extrinsics only)
|
||||
- Add typings for `api.tx.*.*` - the `polkadot-types-from-chain` now also generates these
|
||||
- Remove additional V1-only derives `(staking.recentlyOffline`, `balances.nominatorsFor`)
|
||||
- Add `.isMax()` on int values, an opposite of `isZero()` (e.g. `u128`, as well as derived, e.g. `Balances`)
|
||||
- Add `.keyPrefix()` to all `api.query.*` complementing the `.key()` call, both returning a hex string
|
||||
- Council derives now takes bootstrapping (member, no elections) into account
|
||||
- Account derives now allow for an optional indices module (not required)
|
||||
- Adjust balances fees derivation with optional transfer and creation fees (removed in Substrate)
|
||||
- Adjust enum `.toJSON()` to return type name as specified
|
||||
|
||||
# 1.0.1 Jan 30, 2020
|
||||
|
||||
- **Breaking change** Drop support for Substrate v1 chain in all derives
|
||||
- Return unsub functions from provider .on emitters (Thanks to https://github.com/jak-pan)
|
||||
- `ApiPromise.isReady` now rejects on unrecoverable errors (Thanks to https://github.com/laec)
|
||||
- Add `polkadot-types-from-chain` & `polkadot-types-from-defs` TypeScript generators to `@polkadot/types`
|
||||
- Only decorate derives where relevant parent `api.query.*` is available
|
||||
- Support `.entries(arg?: any)` lookups on DoubleMaps (in addition to previously supported maps)
|
||||
- Allow v9 metadata to parse even in cases where it was wrongly deployed pre-v10
|
||||
- Allow type-aliases on a per-module basis (e.g. `Judgement` in identity as well as society)
|
||||
- Allow passing `{ signer }` to both `api.tx.*` and `api.sign` (in addition to `api.setSigner`)
|
||||
- Add derives for the society module
|
||||
- Don't map empty tuples, e.g. `()` to `Null`, rather keep them empty
|
||||
- Add lookups to the metadata errors via `findMetaError`
|
||||
- Update metadata and types for the latest Substrate & Polkadot versions
|
||||
- Support metadata V11 as per latest Substrate
|
||||
- Remove support for un-deployed metadata
|
||||
- Remove old known types for Substrate V1
|
||||
|
||||
# 0.100.1 Jan 13, 2020
|
||||
|
||||
- **Important** This will the the last API version with Substrate 1.x support. Although you will still be able to use subsequent versions with older chains, dependent libraries such as sr25519 may not be compatible.
|
||||
- Add support for the Substrate identity module
|
||||
- Remove the `codec/Data` type, to remove a conflict with Substrate. This type is now named `Raw`
|
||||
- Fix for linked maps using `Option`
|
||||
- Add support for `BTreeSet` (Thanks to https://github.com/satellitex)
|
||||
- Add support for Metadata v10
|
||||
- Add support for latest Polkadot/Substrate types
|
||||
- Add `paymentInfo` to submittables to calculate fees
|
||||
|
||||
# 0.99.1 Dec 13, 2019
|
||||
|
||||
- **Breaking change** The `Data` and `U8a` type has been renamed and just replaced with the `Raw` type
|
||||
- **Breaking change** The `api.derive.staking.info` has been split into 2 - `staking.query` for non-balance related information (more effective) and `staking.account` that enhances query for all the information previously found `.info`
|
||||
- Cleanup `DoubleMap` hashing to always hash over the full value (in the case of `Vec<T>`, this includes the length)
|
||||
- Update democracy derives to take care of nextTally and lowestUnbaked
|
||||
- Add additional derives for both council & treasury
|
||||
- Alignment with latest Polkadot/Substrate master branch types
|
||||
|
||||
# 0.98.1 Dec 04, 2019
|
||||
|
||||
- Make the TypeScript generation script mor re-usable (Thanks to https://github.com/xlc)
|
||||
- Add `.entries()` for all map-types, returning storage keys and values
|
||||
- Add `.signAsync` to submittable extrinsics (Thanks to https://github.com/c410-f3r)
|
||||
- Cleanup circular references between internal dependencies
|
||||
- Support for new Substrate democracy with preimages in derive
|
||||
- Alignment of types with Substrate/Polkadot master branches
|
||||
|
||||
# 0.97.1 Nov 29, 2019
|
||||
|
||||
- **Breaking change** Add the passing on an explicit `Registry` to all calls to `createType` as well as all codec classes. If you are upgrading form an older version, use the [migration guide](UPGRADING.md) to walk through the changes required.
|
||||
- **Breaking change** The metadata classes have been moved from `@polkadot/types` into `@polkadot/metadata`. If you explicitly create `Metadata` classes, you now would need to do so with the `import Metadata from '@polkadot/metadata';` This is a decorated class, where the previous metadata is now available on `Metadata.metadata`, alongside decorated `consts.*`', `tx.*` and `query.*`.
|
||||
- **Breaking change** Session `Keys` defaults to 4 keys now (Substrate master), depending on your node config, you would want to override with e.g. `Keys: 'SessionKeys3'` (1, 2, 3, 4, 5 & 6)
|
||||
- **Breaking change** `ValidatorPrefs` now default to the new percentage commission model, to use the previous `validatorPayment`, you can override with `ValidatorPrefs: 'ValidatorPrefsTo196'`
|
||||
- `api.derive.*` now has built-in memomization
|
||||
- Various fixes and cleanups to `api.derive.*` including era length progress and vesting calculations
|
||||
- Aligned all types with the latest Polkadot & Substrate, including Kusama CC3
|
||||
- Support for Metadata V9, which adjusts the hashing methods of storage entries
|
||||
- Support for Metadata V10 (still un-released), which includes prefixed map support
|
||||
|
||||
# 0.96.1 Nov 09, 2019
|
||||
|
||||
- Updated types for latest Kusama
|
||||
- Add `filterRecords` (in addition to `findRecord`) on submittable results
|
||||
- Various ABI v2 contract fixes
|
||||
- Update derive for elections (incl. RunnersUp) and heartbeat derives (with blocks & messages)
|
||||
- Add vesting totals & locked breakdowns to derive balances
|
||||
- Update council derives for the latest Substrate master support (with constants)
|
||||
- Derive cleanups, including sharing of instances between the API and internal to derives
|
||||
|
||||
# 0.95.2 Oct 25, 2019
|
||||
|
||||
- Temporary removal of `account_nextIndex` use, will be re-added in a future release
|
||||
|
||||
# 0.95.1 Oct 25, 2019
|
||||
|
||||
- Support Extrinsic V4 with additional signature indicator (Latest Polkadot/Substrate/Kusama)
|
||||
- Adjust subscription update checks to avoid duplicated data updates
|
||||
- Support Metadata V8 (exposes per-module `decl_error` definitions)
|
||||
- Support next generation contracts ABI (with additional type definitions)
|
||||
- Support for `BTreeMap<K, V>` types and definitions
|
||||
- All latest Polkadot & Substrate types (as per master branches)
|
||||
- **Breaking change** `Call.injectMethods` is moved to `Call.injectMetadata` to align with `Events` (This _should_ not be used externally, however mentioned as breaking here)
|
||||
|
||||
# 0.94.1 Oct 07, 2019
|
||||
|
||||
- Add handling of `Result<Ok, Error>` definitions
|
||||
- Adjust API cloning now takes RPC filters from source into account
|
||||
- Simplification of isPedantic checks and less overhead on StorageData types
|
||||
- Cleanups and fixes around RPC and derive type definitions
|
||||
- Fix `derive.imOnline.receivedHeartbeats` to query via indexes
|
||||
- Adjustment of `api.derive.elections.{approvalsOf|approvalsOfAt}` to allow ss58 address input
|
||||
- Cleanup `Enum` `.eq` handling to be more exhaustive
|
||||
- Add documentation for custom extrinsic formats (advanced chains)
|
||||
- Update to latest substrate master metadata
|
||||
|
||||
# 0.93.1 Sep 26, 2019
|
||||
|
||||
- Support for Kusama CC2
|
||||
- In extrinsic submission, use `rpc.account.nextIndex` to retrieve the nonce when available
|
||||
- For TypeScript users `api.query.*.*` is now properly typed for default Substrate calls, i.e. `api.query.balances.freeBalance(...)` will return a `Balance` type. Additionally the `api.queryMulti` and `.multi` on queries not allow generic type params.
|
||||
- Add `api.rpc.accounts.nextIndex`, `api.rpc.contracts.call` and `api.rpc.rpc.methods` calls. Optional calls (such as account/contracts) is decorated based on the results from `rpc.methods`, so they don't show up on nodes where they are not active.
|
||||
- Updated types to support the latest Polkadot/Substrate master changes
|
||||
- Support recursive type registration (self-referencing via `Box`) in addition to better sanitation of user-defined-types
|
||||
- Documentation and example updates (thanks mostly to contributions)
|
||||
|
||||
# 0.92.1 Sep 12, 2019
|
||||
|
||||
- The API now correctly sets the ss58 prefix as retrieved from the chain properties via `ss58Format`
|
||||
- Bump to `@polkadot/util` 1.4.1, removing use of `ExtError`
|
||||
- The `Keyring` from `@polkadot/keyring` is now exposed on the API as well. You can do `import { Keyring } from '@polkadot/api'` - this alleviates the need for extra dependencies (apart from `@polkadot/api`), and since the keyring is critical for signing operations, aligns everything in one bundle
|
||||
- Support the latest Polkadot & Substrate master branches (incl. metadata updates)
|
||||
- Getting started documentation has been made available
|
||||
|
||||
# 0.91.1 Sep 09, 2019
|
||||
|
||||
- This release was focussed on stability, with a number of cleanups and bug-fixes
|
||||
- Adjustments for Substrate 1.x chain detection (with auto-types) and Substrate 2.x support has been extended with all latest types
|
||||
- The `getRuntimeVersion` and `subscribeRuntimeVersion` RPCs are now only available on the `rpc.state.*` endpoints. This aligns with the Substrate implementation.
|
||||
- The `author_insertKey` RPC's last argument `publicKey` is now required, as to reflect Substrate implementation.
|
||||
- Support for extrinsics with versions that is not in the base Substrate implementation (V1-V3) can now be done by providing an implementation for `ExtrinsicUnknown`
|
||||
- Redeemed balance calculation if `api.derive` now returns the correct values again (bug fix)
|
||||
- added the `yarn chain:info [--ws URL]` utility to extract a calls-only metadata version
|
||||
- Missing types are now logged via a `console.warn`, not via `.error`
|
||||
- `Extrinsic`, `ExtrinsicPayload` & `SignerPayload` is registered in the type registry and can be overridden now
|
||||
- **Breaking change** `SignerPayload` is renamed to `SignerPayloadJSON`
|
||||
- **Breaking change** `SignerPayloadJSON`, `SignerPayloadRawBase` and `SignerPayloadRaw` are all moved to `@polkadot/types`
|
||||
|
||||
# 0.90.1 Aug 24, 2019
|
||||
|
||||
If you are upgrading form an older version, use the CHANGELOG hand-in-hand with the [migration guide](UPGRADING.md).
|
||||
|
||||
- **Breaking change** `api.rpc.chain.subscribeNewHeads` is now available as opposed to the old `subscribeNewHead`. This aligns with the Substrate implementation.
|
||||
- **Breaking change** Substrate 2.x & Polkadot master has moved both `BlockNumber` & `Index` to `u32`. The API tracks these closely. If you are running a chain with `u64` values (for either), pass the type override to the API on creation, e.g. `ApiPromise.create({ types: { BlockNumber: 'u64', Index: 'u64' } })` to avoid getting warnings about mismatched types.
|
||||
- **Breaking change** `Api.create(...)` and `new Api(...)` now only takes an options Object, so if you passed the provider directly previously, you need to swap the use to `Api.create({ provider: ... })`
|
||||
- **Breaking change** Runtime types have been extended and moved to definitions instead of classes
|
||||
- Primitive types for `i*` and `u*` (e.g. `u32`) are now only available in their lowercase versions. Additionally `Vector` is now only available as `Vec`, and `Method` has been renamed to `Call`, in both cases aligning with Rust.
|
||||
- `Moment` now implements as `u64` as per the Substrate codebase. (It it up to the user to interpret, for substrate 2.x it is not ms resolution)
|
||||
- For creation of types, it is recommended to use `createType(<TypeName>, <value>)` instead of e.g. `new Proposal(...)`. When passing these to methods/queries, construction should not be needed, the raw value can be passed.
|
||||
- For moved types, a previous import would have been from `@polkadot/types`, i.e. `import { SetIndex } from '@polkadot/types`, now just the interfaces (TypeScript) are available via `import { SetIndex } from '@polkadot/types/interfaces`
|
||||
- `usize` is now a blacklisted type that will throw on construction. Since it is platform-specific, it creates incompatibilities between native (generally `u64`) and WASM (always `u32`) code. Use one of the `u32` or `u64` types explicitly.
|
||||
- Support substrate v7 metadata
|
||||
- The `Method.findFunction(callIndex)` (allowing decoding of raw data), is now available on `api.findCall(callIndex)`. To keep backwards compatibility, it is still available on `GenericCall.findMethod` but the `api.findCall` is recommended and suggested.
|
||||
- The `types/codec/createType` has been moved to `types/codec/create` with the same exports. If you explicitly imported from here (and not doing the suggested `import { createType } from '@polkadot/types`), the reference needs to be updated
|
||||
|
||||
|
||||
# 0.82.0-beta.x Jul 28, 2019
|
||||
|
||||
- Support for substrate 2.x (master) has been extended,
|
||||
- Additional types have been addedd for the modules
|
||||
- `api.derive.contract` is now `api.derive.contracts` to align with the substrate 2.x rename. (Feature detection is used so it supports both 1.x and 2.x chains)
|
||||
- Addition of `api.derive.elections`
|
||||
|
||||
- Support latest substrate 2 v6 metadata with module constants using `api.consts`.
|
||||
- The api now uses the module name for the storage methods, aligning module names for consistency with transactions. The methods of the grandpa module moved from `api.query.grandpaFinality` to `api.query.grandpa`.
|
||||
- Internally the `@polkadot/extrinsics` and `@polkadot/storage` have been moved to `@polkadot/api-metadata` and are now accessible as `@polkadot/api-metadata/extrinsics` and `@polkadot/api-metadata/storage`, respectively.
|
||||
- **Breaking Change** Vote interface extends U8a instead of i8. Vote properties can be accessed via the `isAye`, `isNay`, and `conviction` getters. Votes can still be constructed as before with a raw JS boolean, a SCALE encoded Boolean, an i8 number, or a JS object with properties `aye` and `conviction` defined.
|
||||
|
||||
- Support V2 Extrinsics in addition to V1, v2 includes an optional `tip`
|
||||
- In addition to this support, the `Signer` interface has deprecated the `sign` method and replaced it with `signPayload`
|
||||
- Support for the `sign` interfaces (API detection and calling when `signPayload` is not available) will be removed in subsequent versions.
|
||||
|
||||
- The `ContractsAbi` type has been moved from `@polkadot/types` to `import { Abi } from '@polkadot/api-contract`. This paves the way for an enhanced contracts interface, instead of dealing with low-level API calls.
|
||||
|
||||
|
||||
# 0.81.1 Jun 14, 2019
|
||||
|
||||
- The dependency on `@polkadot/keyring` has been removed - if you relied on the API to provide this, you would now need to manually add it
|
||||
- `createType` allows for the creation of `[u8; <length>]` types (opening the door for contract support)
|
||||
- `api.derive.staking.info` now returns the `rewardDestination`
|
||||
- Fix for disconnection when default providers (non-specified) are used
|
||||
- Don't console.log type decoding errors and then throw, only re-throw with additional info
|
||||
- Support latest substrate 2.x v5 metadata
|
||||
- Add `ApprovalFlag`, `SetIndex`, `VoterInfo` types for council as per substrate
|
||||
- Update `ContractInfo` to match substrate master
|
||||
|
||||
- Add support for new inherent digests from substrate.
|
||||
- **Breaking change** Because of the new `Seal`, the old/new Seals are not compatible. If you were using the old `Seal` from the `Digest`s, you would now use `isSealV0` for the pre-substrate 1.0 version and the new `isSeal` for the current version
|
||||
- Update `HeaderExtended` to retrieve author information from substrate 2.x (new `PreRuntime` digests)
|
||||
|
||||
- Cater for `Vec`, `Option`, `Result`, tuples and fixed vectors for contracts ABIs
|
||||
- Additional examples for subscriptions using multi
|
||||
- Add `off` method to `Api` (Base, for both `ApiPromise` & `ApiRx`) to remove an event listener
|
||||
|
||||
|
||||
# 0.80.1 Jun 04, 2019
|
||||
|
||||
- Support for mortal transactions
|
||||
- Better DoubleMap storage support
|
||||
- api-derive cleanups, including additional info for balances.all and taking.info returning redeemable and locked balances
|
||||
- Added SignaturePayloadRaw for better offline signing support
|
||||
- Updated metadata for current substrate master
|
||||
- Misc. cleanups and fixes
|
||||
|
||||
|
||||
# 0.79.1 May 22, 2019
|
||||
|
||||
- DoubleMap query support
|
||||
- Support latest EventRecord metadata (substrate master)
|
||||
- Introduce RuntimeVersion type overrides in api/nodeCompat.ts
|
||||
- Add `api.queryMulti` and `api.query.<module>.<method>.multi`
|
||||
- Convert `api.derive.*` to use multi queries
|
||||
- `types/codec/Set` now extends the base JS `Set` (**breaking change**: `set.values` -> `set.strings`)
|
||||
- Breaking: rename `meta.arguments` to `meta.args` in function metadata (`arguments` is a JS reserved word)
|
||||
- Add `toRawType` on all type classes (breakdown into primitive types)
|
||||
|
||||
|
||||
# 0.78.1 May 08, 2019
|
||||
# 0.78.1
|
||||
|
||||
- Fix linked-maps (not working since 0.77.1)
|
||||
- Convert Usize to U32 (as found in WASM environments)
|
||||
@@ -333,38 +8,31 @@ If you are upgrading form an older version, use the CHANGELOG hand-in-hand with
|
||||
- Do type assertion on all exposed asXXX getters
|
||||
- Metadata updates for substrate (WithdrawReasons, ContractInfo)
|
||||
|
||||
|
||||
# 0.77.1 Apr 25, 2019
|
||||
# 0.77.1
|
||||
|
||||
- Support Metadata v4, which introduces the use of a custom hasher to hash storage map keys.
|
||||
- Add TreasuryProposal (not the same as democracy, type aliased)
|
||||
- Add TresuryProposal (not the same as democracy, type aliassed)
|
||||
|
||||
|
||||
# 0.76.1 Apr 03, 2019
|
||||
# 0.76.1
|
||||
|
||||
- Caching improvements (duplicate queries, no duplicate subscriptions)
|
||||
- Experimental contract API
|
||||
- Update @polkadot/keyring to enable Alice's stash account on dev chains
|
||||
- Update @polkadot/util-crypto with smaller footprint
|
||||
|
||||
|
||||
# 0.75.1 Mar 29, 2019
|
||||
# 0.75.1
|
||||
|
||||
- Start journey to 1.0
|
||||
|
||||
|
||||
# 0.53.1 Mar 29, 2019
|
||||
# 0.53.1
|
||||
|
||||
- Change spelling to US English as per substrate master (1.0-rc1). Breaking changes as a result:
|
||||
- For extrinsic status results, if you have checked the type returns, i.e. `result.type === 'Finalised'` now check on the status for `result.status.isFinalized` or `result.status.isBroadcast`, ... (the `type` property is now accessible only on `result.status.type`)
|
||||
- If using `subscribeFinalisedHeads` update this to `subscribeFinalizedHeads` (likewise `getFinalisedHead` should be updated to `getFinalizedHead` and `derive.bestNumberFinalized`)
|
||||
- The underlying ss58 addess checksums have changed in the keyring along with the latest specs
|
||||
- All examples have been updated with sr25519 addresses (with the new checksums)
|
||||
|
||||
- The underlying ss58 address checksums have changed
|
||||
- The updated keyring with support for this has been made available
|
||||
- All examples have been updated with sr25519 addresses (with the new checksums)
|
||||
|
||||
|
||||
# 0.52.1 Mar 28, 2019
|
||||
# 0.52.1
|
||||
|
||||
- Support queries to linked mapped storage (found in new staking interfaces)
|
||||
- Add `derive.staking.controllers` to retrieve all active staking controllers
|
||||
@@ -373,43 +41,36 @@ If you are upgrading form an older version, use the CHANGELOG hand-in-hand with
|
||||
- Allow parsing of V3 metadata with DoubleMap support
|
||||
- Check for single instances for api and types as they are loaded (assertSingletonPackage)
|
||||
|
||||
|
||||
# 0.51.1 Mar 25, 2019
|
||||
# 0.51.1
|
||||
|
||||
- Support metadata V2 as per latest substrate master
|
||||
- Update metadata with new types as per latest substrate master
|
||||
- Update metadata with new types as per lastest substrate master
|
||||
|
||||
# 0.50.1
|
||||
|
||||
# 0.50.1 Mar 23, 2019
|
||||
|
||||
- Latest util-crypto (usage of WASM with JS fallbacks if not available)
|
||||
- Lastest util-crypto (usage of WASM with JS fallbacks if not available)
|
||||
- Update upstream @polkadot dependencies (for new crypto)
|
||||
|
||||
|
||||
# 0.49.1 Mar 20, 2019
|
||||
# 0.49.1
|
||||
|
||||
- Fix large message signing on non-known nodes (default is now hashing, there has been enough time between upgrades)
|
||||
|
||||
|
||||
# 0.48.1 Mar 18, 2019
|
||||
# 0.48.1
|
||||
|
||||
- Pull in new sr25519 capable keyring for dev nodes
|
||||
- When using dev mode, it assumes that the node is the latest with derived sr25519 keys
|
||||
|
||||
|
||||
# 0.47.1 Mar 14, 2019
|
||||
# 0.47.1
|
||||
|
||||
- Swap to publishing -beta.x on merge (non-breaking testing)
|
||||
|
||||
|
||||
# 0.46.1 Mar 01, 2019
|
||||
# 0.46.1
|
||||
|
||||
- Extended type registration to now handle internal types as well. Additionally the built-in Extrinsic type can now we overridden with a custom version.
|
||||
- Where `Extrinsic` and `Method` is used as types, consider importing `{ IMethod, IExtrinsic }` from `@polkadot/types/types`, especially in the cases where this is used from a `SubmittableExtrinsic`
|
||||
- Where `Extrinsic` and `Method` is used as types, considder importing `{ IMethod, IExtrinsic }` from `@polkadot/types/types`, especially in the cases where this is uased from a `SubmittableExtrinsic`
|
||||
- The `typeRegistry` constant is now `getTypeRegistry()` as a function
|
||||
|
||||
|
||||
# 0.45.1 Feb 19, 2019
|
||||
# 0.45.1
|
||||
|
||||
- Storage with option values now correctly return `Option<Type>` and is indicated as such in the documentation
|
||||
|
||||
@@ -425,10 +86,9 @@ const llo = await api.query.session.lastLengthChange();
|
||||
console.log('llo', llo.unwrapOr('not set') /* Option<BlockNumber> */)
|
||||
```
|
||||
|
||||
# 0.44.1
|
||||
|
||||
# 0.44.1 Feb 19, 2019
|
||||
|
||||
- Split primitives and types into separate folders. This should not affect external use since the exports remain the same, however does have an impact where classes are referenced directly. e.g.
|
||||
- Split primitives and types into seperate folders. This should not affect external use since the exports remain the same, however does have an impact where classes are referenced directly. e.g.
|
||||
|
||||
```js
|
||||
// old (affected)
|
||||
@@ -443,46 +103,38 @@ import Signature from '@polkadot/types/type/Signature';
|
||||
import { Method, Signature } from '@polkadot/types';
|
||||
```
|
||||
|
||||
# 0.43.1
|
||||
|
||||
# 0.43.1 Feb 14, 2019
|
||||
- Intrduces support for the new keyring with sr25519 support in addition to ed25519. While this does not change the exposed API, it is considerred breaking since @polkadot/keuyring has interface changes. (Unless needed, don't rush the upgrade)
|
||||
|
||||
- Introduces support for the new keyring with sr25519 support in addition to ed25519. While this does not change the exposed API, it is considered breaking since @polkadot/keyring has interface changes. (Unless needed, don't rush the upgrade)
|
||||
|
||||
|
||||
# 0.42.1 Jan 31, 2019
|
||||
# 0.42.1
|
||||
|
||||
- Support for substrate hash signing with implVersion >= 18
|
||||
- Changed signatures for Extrinsic signing, this should not have (much) of an impact since it is generally not used directly. SubmittableExtrinsic (as exposed by the API), supports the old-style use.
|
||||
|
||||
# 0.41.1
|
||||
|
||||
# 0.41.1 Jan 26, 2019
|
||||
- Support the V1 metadata specification from Substrate in addition to the currently testnet-active V0 version
|
||||
|
||||
- Support the V1 metadata specification from Substrate in addition to the currently testnet active V0 version
|
||||
|
||||
|
||||
# 0.40.1 Jan 16, 2019
|
||||
# 0.40.1
|
||||
|
||||
- The API interfaces now require a WS-compatible provider, e.g. subscription support is a must. Previously the HTTPProvider could be use (although it was very limited in the interactions).
|
||||
|
||||
|
||||
# 0.39.1 Jan 11, 2019
|
||||
# 0.39.1
|
||||
|
||||
- The Promise API now returns a `Promise<UnsubFunction>` instead of `UnsubFunction` when making subscriptions.
|
||||
|
||||
|
||||
# 0.38.1 Jan 08, 2019
|
||||
# 0.38.1
|
||||
|
||||
Substrate has been updated with a breaking new transaction format where the Index/Nonce is now encoded as a Compact. This change is being rolled out to both Alexander (Polkadot testnet) as well as Charred Cherry (Substrate testnet) - transactions between old and new are not compatible.
|
||||
|
||||
# 0.37.1
|
||||
|
||||
# 0.37.1 Jan 04, 2019
|
||||
|
||||
api-observable has been removed. This was only used in /apps and inconsistent with the api/rx and api/promise APIs. Future work will include derives like was included in api-observable into the base.
|
||||
api-observable has been removed. This was only used in /apps and inconsistent with the api/rx and api/promise APIs. Future work will include derivates like was included in api-observable into the base.
|
||||
|
||||
Tuples now return single types when only one type is available, i.e. `(AccountId)` would now resolve as `AccountId`. The extra type wrapper adds no benefit to users here.
|
||||
|
||||
|
||||
# 0.36.1 Jan 03, 2019
|
||||
# 0.36.1
|
||||
|
||||
Api Promise has been updated in the way we deal with subscriptions. Previously a subscription returned `Promise<number>` where the caller was to keep track of the id and use it in subsequent unsubscribes. Now any subscriptions return an unsubscribe/destroy function `(): void`, that is use for removing the subscriptions, e.g.
|
||||
|
||||
@@ -492,52 +144,10 @@ const unsubscribe = api.query.balance.freeBalance(Alice, (balance) => {...});
|
||||
unsubscribe(); // here we destroy the subscription
|
||||
```
|
||||
|
||||
|
||||
# 0.35.1 Dec 20, 2018
|
||||
# 0.35.1
|
||||
|
||||
Swapped to new metadata structures from Substrate. If the API is not working with your node, update Substrate to latest master branch. (Or 0.9.1 for Charred Cherry). Dropped support for old metadata as found as far back as BBQ Birch.
|
||||
|
||||
|
||||
# 0.34.1 Dec 18, 2018
|
||||
# 0.34.1
|
||||
|
||||
Changed the send signature (for future expansion of eg. events) to return `result: { status: ExtrinsicStatus }` instead of `status: ExtrinsicStatus`. For most cases where only status `type` checks are used, i.e. `status.type === 'Finalised'` this should not be a breaking change. Deep inspection of the status object however will need to adapt.
|
||||
|
||||
# 0.33.1 Dec 06, 2018
|
||||
|
||||
# 0.32.1 Nov 21, 2018
|
||||
|
||||
# 0.31.1 Oct 10, 2018
|
||||
|
||||
# 0.30.1 Sep 27, 2018
|
||||
|
||||
# 0.29.1 Sep 14, 2018
|
||||
|
||||
# 0.28.1 Aug 11, 2018
|
||||
|
||||
# 0.15.1 Aug 07, 2018
|
||||
|
||||
# 0.14.1 Jun 23, 2018
|
||||
|
||||
# 0.13.1 May 29, 2018
|
||||
|
||||
# 0.12.1 May 18, 2018
|
||||
|
||||
# 0.11.1 May 16, 2018
|
||||
|
||||
# 0.10.1 May 07, 2018
|
||||
|
||||
# 0.9.1 Apr 24, 2018
|
||||
|
||||
# 0.8.1 Mar 15, 2018
|
||||
|
||||
# 0.7.1 Jan 25, 2018
|
||||
|
||||
# 0.6.1 Dec 03, 2017
|
||||
|
||||
# 0.5.1 Nov 28, 2017
|
||||
|
||||
# 0.4.1 Nov 19, 2017
|
||||
|
||||
# 0.3.1 Nov 19, 2017
|
||||
|
||||
# 0.2.1 Nov 18, 2017
|
||||
|
||||
@@ -1,44 +1,39 @@
|
||||
[](https://polkadot.js.org)
|
||||

|
||||
[](https://www.npmjs.com/package/@polkadot/api)
|
||||
[](https://www.npmjs.com/package/@polkadot/api)
|
||||
[](https://codeclimate.com/github/polkadot-js/api)
|
||||
[](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/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://polkadot.js.org/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/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/api-metadata](packages/api-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/api/substrate/rpc.html) 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/jsonrpc](packages/jsonrpc/) Definitions for JSONRPC endpoints
|
||||
- [@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 [@polkadot](https://github.com/polkadot-js/) 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 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/polkadot-js/api <optional local path>`
|
||||
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`
|
||||
|
||||
-201
@@ -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).
|
||||
+3
-1
@@ -1 +1,3 @@
|
||||
module.exports = require('@polkadot/dev/config/babel');
|
||||
module.exports = {
|
||||
extends: '@plugnet/dev/config/babel'
|
||||
};
|
||||
|
||||
@@ -1,23 +0,0 @@
|
||||
#!/usr/bin/env bash
|
||||
|
||||
function copy_folder () {
|
||||
SRC="packages/$1/build"
|
||||
DST="../apps/node_modules/@polkadot/$1"
|
||||
|
||||
echo "** Copying $SRC to $DST"
|
||||
|
||||
rm -rf $DST
|
||||
cp -r $SRC $DST
|
||||
}
|
||||
|
||||
yarn polkadot-dev-build-ts
|
||||
|
||||
copy_folder "api"
|
||||
copy_folder "api-contract"
|
||||
copy_folder "api-derive"
|
||||
copy_folder "metadata"
|
||||
copy_folder "rpc-core"
|
||||
copy_folder "rpc-provider"
|
||||
copy_folder "jsonrpc"
|
||||
copy_folder "types"
|
||||
copy_folder "typegen"
|
||||
@@ -1,102 +0,0 @@
|
||||
# Docker compose file to run Polkadot-JS API e2e test files on supported versions of Polkadot and Substrate
|
||||
#
|
||||
# Setup:
|
||||
# Builds 5 containers with different supported versions of Substrate and Polkadot.
|
||||
# Runs Polkadot-JS API Tests
|
||||
#
|
||||
# Before you can run this script, you need to install Docker and 'Docker Compose' on your machine.
|
||||
# Please follow the steps described here (including the prerequisites): https://docs.docker.com/compose/install/
|
||||
#
|
||||
# Usage:
|
||||
# 1. BUILD: Run `docker-compose pull && docker-compose up -d` to pull the latest docker imaged and run docker-compose in detached mode. This will run the substrate and polkadot containers in the background.
|
||||
# 2. INFO: Run `docker ps` to get a list of Docker containers running in the background including their mapped ports on localhost
|
||||
# 3. TEST: Run `docker-compose logs -f js-api-tests` to run the API tests and print the logs
|
||||
# 4. QUIT: Run `docker-compose down` to stop and remove all running containers.
|
||||
#
|
||||
# Provided Endpoints for localhost:
|
||||
# - Substrate Master: ws://127.0.0.1:9945/
|
||||
# - Substrate 1.0: ws://127.0.0.1:9946/
|
||||
# - Substrate 2.0: ws://127.0.0.1:9947/
|
||||
# - Polkadot Master: ws://127.0.0.1:9948/
|
||||
# - Polkadot Alexander: ws://127.0.0.1:9949/
|
||||
#
|
||||
# Find more Docker images of Substrate https://hub.docker.com/r/parity/substrate/tags
|
||||
# Find more Docker images of Polkadot https://hub.docker.com/r/parity/polkadot/tags
|
||||
|
||||
|
||||
version: "3.7"
|
||||
services:
|
||||
substrate-master:
|
||||
image: parity/substrate:latest
|
||||
ports:
|
||||
- "9945:9944"
|
||||
- "9935:9933"
|
||||
networks:
|
||||
- internet
|
||||
command:
|
||||
- "--dev"
|
||||
- "--ws-external"
|
||||
- "--rpc-external"
|
||||
|
||||
substrate-1.0:
|
||||
image: parity/substrate:v1.0.0
|
||||
ports:
|
||||
- "9946:9944"
|
||||
- "9936:9933"
|
||||
networks:
|
||||
- internet
|
||||
command:
|
||||
- "--dev"
|
||||
- "--ws-external"
|
||||
- "--rpc-external"
|
||||
|
||||
substrate-2.0:
|
||||
image: parity/substrate:2.0.0-b65c315a1
|
||||
ports:
|
||||
- "9947:9944"
|
||||
- "9937:9933"
|
||||
networks:
|
||||
- internet
|
||||
command:
|
||||
- "--dev"
|
||||
- "--ws-external"
|
||||
- "--rpc-external"
|
||||
|
||||
polkadot-master:
|
||||
image: parity/polkadot:latest
|
||||
ports:
|
||||
- "9948:9944"
|
||||
- "9938:9933"
|
||||
networks:
|
||||
- internet
|
||||
command:
|
||||
- "--dev"
|
||||
- "--ws-external"
|
||||
- "--rpc-external"
|
||||
|
||||
polkadot-alexander:
|
||||
image: parity/polkadot:v0.4.4
|
||||
ports:
|
||||
- "9949:9944"
|
||||
- "9939:9933"
|
||||
networks:
|
||||
- internet
|
||||
command:
|
||||
- "--dev"
|
||||
- "--ws-external"
|
||||
- "--rpc-external"
|
||||
|
||||
# This is the container running the API tests
|
||||
js-api-tests:
|
||||
image: node:11
|
||||
volumes:
|
||||
- ./:/polkadot-js/api
|
||||
working_dir: /polkadot-js/api
|
||||
network_mode: host
|
||||
tty: true
|
||||
environment:
|
||||
- TERM=xterm-256color`
|
||||
command: bash -c "NODE_ENV=abc /usr/local/bin/yarn && /usr/local/bin/yarn test:all"
|
||||
|
||||
networks:
|
||||
internet:
|
||||
@@ -1,89 +0,0 @@
|
||||
module.exports = {
|
||||
base: '/api/',
|
||||
title: 'polkadot-js/api',
|
||||
description: 'API libraries and interfaces for communicating with Polkadot and Substrate nodes',
|
||||
markdown: {
|
||||
lineNumbers: true
|
||||
},
|
||||
themeConfig: {
|
||||
displayAllHeaders: true,
|
||||
nav: [
|
||||
{ text: 'Polkadot/Substrate Apps', link: 'https://polkadot.js.org/apps/' },
|
||||
{ text: 'Project family', link: 'https://polkadot.js.org/' },
|
||||
{
|
||||
text: 'Documentation',
|
||||
items: [
|
||||
{ text: 'API Reference (this)', link: 'https://polkadot.js.org/api/' },
|
||||
{ text: 'Utility Reference', link: 'https://polkadot.js.org/common/' },
|
||||
{ text: 'UI Libs Reference', link: 'https://polkadot.js.org/ui/' },
|
||||
]
|
||||
},
|
||||
{ text: 'GitHub', link: 'https://github.com/polkadot-js/api' }
|
||||
],
|
||||
search: false,
|
||||
sidebar: [
|
||||
{
|
||||
title: 'Getting started',
|
||||
path: '/start/',
|
||||
collapsable: false,
|
||||
sidebarDepth: 0,
|
||||
children: [
|
||||
['start/install.md', 'Installation'],
|
||||
['start/basics.md', 'Basics & Metadata'],
|
||||
['start/create.md', 'Creating an instance'],
|
||||
['start/api.consts.md', 'Runtime Constants'],
|
||||
['start/api.query.md', 'State queries'],
|
||||
['start/api.rpc.md', 'RPC calls'],
|
||||
['start/api.query.subs.md', 'Query subscriptions'],
|
||||
['start/api.query.multi.md', 'Multi queries'],
|
||||
['start/api.query.other.md', 'Query extras'],
|
||||
['start/api.tx.md', 'Transactions'],
|
||||
['start/keyring.md', 'Keyring'],
|
||||
['start/api.tx.subs.md', 'Transaction subscriptions'],
|
||||
['start/api.tx.wrap.md', 'Complex transactions'],
|
||||
['start/types.basics.md', 'Type basics'],
|
||||
['start/types.extend.md', 'Extending types'],
|
||||
['start/types.create.md', 'Creating types'],
|
||||
['start/typescript.md', 'TypeScript interfaces'],
|
||||
['start/typescript.user.md', 'TypeScript user generated'],
|
||||
['start/FAQ.md', 'FAQ']
|
||||
]
|
||||
},
|
||||
{
|
||||
title: 'Examples (Promise API)',
|
||||
path: '/examples/promise/',
|
||||
collapsable: false,
|
||||
sidebarDepth: 0,
|
||||
children: [
|
||||
['examples/promise/01_simple_connect/', 'Simple connect'],
|
||||
['examples/promise/02_listen_to_blocks/', 'Listen to blocks'],
|
||||
['examples/promise/03_listen_to_balance_change/', 'Listen to balance change'],
|
||||
['examples/promise/04_unsubscribe/', 'Unsubscribe from listening'],
|
||||
['examples/promise/05_read_storage/', 'Read chain state'],
|
||||
['examples/promise/06_make_transfer/', 'Make a transfer'],
|
||||
['examples/promise/08_system_events/', 'Display system events'],
|
||||
['examples/promise/09_transfer_events/', 'Transaction with events'],
|
||||
['examples/promise/10_upgrade_chain/', 'Upgrade via sudo'],
|
||||
['examples/promise/90_typegen/', 'TypeScript augmentation']
|
||||
]
|
||||
},
|
||||
{
|
||||
title: 'Substrate defaults',
|
||||
path: '/substrate/',
|
||||
collapsable: false,
|
||||
sidebarDepth: 0,
|
||||
children: [
|
||||
['substrate/rpc.md', 'Substrate RPC'],
|
||||
['substrate/constants.md', 'Constants'],
|
||||
['substrate/storage.md', 'State storage'],
|
||||
['substrate/extrinsics.md', 'Extrinsics'],
|
||||
['substrate/events.md', 'System events'],
|
||||
['substrate/errors.md', 'Errors']
|
||||
]
|
||||
},
|
||||
['/api/', '@polkadot/api'],
|
||||
['/types/', '@polkadot/types'],
|
||||
'/CONTRIBUTING.md'
|
||||
]
|
||||
}
|
||||
};
|
||||
@@ -1,9 +0,0 @@
|
||||
$accentColor = #fd8824
|
||||
$textColor = #2c3e50
|
||||
|
||||
.home .hero .description,
|
||||
.home .feature h2,
|
||||
.home .feature p {
|
||||
color: $textColor
|
||||
opacity: 0.75
|
||||
}
|
||||
@@ -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.
|
||||
@@ -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.
|
||||
@@ -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
|
||||
@@ -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,50 +0,0 @@
|
||||
---
|
||||
home: true
|
||||
heroText:
|
||||
tagline:
|
||||
# Bringing JavaScript to the Polkadot world.
|
||||
# actionText: Repository Overview
|
||||
# actionLink: /REPOS.md
|
||||
features:
|
||||
- title: API
|
||||
details: A powerful dynamic API that allows chain interactions with transparent encoding and decoding.
|
||||
- title: Substrate defaults
|
||||
details: An overview of the various default methods, state entries and RPCs for Substrate-based chains.
|
||||
- title: Types
|
||||
details: Various type interfaces to make using returned values from API calls transparent in your code.
|
||||
|
||||
footer: Apache-2 Licensed | Copyright © 2017-2019 polkadot-js authors and contributors
|
||||
---
|
||||
|
||||
## Welcome
|
||||
|
||||
The API provides application developers the ability to query a node and interact with the Polkadot or Substrate chains using Javascript. Here you will find documentation and examples to get you started.
|
||||
|
||||
::: tip Getting started & Examples
|
||||
[Jump right in](/start/) and get an overview on using the API in your projects, from installation all the way through to making it do magic. Already understand how things work and just want the examples? [The ApiPromise examples](/examples/promise/) provide some basic recipies.
|
||||
:::
|
||||
|
||||
## Available packages
|
||||
|
||||
This repository split up into a number of internal packages, namely -
|
||||
|
||||
- [api](api/README.md) Promise and RxJS-based APIs
|
||||
- [types](types/README.md) Type encoding and decoding wrappers
|
||||
|
||||
## The Polkadot Project
|
||||
|
||||
You can read more about the Polkadot Network at [https://polkadot.network/](https://polkadot.network/) and more about the polkadot-js projects at [https://polkadot.js.org](https://polkadot.js.org)
|
||||
|
||||
## Github repositories
|
||||
|
||||
You can find the Polkadot repositories at:
|
||||
|
||||
- [https://github.com/polkadot-js](https://github.com/polkadot-js)
|
||||
- [https://github.com/paritytech/polkadot](https://github.com/paritytech/polkadot)
|
||||
- [https://github.com/paritytech/substrate](https://github.com/paritytech/substrate)
|
||||
|
||||
This documentation is generated from [https://github.com/polkadot-js/api](https://github.com/polkadot-js/api)
|
||||
|
||||
## Contributing
|
||||
|
||||
Contribution to the Polkadot JS API are more than welcome. You can [report issues](https://github.com/polkadot-js/api/issues/new) and [log feature requests](https://github.com/polkadot-js/api/issues/new).
|
||||
@@ -1,62 +0,0 @@
|
||||
## Getting started
|
||||
|
||||
- [Introduction](start/README.md)
|
||||
- [Installation](start/install.md)
|
||||
- [Basics](start/basics.md)
|
||||
- [Creating](start/create.md)
|
||||
- [Constant queries](start/api.consts.md)
|
||||
- [State queries](start/api.query.md)
|
||||
- [RPC queries](start/api.rpc.md)
|
||||
- [State subscriptions](start/api.query.subs.md)
|
||||
- [Multi state retrieval](start/api.query.multi.md)
|
||||
- [State query utilities](start/api.query.other.md)
|
||||
- [Transactions](start/api.tx.md)
|
||||
- [Keyring](start/keyring.md)
|
||||
- [Transaction subscriptions](start/api.tx.subs.md)
|
||||
- [Complex transactions](start/api.tx.wrap.md)
|
||||
- [Type basics](start/types.basics.md)
|
||||
- [Type extension](start/types.extend.md)
|
||||
- [TypeScript interfaces](start/typescript.md)
|
||||
- [TypeScript user generated](start/typescript.user.md)
|
||||
|
||||
## Packages
|
||||
|
||||
- [api](api/README.md)
|
||||
- [ApiPromise](api/classes/_promise_index_.apipromise.md)
|
||||
- [ApiRx](api/classes/_rx_index_.apirx.md)
|
||||
- [rpc-provider](rpc-provider/README.md)
|
||||
- [HttpProvider](rpc-provider/classes/_http_index_.httpprovider.md)
|
||||
- [WsProvider](rpc-provider/classes/_ws_index_.wsprovider.md)
|
||||
- [types (codec implementation)](types/README.md)
|
||||
|
||||
## Interfaces
|
||||
|
||||
- [Substrate](substrate/README.md)
|
||||
- [RPC](substrate/rpc.md)
|
||||
- [Constants (runtime)](substrate/constants.md)
|
||||
- [Chain state (runtime)](substrate/storage.md)
|
||||
- [Extrinsics (runtime)](substrate/extrinsics.md)
|
||||
- [Events (runtime)](substrate/events.md)
|
||||
|
||||
## Examples
|
||||
|
||||
- [ApiPromise](examples/promise/README.md)
|
||||
- [Simple connect](examples/promise/01_simple_connect/README.md)
|
||||
- [Listen to blocks](examples/promise/02_listen_to_blocks/README.md)
|
||||
- [Listen to balance change](examples/promise/03_listen_to_balance_change/README.md)
|
||||
- [Unsubscribe from listening](examples/promise/04_unsubscribe/README.md)
|
||||
- [Read chain state](examples/promise/05_read_storage/README.md)
|
||||
- [Make a transfer](examples/promise/06_make_transfer/README.md)
|
||||
- [Display system events](examples/promise/08_system_events/README.md)
|
||||
- [Transaction with events](examples/promise/09_transfer_events/README.md)
|
||||
- [Upgrade via sudo](examples/promise/10_upgrade_chain/README.md)
|
||||
- [ApiRx](examples/rx/README.md)
|
||||
- [Simple connect](examples/rx/01_simple_connect/README.md)
|
||||
- [Listen to blocks](examples/rx/02_listen_to_blocks/README.md)
|
||||
- [Listen to balance change](examples/rx/03_listen_to_balance_change/README.md)
|
||||
- [Unsubscribe from listening](examples/rx/04_unsubscribe/README.md)
|
||||
- [Read chain state](examples/rx/05_read_storage/README.md)
|
||||
- [Make a transfer](examples/rx/06_make_transfer/README.md)
|
||||
- [Display system events](examples/rx/08_system_events/README.md)(
|
||||
- [Transaction with events](examples/rx/09_transfer_events/README.md)
|
||||
- [Upgrade via sudo](examples/rx/10_upgrade_chain/README.md)
|
||||
@@ -1,5 +1,5 @@
|
||||
# Simple Connect
|
||||
|
||||
The following example shows how to instantiate a Polkadot API object and use it to connect to a node using ApiPromise.
|
||||
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
|
||||
|
||||
@@ -1,15 +1,13 @@
|
||||
/* eslint-disable @typescript-eslint/require-await */
|
||||
/* eslint-disable @typescript-eslint/unbound-method */
|
||||
/* eslint-disable @typescript-eslint/no-var-requires */
|
||||
// @ts-check
|
||||
// Required imports
|
||||
const { ApiPromise, WsProvider } = require('@polkadot/api');
|
||||
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 });
|
||||
const api = await ApiPromise.create(provider);
|
||||
|
||||
// Retrieve the chain & node information information via rpc calls
|
||||
const [chain, nodeName, nodeVersion] = await Promise.all([
|
||||
|
||||
@@ -11,7 +11,7 @@
|
||||
},
|
||||
|
||||
"dependencies": {
|
||||
"@polkadot/api": "*"
|
||||
"@plugnet/api": "^0.76.102"
|
||||
},
|
||||
"devDependencies": {
|
||||
"rimraf": "^2.6.2"
|
||||
|
||||
@@ -1,8 +1,6 @@
|
||||
/* eslint-disable @typescript-eslint/require-await */
|
||||
/* eslint-disable @typescript-eslint/unbound-method */
|
||||
/* eslint-disable @typescript-eslint/no-var-requires */
|
||||
// @ts-check
|
||||
// Import the API
|
||||
const { ApiPromise } = require('@polkadot/api');
|
||||
const { ApiPromise } = require('@plugnet/api');
|
||||
|
||||
async function main () {
|
||||
// Here we don't pass the (optional) provider, connecting directly to the default
|
||||
@@ -10,19 +8,11 @@ async function main () {
|
||||
// the API has connected to the node and completed the initialisation process
|
||||
const api = await ApiPromise.create();
|
||||
|
||||
// We only display a couple, then unsubscribe
|
||||
let count = 0;
|
||||
|
||||
// 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.subscribeNewHeads((header) => {
|
||||
console.log(`Chain is at block: #${header.number}`);
|
||||
|
||||
if (++count === 256) {
|
||||
unsubscribe();
|
||||
process.exit(0);
|
||||
}
|
||||
const unsubscribe = await api.rpc.chain.subscribeNewHead((header) => {
|
||||
console.log(`Chain is at block: #${header.blockNumber}`);
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -10,7 +10,7 @@
|
||||
"start": "node index.js"
|
||||
},
|
||||
"dependencies": {
|
||||
"@polkadot/api": "*"
|
||||
"@plugnet/api": "^0.76.102"
|
||||
},
|
||||
"devDependencies": {
|
||||
"rimraf": "^2.6.2"
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
# Listen to balance changes
|
||||
|
||||
This example shows how to instantiate a Polkadot API object and use it to connect to a node and retrieve balance updates.
|
||||
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
|
||||
|
||||
@@ -1,8 +1,6 @@
|
||||
/* eslint-disable @typescript-eslint/require-await */
|
||||
/* eslint-disable @typescript-eslint/unbound-method */
|
||||
/* eslint-disable @typescript-eslint/no-var-requires */
|
||||
// @ts-check
|
||||
// Import the API
|
||||
const { ApiPromise } = require('@polkadot/api');
|
||||
const { ApiPromise } = require('@plugnet/api');
|
||||
|
||||
// Known account we want to use (available on dev chain, with funds)
|
||||
const Alice = '5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY';
|
||||
@@ -13,23 +11,21 @@ async function main () {
|
||||
|
||||
// Retrieve the initial balance. Since the call has no callback, it is simply a promise
|
||||
// that resolves to the current on-chain value
|
||||
let { nonce: previousNonce, data: { free: previousFree } } = await api.query.system.account(Alice);
|
||||
let previous = await api.query.balances.freeBalance(Alice);
|
||||
|
||||
console.log(`${Alice} has a balance of ${previousFree}, nonce ${previousNonce}`);
|
||||
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.system.account(Alice, ({ nonce: currentNonce, data: { free: currentFree } }) => {
|
||||
api.query.balances.freeBalance(Alice, (current) => {
|
||||
// Calculate the delta
|
||||
const change = currentFree.sub(previousFree);
|
||||
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()) {
|
||||
console.log(`New balance change of ${change}, nonce ${currentNonce}`);
|
||||
|
||||
previousFree = currentFree;
|
||||
previousNonce = currentNonce;
|
||||
previous = current;
|
||||
console.log(`New balance change of: ${change}`);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@@ -10,7 +10,7 @@
|
||||
"start": "node index.js"
|
||||
},
|
||||
"dependencies": {
|
||||
"@polkadot/api": "*"
|
||||
"@plugnet/api": "^0.76.102"
|
||||
},
|
||||
"devDependencies": {
|
||||
"rimraf": "^2.6.2"
|
||||
|
||||
@@ -1,5 +0,0 @@
|
||||
# Listen to balance changes
|
||||
|
||||
This example shows how to instantiate a Polkadot API object and use it to connect to a node and retrieve balance updates.
|
||||
|
||||
<<< @/docs/examples/promise/03_listen_to_balance_change/index.js
|
||||
@@ -1,23 +0,0 @@
|
||||
/* eslint-disable @typescript-eslint/require-await */
|
||||
/* eslint-disable @typescript-eslint/unbound-method */
|
||||
/* eslint-disable @typescript-eslint/no-var-requires */
|
||||
// Import the API
|
||||
const { ApiPromise } = require('@polkadot/api');
|
||||
|
||||
// Known account we want to use (available on dev chain, with funds)
|
||||
const ALICE = '5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY';
|
||||
const BOB = '5FHneW46xGXgs5mUiveU4sbTyGBzmstUspZC92UhjJM694ty';
|
||||
|
||||
async function main () {
|
||||
// Create an await for the API
|
||||
const api = await ApiPromise.create();
|
||||
|
||||
console.log('Tracking balances for:', [ALICE, BOB]);
|
||||
|
||||
// Subscribe and listen to several balance changes
|
||||
api.query.system.account.multi([ALICE, BOB], (balances) => {
|
||||
console.log('Change detected, new balances: ', balances.map(({ data: { free } }) => free));
|
||||
});
|
||||
}
|
||||
|
||||
main().catch(console.error);
|
||||
@@ -1,18 +0,0 @@
|
||||
{
|
||||
"name": "03_listen_to_multiple_balances_change",
|
||||
"version": "0.2.0",
|
||||
"description": "Example showing how to subscribe to multiple balances change",
|
||||
"main": "index.js",
|
||||
"author": "chevdor",
|
||||
"license": "MIT",
|
||||
"scripts": {
|
||||
"clean": "rimraf node_modules",
|
||||
"start": "node index.js"
|
||||
},
|
||||
"dependencies": {
|
||||
"@polkadot/api": "*"
|
||||
},
|
||||
"devDependencies": {
|
||||
"rimraf": "^2.6.2"
|
||||
}
|
||||
}
|
||||
@@ -1,23 +1,22 @@
|
||||
/* eslint-disable @typescript-eslint/require-await */
|
||||
/* eslint-disable @typescript-eslint/unbound-method */
|
||||
/* eslint-disable @typescript-eslint/no-var-requires */
|
||||
// @ts-check
|
||||
// Import the API
|
||||
const { ApiPromise } = require('@polkadot/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.subscribeNewHeads((header) => {
|
||||
console.log(`Chain is at block: #${header.number}`);
|
||||
// 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');
|
||||
console.log('Unsubscribed')
|
||||
}, 20000);
|
||||
}
|
||||
|
||||
|
||||
@@ -10,7 +10,7 @@
|
||||
"start": "node index.js"
|
||||
},
|
||||
"dependencies": {
|
||||
"@polkadot/api": "*"
|
||||
"@plugnet/api": "^0.76.102"
|
||||
},
|
||||
"devDependencies": {
|
||||
"rimraf": "^2.6.2"
|
||||
|
||||
@@ -1,41 +1,38 @@
|
||||
/* eslint-disable @typescript-eslint/require-await */
|
||||
/* eslint-disable @typescript-eslint/unbound-method */
|
||||
/* eslint-disable @typescript-eslint/no-var-requires */
|
||||
// @ts-check
|
||||
// Import the API
|
||||
const { ApiPromise } = require('@polkadot/api');
|
||||
const { ApiPromise } = require('@plugnet/api');
|
||||
|
||||
// Our address for Alice on the dev chain
|
||||
const ALICE = '5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY';
|
||||
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 [{ nonce: accountNonce }, now, validators] = await Promise.all([
|
||||
api.query.system.account(ALICE),
|
||||
api.query.timestamp.now(),
|
||||
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(`last block timestamp ${now.toNumber()}`);
|
||||
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.system.account(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].data.free.toHuman(),
|
||||
nonce: validatorBalances[index].nonce.toHuman()
|
||||
balance: validatorBalances[index].toString()
|
||||
})));
|
||||
}
|
||||
}
|
||||
|
||||
main().catch(console.error).finally(() => process.exit());
|
||||
main().catch(console.error).finally(_ => process.exit());
|
||||
|
||||
@@ -10,7 +10,7 @@
|
||||
"start": "node index.js"
|
||||
},
|
||||
"dependencies": {
|
||||
"@polkadot/api": "*"
|
||||
"@plugnet/api": "^0.76.102"
|
||||
},
|
||||
"devDependencies": {
|
||||
"rimraf": "^2.6.2"
|
||||
|
||||
@@ -1,5 +0,0 @@
|
||||
# Read storage, at a specific blockhash
|
||||
|
||||
In addition to querying the latest storage, you can make storage queries at a specific blockhash. Be aware that the node applies a pruning strategy and typically only keeps the last 256 blocks, unless run in archive mode.
|
||||
|
||||
<<< @/docs/examples/promise/05_read_storage_at/index.js
|
||||
@@ -1,32 +0,0 @@
|
||||
/* eslint-disable @typescript-eslint/require-await */
|
||||
/* eslint-disable @typescript-eslint/unbound-method */
|
||||
/* eslint-disable @typescript-eslint/no-var-requires */
|
||||
// Import the API
|
||||
const { ApiPromise } = require('@polkadot/api');
|
||||
|
||||
// Our address for Alice on the dev chain
|
||||
const ALICE = '5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY';
|
||||
const BOB = '5FHneW46xGXgs5mUiveU4sbTyGBzmstUspZC92UhjJM694ty';
|
||||
|
||||
async function main () {
|
||||
// Create our API with a default connection to the local node
|
||||
const api = await ApiPromise.create();
|
||||
|
||||
// Retrieve the last block header, extracting the hash and parentHash
|
||||
const { hash, parentHash } = await api.rpc.chain.getHeader();
|
||||
|
||||
console.log(`last header hash ${hash.toHex()}`);
|
||||
|
||||
// Retrieve the balance at the preceding block for Alice. For at queries
|
||||
// the format is always `.at(<blockhash>, ...params)`
|
||||
const balance = await api.query.system.account.at(parentHash, ALICE);
|
||||
|
||||
console.log(`Alice's balance at ${parentHash.toHex()} was ${balance.data.free}`);
|
||||
|
||||
// Now perform a multi query, returning multiple balances at once
|
||||
const balances = await api.query.system.account.multi([ALICE, BOB]);
|
||||
|
||||
console.log(`Current balances for Alice and Bob are ${balances[0].data.free} and ${balances[1].data.free}`);
|
||||
}
|
||||
|
||||
main().catch(console.error).finally(() => process.exit());
|
||||
@@ -1,18 +0,0 @@
|
||||
{
|
||||
"name": "05_read_storage_at",
|
||||
"version": "0.2.0",
|
||||
"description": "Example showing how to query storage at a specific block",
|
||||
"main": "index.js",
|
||||
"author": "Jaco Greeff <jacogr@gmail.com>",
|
||||
"license": "MIT",
|
||||
"scripts": {
|
||||
"clean": "rimraf node_modules",
|
||||
"start": "node index.js"
|
||||
},
|
||||
"dependencies": {
|
||||
"@polkadot/api": "*"
|
||||
},
|
||||
"devDependencies": {
|
||||
"rimraf": "^2.6.2"
|
||||
}
|
||||
}
|
||||
@@ -1,9 +1,7 @@
|
||||
/* eslint-disable @typescript-eslint/require-await */
|
||||
/* eslint-disable @typescript-eslint/unbound-method */
|
||||
/* eslint-disable @typescript-eslint/no-var-requires */
|
||||
// @ts-check
|
||||
// Import the API, Keyring and some utility functions
|
||||
const { ApiPromise } = require('@polkadot/api');
|
||||
const { Keyring } = require('@polkadot/keyring');
|
||||
const { ApiPromise } = require('@plugnet/api');
|
||||
const { Keyring } = require('@plugnet/keyring');
|
||||
|
||||
const BOB = '5FHneW46xGXgs5mUiveU4sbTyGBzmstUspZC92UhjJM694ty';
|
||||
|
||||
@@ -14,7 +12,7 @@ async function main () {
|
||||
// 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)
|
||||
// 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
|
||||
|
||||
@@ -10,7 +10,7 @@
|
||||
"start": "node index.js"
|
||||
},
|
||||
"dependencies": {
|
||||
"@polkadot/api": "*"
|
||||
"@plugnet/api": "^0.76.102"
|
||||
},
|
||||
"devDependencies": {
|
||||
"rimraf": "^2.6.2"
|
||||
|
||||
@@ -1,5 +0,0 @@
|
||||
# Make a Transfer with allowed block permissions
|
||||
|
||||
This transactions shows you how to add a nonce and a valid length of blocks a transaction is valid for.
|
||||
|
||||
This is important because as an account drops below the exsistential limit (0.1 dots) it gets pruned from the state tree. If it is added back its nonce starts at 0 again and is now vulnerable to replay attacks.
|
||||
@@ -1,45 +0,0 @@
|
||||
/* eslint-disable @typescript-eslint/require-await */
|
||||
/* eslint-disable @typescript-eslint/unbound-method */
|
||||
/* eslint-disable @typescript-eslint/no-var-requires */
|
||||
// Import the API, Keyring and some utility functions
|
||||
const { ApiPromise } = require('@polkadot/api');
|
||||
const { Keyring } = require('@polkadot/keyring');
|
||||
const { createType } = require('@polkadot/types');
|
||||
|
||||
const BOB = '5FHneW46xGXgs5mUiveU4sbTyGBzmstUspZC92UhjJM694ty';
|
||||
|
||||
async function main () {
|
||||
// Instantiate the API
|
||||
const api = await ApiPromise.create(); // default provider
|
||||
|
||||
// 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-derived path (empty phrase, so uses dev)
|
||||
const alice = keyring.addFromUri('//Alice');
|
||||
|
||||
// Get nonce for account
|
||||
const { nonce } = await api.query.system.account(alice.address);
|
||||
|
||||
// Get current block
|
||||
const signedBlock = await api.rpc.chain.getBlock();
|
||||
|
||||
// Get current block height and hash
|
||||
const currentHeight = signedBlock.block.header.number;
|
||||
const blockHash = signedBlock.block.header.hash;
|
||||
|
||||
// NOTE By default the API will send mortal transactions, only explicitly construct
|
||||
// if you wish to override the defaults
|
||||
// construct a mortal era
|
||||
const era = createType('ExtrinsicEra', { current: currentHeight, period: 10 });
|
||||
|
||||
// Create an extrinsic, transferring 12345 units to Bob
|
||||
const transfer = api.tx.balances.transfer(BOB, 12345);
|
||||
|
||||
// Sign and send the transaction using our account with a nonce and the length of blocks the transaction is valid for
|
||||
const hash = await transfer.signAndSend(alice, { blockHash, era, nonce });
|
||||
|
||||
console.log('Transfer sent with hash', hash.toHex());
|
||||
}
|
||||
|
||||
main().catch(console.error).finally(() => process.exit());
|
||||
-18
@@ -1,18 +0,0 @@
|
||||
{
|
||||
"name": "07_make_transfer_with_allowed_block_permissions_only",
|
||||
"version": "0.1.0",
|
||||
"description": "Example showing how to make a transfer with allowed block permissions",
|
||||
"main": "index.js",
|
||||
"author": "Jesse",
|
||||
"license": "MIT",
|
||||
"scripts": {
|
||||
"clean": "rimraf node_modules",
|
||||
"start": "node index.js"
|
||||
},
|
||||
"dependencies": {
|
||||
"@polkadot/api": "*"
|
||||
},
|
||||
"devDependencies": {
|
||||
"rimraf": "^2.6.2"
|
||||
}
|
||||
}
|
||||
@@ -1,28 +1,26 @@
|
||||
/* eslint-disable @typescript-eslint/require-await */
|
||||
/* eslint-disable @typescript-eslint/unbound-method */
|
||||
/* eslint-disable @typescript-eslint/no-var-requires */
|
||||
// @ts-check
|
||||
// Import the API
|
||||
const { ApiPromise } = require('@polkadot/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
|
||||
// subscribe to system events via storage
|
||||
api.query.system.events((events) => {
|
||||
console.log(`\nReceived ${events.length} events:`);
|
||||
|
||||
// Loop through the Vec<EventRecord>
|
||||
// loop through the Vec<EventRecord>
|
||||
events.forEach((record) => {
|
||||
// Extract the phase, event and the event types
|
||||
// extract the phase, event and the event types
|
||||
const { event, phase } = record;
|
||||
const types = event.typeDef;
|
||||
|
||||
// Show what we are busy with
|
||||
// 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
|
||||
// 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()}`);
|
||||
});
|
||||
|
||||
@@ -10,7 +10,7 @@
|
||||
"start": "node index.js"
|
||||
},
|
||||
"dependencies": {
|
||||
"@polkadot/api": "*"
|
||||
"@plugnet/api": "^0.76.102"
|
||||
},
|
||||
"devDependencies": {
|
||||
"rimraf": "^2.6.2"
|
||||
|
||||
@@ -1,16 +1,14 @@
|
||||
/* eslint-disable @typescript-eslint/require-await */
|
||||
/* eslint-disable @typescript-eslint/unbound-method */
|
||||
/* eslint-disable @typescript-eslint/no-var-requires */
|
||||
// @ts-check
|
||||
// Import the API & Provider and some utility functions
|
||||
const { ApiPromise } = require('@polkadot/api');
|
||||
const { ApiPromise } = require('@plugnet/api');
|
||||
|
||||
// Import the test keyring (already has dev keys for Alice, Bob, Charlie, Eve & Ferdie)
|
||||
const testKeyring = require('@polkadot/keyring/testing');
|
||||
// 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('@polkadot/util-crypto');
|
||||
// utility function for random values
|
||||
const { randomAsU8a } = require('@plugnet/util-crypto');
|
||||
|
||||
// Some constants we are using in this sample
|
||||
// some constants we are using in this sample
|
||||
const ALICE = '5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY';
|
||||
const AMOUNT = 10000;
|
||||
|
||||
@@ -18,37 +16,36 @@ async function main () {
|
||||
// Create the API and wait until ready
|
||||
const api = await ApiPromise.create();
|
||||
|
||||
// Create an instance of our testing keyring
|
||||
// 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.account(ALICE);
|
||||
// get the nonce for the admin key
|
||||
const nonce = await api.query.system.accountNonce(ALICE);
|
||||
|
||||
// Find the actual keypair in the keyring
|
||||
// find the actual keypair in the keyring
|
||||
const alicePair = keyring.getPair(ALICE);
|
||||
|
||||
// Create a new random recipient
|
||||
const recipient = keyring.addFromSeed(randomAsU8a(32)).address;
|
||||
// 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());
|
||||
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)
|
||||
.signAndSend(alicePair, { nonce }, ({ events = [], status }) => {
|
||||
.sign(alicePair, { nonce })
|
||||
.send(({ events = [], status }) => {
|
||||
console.log('Transaction status:', status.type);
|
||||
|
||||
if (status.isInBlock) {
|
||||
console.log('Included at block hash', status.asInBlock.toHex());
|
||||
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());
|
||||
});
|
||||
} else if (status.isFinalized) {
|
||||
console.log('Finalized block hash', status.asFinalized.toHex());
|
||||
|
||||
process.exit(0);
|
||||
}
|
||||
|
||||
@@ -10,7 +10,7 @@
|
||||
"start": "node index.js"
|
||||
},
|
||||
"dependencies": {
|
||||
"@polkadot/api": "*"
|
||||
"@plugnet/api": "^0.76.102"
|
||||
},
|
||||
"devDependencies": {
|
||||
"rimraf": "^2.6.2"
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
# Chain upgrade
|
||||
|
||||
Performs a chain upgrade using the `sudo` module. This may brick your chain, so use it as an educational sample. (use `substrate purge-chain --dev` to remove DB and recover).
|
||||
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
|
||||
|
||||
@@ -1,11 +1,9 @@
|
||||
/* eslint-disable @typescript-eslint/require-await */
|
||||
/* eslint-disable @typescript-eslint/unbound-method */
|
||||
/* eslint-disable @typescript-eslint/no-var-requires */
|
||||
// @ts-check
|
||||
// Import the API & Provider and some utility functions
|
||||
const { ApiPromise, WsProvider } = require('@polkadot/api');
|
||||
const { ApiPromise, WsProvider } = require('@plugnet/api');
|
||||
|
||||
// import the test keyring (already has dev keys for Alice, Bob, Charlie, Eve & Ferdie)
|
||||
const testKeyring = require('@polkadot/keyring/testing');
|
||||
const testKeyring = require('@plugnet/keyring/testing');
|
||||
|
||||
const fs = require('fs');
|
||||
|
||||
@@ -14,40 +12,38 @@ async function main () {
|
||||
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 });
|
||||
const api = await ApiPromise.create(provider);
|
||||
|
||||
// Retrieve the upgrade key from the chain state
|
||||
// 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 a changed value, the 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
|
||||
// retrieve the runtime to upgrade to
|
||||
const code = fs.readFileSync('./test.wasm').toString('hex');
|
||||
const proposal = api.tx.system && api.tx.system.setCode
|
||||
? api.tx.system.setCode(`0x${code}`) // For newer versions of Substrate
|
||||
: api.tx.consensus.setCode(`0x${code}`); // For previous versions
|
||||
const proposal = api.tx.consensus.setCode(`0x${code}`);
|
||||
|
||||
console.log(`Upgrading from ${adminId}, ${code.length / 2} bytes`);
|
||||
|
||||
// Perform the actual chain upgrade via the sudo module
|
||||
// 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.isInBlock) {
|
||||
if (status.isFinalized) {
|
||||
console.error('You have just upgraded your chain');
|
||||
|
||||
console.log('Included at block hash', status.asInBlock.toHex());
|
||||
console.log('Completed at block hash', status.asFinalized.toHex());
|
||||
console.log('Events:');
|
||||
|
||||
console.log(JSON.stringify(events.toHuman(), null, 2));
|
||||
} else if (status.isFinalized) {
|
||||
console.log('Finalized block hash', status.asFinalized.toHex());
|
||||
events.forEach(({ phase, event: { data, method, section } }) => {
|
||||
console.log('\t', phase.toString(), `: ${section}.${method}`, data.toString());
|
||||
});
|
||||
|
||||
process.exit(0);
|
||||
}
|
||||
|
||||
@@ -10,7 +10,7 @@
|
||||
"start": "node index.js"
|
||||
},
|
||||
"dependencies": {
|
||||
"@polkadot/api": "*"
|
||||
"@plugnet/api": "^0.76.102"
|
||||
},
|
||||
"devDependencies": {
|
||||
"rimraf": "^2.6.2"
|
||||
|
||||
@@ -1,248 +0,0 @@
|
||||
# typegen
|
||||
|
||||
This is a sample TypeScript project [with full source & config on GithHub](https://github.com/polkadot-js/api/tree/master/docs/examples/promise/90_typegen), that uses `@polkadot/typegen` to generate type definitions that can be used to decorate the `@polkadot/api`. It uses both types defined for the specific chain as well as the chain metadata to generate TypeScript interfaces. This means that interfaces such as `api.query.*`, `api.tx.*` and `api.consts.*` will be decorated based on chain-specific information, instead of an un-augmented catch-all definition.
|
||||
|
||||
**NOTE** This is built using the updates in the `1.4.0` api track and as such it uses the latest (at the time of writing) `@polkadot/api 1.4.0`. If you want to play on your own, it is also suggested that you use the `1.4+` series since some generation types have moved around internally, making it easier to augment.
|
||||
|
||||
## Packages
|
||||
|
||||
For the packages we need from the `@polkadot/*` we have added `@polkadot/api` (we want to do API stuff) and `@polkadot/typegen` (to generate the actual interfaces). So our scripts and dependencies inside `package.json` contain the following -
|
||||
|
||||
```json
|
||||
{
|
||||
"scripts": {
|
||||
"build": "yarn generate:defs && yarn generate:meta",
|
||||
"generate:defs": "ts-node --skip-project node_modules/.bin/polkadot-types-from-defs --package sample-polkadotjs-typegen/interfaces --input ./src/interfaces",
|
||||
"generate:meta": "ts-node --skip-project node_modules/.bin/polkadot-types-from-chain --package sample-polkadotjs-typegen/interfaces --endpoint ./edgeware.json --output ./src/interfaces",
|
||||
"lint": "tsc --noEmit --pretty"
|
||||
},
|
||||
"dependencies": {
|
||||
"@polkadot/api": "^1.4.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@polkadot/typegen": "^1.4.0",
|
||||
"ts-node": "^8.6.2",
|
||||
"typescript": "^3.8.2"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
We will delve into the setup and running the scripts and what they do in a short bit, but as of now just notice that we are running the scripts via `ts-node`. Since we supply our definitions as `*.ts` files, this is important otherwise they will not be parsable. `build` will just run both the types and meta generators (in that order, so metadata can use the types) and we have a `lint` that can just check that everything is as it is meant to be.
|
||||
|
||||
## Metadata setup
|
||||
|
||||
The idea here is to use the actual chain metadata to generate the actual api augmented endpoints. The metadata we are adding here (in addition to the user types), is from the Edgeware Berlin testnet. So this is a real-world example of configuring the API for a specific substrate chain. For the metadata retrieval, we just ran a simple curl command to get it from the node -
|
||||
|
||||
`curl -H "Content-Type: application/json" -d '{"id":"1", "jsonrpc":"2.0", "method": "state_getMetadata", "params":[]}' http://localhost:9933`
|
||||
|
||||
And then add the full JSONPC output as received to the `edgeware.json` file as specified by the generation command. A trimmed version would look like -
|
||||
|
||||
```json
|
||||
{"jsonrpc":"2.0","result":"0x6d6574610b6c185379737....","id":29}
|
||||
```
|
||||
|
||||
The generator can also use a `wss://` as an `--endpoint` param as part of the generation, but in most cases you would want a static metadata to work from in development, hence we are actually adding it here.
|
||||
|
||||
## Types setup
|
||||
|
||||
The types are defined in the `src/interfaces` folder. While this repo contains a number of generated files in there as well, you basically only need to manually add the following -
|
||||
|
||||
- `src/interfaces/definitions.ts` - this just exports all the sub-folder definitions in one go
|
||||
- `src/interfaces/<module>/definitions.ts` - type definitions for a specific module
|
||||
|
||||
This structure fully matches what is available in the `@polkadot/type/interfaces` folder, so the structure is setup based on the convention used in the `@polkadot/types` library. The generating scripts will expect something matching this since the same underlying code is actually used inside `@polkadot/types` as well. The top-level `interfaces/` folder can be name anything, however the internal content structure need to match what is defined above.
|
||||
|
||||
For the top-level the definition file has the following contents -
|
||||
|
||||
```js
|
||||
export { default as signaling } from './signaling/definitions';
|
||||
export { default as treasuryRewards } from './treasuryRewards/definitions';
|
||||
export { default as voting } from './voting/definitions';
|
||||
```
|
||||
|
||||
As explained above, it really is just a re-export of the definitions, so they are all easily accessible to the outside, i.e. we will use this import inside our own code to use the definitions in API initialization. The generation scripts will load this file to determine which types it needs to import. By the `@polkadot/types` convention, match the export names with the folders (preferably your runtime module names), the generation scripts will use these names to find the correct folders to output the generated `types.ts` to.
|
||||
|
||||
For each of the folders, `signaling`, `treasuryRewards` and `voting` another `definitions.ts` file is contained within. Looking at the one from `signaling`, it contains this -
|
||||
|
||||
```js
|
||||
export default {
|
||||
types: {
|
||||
ProposalRecord: {
|
||||
index: 'u32',
|
||||
author: 'AccountId',
|
||||
stage: 'VoteStage',
|
||||
transition_time: 'u32',
|
||||
title: 'Text',
|
||||
contents: 'Text',
|
||||
vote_id: 'u64'
|
||||
},
|
||||
ProposalContents: 'Vec<u8>',
|
||||
ProposalTitle: 'Vec<u8>'
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Just the type definitions (the structure of which you should be familiar with), nested inside a `types: {...}` container. This allows us future extension points, i.e. there is some work to expose the custom RPC types alongside, so that would become another key on a per-module basis.
|
||||
|
||||
In the above, you will note that the `ProposalRecord` references a type for `voting`, i.e. `VoteStage`. The type generation and resolution will determine where the type comes from, and provide the required imports on generation.
|
||||
|
||||
Looking at the example in this repo, it also has `augment*`, `index.ts` and `types.ts` files in the interfaces folder. These are all generated, and will be re-generated when the generator is run - so all edits to these files will be lost. The only requirement for user-edits are the `definitions.ts` files.
|
||||
|
||||
## Generating
|
||||
|
||||
Now that both the metadata nd types setup is completed, we just run the build command via `yarn build` and magically (assuming you didn't have the `augment*` and other generated files), these files will be added. When running this command, the console should display something like -
|
||||
|
||||
```
|
||||
> yarn build
|
||||
$ yarn generate:defs && yarn generate:meta
|
||||
$ ts-node --skip-project \
|
||||
node_modules/.bin/polkadot-types-from-defs \
|
||||
--package sample-polkadotjs-typegen/interfaces \
|
||||
--input ./src/interfaces
|
||||
|
||||
sample-polkadotjs-typegen/src/interfaces/types.ts
|
||||
Generating
|
||||
Extracting interfaces for signaling
|
||||
...
|
||||
Writing
|
||||
|
||||
sample-polkadotjs-typegen/src/interfaces/augment-types.ts
|
||||
Generating
|
||||
Writing
|
||||
|
||||
$ ts-node --skip-project \
|
||||
node_modules/.bin/polkadot-types-from-chain \
|
||||
--package sample-polkadotjs-typegen/interfaces \
|
||||
--endpoint ./edgeware.json \
|
||||
--output ./src/interfaces
|
||||
|
||||
Generating from metadata, 81,267 bytes
|
||||
...
|
||||
|
||||
sample-polkadotjs-typegen/src/interfaces/augment-api.ts
|
||||
Generating
|
||||
Writing
|
||||
|
||||
✨ Done in 4.04s.
|
||||
```
|
||||
|
||||
Now if we check the actual output against the source via `yarn lint`, we would see that valid output has been generated -
|
||||
|
||||
```
|
||||
> yarn lint
|
||||
$ tsc --noEmit --pretty
|
||||
✨ Done in 2.28s.
|
||||
```
|
||||
|
||||
## Peering at the output
|
||||
|
||||
We are ready to use all these generated types this after some TS config. If you take a look at the generated `src/signaling/types.ts`, you would see generated TS interfaces, such as -
|
||||
|
||||
```js
|
||||
import { Struct } from '@polkadot/types/codec';
|
||||
import { Bytes, Text, u32, u64 } from '@polkadot/types/primitive';
|
||||
import { AccountId } from '@polkadot/types/interfaces/runtime';
|
||||
import { VoteStage } from 'sample-polkadotjs-typegen/interfaces/voting';
|
||||
|
||||
/** @name ProposalContents */
|
||||
export interface ProposalContents extends Bytes {}
|
||||
|
||||
/** @name ProposalRecord */
|
||||
export interface ProposalRecord extends Struct {
|
||||
readonly index: u32;
|
||||
readonly author: AccountId;
|
||||
readonly stage: VoteStage;
|
||||
readonly transition_time: u32;
|
||||
readonly title: Text;
|
||||
readonly contents: Text;
|
||||
readonly vote_id: u64;
|
||||
}
|
||||
|
||||
/** @name ProposalTitle */
|
||||
export interface ProposalTitle extends Bytes {}
|
||||
```
|
||||
|
||||
As mentioned earlier, here you will notice the `import { VoteStage }`, the generator has determined that `voting` exports that interface and has added the required imports.
|
||||
|
||||
## TypeScript config
|
||||
|
||||
Now that we have files generated, it is time to make TypeScript aware of the types and add an explicit override into out `tsconfig.json`. After some changes, the paths in the config looks as follow (comments are in teh actual config file here) -
|
||||
|
||||
```json
|
||||
{
|
||||
"compilerOptions": {
|
||||
"paths": {
|
||||
"sample-polkadotjs-typegen/*": ["src/*"],
|
||||
"@polkadot/api/augment": ["src/interfaces/augment-api.ts"],
|
||||
"@polkadot/types/augment": ["src/interfaces/augment-types.ts"]
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Effectively what we do above is tell the TypeScript compiler to not use the built-in API augmentation, but rather to replace it with our version. This means that all types from these are injected not by the substrate-latest-master version, but rather with what we have defined above.
|
||||
|
||||
## Usage
|
||||
|
||||
For simple usage, we have added the `src/index.ts` file that show how the metadata and types actually decorate the API. In addition, we also have setup instructions included here.
|
||||
|
||||
```js
|
||||
// We need to import the augmented definitions "somewhere" in our project, however since we have
|
||||
// it in tsconfig as an override and the api/types has imports, it is not strictly required here.
|
||||
// Because of the tsconfig override, we could import from '@polkadot/{api, types}/augment'
|
||||
import './interfaces/augment-api';
|
||||
import './interfaces/augment-types';
|
||||
|
||||
// all type stuff, the only one we are using here
|
||||
import type { VoteRecord } from './interfaces';
|
||||
|
||||
// external imports
|
||||
import { ApiPromise } from '@polkadot/api';
|
||||
import { createType } from '@polkadot/types';
|
||||
|
||||
// our local stuff
|
||||
import * as definitions from './interfaces/definitions';
|
||||
|
||||
async function main (): Promise<void> {
|
||||
// extract all types from definitions - fast and dirty approach, flatted on 'types'
|
||||
const types = Object.values(definitions).reduce((res, { types }): object => ({ ...res, ...types }), {});
|
||||
|
||||
const api = await ApiPromise.create({
|
||||
types: {
|
||||
...types,
|
||||
// aliases that don't do well as part of interfaces
|
||||
'voting::VoteType': 'VoteType',
|
||||
'voting::TallyType': 'TallyType',
|
||||
// chain-specific overrides
|
||||
Keys: 'SessionKeys4'
|
||||
}
|
||||
});
|
||||
|
||||
// get a query
|
||||
const recordOpt = await api.query.voting.voteRecords(123);
|
||||
|
||||
// the types match with what we expect here
|
||||
let firstRecord: VoteRecord | null = recordOpt.unwrapOr(null);
|
||||
console.log(firstRecord?.toHuman());
|
||||
|
||||
// it even does work for arrays & subscriptions
|
||||
api.query.signaling.activeProposals((results): void => {
|
||||
results.forEach(([hash, blockNumber]): void => {
|
||||
console.log(hash.toHex(), ':', blockNumber.toNumber());
|
||||
});
|
||||
});
|
||||
|
||||
// even createType works, allowing for our types to be used
|
||||
console.log(`Balance2 bitLength:`, [
|
||||
api.createType('Balance2').bitLength(),
|
||||
api.registry.createType('Balance2').bitLength(),
|
||||
createType(api.registry, 'Balance2').bitLength()
|
||||
]);
|
||||
}
|
||||
|
||||
await main();
|
||||
```
|
||||
|
||||
## And that is a ...
|
||||
|
||||
... wrap. Just a really simple walk-through to customizing the API TypeScript definitions for your chain.
|
||||
File diff suppressed because one or more lines are too long
@@ -1,24 +0,0 @@
|
||||
{
|
||||
"name": "sample-polkadotjs-typegen",
|
||||
"version": "0.0.1",
|
||||
"description": "A sample using @polkadot/typegen to generate type definitions",
|
||||
"main": "index.js",
|
||||
"repository": "https://github.com/jacogr/sample-polkadotjs-typegen",
|
||||
"author": "Jaco Greeff <jacogr@gmail.com>",
|
||||
"license": "The Unlicense",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"build": "yarn generate:defs && yarn generate:meta",
|
||||
"generate:defs": "ts-node --skip-project node_modules/.bin/polkadot-types-from-defs --package sample-polkadotjs-typegen/interfaces --input ./src/interfaces",
|
||||
"generate:meta": "ts-node --skip-project node_modules/.bin/polkadot-types-from-chain --package sample-polkadotjs-typegen/interfaces --endpoint ./edgeware.json --output ./src/interfaces --strict",
|
||||
"lint": "tsc --noEmit --pretty"
|
||||
},
|
||||
"dependencies": {
|
||||
"@polkadot/api": "^1.4.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@polkadot/typegen": "^1.4.0",
|
||||
"ts-node": "^8.6.2",
|
||||
"typescript": "^3.8.2"
|
||||
}
|
||||
}
|
||||
@@ -1,54 +0,0 @@
|
||||
// We need to import the augmented definitions "somewhere" in our project, however since we have
|
||||
// it in tsconfig as an override and the api/types has imports, it is not strictly required here.
|
||||
// Because of the tsconfig override, we could import from '@polkadot/{api, types}/augment'
|
||||
import './interfaces/augment-api';
|
||||
import './interfaces/augment-types';
|
||||
|
||||
// all type stuff, the only one we are using here
|
||||
import type { VoteRecord } from './interfaces';
|
||||
|
||||
// external imports
|
||||
import { ApiPromise } from '@polkadot/api';
|
||||
import { createType } from '@polkadot/types';
|
||||
|
||||
// our local stuff
|
||||
import * as definitions from './interfaces/definitions';
|
||||
|
||||
async function main (): Promise<void> {
|
||||
// extract all types from definitions - fast and dirty approach, flatted on 'types'
|
||||
const types = Object.values(definitions).reduce((res, { types }): object => ({ ...res, ...types }), {});
|
||||
|
||||
const api = await ApiPromise.create({
|
||||
types: {
|
||||
...types,
|
||||
// aliasses that don't do well as part of interfaces
|
||||
'voting::VoteType': 'VoteType',
|
||||
'voting::TallyType': 'TallyType',
|
||||
// chain-specific overrides
|
||||
Keys: 'SessionKeys4'
|
||||
}
|
||||
});
|
||||
|
||||
// get a query
|
||||
const recordOpt = await api.query.voting.voteRecords(123);
|
||||
|
||||
// the types match with what we expect here
|
||||
let firstRecord: VoteRecord | null = recordOpt.unwrapOr(null);
|
||||
console.log(firstRecord?.toHuman());
|
||||
|
||||
// it even does work for arrays & subscriptions
|
||||
api.query.signaling.activeProposals((results): void => {
|
||||
results.forEach(([hash, blockNumber]): void => {
|
||||
console.log(hash.toHex(), ':', blockNumber.toNumber());
|
||||
});
|
||||
});
|
||||
|
||||
// even createType works, allowing for our types to be used
|
||||
console.log(`Balance2 bitLength:`, [
|
||||
api.createType('Balance2').bitLength(),
|
||||
api.registry.createType('Balance2').bitLength(),
|
||||
createType(api.registry, 'Balance2').bitLength()
|
||||
]);
|
||||
}
|
||||
|
||||
await main();
|
||||
@@ -1,253 +0,0 @@
|
||||
// Auto-generated via `yarn polkadot-types-from-chain`, do not edit
|
||||
/* eslint-disable @typescript-eslint/no-empty-interface */
|
||||
|
||||
import { Bytes, u32 } from '@polkadot/types/primitive';
|
||||
import { Gas } from '@polkadot/types/interfaces/contracts';
|
||||
import { Balance, BalanceOf, BlockNumber, Moment, Percent, Permill } from '@polkadot/types/interfaces/runtime';
|
||||
import { SessionIndex } from '@polkadot/types/interfaces/session';
|
||||
import { EraIndex } from '@polkadot/types/interfaces/staking';
|
||||
|
||||
declare module '@polkadot/metadata/Decorated/consts/types' {
|
||||
export interface Constants {
|
||||
timestamp: {
|
||||
|
||||
/**
|
||||
* The minimum period between blocks. Beware that this is different to the *expected* period
|
||||
* that the block production apparatus provides. Your chosen consensus system will generally
|
||||
* work with this to determine a sensible block time. e.g. For Aura, it will be double this
|
||||
* period on default settings.
|
||||
**/
|
||||
minimumPeriod: AugmentedConst<Moment>;
|
||||
};
|
||||
balances: {
|
||||
|
||||
/**
|
||||
* The minimum amount required to keep an account open.
|
||||
**/
|
||||
existentialDeposit: AugmentedConst<Balance>;
|
||||
/**
|
||||
* The fee required to make a transfer.
|
||||
**/
|
||||
transferFee: AugmentedConst<Balance>;
|
||||
/**
|
||||
* The fee required to create an account.
|
||||
**/
|
||||
creationFee: AugmentedConst<Balance>;
|
||||
};
|
||||
transactionPayment: {
|
||||
|
||||
/**
|
||||
* The fee to be paid for making a transaction; the base.
|
||||
**/
|
||||
transactionBaseFee: AugmentedConst<BalanceOf>;
|
||||
/**
|
||||
* The fee to be paid for making a transaction; the per-byte portion.
|
||||
**/
|
||||
transactionByteFee: AugmentedConst<BalanceOf>;
|
||||
};
|
||||
staking: {
|
||||
|
||||
/**
|
||||
* Number of sessions per era.
|
||||
**/
|
||||
sessionsPerEra: AugmentedConst<SessionIndex>;
|
||||
/**
|
||||
* Number of eras that staked funds must remain bonded for.
|
||||
**/
|
||||
bondingDuration: AugmentedConst<EraIndex>;
|
||||
};
|
||||
session: {
|
||||
|
||||
/**
|
||||
* Used as first key for `NextKeys` and `KeyOwner` to put all the data into the same branch
|
||||
* of the trie.
|
||||
**/
|
||||
dedupKeyPrefix: AugmentedConst<Bytes>;
|
||||
};
|
||||
democracy: {
|
||||
|
||||
/**
|
||||
* The minimum period of locking and the period between a proposal being approved and enacted.
|
||||
* It should generally be a little more than the unstake period to ensure that
|
||||
* voting stakers have an opportunity to remove themselves from the system in the case where
|
||||
* they are on the losing side of a vote.
|
||||
**/
|
||||
enactmentPeriod: AugmentedConst<BlockNumber>;
|
||||
/**
|
||||
* How often (in blocks) new public referenda are launched.
|
||||
**/
|
||||
launchPeriod: AugmentedConst<BlockNumber>;
|
||||
/**
|
||||
* How often (in blocks) to check for new votes.
|
||||
**/
|
||||
votingPeriod: AugmentedConst<BlockNumber>;
|
||||
/**
|
||||
* The minimum amount to be used as a deposit for a public referendum proposal.
|
||||
**/
|
||||
minimumDeposit: AugmentedConst<BalanceOf>;
|
||||
/**
|
||||
* Minimum voting period allowed for an emergency referendum.
|
||||
**/
|
||||
emergencyVotingPeriod: AugmentedConst<BlockNumber>;
|
||||
/**
|
||||
* Period in blocks where an external proposal may not be re-submitted after being vetoed.
|
||||
**/
|
||||
cooloffPeriod: AugmentedConst<BlockNumber>;
|
||||
/**
|
||||
* The amount of balance that must be deposited per byte of preimage stored.
|
||||
**/
|
||||
preimageByteDeposit: AugmentedConst<BalanceOf>;
|
||||
};
|
||||
elections: {
|
||||
|
||||
candidacyBond: AugmentedConst<BalanceOf>;
|
||||
votingBond: AugmentedConst<BalanceOf>;
|
||||
desiredMembers: AugmentedConst<u32>;
|
||||
desiredRunnersUp: AugmentedConst<u32>;
|
||||
termDuration: AugmentedConst<BlockNumber>;
|
||||
};
|
||||
finalityTracker: {
|
||||
|
||||
/**
|
||||
* The number of recent samples to keep from this chain. Default is 101.
|
||||
**/
|
||||
windowSize: AugmentedConst<BlockNumber>;
|
||||
/**
|
||||
* The delay after which point things become suspicious. Default is 1000.
|
||||
**/
|
||||
reportLatency: AugmentedConst<BlockNumber>;
|
||||
};
|
||||
treasury: {
|
||||
|
||||
/**
|
||||
* Fraction of a proposal's value that should be bonded in order to place the proposal.
|
||||
* An accepted proposal gets these back. A rejected proposal does not.
|
||||
**/
|
||||
proposalBond: AugmentedConst<Permill>;
|
||||
/**
|
||||
* Minimum amount of funds that should be placed in a deposit for making a proposal.
|
||||
**/
|
||||
proposalBondMinimum: AugmentedConst<BalanceOf>;
|
||||
/**
|
||||
* Period between successive spends.
|
||||
**/
|
||||
spendPeriod: AugmentedConst<BlockNumber>;
|
||||
/**
|
||||
* Percentage of spare funds (if any) that are burnt per spend period.
|
||||
**/
|
||||
burn: AugmentedConst<Permill>;
|
||||
/**
|
||||
* The period for which a tip remains open after is has achieved threshold tippers.
|
||||
**/
|
||||
tipCountdown: AugmentedConst<BlockNumber>;
|
||||
/**
|
||||
* The amount of the final tip which goes to the original reporter of the tip.
|
||||
**/
|
||||
tipFindersFee: AugmentedConst<Percent>;
|
||||
/**
|
||||
* The amount held on deposit for placing a tip report.
|
||||
**/
|
||||
tipReportDepositBase: AugmentedConst<BalanceOf>;
|
||||
/**
|
||||
* The amount held on deposit per byte within the tip report reason.
|
||||
**/
|
||||
tipReportDepositPerByte: AugmentedConst<BalanceOf>;
|
||||
};
|
||||
contracts: {
|
||||
|
||||
/**
|
||||
* Number of block delay an extrinsic claim surcharge has.
|
||||
* When claim surcharge is called by an extrinsic the rent is checked
|
||||
* for current_block - delay
|
||||
**/
|
||||
signedClaimHandicap: AugmentedConst<BlockNumber>;
|
||||
/**
|
||||
* The minimum amount required to generate a tombstone.
|
||||
**/
|
||||
tombstoneDeposit: AugmentedConst<BalanceOf>;
|
||||
/**
|
||||
* Size of a contract at the time of instantiaion. This is a simple way to ensure that
|
||||
* empty contracts eventually gets deleted.
|
||||
**/
|
||||
storageSizeOffset: AugmentedConst<u32>;
|
||||
/**
|
||||
* Price of a byte of storage per one block interval. Should be greater than 0.
|
||||
**/
|
||||
rentByteFee: AugmentedConst<BalanceOf>;
|
||||
/**
|
||||
* The amount of funds a contract should deposit in order to offset
|
||||
* the cost of one byte.
|
||||
* Let's suppose the deposit is 1,000 BU (balance units)/byte and the rent is 1 BU/byte/day,
|
||||
* then a contract with 1,000,000 BU that uses 1,000 bytes of storage would pay no rent.
|
||||
* But if the balance reduced to 500,000 BU and the storage stayed the same at 1,000,
|
||||
* then it would pay 500 BU/day.
|
||||
**/
|
||||
rentDepositOffset: AugmentedConst<BalanceOf>;
|
||||
/**
|
||||
* Reward that is received by the party whose touch has led
|
||||
* to removal of a contract.
|
||||
**/
|
||||
surchargeReward: AugmentedConst<BalanceOf>;
|
||||
/**
|
||||
* The fee required to make a transfer.
|
||||
**/
|
||||
transferFee: AugmentedConst<BalanceOf>;
|
||||
/**
|
||||
* The fee required to create an account.
|
||||
**/
|
||||
creationFee: AugmentedConst<BalanceOf>;
|
||||
/**
|
||||
* The fee to be paid for making a transaction; the base.
|
||||
**/
|
||||
transactionBaseFee: AugmentedConst<BalanceOf>;
|
||||
/**
|
||||
* The fee to be paid for making a transaction; the per-byte portion.
|
||||
**/
|
||||
transactionByteFee: AugmentedConst<BalanceOf>;
|
||||
/**
|
||||
* The fee required to instantiate a contract instance. A reasonable default value
|
||||
* is 21.
|
||||
**/
|
||||
contractFee: AugmentedConst<BalanceOf>;
|
||||
/**
|
||||
* The base fee charged for calling into a contract. A reasonable default
|
||||
* value is 135.
|
||||
**/
|
||||
callBaseFee: AugmentedConst<Gas>;
|
||||
/**
|
||||
* The base fee charged for instantiating a contract. A reasonable default value
|
||||
* is 175.
|
||||
**/
|
||||
instantiateBaseFee: AugmentedConst<Gas>;
|
||||
/**
|
||||
* The maximum nesting level of a call/instantiate stack. A reasonable default
|
||||
* value is 100.
|
||||
**/
|
||||
maxDepth: AugmentedConst<u32>;
|
||||
/**
|
||||
* The maximum size of a storage value in bytes. A reasonable default is 16 KiB.
|
||||
**/
|
||||
maxValueSize: AugmentedConst<u32>;
|
||||
/**
|
||||
* The maximum amount of gas that could be expended per block. A reasonable
|
||||
* default value is 10_000_000.
|
||||
**/
|
||||
blockGasLimit: AugmentedConst<Gas>;
|
||||
};
|
||||
nicks: {
|
||||
|
||||
/**
|
||||
* Reservation fee.
|
||||
**/
|
||||
reservationFee: AugmentedConst<BalanceOf>;
|
||||
/**
|
||||
* The minimum length a name may be.
|
||||
**/
|
||||
minLength: AugmentedConst<u32>;
|
||||
/**
|
||||
* The maximum length a name may be.
|
||||
**/
|
||||
maxLength: AugmentedConst<u32>;
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -1,706 +0,0 @@
|
||||
// Auto-generated via `yarn polkadot-types-from-chain`, do not edit
|
||||
/* eslint-disable @typescript-eslint/no-empty-interface */
|
||||
|
||||
import { AnyNumber, ITuple } from '@polkadot/types/types';
|
||||
import { Option, U8aFixed, Vec } from '@polkadot/types/codec';
|
||||
import { Bytes, Data, bool, u32, u64 } from '@polkadot/types/primitive';
|
||||
import { UncleEntryItem } from '@polkadot/types/interfaces/authorship';
|
||||
import { BalanceLock, VestingSchedule } from '@polkadot/types/interfaces/balances';
|
||||
import { ProposalIndex, Votes } from '@polkadot/types/interfaces/collective';
|
||||
import { AuthorityId } from '@polkadot/types/interfaces/consensus';
|
||||
import { CodeHash, ContractInfo, Gas, PrefabWasmModule, Schedule } from '@polkadot/types/interfaces/contracts';
|
||||
import { Conviction, PropIndex, Proposal, ReferendumIndex, ReferendumInfo } from '@polkadot/types/interfaces/democracy';
|
||||
import { Vote, VoteThreshold } from '@polkadot/types/interfaces/elections';
|
||||
import { AuthorityList, SetId, StoredPendingChange, StoredState } from '@polkadot/types/interfaces/grandpa';
|
||||
import { RegistrarInfo, Registration } from '@polkadot/types/interfaces/identity';
|
||||
import { AuthIndex } from '@polkadot/types/interfaces/imOnline';
|
||||
import { Kind, OffenceDetails, OpaqueTimeSlot, ReportIdOf } from '@polkadot/types/interfaces/offences';
|
||||
import { AccountId, AccountIndex, Balance, BalanceOf, BlockNumber, Hash, Index, KeyTypeId, Moment, Perbill, ValidatorId, Weight } from '@polkadot/types/interfaces/runtime';
|
||||
import { Keys, SessionIndex } from '@polkadot/types/interfaces/session';
|
||||
import { ProposalRecord } from 'sample-polkadotjs-typegen/interfaces/signaling';
|
||||
import { EraIndex, EraPoints, Exposure, Forcing, MomentOf, Nominations, RewardDestination, SlashingSpans, SpanIndex, SpanRecord, StakingLedger, UnappliedSlash, ValidatorPrefs } from '@polkadot/types/interfaces/staking';
|
||||
import { DigestOf, EventIndex, EventRecord } from '@polkadot/types/interfaces/system';
|
||||
import { OpenTip, TreasuryProposal } from '@polkadot/types/interfaces/treasury';
|
||||
import { Multiplier } from '@polkadot/types/interfaces/txpayment';
|
||||
import { Multisig } from '@polkadot/types/interfaces/utility';
|
||||
import { VoteRecord } from 'sample-polkadotjs-typegen/interfaces/voting';
|
||||
import { Observable } from 'rxjs';
|
||||
import { ApiTypes } from '@polkadot/api/types';
|
||||
|
||||
declare module '@polkadot/api/types/storage' {
|
||||
export interface AugmentedQueries<ApiType> {
|
||||
system: {
|
||||
|
||||
/**
|
||||
* Extrinsics nonce for accounts.
|
||||
**/
|
||||
accountNonce: AugmentedQuery<ApiType, (arg: AccountId | string | Uint8Array) => Observable<Index>>;
|
||||
/**
|
||||
* Total extrinsics count for the current block.
|
||||
**/
|
||||
extrinsicCount: AugmentedQuery<ApiType, () => Observable<Option<u32>>>;
|
||||
/**
|
||||
* Total weight for all extrinsics put together, for the current block.
|
||||
**/
|
||||
allExtrinsicsWeight: AugmentedQuery<ApiType, () => Observable<Option<Weight>>>;
|
||||
/**
|
||||
* Total length (in bytes) for all extrinsics put together, for the current block.
|
||||
**/
|
||||
allExtrinsicsLen: AugmentedQuery<ApiType, () => Observable<Option<u32>>>;
|
||||
/**
|
||||
* Map of block numbers to block hashes.
|
||||
**/
|
||||
blockHash: AugmentedQuery<ApiType, (arg: BlockNumber | AnyNumber | Uint8Array) => Observable<Hash>>;
|
||||
/**
|
||||
* Extrinsics data for the current block (maps an extrinsic's index to its data).
|
||||
**/
|
||||
extrinsicData: AugmentedQuery<ApiType, (arg: u32 | AnyNumber | Uint8Array) => Observable<Bytes>>;
|
||||
/**
|
||||
* The current block number being processed. Set by `execute_block`.
|
||||
**/
|
||||
number: AugmentedQuery<ApiType, () => Observable<BlockNumber>>;
|
||||
/**
|
||||
* Hash of the previous block.
|
||||
**/
|
||||
parentHash: AugmentedQuery<ApiType, () => Observable<Hash>>;
|
||||
/**
|
||||
* Extrinsics root of the current block, also part of the block header.
|
||||
**/
|
||||
extrinsicsRoot: AugmentedQuery<ApiType, () => Observable<Hash>>;
|
||||
/**
|
||||
* Digest of the current block, also part of the block header.
|
||||
**/
|
||||
digest: AugmentedQuery<ApiType, () => Observable<DigestOf>>;
|
||||
/**
|
||||
* Events deposited for the current block.
|
||||
**/
|
||||
events: AugmentedQuery<ApiType, () => Observable<Vec<EventRecord>>>;
|
||||
/**
|
||||
* The number of events in the `Events<T>` list.
|
||||
**/
|
||||
eventCount: AugmentedQuery<ApiType, () => Observable<EventIndex>>;
|
||||
/**
|
||||
* Mapping between a topic (represented by T::Hash) and a vector of indexes
|
||||
* of events in the `<Events<T>>` list.
|
||||
* All topic vectors have deterministic storage locations depending on the topic. This
|
||||
* allows light-clients to leverage the changes trie storage tracking mechanism and
|
||||
* in case of changes fetch the list of events of interest.
|
||||
* The value has the type `(T::BlockNumber, EventIndex)` because if we used only just
|
||||
* the `EventIndex` then in case if the topic has the same contents on the next block
|
||||
* no notification will be triggered thus the event might be lost.
|
||||
**/
|
||||
eventTopics: AugmentedQuery<ApiType, (arg: Hash | string | Uint8Array) => Observable<Vec<ITuple<[BlockNumber, EventIndex]>>>>;
|
||||
};
|
||||
utility: {
|
||||
|
||||
/**
|
||||
* The set of open multisig operations.
|
||||
**/
|
||||
multisigs: AugmentedQueryDoubleMap<ApiType, (key1: AccountId | string | Uint8Array, key2: U8aFixed | string | Uint8Array) => Observable<Option<Multisig>>>;
|
||||
};
|
||||
timestamp: {
|
||||
|
||||
/**
|
||||
* Current time for the current block.
|
||||
**/
|
||||
now: AugmentedQuery<ApiType, () => Observable<Moment>>;
|
||||
/**
|
||||
* Did the timestamp get updated in this block?
|
||||
**/
|
||||
didUpdate: AugmentedQuery<ApiType, () => Observable<bool>>;
|
||||
};
|
||||
authorship: {
|
||||
|
||||
/**
|
||||
* Uncles
|
||||
**/
|
||||
uncles: AugmentedQuery<ApiType, () => Observable<Vec<UncleEntryItem>>>;
|
||||
/**
|
||||
* Author of current block.
|
||||
**/
|
||||
author: AugmentedQuery<ApiType, () => Observable<Option<AccountId>>>;
|
||||
/**
|
||||
* Whether uncles were already set in this block.
|
||||
**/
|
||||
didSetUncles: AugmentedQuery<ApiType, () => Observable<bool>>;
|
||||
};
|
||||
indices: {
|
||||
|
||||
/**
|
||||
* The next free enumeration set.
|
||||
**/
|
||||
nextEnumSet: AugmentedQuery<ApiType, () => Observable<AccountIndex>>;
|
||||
/**
|
||||
* The enumeration sets.
|
||||
**/
|
||||
enumSet: AugmentedQuery<ApiType, (arg: AccountIndex | AnyNumber | Uint8Array) => Observable<Vec<AccountId>>>;
|
||||
};
|
||||
balances: {
|
||||
|
||||
/**
|
||||
* The total units issued in the system.
|
||||
**/
|
||||
totalIssuance: AugmentedQuery<ApiType, () => Observable<Balance>>;
|
||||
/**
|
||||
* Information regarding the vesting of a given account.
|
||||
**/
|
||||
vesting: AugmentedQuery<ApiType, (arg: AccountId | string | Uint8Array) => Observable<Option<VestingSchedule>>>;
|
||||
/**
|
||||
* 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.
|
||||
* `frame_system::AccountNonce` is also deleted if `ReservedBalance` is also zero (it also gets
|
||||
* collapsed to zero if it ever becomes less than `ExistentialDeposit`.
|
||||
**/
|
||||
freeBalance: AugmentedQuery<ApiType, (arg: AccountId | string | Uint8Array) => Observable<Balance>>;
|
||||
/**
|
||||
* 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`.
|
||||
* `frame_system::AccountNonce` is also deleted if `FreeBalance` is also zero (it also gets
|
||||
* collapsed to zero if it ever becomes less than `ExistentialDeposit`.)
|
||||
**/
|
||||
reservedBalance: AugmentedQuery<ApiType, (arg: AccountId | string | Uint8Array) => Observable<Balance>>;
|
||||
/**
|
||||
* Any liquidity locks on some account balances.
|
||||
**/
|
||||
locks: AugmentedQuery<ApiType, (arg: AccountId | string | Uint8Array) => Observable<Vec<BalanceLock>>>;
|
||||
};
|
||||
transactionPayment: {
|
||||
|
||||
nextFeeMultiplier: AugmentedQuery<ApiType, () => Observable<Multiplier>>;
|
||||
};
|
||||
staking: {
|
||||
|
||||
/**
|
||||
* The ideal number of staking participants.
|
||||
**/
|
||||
validatorCount: AugmentedQuery<ApiType, () => Observable<u32>>;
|
||||
/**
|
||||
* Minimum number of staking participants before emergency conditions are imposed.
|
||||
**/
|
||||
minimumValidatorCount: AugmentedQuery<ApiType, () => Observable<u32>>;
|
||||
/**
|
||||
* 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.
|
||||
**/
|
||||
invulnerables: AugmentedQuery<ApiType, () => Observable<Vec<AccountId>>>;
|
||||
/**
|
||||
* Map from all locked "stash" accounts to the controller account.
|
||||
**/
|
||||
bonded: AugmentedQuery<ApiType, (arg: AccountId | string | Uint8Array) => Observable<Option<AccountId>>>;
|
||||
/**
|
||||
* Map from all (unlocked) "controller" accounts to the info regarding the staking.
|
||||
**/
|
||||
ledger: AugmentedQuery<ApiType, (arg: AccountId | string | Uint8Array) => Observable<Option<StakingLedger>>>;
|
||||
/**
|
||||
* Where the reward payment should be made. Keyed by stash.
|
||||
**/
|
||||
payee: AugmentedQuery<ApiType, (arg: AccountId | string | Uint8Array) => Observable<RewardDestination>>;
|
||||
/**
|
||||
* The map from (wannabe) validator stash key to the preferences of that validator.
|
||||
**/
|
||||
validators: AugmentedQuery<ApiType, (arg: AccountId | string | Uint8Array) => Observable<ValidatorPrefs>>;
|
||||
/**
|
||||
* The map from nominator stash key to the set of stash keys of all validators to nominate.
|
||||
* NOTE: is private so that we can ensure upgraded before all typical accesses.
|
||||
* Direct storage APIs can still bypass this protection.
|
||||
**/
|
||||
nominators: AugmentedQuery<ApiType, (arg: AccountId | string | Uint8Array) => Observable<Option<Nominations>>>;
|
||||
/**
|
||||
* 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 Session module.
|
||||
* This is keyed by the stash account.
|
||||
**/
|
||||
stakers: AugmentedQuery<ApiType, (arg: AccountId | string | Uint8Array) => Observable<Exposure>>;
|
||||
/**
|
||||
* The currently elected validator set keyed by stash account ID.
|
||||
**/
|
||||
currentElected: AugmentedQuery<ApiType, () => Observable<Vec<AccountId>>>;
|
||||
/**
|
||||
* The current era index.
|
||||
**/
|
||||
currentEra: AugmentedQuery<ApiType, () => Observable<EraIndex>>;
|
||||
/**
|
||||
* The start of the current era.
|
||||
**/
|
||||
currentEraStart: AugmentedQuery<ApiType, () => Observable<MomentOf>>;
|
||||
/**
|
||||
* The session index at which the current era started.
|
||||
**/
|
||||
currentEraStartSessionIndex: AugmentedQuery<ApiType, () => Observable<SessionIndex>>;
|
||||
/**
|
||||
* Rewards for the current era. Using indices of current elected set.
|
||||
**/
|
||||
currentEraPointsEarned: AugmentedQuery<ApiType, () => Observable<EraPoints>>;
|
||||
/**
|
||||
* The amount of balance actively at stake for each validator slot, currently.
|
||||
* This is used to derive rewards and punishments.
|
||||
**/
|
||||
slotStake: AugmentedQuery<ApiType, () => Observable<BalanceOf>>;
|
||||
/**
|
||||
* True if the next session change will be a new era regardless of index.
|
||||
**/
|
||||
forceEra: AugmentedQuery<ApiType, () => Observable<Forcing>>;
|
||||
/**
|
||||
* The percentage of the slash that is distributed to reporters.
|
||||
* The rest of the slashed value is handled by the `Slash`.
|
||||
**/
|
||||
slashRewardFraction: AugmentedQuery<ApiType, () => Observable<Perbill>>;
|
||||
/**
|
||||
* The amount of currency given to reporters of a slash event which was
|
||||
* canceled by extraordinary circumstances (e.g. governance).
|
||||
**/
|
||||
canceledSlashPayout: AugmentedQuery<ApiType, () => Observable<BalanceOf>>;
|
||||
/**
|
||||
* All unapplied slashes that are queued for later.
|
||||
**/
|
||||
unappliedSlashes: AugmentedQuery<ApiType, (arg: EraIndex | AnyNumber | Uint8Array) => Observable<Vec<UnappliedSlash>>>;
|
||||
/**
|
||||
* A mapping from still-bonded eras to the first session index of that era.
|
||||
**/
|
||||
bondedEras: AugmentedQuery<ApiType, () => Observable<Vec<ITuple<[EraIndex, SessionIndex]>>>>;
|
||||
/**
|
||||
* All slashing events on validators, mapped by era to the highest slash proportion
|
||||
* and slash value of the era.
|
||||
**/
|
||||
validatorSlashInEra: AugmentedQueryDoubleMap<ApiType, (key1: EraIndex | AnyNumber | Uint8Array, key2: AccountId | string | Uint8Array) => Observable<Option<ITuple<[Perbill, BalanceOf]>>>>;
|
||||
/**
|
||||
* All slashing events on nominators, mapped by era to the highest slash value of the era.
|
||||
**/
|
||||
nominatorSlashInEra: AugmentedQueryDoubleMap<ApiType, (key1: EraIndex | AnyNumber | Uint8Array, key2: AccountId | string | Uint8Array) => Observable<Option<BalanceOf>>>;
|
||||
/**
|
||||
* Slashing spans for stash accounts.
|
||||
**/
|
||||
slashingSpans: AugmentedQuery<ApiType, (arg: AccountId | string | Uint8Array) => Observable<Option<SlashingSpans>>>;
|
||||
/**
|
||||
* Records information about the maximum slash of a stash within a slashing span,
|
||||
* as well as how much reward has been paid out.
|
||||
**/
|
||||
spanSlash: AugmentedQuery<ApiType, (arg: ITuple<[AccountId, SpanIndex]> | [AccountId | string | Uint8Array, SpanIndex | AnyNumber | Uint8Array]) => Observable<SpanRecord>>;
|
||||
/**
|
||||
* The earliest era for which we have a pending, unapplied slash.
|
||||
**/
|
||||
earliestUnappliedSlash: AugmentedQuery<ApiType, () => Observable<Option<EraIndex>>>;
|
||||
/**
|
||||
* The version of storage for upgrade.
|
||||
**/
|
||||
storageVersion: AugmentedQuery<ApiType, () => Observable<u32>>;
|
||||
};
|
||||
session: {
|
||||
|
||||
/**
|
||||
* The current set of validators.
|
||||
**/
|
||||
validators: AugmentedQuery<ApiType, () => Observable<Vec<ValidatorId>>>;
|
||||
/**
|
||||
* Current index of the session.
|
||||
**/
|
||||
currentIndex: AugmentedQuery<ApiType, () => Observable<SessionIndex>>;
|
||||
/**
|
||||
* True if the underlying economic identities or weighting behind the validators
|
||||
* has changed in the queued validator set.
|
||||
**/
|
||||
queuedChanged: AugmentedQuery<ApiType, () => Observable<bool>>;
|
||||
/**
|
||||
* The queued keys for the next session. When the next session begins, these keys
|
||||
* will be used to determine the validator's session keys.
|
||||
**/
|
||||
queuedKeys: AugmentedQuery<ApiType, () => Observable<Vec<ITuple<[ValidatorId, Keys]>>>>;
|
||||
/**
|
||||
* Indices of disabled validators.
|
||||
* The set is cleared when `on_session_ending` returns a new set of identities.
|
||||
**/
|
||||
disabledValidators: AugmentedQuery<ApiType, () => Observable<Vec<u32>>>;
|
||||
/**
|
||||
* The next session keys for a validator.
|
||||
* The first key is always `DEDUP_KEY_PREFIX` to have all the data in the same branch of
|
||||
* the trie. Having all data in the same branch should prevent slowing down other queries.
|
||||
**/
|
||||
nextKeys: AugmentedQueryDoubleMap<ApiType, (key1: Bytes | string | Uint8Array, key2: ValidatorId | string | Uint8Array) => Observable<Option<Keys>>>;
|
||||
/**
|
||||
* The owner of a key. The second key is the `KeyTypeId` + the encoded key.
|
||||
* The first key is always `DEDUP_KEY_PREFIX` to have all the data in the same branch of
|
||||
* the trie. Having all data in the same branch should prevent slowing down other queries.
|
||||
**/
|
||||
keyOwner: AugmentedQueryDoubleMap<ApiType, (key1: Bytes | string | Uint8Array, key2: ITuple<[KeyTypeId, Bytes]> | [KeyTypeId | AnyNumber | Uint8Array, Bytes | string | Uint8Array]) => Observable<Option<ValidatorId>>>;
|
||||
};
|
||||
democracy: {
|
||||
|
||||
/**
|
||||
* The number of (public) proposals that have been made so far.
|
||||
**/
|
||||
publicPropCount: AugmentedQuery<ApiType, () => Observable<PropIndex>>;
|
||||
/**
|
||||
* The public proposals. Unsorted. The second item is the proposal's hash.
|
||||
**/
|
||||
publicProps: AugmentedQuery<ApiType, () => Observable<Vec<ITuple<[PropIndex, Hash, AccountId]>>>>;
|
||||
/**
|
||||
* Map of hashes to the proposal preimage, along with who registered it and their deposit.
|
||||
* The block number is the block at which it was deposited.
|
||||
**/
|
||||
preimages: AugmentedQuery<ApiType, (arg: Hash | string | Uint8Array) => Observable<Option<ITuple<[Bytes, AccountId, BalanceOf, BlockNumber]>>>>;
|
||||
/**
|
||||
* Those who have locked a deposit.
|
||||
**/
|
||||
depositOf: AugmentedQuery<ApiType, (arg: PropIndex | AnyNumber | Uint8Array) => Observable<Option<ITuple<[BalanceOf, Vec<AccountId>]>>>>;
|
||||
/**
|
||||
* The next free referendum index, aka the number of referenda started so far.
|
||||
**/
|
||||
referendumCount: AugmentedQuery<ApiType, () => Observable<ReferendumIndex>>;
|
||||
/**
|
||||
* The lowest referendum index representing an unbaked referendum. Equal to
|
||||
* `ReferendumCount` if there isn't a unbaked referendum.
|
||||
**/
|
||||
lowestUnbaked: AugmentedQuery<ApiType, () => Observable<ReferendumIndex>>;
|
||||
/**
|
||||
* Information concerning any given referendum.
|
||||
**/
|
||||
referendumInfoOf: AugmentedQuery<ApiType, (arg: ReferendumIndex | AnyNumber | Uint8Array) => Observable<Option<ReferendumInfo>>>;
|
||||
/**
|
||||
* Queue of successful referenda to be dispatched. Stored ordered by block number.
|
||||
**/
|
||||
dispatchQueue: AugmentedQuery<ApiType, () => Observable<Vec<ITuple<[BlockNumber, Hash, ReferendumIndex]>>>>;
|
||||
/**
|
||||
* Get the voters for the current proposal.
|
||||
**/
|
||||
votersFor: AugmentedQuery<ApiType, (arg: ReferendumIndex | AnyNumber | Uint8Array) => Observable<Vec<AccountId>>>;
|
||||
/**
|
||||
* 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.
|
||||
**/
|
||||
voteOf: AugmentedQuery<ApiType, (arg: ITuple<[ReferendumIndex, AccountId]> | [ReferendumIndex | AnyNumber | Uint8Array, AccountId | string | Uint8Array]) => Observable<Vote>>;
|
||||
/**
|
||||
* Who is able to vote for whom. Value is the fund-holding account, key is the
|
||||
* vote-transaction-sending account.
|
||||
**/
|
||||
proxy: AugmentedQuery<ApiType, (arg: AccountId | string | Uint8Array) => Observable<Option<AccountId>>>;
|
||||
/**
|
||||
* Get the account (and lock periods) to which another account is delegating vote.
|
||||
**/
|
||||
delegations: AugmentedQuery<ApiType, (arg: AccountId | string | Uint8Array) => Observable<ITuple<[AccountId, Conviction]>>>;
|
||||
/**
|
||||
* True if the last referendum tabled was submitted externally. False if it was a public
|
||||
* proposal.
|
||||
**/
|
||||
lastTabledWasExternal: AugmentedQuery<ApiType, () => Observable<bool>>;
|
||||
/**
|
||||
* The referendum to be tabled whenever it would be valid to table an external proposal.
|
||||
* This happens when a referendum needs to be tabled and one of two conditions are met:
|
||||
* - `LastTabledWasExternal` is `false`; or
|
||||
* - `PublicProps` is empty.
|
||||
**/
|
||||
nextExternal: AugmentedQuery<ApiType, () => Observable<Option<ITuple<[Hash, VoteThreshold]>>>>;
|
||||
/**
|
||||
* A record of who vetoed what. Maps proposal hash to a possible existent block number
|
||||
* (until when it may not be resubmitted) and who vetoed it.
|
||||
**/
|
||||
blacklist: AugmentedQuery<ApiType, (arg: Hash | string | Uint8Array) => Observable<Option<ITuple<[BlockNumber, Vec<AccountId>]>>>>;
|
||||
/**
|
||||
* Record of all proposals that have been subject to emergency cancellation.
|
||||
**/
|
||||
cancellations: AugmentedQuery<ApiType, (arg: Hash | string | Uint8Array) => Observable<bool>>;
|
||||
};
|
||||
council: {
|
||||
|
||||
/**
|
||||
* The hashes of the active proposals.
|
||||
**/
|
||||
proposals: AugmentedQuery<ApiType, () => Observable<Vec<Hash>>>;
|
||||
/**
|
||||
* Actual proposal for a given hash, if it's current.
|
||||
**/
|
||||
proposalOf: AugmentedQuery<ApiType, (arg: Hash | string | Uint8Array) => Observable<Option<Proposal>>>;
|
||||
/**
|
||||
* Votes on a given proposal, if it is ongoing.
|
||||
**/
|
||||
voting: AugmentedQuery<ApiType, (arg: Hash | string | Uint8Array) => Observable<Option<Votes>>>;
|
||||
/**
|
||||
* Proposals so far.
|
||||
**/
|
||||
proposalCount: AugmentedQuery<ApiType, () => Observable<u32>>;
|
||||
/**
|
||||
* The current members of the collective. This is stored sorted (just by value).
|
||||
**/
|
||||
members: AugmentedQuery<ApiType, () => Observable<Vec<AccountId>>>;
|
||||
};
|
||||
elections: {
|
||||
|
||||
/**
|
||||
* The current elected membership. Sorted based on account id.
|
||||
**/
|
||||
members: AugmentedQuery<ApiType, () => Observable<Vec<ITuple<[AccountId, BalanceOf]>>>>;
|
||||
/**
|
||||
* The current runners_up. Sorted based on low to high merit (worse to best runner).
|
||||
**/
|
||||
runnersUp: AugmentedQuery<ApiType, () => Observable<Vec<ITuple<[AccountId, BalanceOf]>>>>;
|
||||
/**
|
||||
* The total number of vote rounds that have happened, excluding the upcoming one.
|
||||
**/
|
||||
electionRounds: AugmentedQuery<ApiType, () => Observable<u32>>;
|
||||
/**
|
||||
* Votes of a particular voter, with the round index of the votes.
|
||||
**/
|
||||
votesOf: AugmentedQuery<ApiType, (arg: AccountId | string | Uint8Array) => Observable<Vec<AccountId>>>;
|
||||
/**
|
||||
* Locked stake of a voter.
|
||||
**/
|
||||
stakeOf: AugmentedQuery<ApiType, (arg: AccountId | string | Uint8Array) => Observable<BalanceOf>>;
|
||||
/**
|
||||
* The present candidate list. Sorted based on account-id. A current member or a runner can
|
||||
* never enter this vector and is always implicitly assumed to be a candidate.
|
||||
**/
|
||||
candidates: AugmentedQuery<ApiType, () => Observable<Vec<AccountId>>>;
|
||||
};
|
||||
grandpa: {
|
||||
|
||||
/**
|
||||
* DEPRECATED
|
||||
* This used to store the current authority set, which has been migrated to the well-known
|
||||
* GRANDPA_AUTHORITES_KEY unhashed key.
|
||||
**/
|
||||
authorities: AugmentedQuery<ApiType, () => Observable<AuthorityList>>;
|
||||
/**
|
||||
* State of the current authority set.
|
||||
**/
|
||||
state: AugmentedQuery<ApiType, () => Observable<StoredState>>;
|
||||
/**
|
||||
* Pending change: (signaled at, scheduled change).
|
||||
**/
|
||||
pendingChange: AugmentedQuery<ApiType, () => Observable<Option<StoredPendingChange>>>;
|
||||
/**
|
||||
* next block number where we can force a change.
|
||||
**/
|
||||
nextForced: AugmentedQuery<ApiType, () => Observable<Option<BlockNumber>>>;
|
||||
/**
|
||||
* `true` if we are currently stalled.
|
||||
**/
|
||||
stalled: AugmentedQuery<ApiType, () => Observable<Option<ITuple<[BlockNumber, BlockNumber]>>>>;
|
||||
/**
|
||||
* The number of changes (both in terms of keys and underlying economic responsibilities)
|
||||
* in the "set" of Grandpa validators from genesis.
|
||||
**/
|
||||
currentSetId: AugmentedQuery<ApiType, () => Observable<SetId>>;
|
||||
/**
|
||||
* A mapping from grandpa set ID to the index of the *most recent* session for which its members were responsible.
|
||||
**/
|
||||
setIdSession: AugmentedQuery<ApiType, (arg: SetId | AnyNumber | Uint8Array) => Observable<Option<SessionIndex>>>;
|
||||
};
|
||||
treasury: {
|
||||
|
||||
/**
|
||||
* Number of proposals that have been made.
|
||||
**/
|
||||
proposalCount: AugmentedQuery<ApiType, () => Observable<ProposalIndex>>;
|
||||
/**
|
||||
* Proposals that have been made.
|
||||
**/
|
||||
proposals: AugmentedQuery<ApiType, (arg: ProposalIndex | AnyNumber | Uint8Array) => Observable<Option<TreasuryProposal>>>;
|
||||
/**
|
||||
* Proposal indices that have been approved but not yet awarded.
|
||||
**/
|
||||
approvals: AugmentedQuery<ApiType, () => Observable<Vec<ProposalIndex>>>;
|
||||
/**
|
||||
* Tips that are not yet completed. Keyed by the hash of `(reason, who)` from the value.
|
||||
* This has the insecure enumerable hash function since the key itself is already
|
||||
* guaranteed to be a secure hash.
|
||||
**/
|
||||
tips: AugmentedQuery<ApiType, (arg: Hash | string | Uint8Array) => Observable<Option<OpenTip>>>;
|
||||
/**
|
||||
* Simple preimage lookup from the reason's hash to the original data. Again, has an
|
||||
* insecure enumerable hash since the key is guaranteed to be the result of a secure hash.
|
||||
**/
|
||||
reasons: AugmentedQuery<ApiType, (arg: Hash | string | Uint8Array) => Observable<Option<Bytes>>>;
|
||||
};
|
||||
contracts: {
|
||||
|
||||
/**
|
||||
* Gas spent so far in this block.
|
||||
**/
|
||||
gasSpent: AugmentedQuery<ApiType, () => Observable<Gas>>;
|
||||
/**
|
||||
* Current cost schedule for contracts.
|
||||
**/
|
||||
currentSchedule: AugmentedQuery<ApiType, () => Observable<Schedule>>;
|
||||
/**
|
||||
* A mapping from an original code hash to the original code, untouched by instrumentation.
|
||||
**/
|
||||
pristineCode: AugmentedQuery<ApiType, (arg: CodeHash | string | Uint8Array) => Observable<Option<Bytes>>>;
|
||||
/**
|
||||
* A mapping between an original code hash and instrumented wasm code, ready for execution.
|
||||
**/
|
||||
codeStorage: AugmentedQuery<ApiType, (arg: CodeHash | string | Uint8Array) => Observable<Option<PrefabWasmModule>>>;
|
||||
/**
|
||||
* The subtrie counter.
|
||||
**/
|
||||
accountCounter: AugmentedQuery<ApiType, () => Observable<u64>>;
|
||||
/**
|
||||
* The code associated with a given account.
|
||||
**/
|
||||
contractInfoOf: AugmentedQuery<ApiType, (arg: AccountId | string | Uint8Array) => Observable<Option<ContractInfo>>>;
|
||||
/**
|
||||
* The price of one unit of gas.
|
||||
**/
|
||||
gasPrice: AugmentedQuery<ApiType, () => Observable<BalanceOf>>;
|
||||
};
|
||||
identity: {
|
||||
|
||||
/**
|
||||
* Information that is pertinent to identify the entity behind an account.
|
||||
**/
|
||||
identityOf: AugmentedQuery<ApiType, (arg: AccountId | string | Uint8Array) => Observable<Option<Registration>>>;
|
||||
/**
|
||||
* The super-identity of an alternative "sub" identity together with its name, within that
|
||||
* context. If the account is not some other account's sub-identity, then just `None`.
|
||||
**/
|
||||
superOf: AugmentedQuery<ApiType, (arg: AccountId | string | Uint8Array) => Observable<Option<ITuple<[AccountId, Data]>>>>;
|
||||
/**
|
||||
* Alternative "sub" identities of this account.
|
||||
* The first item is the deposit, the second is a vector of the accounts.
|
||||
**/
|
||||
subsOf: AugmentedQuery<ApiType, (arg: AccountId | string | Uint8Array) => Observable<ITuple<[BalanceOf, Vec<AccountId>]>>>;
|
||||
/**
|
||||
* The set of registrars. Not expected to get very big as can only be added through a
|
||||
* special origin (likely a council motion).
|
||||
* The index into this can be cast to `RegistrarIndex` to get a valid value.
|
||||
**/
|
||||
registrars: AugmentedQuery<ApiType, () => Observable<Vec<Option<RegistrarInfo>>>>;
|
||||
};
|
||||
imOnline: {
|
||||
|
||||
/**
|
||||
* The block number after which it's ok to send heartbeats in current session.
|
||||
* At the beginning of each session we set this to a value that should
|
||||
* fall roughly in the middle of the session duration.
|
||||
* The idea is to first wait for the validators to produce a block
|
||||
* in the current session, so that the heartbeat later on will not be necessary.
|
||||
**/
|
||||
heartbeatAfter: AugmentedQuery<ApiType, () => Observable<BlockNumber>>;
|
||||
/**
|
||||
* The current set of keys that may issue a heartbeat.
|
||||
**/
|
||||
keys: AugmentedQuery<ApiType, () => Observable<Vec<AuthorityId>>>;
|
||||
/**
|
||||
* For each session index, we keep a mapping of `AuthIndex`
|
||||
* to `offchain::OpaqueNetworkState`.
|
||||
**/
|
||||
receivedHeartbeats: AugmentedQueryDoubleMap<ApiType, (key1: SessionIndex | AnyNumber | Uint8Array, key2: AuthIndex | AnyNumber | Uint8Array) => Observable<Option<Bytes>>>;
|
||||
/**
|
||||
* For each session index, we keep a mapping of `T::ValidatorId` to the
|
||||
* number of blocks authored by the given authority.
|
||||
**/
|
||||
authoredBlocks: AugmentedQueryDoubleMap<ApiType, (key1: SessionIndex | AnyNumber | Uint8Array, key2: ValidatorId | string | Uint8Array) => Observable<u32>>;
|
||||
};
|
||||
offences: {
|
||||
|
||||
/**
|
||||
* The primary structure that holds all offence records keyed by report identifiers.
|
||||
**/
|
||||
reports: AugmentedQuery<ApiType, (arg: ReportIdOf | string | Uint8Array) => Observable<Option<OffenceDetails>>>;
|
||||
/**
|
||||
* A vector of reports of the same kind that happened at the same time slot.
|
||||
**/
|
||||
concurrentReportsIndex: AugmentedQueryDoubleMap<ApiType, (key1: Kind | string | Uint8Array, key2: OpaqueTimeSlot | string | Uint8Array) => Observable<Vec<ReportIdOf>>>;
|
||||
/**
|
||||
* Enumerates all reports of a kind along with the time they happened.
|
||||
* All reports are sorted by the time of offence.
|
||||
* Note that the actual type of this mapping is `Vec<u8>`, this is because values of
|
||||
* different types are not supported at the moment so we are doing the manual serialization.
|
||||
**/
|
||||
reportsByKindIndex: AugmentedQuery<ApiType, (arg: Kind | string | Uint8Array) => Observable<Bytes>>;
|
||||
};
|
||||
randomnessCollectiveFlip: {
|
||||
|
||||
/**
|
||||
* Series of block headers from the last 81 blocks that acts as random seed material. This
|
||||
* is arranged as a ring buffer with `block_number % 81` being the index into the `Vec` of
|
||||
* the oldest hash.
|
||||
**/
|
||||
randomMaterial: AugmentedQuery<ApiType, () => Observable<Vec<Hash>>>;
|
||||
};
|
||||
nicks: {
|
||||
|
||||
/**
|
||||
* The lookup table for names.
|
||||
**/
|
||||
nameOf: AugmentedQuery<ApiType, (arg: AccountId | string | Uint8Array) => Observable<Option<ITuple<[Bytes, BalanceOf]>>>>;
|
||||
};
|
||||
sudo: {
|
||||
|
||||
/**
|
||||
* The `AccountId` of the sudo key.
|
||||
**/
|
||||
key: AugmentedQuery<ApiType, () => Observable<AccountId>>;
|
||||
};
|
||||
signaling: {
|
||||
|
||||
/**
|
||||
* The total number of proposals created thus far.
|
||||
**/
|
||||
proposalCount: AugmentedQuery<ApiType, () => Observable<u32>>;
|
||||
/**
|
||||
* A list of all extant proposals.
|
||||
**/
|
||||
inactiveProposals: AugmentedQuery<ApiType, () => Observable<Vec<ITuple<[Hash, BlockNumber]>>>>;
|
||||
/**
|
||||
* A list of active proposals along with the time at which they complete.
|
||||
**/
|
||||
activeProposals: AugmentedQuery<ApiType, () => Observable<Vec<ITuple<[Hash, BlockNumber]>>>>;
|
||||
/**
|
||||
* A list of completed proposals, pending deletion
|
||||
**/
|
||||
completedProposals: AugmentedQuery<ApiType, () => Observable<Vec<ITuple<[Hash, BlockNumber]>>>>;
|
||||
/**
|
||||
* Amount of time a proposal remains in "Voting" stage.
|
||||
**/
|
||||
votingLength: AugmentedQuery<ApiType, () => Observable<BlockNumber>>;
|
||||
/**
|
||||
* Map for retrieving the information about any proposal from its hash.
|
||||
**/
|
||||
proposalOf: AugmentedQuery<ApiType, (arg: Hash | string | Uint8Array) => Observable<Option<ProposalRecord>>>;
|
||||
/**
|
||||
* Registration bond
|
||||
**/
|
||||
proposalCreationBond: AugmentedQuery<ApiType, () => Observable<BalanceOf>>;
|
||||
};
|
||||
voting: {
|
||||
|
||||
/**
|
||||
* The map of all vote records indexed by id
|
||||
**/
|
||||
voteRecords: AugmentedQuery<ApiType, (arg: u64 | AnyNumber | Uint8Array) => Observable<Option<VoteRecord>>>;
|
||||
/**
|
||||
* The number of vote records that have been created
|
||||
**/
|
||||
voteRecordCount: AugmentedQuery<ApiType, () => Observable<u64>>;
|
||||
};
|
||||
treasuryReward: {
|
||||
|
||||
/**
|
||||
* Interval in number of blocks to reward treasury
|
||||
**/
|
||||
mintingInterval: AugmentedQuery<ApiType, () => Observable<BlockNumber>>;
|
||||
/**
|
||||
* Current payout of module
|
||||
**/
|
||||
currentPayout: AugmentedQuery<ApiType, () => Observable<BalanceOf>>;
|
||||
/**
|
||||
* Current pot
|
||||
**/
|
||||
pot: AugmentedQuery<ApiType, () => Observable<Balance>>;
|
||||
};
|
||||
}
|
||||
|
||||
export interface QueryableStorage<ApiType extends ApiTypes> extends AugmentedQueries<ApiType> {
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,7 +0,0 @@
|
||||
// Auto-generated via `yarn polkadot-types-from-chain`, do not edit
|
||||
/* eslint-disable @typescript-eslint/no-empty-interface */
|
||||
|
||||
import '@polkadot/api/augment/rpc';
|
||||
import './augment-api-consts';
|
||||
import './augment-api-query';
|
||||
import './augment-api-tx';
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,7 +0,0 @@
|
||||
// order here matches with what is found in (unused removed)
|
||||
// https://www.npmjs.com/package/edgeware-node-types
|
||||
// https://github.com/hicommonwealth/edgeware-node-types/tree/master/types
|
||||
|
||||
export { default as signaling } from './signaling/definitions';
|
||||
export { default as treasuryRewards } from './treasuryRewards/definitions';
|
||||
export { default as voting } from './voting/definitions';
|
||||
@@ -1,4 +0,0 @@
|
||||
// Auto-generated via `yarn polkadot-types-from-defs`, do not edit
|
||||
/* eslint-disable @typescript-eslint/no-empty-interface */
|
||||
|
||||
export * from './types';
|
||||
@@ -1,17 +0,0 @@
|
||||
/* eslint-disable @typescript-eslint/camelcase */
|
||||
|
||||
export default {
|
||||
types: {
|
||||
ProposalRecord: {
|
||||
index: 'u32',
|
||||
author: 'AccountId',
|
||||
stage: 'VoteStage',
|
||||
transition_time: 'u32',
|
||||
title: 'Text',
|
||||
contents: 'Text',
|
||||
vote_id: 'u64'
|
||||
},
|
||||
ProposalContents: 'Vec<u8>',
|
||||
ProposalTitle: 'Vec<u8>'
|
||||
}
|
||||
};
|
||||
@@ -1,4 +0,0 @@
|
||||
// Auto-generated via `yarn polkadot-types-from-defs`, do not edit
|
||||
/* eslint-disable @typescript-eslint/no-empty-interface */
|
||||
|
||||
export * from './types';
|
||||
@@ -1,24 +0,0 @@
|
||||
// Auto-generated via `yarn polkadot-types-from-defs`, do not edit
|
||||
/* eslint-disable @typescript-eslint/no-empty-interface */
|
||||
|
||||
import { Struct } from '@polkadot/types/codec';
|
||||
import { Bytes, Text, u32, u64 } from '@polkadot/types/primitive';
|
||||
import { AccountId } from '@polkadot/types/interfaces/runtime';
|
||||
import { VoteStage } from 'sample-polkadotjs-typegen/interfaces/voting';
|
||||
|
||||
/** @name ProposalContents */
|
||||
export interface ProposalContents extends Bytes {}
|
||||
|
||||
/** @name ProposalRecord */
|
||||
export interface ProposalRecord extends Struct {
|
||||
readonly index: u32;
|
||||
readonly author: AccountId;
|
||||
readonly stage: VoteStage;
|
||||
readonly transition_time: u32;
|
||||
readonly title: Text;
|
||||
readonly contents: Text;
|
||||
readonly vote_id: u64;
|
||||
}
|
||||
|
||||
/** @name ProposalTitle */
|
||||
export interface ProposalTitle extends Bytes {}
|
||||
@@ -1,7 +0,0 @@
|
||||
/* eslint-disable @typescript-eslint/camelcase */
|
||||
|
||||
export default {
|
||||
types: {
|
||||
Balance2: 'u128'
|
||||
}
|
||||
};
|
||||
@@ -1,4 +0,0 @@
|
||||
// Auto-generated via `yarn polkadot-types-from-defs`, do not edit
|
||||
/* eslint-disable @typescript-eslint/no-empty-interface */
|
||||
|
||||
export * from './types';
|
||||
@@ -1,7 +0,0 @@
|
||||
// Auto-generated via `yarn polkadot-types-from-defs`, do not edit
|
||||
/* eslint-disable @typescript-eslint/no-empty-interface */
|
||||
|
||||
import { u128 } from '@polkadot/types/primitive';
|
||||
|
||||
/** @name Balance2 */
|
||||
export interface Balance2 extends u128 {}
|
||||
@@ -1,6 +0,0 @@
|
||||
// Auto-generated via `yarn polkadot-types-from-defs`, do not edit
|
||||
/* eslint-disable @typescript-eslint/no-empty-interface */
|
||||
|
||||
export * from './signaling/types';
|
||||
export * from './treasuryRewards/types';
|
||||
export * from './voting/types';
|
||||
@@ -1,33 +0,0 @@
|
||||
/* eslint-disable @typescript-eslint/camelcase */
|
||||
|
||||
export default {
|
||||
types: {
|
||||
VoteStage: {
|
||||
_enum: ['PreVoting', 'Commit', 'Voting', 'Completed']
|
||||
},
|
||||
VoteType: {
|
||||
_enum: ['Binary', 'MultiOption', 'RankedChoice']
|
||||
},
|
||||
TallyType: {
|
||||
_enum: ['OnePerson', 'OneCoin']
|
||||
},
|
||||
VoteOutcome: '[u8; 32]',
|
||||
Tally: 'Option<Vec<(VoteOutcome, u128)>>',
|
||||
VoteData: {
|
||||
initiator: 'AccountId',
|
||||
stage: 'VoteStage',
|
||||
vote_type: 'VoteType',
|
||||
tally_type: 'TallyType',
|
||||
is_commit_reveal: 'bool'
|
||||
},
|
||||
Commitments: 'Vec<(AccountId, VoteOutcome)>',
|
||||
Reveals: 'Vec<(AccountId, Vec<VoteOutcome>)>',
|
||||
VoteRecord: {
|
||||
id: 'u64',
|
||||
commitments: 'Commitments',
|
||||
reveals: 'Reveals',
|
||||
data: 'VoteData',
|
||||
outcomes: 'Vec<VoteOutcome>'
|
||||
}
|
||||
}
|
||||
};
|
||||
@@ -1,4 +0,0 @@
|
||||
// Auto-generated via `yarn polkadot-types-from-defs`, do not edit
|
||||
/* eslint-disable @typescript-eslint/no-empty-interface */
|
||||
|
||||
export * from './types';
|
||||
@@ -1,58 +0,0 @@
|
||||
// Auto-generated via `yarn polkadot-types-from-defs`, do not edit
|
||||
/* eslint-disable @typescript-eslint/no-empty-interface */
|
||||
|
||||
import { ITuple } from '@polkadot/types/types';
|
||||
import { Enum, Option, Struct, U8aFixed, Vec } from '@polkadot/types/codec';
|
||||
import { bool, u128, u64 } from '@polkadot/types/primitive';
|
||||
import { AccountId } from '@polkadot/types/interfaces/runtime';
|
||||
|
||||
/** @name Commitments */
|
||||
export interface Commitments extends Vec<ITuple<[AccountId, VoteOutcome]>> {}
|
||||
|
||||
/** @name Reveals */
|
||||
export interface Reveals extends Vec<ITuple<[AccountId, Vec<VoteOutcome>]>> {}
|
||||
|
||||
/** @name Tally */
|
||||
export interface Tally extends Option<Vec<ITuple<[VoteOutcome, u128]>>> {}
|
||||
|
||||
/** @name TallyType */
|
||||
export interface TallyType extends Enum {
|
||||
readonly isOnePerson: boolean;
|
||||
readonly isOneCoin: boolean;
|
||||
}
|
||||
|
||||
/** @name VoteData */
|
||||
export interface VoteData extends Struct {
|
||||
readonly initiator: AccountId;
|
||||
readonly stage: VoteStage;
|
||||
readonly vote_type: VoteType;
|
||||
readonly tally_type: TallyType;
|
||||
readonly is_commit_reveal: bool;
|
||||
}
|
||||
|
||||
/** @name VoteOutcome */
|
||||
export interface VoteOutcome extends U8aFixed {}
|
||||
|
||||
/** @name VoteRecord */
|
||||
export interface VoteRecord extends Struct {
|
||||
readonly id: u64;
|
||||
readonly commitments: Commitments;
|
||||
readonly reveals: Reveals;
|
||||
readonly data: VoteData;
|
||||
readonly outcomes: Vec<VoteOutcome>;
|
||||
}
|
||||
|
||||
/** @name VoteStage */
|
||||
export interface VoteStage extends Enum {
|
||||
readonly isPreVoting: boolean;
|
||||
readonly isCommit: boolean;
|
||||
readonly isVoting: boolean;
|
||||
readonly isCompleted: boolean;
|
||||
}
|
||||
|
||||
/** @name VoteType */
|
||||
export interface VoteType extends Enum {
|
||||
readonly isBinary: boolean;
|
||||
readonly isMultiOption: boolean;
|
||||
readonly isRankedChoice: boolean;
|
||||
}
|
||||
@@ -1,34 +0,0 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
// this is specific with augmented overrides
|
||||
"paths": {
|
||||
// this is the package name we use (in the interface imports, --package for generators)
|
||||
"sample-polkadotjs-typegen/*": ["src/*"],
|
||||
// here we replace the @polkadot/api augmentation with our own, generated from chain
|
||||
"@polkadot/api/augment": ["src/interfaces/augment-api.ts"],
|
||||
// replace the augmented types with our own, as generated from definitions
|
||||
"@polkadot/types/augment": ["src/interfaces/augment-types.ts"]
|
||||
},
|
||||
// some other options, whatever you want for your environment
|
||||
"target": "esnext",
|
||||
"module": "esnext",
|
||||
"jsx": "preserve",
|
||||
"declaration": true,
|
||||
"strict": true,
|
||||
"noImplicitAny": true,
|
||||
"noUnusedLocals": true,
|
||||
"noImplicitReturns": true,
|
||||
"moduleResolution": "node",
|
||||
"allowSyntheticDefaultImports": true,
|
||||
"esModuleInterop": true,
|
||||
"baseUrl": ".",
|
||||
"skipLibCheck": true,
|
||||
"typeRoots": [
|
||||
"./node_modules/@types"
|
||||
]
|
||||
},
|
||||
"exclude": [
|
||||
"build/**/*",
|
||||
"node_modules"
|
||||
]
|
||||
}
|
||||
@@ -18,7 +18,9 @@ From each folder, run `yarn` to install the required dependencies and then run `
|
||||
|
||||
Some of the examples use the following accounts:
|
||||
|
||||
- Alice: `5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY`
|
||||
- Bob: `5FHneW46xGXgs5mUiveU4sbTyGBzmstUspZC92UhjJM694ty`
|
||||
- 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` (via `keyring.addUri(...)`, dev seed implied) and the seed of Bob is... well you guess...
|
||||
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.
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
# Simple Connect
|
||||
|
||||
The following example shows how to instantiate a Polkadot API object and use it to connect to a node using ApiRx.
|
||||
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
|
||||
|
||||
@@ -1,17 +1,14 @@
|
||||
/* eslint-disable @typescript-eslint/require-await */
|
||||
/* eslint-disable @typescript-eslint/unbound-method */
|
||||
/* eslint-disable @typescript-eslint/no-var-requires */
|
||||
// Required imports
|
||||
const { zip } = require('rxjs');
|
||||
const { ApiRx } = require('@polkadot/api');
|
||||
const { WsProvider } = require('@polkadot/rpc-provider');
|
||||
const { ApiRx } = require('@plugnet/api');
|
||||
const { WsProvider } = require('@plugnet/rpc-provider');
|
||||
|
||||
async function main () {
|
||||
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();
|
||||
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
|
||||
@@ -19,7 +16,9 @@ async function main () {
|
||||
api.rpc.system.chain(),
|
||||
api.rpc.system.name(),
|
||||
api.rpc.system.version()
|
||||
).subscribe(([chain, nodeName, nodeVersion]) => {
|
||||
)
|
||||
// Then we subscribe to the result
|
||||
.subscribe(([chain, nodeName, nodeVersion]) => {
|
||||
console.log(`You are connected to chain ${chain} using ${nodeName} v${nodeVersion}`);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -11,7 +11,7 @@
|
||||
},
|
||||
|
||||
"dependencies": {
|
||||
"@polkadot/api": "*"
|
||||
"@plugnet/api": "^0.76.102"
|
||||
},
|
||||
"devDependencies": {
|
||||
"rimraf": "^2.6.2"
|
||||
|
||||
@@ -1,8 +1,5 @@
|
||||
/* eslint-disable @typescript-eslint/require-await */
|
||||
/* eslint-disable @typescript-eslint/unbound-method */
|
||||
/* eslint-disable @typescript-eslint/no-var-requires */
|
||||
// Import the API
|
||||
const { ApiRx } = require('@polkadot/api');
|
||||
const { ApiRx } = require('@plugnet/api');
|
||||
const { switchMap } = require('rxjs/operators');
|
||||
|
||||
async function main () {
|
||||
@@ -12,10 +9,10 @@ async function main () {
|
||||
new ApiRx().isReady
|
||||
.pipe(
|
||||
switchMap((api) =>
|
||||
api.rpc.chain.subscribeNewHeads()
|
||||
api.rpc.chain.subscribeNewHead()
|
||||
))
|
||||
.subscribe((header) => {
|
||||
console.log(`Chain is at block: #${header.number}`);
|
||||
console.log(`Chain is at block: #${header.blockNumber}`);
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -10,7 +10,7 @@
|
||||
"start": "node index.js"
|
||||
},
|
||||
"dependencies": {
|
||||
"@polkadot/api": "*"
|
||||
"@plugnet/api": "^0.76.102"
|
||||
},
|
||||
"devDependencies": {
|
||||
"rimraf": "^2.6.2"
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
# Listen to balance changes
|
||||
|
||||
This example shows how to instantiate a Polkadot API object and use it to connect to a node and retrieve balance updates.
|
||||
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_listen_to_balance_change/index.js
|
||||
<<< @/docs/examples/rx/03_listent_to_balance_change/index.js
|
||||
|
||||
@@ -1,8 +1,5 @@
|
||||
/* eslint-disable @typescript-eslint/require-await */
|
||||
/* eslint-disable @typescript-eslint/unbound-method */
|
||||
/* eslint-disable @typescript-eslint/no-var-requires */
|
||||
// Import the API and operators from RxJs
|
||||
const { ApiRx } = require('@polkadot/api');
|
||||
const { ApiRx } = require('@plugnet/api');
|
||||
const { pairwise, startWith } = require('rxjs/operators');
|
||||
|
||||
// Known account we want to use (available on dev chain, with funds)
|
||||
@@ -14,7 +11,7 @@ async function main () {
|
||||
|
||||
// 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.system.account(Alice)
|
||||
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
|
||||
@@ -25,13 +22,12 @@ async function main () {
|
||||
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].data.free}`);
|
||||
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].data.free.sub(balance[0].date.free);
|
||||
|
||||
const change = balance[1].sub(balance[0]);
|
||||
// Only display value changes
|
||||
if (!change.isZero()) {
|
||||
console.log(`New balance change of: ${change}`);
|
||||
|
||||
@@ -10,7 +10,7 @@
|
||||
"start": "node index.js"
|
||||
},
|
||||
"dependencies": {
|
||||
"@polkadot/api": "*"
|
||||
"@plugnet/api": "^0.76.102"
|
||||
},
|
||||
"devDependencies": {
|
||||
"rimraf": "^2.6.2"
|
||||
|
||||
@@ -1,20 +1,17 @@
|
||||
/* eslint-disable @typescript-eslint/require-await */
|
||||
/* eslint-disable @typescript-eslint/unbound-method */
|
||||
/* eslint-disable @typescript-eslint/no-var-requires */
|
||||
// Import the API
|
||||
const { ApiRx } = require('@polkadot/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.
|
||||
// Subscribe to chain updates and log the current block number on update.
|
||||
const subscription = new ApiRx().isReady
|
||||
.pipe(
|
||||
switchMap((api) =>
|
||||
api.rpc.chain.subscribeNewHeads()
|
||||
api.rpc.chain.subscribeNewHead()
|
||||
))
|
||||
.subscribe((header) => {
|
||||
console.log(`Chain is at block: #${header.number}`);
|
||||
console.log(`Chain is at block: #${header.blockNumber}`);
|
||||
});
|
||||
|
||||
// In this example we're calling the Overvables unsubscribe() //
|
||||
|
||||
@@ -10,7 +10,7 @@
|
||||
"start": "node index.js"
|
||||
},
|
||||
"dependencies": {
|
||||
"@polkadot/api": "*"
|
||||
"@plugnet/api": "^0.76.102"
|
||||
},
|
||||
"devDependencies": {
|
||||
"rimraf": "^2.6.2"
|
||||
|
||||
@@ -1,8 +1,6 @@
|
||||
/* eslint-disable @typescript-eslint/require-await */
|
||||
/* eslint-disable @typescript-eslint/unbound-method */
|
||||
/* eslint-disable @typescript-eslint/no-var-requires */
|
||||
// Import the API
|
||||
const { ApiRx } = require('@polkadot/api');
|
||||
const { ApiRx } = require('@plugnet/api');
|
||||
// Import dependencies from RxJs
|
||||
const { combineLatest, of } = require('rxjs');
|
||||
const { first, switchMap } = require('rxjs/operators');
|
||||
|
||||
@@ -11,7 +9,7 @@ const Alice = '5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY';
|
||||
|
||||
function main () {
|
||||
// Create our API with a default connection to the local node
|
||||
new ApiRx().isReady
|
||||
new ApiRx(provider).isReady
|
||||
.pipe(
|
||||
// Here we ake our basic chain state/storage queries
|
||||
switchMap((api) => combineLatest(
|
||||
@@ -22,13 +20,13 @@ function main () {
|
||||
// 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.system.account(authorityId).pipe(first())))
|
||||
? 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.account(Alice).pipe(first()),
|
||||
api.query.system.accountNonce(Alice).pipe(first()),
|
||||
api.query.timestamp.blockPeriod().pipe(first()),
|
||||
of(validators),
|
||||
balances
|
||||
@@ -36,19 +34,18 @@ function main () {
|
||||
})
|
||||
)
|
||||
// Then we're subscribing to the emitted results
|
||||
.subscribe(([{ nonce }, blockPeriod, validators, validatorBalances]) => {
|
||||
console.log(`accountNonce(${Alice}) ${nonce}`);
|
||||
.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].data.free.toString(),
|
||||
nonce: validatorBalances[index].data.toString()
|
||||
balance: validatorBalances[index].toString()
|
||||
})));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
main().catch(console.error).finally(() => process.exit());
|
||||
main().catch(console.error).finally(_ => process.exit());
|
||||
|
||||
@@ -10,7 +10,7 @@
|
||||
"start": "node index.js"
|
||||
},
|
||||
"dependencies": {
|
||||
"@polkadot/api": "*"
|
||||
"@plugnet/api": "^0.76.102"
|
||||
},
|
||||
"devDependencies": {
|
||||
"rimraf": "^2.6.2"
|
||||
|
||||
@@ -1,9 +1,6 @@
|
||||
/* eslint-disable @typescript-eslint/require-await */
|
||||
/* eslint-disable @typescript-eslint/unbound-method */
|
||||
/* eslint-disable @typescript-eslint/no-var-requires */
|
||||
// Import the API, Keyring and some utility functions
|
||||
const { ApiRx } = require('@polkadot/api');
|
||||
const { Keyring } = require('@polkadot/keyring');
|
||||
const { ApiRx } = require('@plugnet/api');
|
||||
const { Keyring } = require('@plugnet/keyring');
|
||||
|
||||
const BOB = '5FHneW46xGXgs5mUiveU4sbTyGBzmstUspZC92UhjJM694ty';
|
||||
|
||||
@@ -12,31 +9,25 @@ async function main () {
|
||||
const api = await ApiRx.create().toPromise();
|
||||
|
||||
// Create an instance of the keyring
|
||||
const keyring = new Keyring({ type: 'sr25519' });
|
||||
const keyring = new Keyring({ type: 's25519' });
|
||||
|
||||
// Add Alice to our keyring (with the known seed for the account)
|
||||
const alice = keyring.addFromUri('//Alice');
|
||||
const alice = keyring.addFomUri('//Alice');
|
||||
|
||||
// Create a extrinsic, transferring 12345 units to Bob.
|
||||
const subscription = api.tx.balances
|
||||
// Create a extrinsic, transferring 12345 units to Bob.
|
||||
api.tx.balances
|
||||
// create transfer
|
||||
.transfer(BOB, 12345)
|
||||
.transfer(BOB, randomAmount)
|
||||
// Sign and send the transcation
|
||||
.signAndSend(alice)
|
||||
// Subscribe to the status updates of the transfer
|
||||
.subscribe(({ status }) => {
|
||||
if (status.isInBlock) {
|
||||
console.log(`Successful transfer of 12345 from Alice to Bob at block ${status.asInBlock.toHex()}`);
|
||||
} else if (status.isFinalized) {
|
||||
console.log('Finalized block hash', status.asFinalized.toHex());
|
||||
|
||||
subscription.unsubscribe();
|
||||
|
||||
process.exit(0);
|
||||
if (status.isFinalized) {
|
||||
console.log(`Successful transfer of 12345 from Alice to Bob with hash ${status.asFinalized.toHex()}`);
|
||||
} else {
|
||||
console.log(`Status of transfer: ${status.type}`);
|
||||
console.log(`Staus of transfer: ${status.type}`);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
main().catch(console.error);
|
||||
main().catch(console.error).finally(_ => process.exit());
|
||||
|
||||
@@ -10,7 +10,7 @@
|
||||
"start": "node index.js"
|
||||
},
|
||||
"dependencies": {
|
||||
"@polkadot/api": "*"
|
||||
"@plugnet/api": "^0.76.102"
|
||||
},
|
||||
"devDependencies": {
|
||||
"rimraf": "^2.6.2"
|
||||
|
||||
@@ -1,9 +1,6 @@
|
||||
/* eslint-disable @typescript-eslint/require-await */
|
||||
/* eslint-disable @typescript-eslint/unbound-method */
|
||||
/* eslint-disable @typescript-eslint/no-var-requires */
|
||||
// Import the API and selected RxJs operators
|
||||
const { switchMap } = require('rxjs/operators');
|
||||
const { ApiRx } = require('@polkadot/api');
|
||||
const { ApiRx } = require('@plugnet/api');
|
||||
|
||||
async function main () {
|
||||
// Create our API with a default connection to the local node
|
||||
@@ -12,9 +9,8 @@ async function main () {
|
||||
switchMap((api) =>
|
||||
// subscribe to system events via storage
|
||||
api.query.system.events()
|
||||
)
|
||||
)
|
||||
// Then we're subscribing to the emitted results
|
||||
))
|
||||
// Then we're subscribing to the emitted results
|
||||
.subscribe((events) => {
|
||||
console.log(`\nReceived ${events.length} events:`);
|
||||
// loop through the Vec<EventRecord>
|
||||
@@ -33,7 +29,7 @@ async function main () {
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
main().catch((error) => {
|
||||
console.error(error);
|
||||
|
||||
@@ -10,7 +10,7 @@
|
||||
"start": "node index.js"
|
||||
},
|
||||
"dependencies": {
|
||||
"@polkadot/api": "*"
|
||||
"@plugnet/api": "^0.76.102"
|
||||
},
|
||||
"devDependencies": {
|
||||
"rimraf": "^2.6.2"
|
||||
|
||||
@@ -1,16 +1,13 @@
|
||||
/* eslint-disable @typescript-eslint/require-await */
|
||||
/* eslint-disable @typescript-eslint/unbound-method */
|
||||
/* eslint-disable @typescript-eslint/no-var-requires */
|
||||
// Import the API and some utility functions
|
||||
const { ApiRx } = require('@polkadot/api');
|
||||
const { ApiRx } = require('@plugnet/api');
|
||||
|
||||
// Import the test keyring (already has dev keys for Alice, Bob, Charlie, Eve & Ferdie)
|
||||
const testKeyring = require('@polkadot/keyring/testing');
|
||||
// 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('@polkadot/util-crypto');
|
||||
// utility function for random values
|
||||
const { randomAsU8a } = require('@plugnet/util-crypto');
|
||||
|
||||
// Some constants we are using in this sample
|
||||
// some constants we are using in this sample
|
||||
const ALICE = '5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY';
|
||||
const AMOUNT = 10000;
|
||||
|
||||
@@ -18,21 +15,21 @@ 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
|
||||
// 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
|
||||
// find the actual keypair in the keyring
|
||||
const alicePair = keyring.getPair(ALICE);
|
||||
|
||||
// Create a new random recipient
|
||||
const recipient = keyring.addFromSeed(randomAsU8a(32)).address;
|
||||
// create a new random recipient
|
||||
const recipient = keyring.addFromSeed(randomAsU8a(32)).address();
|
||||
|
||||
console.log('Sending', AMOUNT, 'from', alicePair.address, 'to', recipient);
|
||||
console.log('Sending', AMOUNT, 'from', alicePair.address(), 'to', recipient);
|
||||
|
||||
// Get the nonce for the admin key
|
||||
// Create a extrinsic, transferring 12345 units to Bob.
|
||||
// get the nonce for the admin key
|
||||
// Create a extrinsic, transferring 12345 units to Bob.
|
||||
api.tx.balances
|
||||
// Do the transfer
|
||||
.transfer(recipient, AMOUNT)
|
||||
@@ -44,17 +41,13 @@ async function main () {
|
||||
console.log('Transfer status:', status.type);
|
||||
|
||||
// Log system events once the transfer is finalised
|
||||
if (status.isInBlock) {
|
||||
console.log('Included at block hash', status.asInBlock.toHex());
|
||||
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());
|
||||
});
|
||||
} else if (status.isFinalized) {
|
||||
console.log('Finalized block hash', status.asFinalized.toHex());
|
||||
|
||||
process.exit(0);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@@ -10,7 +10,7 @@
|
||||
"start": "node index.js"
|
||||
},
|
||||
"dependencies": {
|
||||
"@polkadot/api": "*"
|
||||
"@plugnet/api": "^0.76.102"
|
||||
},
|
||||
"devDependencies": {
|
||||
"rimraf": "^2.6.2"
|
||||
|
||||
@@ -1,10 +1,7 @@
|
||||
/* eslint-disable @typescript-eslint/require-await */
|
||||
/* eslint-disable @typescript-eslint/unbound-method */
|
||||
/* eslint-disable @typescript-eslint/no-var-requires */
|
||||
// Import the API & Provider and some utility functions
|
||||
const { ApiRx, WsProvider } = require('@polkadot/api');
|
||||
// Import the test keyring (already has dev keys for Alice, Bob, Charlie, Eve & Ferdie)
|
||||
const testKeyring = require('@polkadot/keyring/testing');
|
||||
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 () {
|
||||
@@ -12,44 +9,43 @@ async function main () {
|
||||
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();
|
||||
const api = await ApiRx.create(provider).toPromise();
|
||||
|
||||
// Retrieve the upgrade key from the chain state
|
||||
// TODO It seems like this promise doesn't resolve
|
||||
// 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
|
||||
// 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
|
||||
// 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
|
||||
// Perform the actual chain upgrade via the sudo module
|
||||
// preform the actual chain upgrade via the sudo module
|
||||
.sudo(proposal)
|
||||
// Sign and send the proposal
|
||||
// sign and send the proposal
|
||||
.signAndSend(adminPair)
|
||||
// Subscribe to overall result
|
||||
// subscribe to overall result
|
||||
.subscribe(({ events = [], status }) => {
|
||||
// Log transfer events
|
||||
console.log('Proposal status:', status.type);
|
||||
|
||||
if (status.isInBlock) {
|
||||
if (status.isFinalized) {
|
||||
console.error('You have just upgraded your chain');
|
||||
|
||||
console.log('Included at block hash', status.asInBlock.toHex());
|
||||
console.log('Completed at block hash', status.asFinalized.toHex());
|
||||
console.log('Events:');
|
||||
|
||||
// Log system events once the chain update is finalised
|
||||
console.log(JSON.stringify(events.toHuman(), null, 2));
|
||||
} else if (status.isFinalized) {
|
||||
console.log('Finalized block hash', status.asFinalized.toHex());
|
||||
events.forEach(({ phase, event: { data, method, section } }) => {
|
||||
console.log('\t', phase.toString(), `: ${section}.${method}`, data.toString());
|
||||
});
|
||||
|
||||
process.exit(0);
|
||||
}
|
||||
|
||||
@@ -10,7 +10,7 @@
|
||||
"start": "node index.js"
|
||||
},
|
||||
"dependencies": {
|
||||
"@polkadot/api": "*"
|
||||
"@plugnet/api": "^0.76.102"
|
||||
},
|
||||
"devDependencies": {
|
||||
"rimraf": "^2.6.2"
|
||||
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 7.3 KiB |
@@ -1,157 +0,0 @@
|
||||
**NOTE** Removed - in metadata v11 we get the extensions from the chain, we need to be able to specify these. These docs are now outdated.
|
||||
|
||||
# Extending extrinsics
|
||||
|
||||
On some chains, the need may arise to customize the extrinsic format. In this section we will explain what extrinsics and their payloads contain, explain how signed extensions work and provide a walk through of an advanced use-case where extrinsics are customized for a specific Substrate chain.
|
||||
|
||||
## Extensions
|
||||
|
||||
In Substrate (which forms the base of Polkadot and a number of custom chains), an extrinsic has a specific version, flag to indicating if it has been signed, the address, signature, extra data as well as the actual method with params. In addition, the signature is generated over the call and may include values that are not encoded into the final extrinsic.
|
||||
|
||||
For instance, with version 3 extrinsics, the signature payload contains the runtime spec version as well as the `genesisHash` and `blockHash` (the latter being equivalent to the `genesisHash` in case of immortal transactions), however while these 3 fields are signed together with the method data, they do not actually appear in the extrinsic itself. Rather the chain executing the transaction will retrieve this information, add it to the method data and compare the signatures thereof.
|
||||
|
||||
So in both the cases of the `genesisHash` and `specVersion`, if these do not match the signer version, the transaction won't be accepted - however the extrinsic doesn't explicitly carry this information in the data being transmitted, rather only implicitly as part of the signature. And it always forms part of the validation.
|
||||
|
||||
## Default extrinsics
|
||||
|
||||
With the above in-mind, the extrinsic format is explicitly defined as having the following structure in Substrate -
|
||||
|
||||
```rust
|
||||
pub struct UncheckedExtrinsic<Address, Call, Signature, Extra>
|
||||
where Extra: SignedExtension
|
||||
{
|
||||
pub signature: Option<(Address, Signature, Extra)>,
|
||||
pub function: Call,
|
||||
}
|
||||
```
|
||||
|
||||
The `Option` is here encoded such that is conveys both the extrinsic version `0x03` for Substrate 2.x chains (`0x01` for Substrate 1.x chains) as well as a high-bit that indicates if the transaction is signed or unsigned. (For unsigned the `signature` details therefore does not appear). The `SignedExtension` part defined both the data in the actual extrinsic as well as data, i.e. `AdditionalSigned`, that appears in the payload for the signature, but is not explicitly contained in the extrinsic.
|
||||
|
||||
The default `SignedExtension` for Substrate 2.x with extrinsic version 3 is defined as follow -
|
||||
|
||||
```rust
|
||||
pub type SignedExtra = (
|
||||
system::CheckVersion<Runtime>,
|
||||
system::CheckGenesis<Runtime>,
|
||||
system::CheckEra<Runtime>,
|
||||
system::CheckNonce<Runtime>,
|
||||
system::CheckWeight<Runtime>,
|
||||
balances::TakeFees<Runtime>,
|
||||
contracts::CheckBlockGasLimit<Runtime>,
|
||||
);
|
||||
```
|
||||
|
||||
Some of these are only checks, requiring no additional data in the payload or extrinsic itself, i.e. the contracts checks do exactly that. It only applies checks and invalidates when those checks are invalid. This is a powerful concept, for instance on the [initial Kusama chain this was used to limit the types of calls allowed](https://github.com/paritytech/polkadot/blob/f52c714ec3411eea58647d0f5176f4eb81660188/runtime/src/lib.rs#L117-L139).
|
||||
|
||||
## Extension deep-dive
|
||||
|
||||
For each of the default extensions, we will take a look through to understand the implications of the specific extension and how it relates to both the data contained in the extrinsic as well as the signature payload.
|
||||
|
||||
- `system::CheckVersion` - This checks that the spec version matches between the extrinsic and the chain. It takes no parameters which means that these is no explicit data in the extrinsic format for this field, however it has `type AdditionalSigned = u32` which means that a `u32` containing the runtime spec version is part of the signature payload.
|
||||
|
||||
- `system::CheckGenesis` - This checks that the `genesisHash` matches between extrinsic and chain. Like the previous check, no additional data is added to the extrinsic, however with `type AdditionalSigned = T::Hash`, the `genesisHash` is part of the signature payload.
|
||||
|
||||
- `system::CheckEra` - This checks the era (mortal or immortal) for the transaction being sent. It checks both the `era: Era` as part of the actual extrinsic and the `blockHash` via the `type AdditionalSigned = T::Hash`. This means that the extrinsic era is both in the data being signed and the extrinsic itself, while the `blockHash` the era applies to is only available in the signature payload.
|
||||
|
||||
- `system::CheckNonce` - This checks the nonce for the sending account. Unlike the preceding checks, it has no payload-specific data, however the `nonce: Compact<T::Index>` (`Index` is default `u32`) is applicable to both the extrinsic and, therefore, the actual signature payload as well.
|
||||
|
||||
- `system::CheckWeight` - This checks the weight and length of the block and ensure that it does not exceed the limits. It does not have any specific data attached to either the extrinsic nor payload, but rather just does calculations based on the weights and type of transaction received.
|
||||
|
||||
- `balances::TakeFees` - Consumes fees proportional to the length and weight of the transaction. It operates on the `fee: Compact<T::Balance>`, which means this value is included in both the extrinsic and subsequent payload being signed.
|
||||
|
||||
- `contracts::CheckBlockGasLimit` - As explained briefly above, this extension does not add data to the extrinsic, or the signature payload, however it ensures that the transaction does not exceeds the block gas limit.
|
||||
|
||||
## Extrinsic and signature payloads
|
||||
|
||||
With the above extension, the following formats for the extrinsic and payloads are the outcome of the application of the signed extension. For the extrinsic the following data is [always encoded for v3 extrinsics](https://github.com/polkadot-js/api/blob/8b0ef159c05bcb5d9b664546d0e7289e79b5c9d5/packages/types/src/primitive/Extrinsic/v3/Extrinsic.ts#L27) -
|
||||
|
||||
```js
|
||||
class ExtrinsicV3 extends Struct {
|
||||
constructor (value) {
|
||||
super({
|
||||
signer: 'Address',
|
||||
signature: 'Signature',
|
||||
era: 'ExtrinsicEra', // extra via system::CheckEra
|
||||
nonce: 'Compact<Index>', // extra via system::CheckNonce
|
||||
tip: 'Compact<Balance>', // extra via balances::TakeFees
|
||||
method: 'Call'
|
||||
}, value);
|
||||
}
|
||||
...
|
||||
```
|
||||
|
||||
The signature payload will contain the same information as the extrinsic, with the following [additional information](https://github.com/polkadot-js/api/blob/8b0ef159c05bcb5d9b664546d0e7289e79b5c9d5/packages/types/src/primitive/Extrinsic/v3/ExtrinsicPayload.ts#L33) as expected by the `AdditionalSigned` portions of the extensions -
|
||||
|
||||
```js
|
||||
class ExtrinsicPayloadV3 extends Struct {
|
||||
constructor (value) {
|
||||
super({
|
||||
method: 'Bytes',
|
||||
era: 'ExtrinsicEra', // extra via system::CheckEra
|
||||
nonce: 'Compact<Index>', // extra via system::CheckNonce
|
||||
tip: 'Compact<Balance>', // extra via balances::TakeFees
|
||||
specVersion: 'u32', // additional via system::CheckVersion
|
||||
genesisHash: 'Hash', // additional via system::CheckGenesis
|
||||
blockHash: 'Hash' // additional via system::CheckEra
|
||||
}, value);
|
||||
}
|
||||
...
|
||||
```
|
||||
|
||||
As per the above structures, it means that both the extrinsic sent on-chain as well as the data being signed to generate the signature is tied by the hip based on the logic the chain expects via `SignedExtension`. The API is only aware of the version of the extrinsic being used on-chain (it determines this on connection) and therefore only knows about the specific logic that has been coded for the extrinsic version.
|
||||
|
||||
## Extending existing or implementing new
|
||||
|
||||
When the API encodes or decodes an extrinsic, it uses the first `Option` byte to determine the version. Once it has this value, it will create a specific extrinsic via `createType('ExtrinsicV3', value)`. This means that at any point, you can supply your own version of either the `Extrinsic` or `ExtrinsicPayload` and you can do so via 2 avenues -
|
||||
|
||||
- If you are extending/replacing the existing version, you can inject your own types for both `ExtrinsicV3` and `ExtrinsicV3Payload` (assuming you are replacing v3)
|
||||
|
||||
- If you are adding a new version, you can add a handler for both `ExtrinsicUnknown` and `ExtrinsicPayloadUnknown`. These will be constructed when the version the API is aware of does not match with the on-chain version.
|
||||
|
||||
While we will not provide a full example of all the code here, the above links will show the existing implementations. However, assuming we have a chain where neither the nonce or tip is applicable (or we just don't care) and we are ignoring the check to the runtime versioning.
|
||||
|
||||
Additionally assuming that we have made the required `SignedExtension` updates by removing `system::CheckVersion`, `system::CheckNonce` and `balances::TakeFees`, we can do the following -
|
||||
|
||||
```js
|
||||
...
|
||||
class OwnExtrinsic extends Struct {
|
||||
constructor (value) {
|
||||
super({
|
||||
signer: 'Address',
|
||||
signature: 'Signature',
|
||||
era: 'ExtrinsicEra', // extra via system::CheckEra
|
||||
method: 'Call'
|
||||
}, value);
|
||||
}
|
||||
...
|
||||
}
|
||||
|
||||
class OwnExtrinsicPayload extends Struct {
|
||||
constructor (value) {
|
||||
super({
|
||||
method: 'Bytes',
|
||||
era: 'ExtrinsicEra', // extra via system::CheckEra
|
||||
genesisHash: 'Hash', // additional via system::CheckGenesis
|
||||
blockHash: 'Hash' // additional via system::CheckEra
|
||||
}, value);
|
||||
}
|
||||
...
|
||||
// signing logic needs to be included, as per existing
|
||||
}
|
||||
...
|
||||
|
||||
// inject our types at API construction
|
||||
const api = ApiPromise.create({
|
||||
types: {
|
||||
'ExtrinsicV3': OwnExtrinsic,
|
||||
'ExtrinsicV3Payload': OwnExtrinsicPayload,
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
The above example is certainly an advanced example, but it shows that all data types in the API can be adjusted and these adjustment can be provided to the API. In all cases, if you made updates to the formats and types of the actual runtime, you need to ensure that the API is aware of these changes.
|
||||
|
||||
In the above example, should these updates only be made on the node side, without the required API adjustments, the API will generate invalid transactions for the node since it is unaware of the changes and adjusted formats. Making the adjustments on only one side will mean that the signature verification can fail and that the format will not be decodable via the node.
|
||||
|
||||
(These extensions are not exposed via metadata at all, and would be quite difficult to do as well - since each of these have specific logic as well as data types assigned.)
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user