Compare commits

...
99 Commits
Author SHA1 Message Date
Github Actions 033cba718d [CI Skip] release/stable 2.7.1
skip-checks: true
2020-11-16 09:39:20 +00:00
Jaco Greeff c4470eba14 2.7 (#2854) 2020-11-16 10:30:33 +01:00
Github Actions fb2bc42fe0 [CI Skip] release/beta 2.6.2-16
skip-checks: true
2020-11-16 06:42:42 +00:00
Jaco Greeff d3b13bceb0 Allow salt in contract deploy (#2849)
* Allow salt in contract deploy

* Mark deprecated

* Shorten

* Cleanups

* Additional cleanups

* Cleanups

* Explicit Bytes to decodeEvent

* Adjust method creation

* Allow null salt
2020-11-16 07:35:02 +01:00
Github Actions 0fc5e1d387 [CI Skip] release/beta 2.6.2-15
skip-checks: true
2020-11-16 05:48:24 +00:00
Jaco Greeff ce6c25e4e2 Tests & adjustments for encodeTypes (#2853)
* Tests & adjustments for encodeTypes

* explicit wrap types

* Remove params

* cleanups
2020-11-16 06:40:49 +01:00
Github Actions 165381d79a [CI Skip] release/beta 2.6.2-14
skip-checks: true
2020-11-15 16:15:39 +00:00
Jaco Greeff 2da3f16bda Bumps (#2852) 2020-11-15 17:07:30 +01:00
Github Actions 02c349093b [CI Skip] release/beta 2.6.2-13
skip-checks: true
2020-11-14 15:50:17 +00:00
Jaco Greeff 82873c44f8 Pass raw data for contract event decoding (#2851) 2020-11-14 16:42:47 +01:00
Github Actions 7afc696da3 [CI Skip] release/beta 2.6.2-12
skip-checks: true
2020-11-13 09:53:49 +00:00
Jaco Greeff 4e0d430504 Adjust generated @polkadot/types imports (#2848)
* Adjust generated @polkadot/types imports

* import type

* Only export types from codec/types
2020-11-13 10:46:16 +01:00
Github Actions 0b091fa935 [CI Skip] release/beta 2.6.2-11
skip-checks: true
2020-11-12 18:39:33 +00:00
Jaco Greeff 4db33b6caf Configurable extrinsic signature (#2845)
* Configurable extrinsic signature

* With Address override as well
2020-11-12 19:31:55 +01:00
Github Actions 4dd0372702 [CI Skip] release/beta 2.6.2-10
skip-checks: true
2020-11-12 15:41:37 +00:00
Jaco Greeff 98b01a462d Mark Polkadot 26 upgrade (#2843) 2020-11-12 16:33:26 +01:00
Github Actions 03570f2f11 [CI Skip] release/beta 2.6.2-9
skip-checks: true
2020-11-12 13:52:19 +00:00
Jaco Greeff f810e65ea2 Additional enum tests (#2842)
* Additional enum tests

* Adjust compare files

* Remove debug log
2020-11-12 14:45:32 +01:00
Github Actions c04b63e4af [CI Skip] release/beta 2.6.2-8
skip-checks: true
2020-11-12 11:31:15 +00:00
Jaco Greeff 98a2ef9d72 Support ABI files with wasm (.contract output) (#2841)
* Support ABI files with wasm (.contract output)

* AbiBase exports

* Additional default exports

* Remove any

* Fix build
2020-11-12 12:23:28 +01:00
Github Actions 999e69b031 [CI Skip] release/beta 2.6.2-7
skip-checks: true
2020-11-11 12:05:51 +00:00
Jaco Greeff 79e99fd6e3 Dev bump (#2839)
* Adjust internal generic imports

* Update dev

* Adjust primitive imports

* Class exports has uppercase variant

* common

* to* chenges

* Adjust EventData for registry creation
2020-11-11 12:58:35 +01:00
Jaco Greeff d91460b79d New contracts Schedule types (#2792) 2020-11-11 11:32:04 +01:00
Github Actions b1f7b72043 [CI Skip] release/beta 2.6.2-6
skip-checks: true
2020-11-11 08:47:40 +00:00
Jaco Greeff 5a1fd4a1bb Adjust internal generic imports (#2838) 2020-11-11 09:40:35 +01:00
Github Actions 3ec469bbaf [CI Skip] release/beta 2.6.2-5
skip-checks: true
2020-11-10 16:52:17 +00:00
Jaco Greeff 091ee7624a Bumps 2020-11-10 17:45:08 +01:00
Github Actions 1918547fdc [CI Skip] release/beta 2.6.2-4
skip-checks: true
2020-11-10 13:06:53 +00:00
Jaco Greeff a8a956c85d Re-enable esnext (with mjs) (#2836)
* Re-enable esnext (with mjs)

* Updates

* Adjust
2020-11-10 13:58:11 +01:00
Github Actions 143febf807 [CI Skip] release/beta 2.6.2-3
skip-checks: true
2020-11-10 10:22:15 +00:00
Jaco Greeff af9437f80a Adjust create imports (#2834)
* Adjust create imports

* Restore create root exports

* Adjust unsafe creation
2020-11-10 11:14:38 +01:00
Github Actions 5cf585c8dd [CI Skip] release/beta 2.6.2-2
skip-checks: true
2020-11-09 22:24:21 +00:00
Jaco Greeff e6dbbfae34 Adjust interfaces for cleaner esnext usage (#2833)
* Adjust interfaces for cleaner esnext usage

* Swap out esnext
2020-11-09 23:17:52 +01:00
Github Actions 8993844739 [CI Skip] release/beta 2.6.2-1
skip-checks: true
2020-11-09 18:49:06 +00:00
Jaco Greeff 21d0622f84 Bump common (#2832)
* Bump common

* Update for new common non-default exports

* Don't export createSubmittable

* Adjust exports

* default export adjustments

* Some additional non-default exports
2020-11-09 19:41:29 +01:00
Github Actions e787c08bd9 [CI Skip] release/beta 2.6.2-0
skip-checks: true
2020-11-09 16:48:15 +00:00
Jaco Greeff ce6d9424e6 Build esnext modules (#2831) 2020-11-09 17:40:52 +01:00
Github Actions 930252e3bc [CI Skip] release/stable 2.6.1
skip-checks: true
2020-11-09 10:48:02 +00:00
Jaco Greeff 613aebd26d 2.6 (#2829) 2020-11-09 11:40:26 +01:00
Github Actions 79e0d807ab [CI Skip] release/beta 2.5.2-6
skip-checks: true
2020-11-09 10:23:02 +00:00
Jaco Greeff 0cbd702c93 Remove peerDeps (explicit) (#2828) 2020-11-09 11:14:22 +01:00
Github Actions e7ee68d138 [CI Skip] release/beta 2.5.2-5
skip-checks: true
2020-11-09 09:19:58 +00:00
Jaco Greeff 46fb44d3d8 Bump metadata (#2826) 2020-11-09 10:12:26 +01:00
Github Actions 2085a0662c [CI Skip] release/beta 2.5.2-4
skip-checks: true
2020-11-08 13:27:05 +00:00
Jaco Greeff 4476f2838a Bump common (#2824) 2020-11-08 14:20:37 +01:00
Github Actions ddd994ea4a [CI Skip] release/beta 2.5.2-3
skip-checks: true
2020-11-06 12:47:40 +00:00
Jaco Greeff 06a325795b Adjust max allowed call gas (5 * 10 ^ 12) (#2821)
* Adjust max allowed call gas (5 * 10 ^ 12)

* Update packages/api-contract/src/base/Contract.ts

* Update dev
2020-11-06 13:40:17 +01:00
Github Actions 67d7df82d3 [CI Skip] release/beta 2.5.2-2
skip-checks: true
2020-11-05 16:28:20 +00:00
Jaco Greeff ca1bd8fa19 Hack for invalid chain-data on proposals (due to mismatched upgrade) (#2820) 2020-11-05 17:19:35 +01:00
Github Actions 33978d5007 [CI Skip] release/beta 2.5.2-1
skip-checks: true
2020-11-03 18:34:53 +00:00
Jaco Greeff b6ff8a400e Swap accountId check (Ethereum-addr chains have === 20) (#2816) 2020-11-03 19:27:39 +01:00
Github Actions 2bc3b711b2 [CI Skip] release/beta 2.5.2-0
skip-checks: true
2020-11-03 17:54:42 +00:00
Jaco Greeff 09348d1197 Bump deps (#2815) 2020-11-03 18:45:31 +01:00
Github Actions cb791d3963 [CI Skip] release/stable 2.5.1
skip-checks: true
2020-11-02 11:30:30 +00:00
Jaco Greeff bc49e75e61 CHANGELOG for 2.5.1 2020-11-02 12:22:24 +01:00
Jaco Greeff 67f8dcafdb 2.5 (#2813) 2020-11-02 11:45:57 +01:00
Github Actions e95117839b [CI Skip] release/beta 2.4.2-20
skip-checks: true
2020-10-31 12:27:54 +00:00
Jaco Greeff 9f60a8cd5f Add decoded contract events to execution (#2812)
* Cleanup assignments

* Small adjustments

* Add decoded contract events to execution

* Adjust all applyOnEvent
2020-10-31 13:19:57 +01:00
Github Actions e23fae86d5 [CI Skip] release/beta 2.4.2-19
skip-checks: true
2020-10-31 11:58:34 +00:00
Jaco Greeff 94a4594d32 Cleanup assignments (#2811)
* Cleanup assignments

* Small adjustments

* Cleanup AnyJson results

* Event toHuman
2020-10-31 12:50:44 +01:00
Github Actions 5be8ef8f0d [CI Skip] release/beta 2.4.2-18
skip-checks: true
2020-10-31 10:25:53 +00:00
Jaco Greeff e855d5a9d4 Cater for new/old contracts_call results (#2810)
* Cater for new/old contracts_call results

* Update packages/types/src/interfaces/contracts/definitions.ts

* Allow RPC layer to output JSON

* Typing for json outputs

* Convert results

* RPC compat mapping

* Ensure RPC .json is exposed

* Remove compat layer

* Old error detection

* Map to unknown

* Update packages/rpc-core/src/index.ts

* linting
2020-10-31 11:18:58 +01:00
Github Actions 2a0e481710 [CI Skip] release/beta 2.4.2-17
skip-checks: true
2020-10-30 13:37:09 +00:00
Jaco Greeff 161c121cb2 Cleanups for maintainability (#2809)
* Cleanups for maintainability

* Split referendumsInfo

* Extract didUpdate -> bool

* Era filtering

* Default to council

* Points cache

* Remove cache

* Move map arg
2020-10-30 14:28:38 +01:00
Github Actions de38735498 [CI Skip] release/beta 2.4.2-16
skip-checks: true
2020-10-30 11:17:23 +00:00
Jaco Greeff ce1e6615e3 Add derive for single council proposal (#2808) 2020-10-30 12:09:12 +01:00
Github Actions 3ebe9f5243 [CI Skip] release/beta 2.4.2-15
skip-checks: true
2020-10-30 09:54:52 +00:00
Jaco Greeff f686cfcce7 Cleanup always primitive (caters for solang) (#2807)
* Cleanup always primitive (caters for solang)

* Compare (with primitive)
2020-10-30 10:47:18 +01:00
Github Actions c27e49c6f5 [CI Skip] release/beta 2.4.2-14
skip-checks: true
2020-10-30 09:25:37 +00:00
Jaco Greeff 5c69f78676 Expand Call errors with actual callIndex info (#2806)
* Expand Call errors with actutl callIndex info

* Update test expectation

* casing
2020-10-30 10:17:19 +01:00
Github Actions 8f00351405 [CI Skip] release/beta 2.4.2-13
skip-checks: true
2020-10-29 16:25:25 +00:00
Jaco Greeff 1f6c8c2eb8 Use assertReturn to cleanup (#2804)
* Use assertReturn to cleanup

* Remove Uint/Int duplication

* Adjust

* ws errors, part 2

* .

* Adj. manual

* adj

* switchMap

* Revert "switchMap"

This reverts commit edfa4a2258f09042b61a27fd3812f0c53039fe4f.

* Revert.

* Revert.

* protected constructor

* Correct isHexJson flag

* Remove isHexJson (always detect)

* Adjust

* Flags
2020-10-29 17:17:22 +01:00
Github Actions 9bb1343255 [CI Skip] release/beta 2.4.2-12
skip-checks: true
2020-10-29 13:27:28 +00:00
Jaco Greeff 94ebb321f1 Complexity adjustments (#2803)
* Complexity adjustments

* cleanups

* Small cleanups

* Additional

* revert era

* ExtrinsicEra
2020-10-29 14:20:10 +01:00
Github Actions 63fd5baa8f [CI Skip] release/beta 2.4.2-11
skip-checks: true
2020-10-29 11:08:09 +00:00
Jaco Greeff ea3ee428d8 Rework asLatest update (#2802)
* Revert "[CI Skip] release/beta 2.4.2-10"

This reverts commit 5cb1c2d33a.

* Revert "Use asLatest in metadata extraction (#2800)"

This reverts commit 600666de1c.

* Bumps

* Expansion

* Flatten

* Metadata class imports

* Cleanup Decorate exports

* Move Metadata to top-level

* Swap logger on ABI

* Adjust imports

* Cleanups

* Updates
2020-10-29 11:59:37 +01:00
Github Actions 5cb1c2d33a [CI Skip] release/beta 2.4.2-10
skip-checks: true
2020-10-29 08:13:14 +00:00
Jaco Greeff 600666de1c Use asLatest in metadata extraction (#2800)
* User asLatest in metadata extraction

* Cleanup Decorated, bump

* linting

* cleanup decorate

* Remove registry arg from Decorated
2020-10-29 09:05:53 +01:00
Github Actions 524885e8de [CI Skip] release/beta 2.4.2-9
skip-checks: true
2020-10-28 13:37:25 +00:00
Jaco Greeff 1476e5e5e9 Bump common, string* with String (#2799)
* Bump common, string* with String

* Linting, TS 4.0.5
2020-10-28 14:28:49 +01:00
Github Actions 3f48b3c29f [CI Skip] release/beta 2.4.2-8
skip-checks: true
2020-10-28 12:34:15 +00:00
Jaco Greeff 9debb854f9 syncState RPCs (#2797)
* syncState RPCs

* Use endpoint override as available

* Allow Json construction, update syncstate_get def
2020-10-28 13:26:37 +01:00
Github Actions db3fe7d103 [CI Skip] release/beta 2.4.2-7
skip-checks: true
2020-10-28 09:40:45 +00:00
Jaco Greeff a93063c6fb Know-types for Rococo v1 (#2795) 2020-10-28 10:31:32 +01:00
Github Actions 8e4bbd2b23 [CI Skip] release/beta 2.4.2-6
skip-checks: true
2020-10-27 14:27:45 +00:00
Jaco Greeff cf1c2ea58a Add dryRun capability on Submittable (#2793)
* Add dryRun capability on Submittable

* Ordering, add to interface

* Dry run with signing

* Revert paymentInfo changes
2020-10-27 15:19:00 +01:00
Github Actions ca2909e4ba [CI Skip] release/beta 2.4.2-5
skip-checks: true
2020-10-27 12:55:21 +00:00
Jaco Greeff cc9ea53e1a Registry hash returns H256 object (#2791)
* Use logger in error/warning messages

* Update packages/types/src/codec/BTreeSet.ts

* Update expectation

* Some additional type tests

* resgirty.hash returns H256

* Additional override test
2020-10-27 13:47:18 +01:00
Github Actions d876e19fa1 [CI Skip] release/beta 2.4.2-4
skip-checks: true
2020-10-27 12:22:14 +00:00
Jaco Greeff bb7b94dc35 Use logger in error/warning messages (#2790)
* Use logger in error/warning messages

* Update packages/types/src/codec/BTreeSet.ts

* Update expectation

* Some additional type tests
2020-10-27 13:14:03 +01:00
Github Actions be1deb1a75 [CI Skip] release/beta 2.4.2-3
skip-checks: true
2020-10-27 11:30:53 +00:00
Jaco Greeff 14026fef42 Format similar types transparently (#2788)
* Format similar types transparently

* Adjust test expectations

* Remove console.error

* Adjust getTypeDef for check-only
2020-10-27 12:23:18 +01:00
Github Actions b2ea2da6aa [CI Skip] release/beta 2.4.2-2
skip-checks: true
2020-10-27 09:07:26 +00:00
Jaco Greeff f1d21847db Bump deps (util) (#2787) 2020-10-27 09:59:27 +01:00
Github Actions b1fcfd11f4 [CI Skip] release/beta 2.4.2-1
skip-checks: true
2020-10-26 21:44:52 +00:00
Jeremías Díaz 7d1f0e2900 fix(typegen): dedupe similar types (#2786) 2020-10-26 22:37:09 +01:00
Jaco Greeff fb377fb0d4 Adjust index WS imports (#2785) 2020-10-26 22:36:03 +01:00
Github Actions 26de59ed79 [CI Skip] release/beta 2.4.2-0
skip-checks: true
2020-10-26 14:51:50 +00:00
Jaco Greeff 964bd33bb1 Bump GH actions, root cleanups (#2783)
* Bump GH actions, root cleanups

* Remove copy scripts
2020-10-26 15:42:51 +01:00
473 changed files with 7144 additions and 7088 deletions
-4
View File
@@ -1,4 +0,0 @@
// Copyright 2017-2020 @polkadot/api authors & contributors
// SPDX-License-Identifier: Apache-2.0
module.exports = require('./babel.config.js');
-5
View File
@@ -1,5 +0,0 @@
.eslintrc.js
**/build/*
**/coverage/*
**/node_modules/*
docs/examples/promise/90_typegen/*
+10 -1
View File
@@ -1,10 +1,19 @@
// Copyright 2017-2020 @polkadot/api authors & contributors
// SPDX-License-Identifier: Apache-2.0
const base = require('@polkadot/dev/config/eslint');
const base = require('@polkadot/dev/config/eslint.cjs');
module.exports = {
...base,
ignorePatterns: [
'.eslintrc.js',
'.github/**',
'.vscode/**',
'.yarn/**',
'**/build/*',
'**/coverage/*',
'**/node_modules/*'
],
parserOptions: {
...base.parserOptions,
project: [
+1 -1
View File
@@ -9,7 +9,7 @@ jobs:
name: ${{ matrix.step }}
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v1
- uses: actions/checkout@v2
- name: ${{ matrix.step }}
run: |
yarn install --immutable | grep -v 'YN0013'
+1 -1
View File
@@ -13,7 +13,7 @@ jobs:
if: "! startsWith(github.event.head_commit.message, '[CI Skip]') && github.repository == 'polkadot-js/api'"
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v1
- uses: actions/checkout@v2
with:
token: ${{ secrets.GH_PAT }}
- name: ${{ matrix.step }}
+1 -1
View File
@@ -1 +1 @@
10
12
+54
View File
@@ -1,5 +1,59 @@
# CHANGELOG
## 2.7.1 Nov 16, 2020
Upgrade priority: Medium. Recommended for users of Polkadot/Kusama and api-contract users.
Changes:
- Allow for `ExtrinsicSignature` overrides (defaults to `MultiSignature`)
- Update api-contract `Blueprint` to allow for optional salt (auto if not provided)
- Support for ink! `.contract` files (in addition to ABI `.json`)
- Fix contract event decoding with pass-through of raw `Bytes`
- Fix support for enum encoding in api-contract
- Support new contract `Schedule` type as per Substrate
- Update Kusama/Polkadot known upgrade blocks
- Adjust typegen generated `@polkadot/types` imports
- Adjust internal `@polkadot/types` imports/exports (overall bundle sizes)
## 2.6.1 Nov 9, 2020
Upgrade priority: Low. Should be done alongside an update to `@polkadot/util` to 4.0
Changes:
- Adjust auto-gas to contract RPC call to 5 * 10 ^ 12 (align with Rust)
- Adjust derive `AccountId` check to take Ethereum-compatible chains into account
- Fallback for chains with invalid council proposal data in derives
- Bump static v12 Metadata (tests) to latest Substrate version
- Bump `@polkadot/{util,util-crypto}` to 4.0 (optimized WASM layers)
## 2.5.1 Nov 2, 2020
Upgrade priority: Low. Recommended for `api-contract` developers.
- **Breaking change** Substrate changed the `ContractExecResult` from `api.rpc.contracts.call`. The API does have pass-through support for both old and new variants via the `Contract` interface, however it means the structure has changed to accommodate the new Substrate structure. Refer to the [docs for the latest interface](https://polkadot.js.org/docs/api-contract/start/contract.read) (including `isSuccess/isError` -> `isOk/isErr`, and the availability of the `gasConsumed`)
Contributed:
- Dedup similar types on generation (Thanks to https://github.com/monitz87)
Changes:
- `Contract` execution will now return contract events decoded in the result
- Add `.dryRun` on extrinsics (alongside `.paymentInfo` usage)
- Add `system_syncState` and `syncstate_genSyncSpec` RPCs
- Enhance error reporting, `Call` indicates explicit call as found
- Adjust internal metadata decoration and use as exposed from `@types/metadata`
- Expand Rococo known types to cater for v1 (specVersion 10)
- `registry.hash` now returns an `H256` object (as opposed to raw Uint8Array)
- Use utility logger in all relevant error messages (consistency in logging)
- Add `derive.council.proposal(<hash>)` for retrieval of a single (expanded) proposal
- Correctly and transparently format type generation types (allowing for nested variants)
## 2.4.1 Oct 26, 2020
Upgrade priority: Low. No breaking changes, however it does move `api-contract` forward with additional features.
+1 -1
View File
@@ -1,4 +1,4 @@
// Copyright 2017-2020 @polkadot/api authors & contributors
// SPDX-License-Identifier: Apache-2.0
module.exports = require('@polkadot/dev/config/babel');
module.exports = require('@polkadot/dev/config/babel-config-cjs.cjs');
-25
View File
@@ -1,25 +0,0 @@
#!/usr/bin/env bash
# Copyright 2017-2020 @polkadot/api authors & contributors
# SPDX-License-Identifier: Apache-2.0
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 "types"
copy_folder "types-known"
copy_folder "typegen"
-25
View File
@@ -1,25 +0,0 @@
#!/usr/bin/env bash
# Copyright 2017-2020 @polkadot/api authors & contributors
# SPDX-License-Identifier: Apache-2.0
function copy_folder () {
SRC="packages/$1/build"
DST="../test/js-test/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 "types"
copy_folder "types-known"
copy_folder "typegen"
-102
View File
@@ -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:
+6 -5
View File
@@ -1,29 +1,30 @@
// Copyright 2017-2020 @polkadot/api authors & contributors
// SPDX-License-Identifier: Apache-2.0
const config = require('@polkadot/dev/config/jest');
const config = require('@polkadot/dev/config/jest.cjs');
module.exports = Object.assign({}, config, {
moduleNameMapper: {
'@polkadot/api-contract(.*)$': '<rootDir>/packages/api-contract/src/$1',
'@polkadot/api-derive(.*)$': '<rootDir>/packages/api-derive/src/$1',
'@polkadot/api-(contract|derive)(.*)$': '<rootDir>/packages/api-$1/src/$2',
// eslint-disable-next-line sort-keys
'@polkadot/api(.*)$': '<rootDir>/packages/api/src/$1',
'@polkadot/metadata(.*)$': '<rootDir>/packages/metadata/src/$1',
'@polkadot/rpc-(core|provider)(.*)$': '<rootDir>/packages/rpc-$1/src/$2',
'@polkadot/typegen(.*)$': '<rootDir>/packages/typegen/src/$1',
'@polkadot/types-known(.*)$': '<rootDir>/packages/types-known/src/$1',
// eslint-disable-next-line sort-keys
'@polkadot/types(.*)$': '<rootDir>/packages/types/src/$1'
},
modulePathIgnorePatterns: [
'<rootDir>/packages/api/build',
'<rootDir>/packages/api-derive/build',
'<rootDir>/packages/api-contract/build',
'<rootDir>/packages/api-derive/build',
'<rootDir>/packages/metadata/build',
'<rootDir>/packages/rpc-core/build',
'<rootDir>/packages/rpc-provider/build',
'<rootDir>/packages/typegen/build',
'<rootDir>/packages/types/build',
'<rootDir>/packages/types-known/build'
],
resolver: './jest.resolver.js'
resolver: '@polkadot/dev/config/jest-resolver.cjs'
});
-12
View File
@@ -1,12 +0,0 @@
// Copyright 2017-2020 @polkadot/api authors & contributors
// SPDX-License-Identifier: Apache-2.0
const path = require('path');
module.exports = function resolver (file, config) {
if (file.includes('package.json')) {
return path.join(config.basedir.replace('/src', '/'), file);
}
return config.defaultResolver(file, config);
};
+5 -6
View File
@@ -7,8 +7,7 @@
"packages/*"
],
"resolutions": {
"babel-core": "^7.0.0-bridge.0",
"typescript": "^4.0.3"
"typescript": "^4.0.5"
},
"scripts": {
"build": "yarn build:interfaces && polkadot-dev-build-ts && (cd packages/typegen && copyfiles scripts/* build)",
@@ -26,12 +25,12 @@
"devDependencies": {
"@babel/core": "^7.12.3",
"@babel/register": "^7.12.1",
"@babel/runtime": "^7.12.1",
"@polkadot/dev": "^0.59.6",
"@polkadot/ts": "^0.3.51",
"@babel/runtime": "^7.12.5",
"@polkadot/dev": "^0.60.2",
"@polkadot/ts": "^0.3.55",
"@polkadot/typegen": "workspace:packages/typegen",
"@types/jest": "^26.0.15",
"copyfiles": "^2.4.0"
},
"version": "2.4.1"
"version": "2.7.1"
}
+9 -20
View File
@@ -1,36 +1,25 @@
{
"name": "@polkadot/api-contract",
"version": "2.4.1",
"version": "2.7.1",
"description": "Interfaces for interacting with contracts and contract ABIs",
"main": "index.js",
"sideEffects": false,
"keywords": [
"Polkadot",
"ABI"
],
"author": "Jaco Greeff <jacogr@gmail.com>",
"maintainers": [
"Jaco Greeff <jacogr@gmail.com>"
],
"maintainers": [],
"contributors": [],
"license": "Apache-2.0",
"publishConfig": {
"access": "public",
"registry": "https://registry.npmjs.org"
},
"repository": {
"type": "git",
"url": "git+https://github.com/polkadot-js/api.git"
},
"bugs": {
"url": "https://github.com/polkadot-js/api/issues"
},
"repository": "github:polkadot-js/api",
"bugs": "https://github.com/polkadot-js/api/issues",
"homepage": "https://github.com/polkadot-js/api/tree/master/packages/api-contract#readme",
"dependencies": {
"@babel/runtime": "^7.12.1",
"@polkadot/api": "^2.4.1",
"@polkadot/rpc-core": "^2.4.1",
"@polkadot/types": "^2.4.1",
"@polkadot/util": "^3.6.1",
"@babel/runtime": "^7.12.5",
"@polkadot/api": "2.7.1",
"@polkadot/types": "2.7.1",
"@polkadot/util": "^4.1.1",
"bn.js": "^5.1.3",
"rxjs": "^6.6.3"
}
+2 -4
View File
@@ -1,11 +1,9 @@
// Copyright 2017-2020 @polkadot/api-contract authors & contributors
// SPDX-License-Identifier: Apache-2.0
import Abi from './Abi';
import { Abi } from '.';
import * as testContracts from '../test/contracts';
const abis: Record<string, any> = { ...testContracts };
import abis from '../test/contracts';
interface JSONAbi {
spec: {
+17 -13
View File
@@ -5,9 +5,14 @@ import { AnyJson, Codec, CodecArg } from '@polkadot/types/types';
import { ChainProperties, ContractConstructorSpec, ContractEventSpec, ContractMessageSpec, ContractMessageParamSpec, ContractProject } from '@polkadot/types/interfaces';
import { AbiConstructor, AbiEvent, AbiMessage, AbiParam, DecodedEvent, DecodedMessage } from './types';
import { assert, compactAddLength, compactStripLength, isNumber, isObject, isString, stringCamelCase, u8aConcat, u8aToHex } from '@polkadot/util';
import { Bytes } from '@polkadot/types';
import { assert, assertReturn, compactAddLength, compactStripLength, isNumber, isObject, isString, logger, stringCamelCase, u8aConcat, u8aToHex } from '@polkadot/util';
import MetaRegistry from './MetaRegistry';
import { MetaRegistry } from './MetaRegistry';
const EMPTY_U8A = new Uint8Array();
const l = logger('Abi');
function findMessage <T extends AbiMessage> (list: T[], messageOrId: T | string | number): T {
const message = isNumber(messageOrId)
@@ -16,12 +21,10 @@ function findMessage <T extends AbiMessage> (list: T[], messageOrId: T | string
? list.find(({ identifier }) => [identifier, stringCamelCase(identifier)].includes(messageOrId.toString()))
: messageOrId;
assert(message, `Attempted to call an invalid contract interface, ${JSON.stringify(messageOrId)}`);
return message;
return assertReturn(message, `Attempted to call an invalid contract interface, ${JSON.stringify(messageOrId)}`);
}
export default class Abi {
export class Abi {
readonly #events: AbiEvent[];
public readonly constructors: AbiConstructor[];
@@ -74,7 +77,7 @@ export default class Abi {
/**
* Warning: Unstable API, bound to change
*/
public decodeEvent (data: Uint8Array): DecodedEvent {
public decodeEvent (data: Bytes | Uint8Array): DecodedEvent {
const index = data[0];
const event = this.#events[index];
@@ -111,11 +114,11 @@ export default class Abi {
assert(isObject(arg.type), 'Invalid type definition found');
return {
name: stringCamelCase(arg.name.toString()),
name: stringCamelCase(arg.name),
type: this.registry.getMetaTypeDef(arg.type)
};
} catch (error) {
console.error(`Error expanding argument ${index} in ${JSON.stringify(spec)}`);
l.error(`Error expanding argument ${index} in ${JSON.stringify(spec)}`);
throw error;
}
@@ -151,8 +154,8 @@ export default class Abi {
identifier: spec.name.toString(),
index,
selector: spec.selector,
toU8a: (params: CodecArg[]) =>
this.#encodeArgs(spec, args, params)
toU8a: (params: CodecArg[], additional?: Uint8Array) =>
this.#encodeArgs(spec, args, params, additional)
};
return message;
@@ -182,13 +185,14 @@ export default class Abi {
return message.fromU8a(trimmed.subarray(4));
}
#encodeArgs = ({ name, selector }: ContractMessageSpec | ContractConstructorSpec, args: AbiParam[], data: CodecArg[]): Uint8Array => {
#encodeArgs = ({ name, selector }: ContractMessageSpec | ContractConstructorSpec, args: AbiParam[], data: CodecArg[], additional = EMPTY_U8A): Uint8Array => {
assert(data.length === args.length, `Expected ${args.length} arguments to contract message '${name.toString()}', found ${data.length}`);
return compactAddLength(
u8aConcat(
this.registry.createType('ContractSelector', selector).toU8a(),
...args.map(({ type }, index) => this.registry.createType(type.type as 'Text', data[index]).toU8a())
...args.map(({ type }, index) => this.registry.createType(type.type as 'Text', data[index]).toU8a()),
additional
)
);
}
@@ -4,11 +4,9 @@
import fs from 'fs';
import path from 'path';
import Abi from './Abi';
import { Abi } from '.';
import * as testContracts from '../test/contracts';
const abis: Record<string, any> = { ...testContracts };
import abis from '../test/contracts';
describe('MetaRegistry', (): void => {
Object.keys(abis).forEach((abiName) => {
@@ -33,6 +31,6 @@ describe('MetaRegistry', (): void => {
});
it('stores base project as JSON', (): void => {
expect(new Abi(abis.dns).json).toEqual(abis.dns);
expect(new Abi(abis.ink_dns).json).toEqual(abis.ink_dns);
});
});
+9 -7
View File
@@ -5,7 +5,7 @@ import { ContractDisplayName, ChainProperties, SiField, SiLookupTypeId, SiType,
import { InterfaceTypes, TypeDef, TypeDefInfo } from '@polkadot/types/types';
import { assert, isUndefined } from '@polkadot/util';
import { TypeRegistry, withTypeString } from '@polkadot/types';
import { TypeRegistry, withTypeString } from '@polkadot/types/create';
interface PartialTypeSpec {
readonly type: SiLookupTypeId;
@@ -22,7 +22,9 @@ const PRIMITIVE_ALIAS: Record<string, keyof InterfaceTypes> = {
Str: 'Text'
};
export default class MetaRegistry extends TypeRegistry {
const PRIMITIVE_ALWAYS = ['AccountId', 'AccountIndex', 'Address', 'Balance'];
export class MetaRegistry extends TypeRegistry {
public readonly metaTypeDefs: TypeDef[] = [];
#siTypes: SiType[] = [];
@@ -56,8 +58,8 @@ export default class MetaRegistry extends TypeRegistry {
typeDef = {
...typeDef,
displayName,
type: ['Balance'].includes(displayName)
? 'Balance'
type: PRIMITIVE_ALWAYS.includes(displayName)
? displayName
: typeDef.type
};
}
@@ -84,10 +86,10 @@ export default class MetaRegistry extends TypeRegistry {
#extract = (type: SiType, id: SiLookupTypeId): TypeDef => {
const path = [...type.path];
const pathFinal = path.length ? path[path.length - 1].toString() : '';
let typeDef: Omit<TypeDef, 'type'>;
// TODO solang?
if (type.path.join('::').startsWith('ink_env::types::')) {
if (type.path.join('::').startsWith('ink_env::types::') || PRIMITIVE_ALWAYS.includes(pathFinal)) {
typeDef = this.#extractPrimitivePath(type);
} else if (type.def.isPrimitive) {
typeDef = this.#extractPrimitive(type);
@@ -117,7 +119,7 @@ export default class MetaRegistry extends TypeRegistry {
: {}
),
...(type.params.length > 0
? { params: type.params.map((type) => this.getMetaTypeDef({ type })) }
? { sub: type.params.map((type) => this.getMetaTypeDef({ type })) }
: {}
),
...typeDef
+3 -3
View File
@@ -4,12 +4,12 @@
import { ApiTypes, DecorateMethod } from '@polkadot/api/types';
import { AnyJson, Registry } from '@polkadot/types/types';
import ApiBase from '@polkadot/api/base';
import { ApiBase } from '@polkadot/api/base';
import { assert } from '@polkadot/util';
import Abi from '../Abi';
import { Abi } from '../Abi';
export default abstract class Base<ApiType extends ApiTypes> {
export abstract class Base<ApiType extends ApiTypes> {
public readonly abi: Abi;
public readonly api: ApiBase<ApiType>;
+60 -22
View File
@@ -5,18 +5,44 @@ import { ApiTypes, DecorateMethod } from '@polkadot/api/types';
import { SubmittableExtrinsic } from '@polkadot/api/submittable/types';
import { AccountId, EventRecord, Hash } from '@polkadot/types/interfaces';
import { AnyJson, CodecArg, ISubmittableResult } from '@polkadot/types/types';
import { AbiConstructor } from '../types';
import { MapConstructorExec } from './types';
import { AbiConstructor, BlueprintOptions } from '../types';
import { BlueprintDeploy, ContractGeneric, MapConstructorExec } from './types';
import BN from 'bn.js';
import { SubmittableResult } from '@polkadot/api';
import ApiBase from '@polkadot/api/base';
import { isUndefined, stringCamelCase } from '@polkadot/util';
import { ApiBase } from '@polkadot/api/base';
import { Bytes } from '@polkadot/types';
import { isUndefined, stringCamelCase, compactAddLength, u8aToU8a } from '@polkadot/util';
import { randomAsU8a } from '@polkadot/util-crypto';
import Abi from '../Abi';
import { applyOnEvent } from '../util';
import Base from './Base';
import Contract from './Contract';
import { Abi } from '../Abi';
import { applyOnEvent, extractOptions, isOptions } from '../util';
import { Base } from './Base';
import { Contract } from './Contract';
const EMPTY_SALT = new Uint8Array();
function createTx <ApiType extends ApiTypes> (fn: (options: BlueprintOptions, params: CodecArg[]) => SubmittableExtrinsic<ApiType, BlueprintSubmittableResult<ApiType>>): BlueprintDeploy<ApiType> {
return (options: BigInt | string | number | BN | BlueprintOptions, ...params: CodecArg[]): SubmittableExtrinsic<ApiType, BlueprintSubmittableResult<ApiType>> =>
isOptions(options)
? fn(options, params)
: fn(...extractOptions(options, params));
}
function createWithId <T> (fn: (constructorOrId: AbiConstructor | string | number, options: BlueprintOptions, params: CodecArg[]) => T): ContractGeneric<BlueprintOptions, T> {
return (constructorOrId: AbiConstructor | string | number, options: BigInt | string | number | BN | BlueprintOptions, ...params: CodecArg[]): T =>
isOptions(options)
? fn(constructorOrId, options, params)
: fn(constructorOrId, ...extractOptions(options, params));
}
function encodeSalt (salt: Uint8Array | string | null = randomAsU8a()) {
return salt instanceof Bytes
? salt
: salt && salt.length
? compactAddLength(u8aToU8a(salt))
: EMPTY_SALT;
}
export class BlueprintSubmittableResult<ApiType extends ApiTypes> extends SubmittableResult {
public readonly contract?: Contract<ApiType>;
@@ -28,22 +54,31 @@ export class BlueprintSubmittableResult<ApiType extends ApiTypes> extends Submit
}
}
export default class Blueprint<ApiType extends ApiTypes> extends Base<ApiType> {
export class Blueprint<ApiType extends ApiTypes> extends Base<ApiType> {
/**
* @description The on-chain code hash for this blueprint
*/
public readonly codeHash: Hash;
/**
* @deprecated
* @description Deprecated. Use `.tx.<constructorName>`. Creates a contract in a non-deterministic way.
*/
public readonly createContract: ContractGeneric<BlueprintOptions, SubmittableExtrinsic<ApiType, BlueprintSubmittableResult<ApiType>>>;
readonly #tx: MapConstructorExec<ApiType> = {};
constructor (api: ApiBase<ApiType>, abi: AnyJson | Abi, codeHash: string | Hash | Uint8Array, decorateMethod: DecorateMethod<ApiType>) {
super(api, abi, decorateMethod);
this.codeHash = this.registry.createType('Hash', codeHash);
this.createContract = createWithId(this.#deploy);
this.abi.constructors.forEach((c): void => {
const messageName = stringCamelCase(c.identifier);
if (isUndefined(this.#tx[messageName])) {
this.#tx[messageName] = (endowment: BigInt | string | number | BN, gasLimit: BigInt | string | number | BN, ...params: CodecArg[]) =>
this.#deploy(c, endowment, gasLimit, params);
this.#tx[messageName] = createTx((o, p) => this.#deploy(c, o, p));
}
});
}
@@ -52,17 +87,20 @@ export default class Blueprint<ApiType extends ApiTypes> extends Base<ApiType> {
return this.#tx;
}
#deploy = (constructorOrId: AbiConstructor | string| number, endowment: BigInt | string | number | BN, gasLimit: BigInt | string | number | BN, params: CodecArg[]): SubmittableExtrinsic<ApiType, BlueprintSubmittableResult<ApiType>> => {
return this.api.tx.contracts
.instantiate(endowment, gasLimit, this.codeHash, this.abi.findConstructor(constructorOrId).toU8a(params))
.withResultTransform((result: ISubmittableResult) =>
new BlueprintSubmittableResult(result, applyOnEvent(result, 'Instantiated', (record: EventRecord) =>
new Contract<ApiType>(this.api, this.abi, record.event.data[1] as AccountId, this._decorateMethod)
))
);
}
#deploy = (constructorOrId: AbiConstructor | string| number, { gasLimit = 0, salt, value = 0 }: BlueprintOptions, params: CodecArg[]): SubmittableExtrinsic<ApiType, BlueprintSubmittableResult<ApiType>> => {
const encodedSalt = encodeSalt(salt);
const withSalt = this.api.tx.contracts.instantiate.meta.args.length === 5;
const encoded = this.abi.findConstructor(constructorOrId).toU8a(params, withSalt ? EMPTY_SALT : encodedSalt);
const tx = withSalt
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore new style with salt included
? this.api.tx.contracts.instantiate(value, gasLimit, this.codeHash, encoded, encodedSalt)
: this.api.tx.contracts.instantiate(value, gasLimit, this.codeHash, encoded);
public createContract (constructorOrId: AbiConstructor | string| number, endowment: BigInt | string | number | BN, gasLimit: BigInt | string | number | BN, ...params: CodecArg[]): SubmittableExtrinsic<ApiType, BlueprintSubmittableResult<ApiType>> {
return this.#deploy(constructorOrId, endowment, gasLimit, params);
return tx.withResultTransform((result: ISubmittableResult) =>
new BlueprintSubmittableResult(result, applyOnEvent(result, 'Instantiated', ([record]: EventRecord[]) =>
new Contract<ApiType>(this.api, this.abi, record.event.data[1] as AccountId, this._decorateMethod)
))
);
}
}
@@ -0,0 +1,27 @@
// Copyright 2017-2020 @polkadot/api-contract authors & contributors
// SPDX-License-Identifier: Apache-2.0
import fs from 'fs';
import path from 'path';
import { decorateMethod } from '@polkadot/api/promise';
import contractFlipper from '../../test/contracts/ink/flipper.contract.json';
import abiFlipper from '../../test/contracts/ink/flipper.json';
import { mockApi } from './mock';
import { Code } from './Code';
const wasmFlipper = fs.readFileSync(path.join(__dirname, '../../test/contracts/ink/flipper.wasm'));
describe('Code', (): void => {
it('can construct with an individual ABI/WASM combo', (): void => {
expect(
() => new Code(mockApi, abiFlipper, wasmFlipper, decorateMethod)
).not.toThrow();
});
it('can construct with an .contract ABI', (): void => {
expect(
() => new Code(mockApi, contractFlipper, null, decorateMethod)
).not.toThrow();
});
});
+16 -9
View File
@@ -7,13 +7,13 @@ import { EventRecord, Hash } from '@polkadot/types/interfaces';
import { AnyJson, ISubmittableResult } from '@polkadot/types/types';
import { SubmittableResult } from '@polkadot/api';
import ApiBase from '@polkadot/api/base';
import { compactAddLength, u8aToU8a } from '@polkadot/util';
import { ApiBase } from '@polkadot/api/base';
import { assert, compactAddLength, isWasm, u8aToU8a } from '@polkadot/util';
import Abi from '../Abi';
import { Abi } from '../Abi';
import { applyOnEvent } from '../util';
import Base from './Base';
import Blueprint from './Blueprint';
import { Base } from './Base';
import { Blueprint } from './Blueprint';
export class CodeSubmittableResult<ApiType extends ApiTypes> extends SubmittableResult {
public readonly blueprint?: Blueprint<ApiType>;
@@ -25,20 +25,27 @@ export class CodeSubmittableResult<ApiType extends ApiTypes> extends Submittable
}
}
export default class Code<ApiType extends ApiTypes> extends Base<ApiType> {
export class Code<ApiType extends ApiTypes> extends Base<ApiType> {
public readonly code: Uint8Array;
constructor (api: ApiBase<ApiType>, abi: AnyJson | Abi, wasm: Uint8Array | string | Buffer, decorateMethod: DecorateMethod<ApiType>) {
constructor (api: ApiBase<ApiType>, abi: AnyJson | Abi, wasm: Uint8Array | string | Buffer | null | undefined, decorateMethod: DecorateMethod<ApiType>) {
super(api, abi, decorateMethod);
this.code = u8aToU8a(wasm);
this.code = isWasm(this.abi.project.source.wasm)
? this.abi.project.source.wasm
: u8aToU8a(wasm);
assert(isWasm(this.code), 'No WASM code provided');
}
/**
* @description Deploy the code bundle, creating a Blueprint.
*/
public createBlueprint (): SubmittableExtrinsic<ApiType, CodeSubmittableResult<ApiType>> {
return this.api.tx.contracts
.putCode(compactAddLength(this.code))
.withResultTransform((result: ISubmittableResult) =>
new CodeSubmittableResult(result, applyOnEvent(result, 'CodeStored', (record: EventRecord) =>
new CodeSubmittableResult(result, applyOnEvent(result, 'CodeStored', ([record]: EventRecord[]) =>
new Blueprint<ApiType>(this.api, this.abi, record.event.data[0] as Hash, this._decorateMethod)
))
);
+131 -39
View File
@@ -3,45 +3,123 @@
import { ApiTypes, DecorateMethod } from '@polkadot/api/types';
import { SubmittableExtrinsic } from '@polkadot/api/submittable/types';
import { AccountId, ContractExecResult } from '@polkadot/types/interfaces';
import { AnyJson, CodecArg } from '@polkadot/types/types';
import { AbiMessage, ContractCallOutcome } from '../types';
import { ContractRead, MapMessageExec, MapMessageRead } from './types';
import { AccountId, ContractExecResult, EventRecord } from '@polkadot/types/interfaces';
import { AnyJson, CodecArg, ISubmittableResult, Registry } from '@polkadot/types/types';
import { AbiMessage, ContractCallOutcome, ContractOptions, DecodedEvent } from '../types';
import { ContractCallResult, ContractCallSend, ContractGeneric, ContractQuery, ContractTx, MapMessageQuery, MapMessageTx } from './types';
import BN from 'bn.js';
import { map } from 'rxjs/operators';
import ApiBase from '@polkadot/api/base';
import { assert, bnToBn, isFunction, isUndefined, stringCamelCase } from '@polkadot/util';
import { SubmittableResult } from '@polkadot/api';
import { ApiBase } from '@polkadot/api/base';
import { Bytes } from '@polkadot/types';
import { assert, bnToBn, isFunction, isUndefined, logger, stringCamelCase } from '@polkadot/util';
import Abi from '../Abi';
import { formatData } from '../util';
import Base from './Base';
import { Abi } from '../Abi';
import { applyOnEvent, extractOptions, formatData, isOptions } from '../util';
import { Base } from './Base';
// As per Rust, 5 * GAS_PER_SEC
const MAX_CALL_GAS = new BN(5_000_000_000_000).subn(1);
const ERROR_NO_CALL = 'Your node does not expose the contracts.call RPC. This is most probably due to a runtime configuration.';
const l = logger('Contract');
export default class Contract<ApiType extends ApiTypes> extends Base<ApiType> {
function createQuery <ApiType extends ApiTypes> (fn: (origin: string | AccountId | Uint8Array, options: ContractOptions, params: CodecArg[]) => ContractCallResult<ApiType, ContractCallOutcome>): ContractQuery<ApiType> {
return (origin: string | AccountId | Uint8Array, options: BigInt | string | number | BN | ContractOptions, ...params: CodecArg[]): ContractCallResult<ApiType, ContractCallOutcome> =>
isOptions(options)
? fn(origin, options, params)
: fn(origin, ...extractOptions(options, params));
}
function createTx <ApiType extends ApiTypes> (fn: (options: ContractOptions, params: CodecArg[]) => SubmittableExtrinsic<ApiType>): ContractTx<ApiType> {
return (options: BigInt | string | number | BN | ContractOptions, ...params: CodecArg[]): SubmittableExtrinsic<ApiType> =>
isOptions(options)
? fn(options, params)
: fn(...extractOptions(options, params));
}
function createWithId <T> (fn: (messageOrId: AbiMessage | string | number, options: ContractOptions, params: CodecArg[]) => T): ContractGeneric<ContractOptions, T> {
return (messageOrId: AbiMessage | string | number, options: BigInt | string | number | BN | ContractOptions, ...params: CodecArg[]): T =>
isOptions(options)
? fn(messageOrId, options, params)
: fn(messageOrId, ...extractOptions(options, params));
}
export class ContractSubmittableResult extends SubmittableResult {
public readonly contractEvents?: DecodedEvent[];
constructor (result: ISubmittableResult, contractEvents?: DecodedEvent[]) {
super(result);
this.contractEvents = contractEvents;
}
}
// map from a JSON result to current-style ContractExecResult
function mapExecResult (registry: Registry, json: Record<string, AnyJson>): ContractExecResult {
if (!Object.keys(json).some((key) => ['error', 'success'].includes(key))) {
return registry.createType('ContractExecResult', json);
}
const from = registry.createType('ContractExecResultTo260', json);
if (from.isSuccess) {
const s = from.asSuccess;
return registry.createType('ContractExecResult', {
gasConsumed: s.gasConsumed,
result: {
ok: {
data: s.data,
flags: s.flags
}
}
});
}
// in the old format error has no additional information,
// map it as-is with an "unknown" error
return registry.createType('ContractExecResult', { result: { err: { other: 'unknown' } } });
}
export class Contract<ApiType extends ApiTypes> extends Base<ApiType> {
/**
* @description The on-chain address for this contract
*/
public readonly address: AccountId;
readonly #tx: MapMessageExec<ApiType> = {};
/**
* @deprecated
* @description Deprecated. Use `.tx.<messageName>` to send a transaction.
*/
public readonly exec: ContractGeneric<ContractOptions, SubmittableExtrinsic<ApiType>>;
readonly #query: MapMessageRead<ApiType> = {};
/**
* @deprecated
* @description Deprecated. Use `.tx.<messageName>` to send a transaction.
*/
public readonly read: ContractGeneric<ContractOptions, ContractCallSend<ApiType>>;
readonly #query: MapMessageQuery<ApiType> = {};
readonly #tx: MapMessageTx<ApiType> = {};
constructor (api: ApiBase<ApiType>, abi: AnyJson | Abi, address: string | AccountId, decorateMethod: DecorateMethod<ApiType>) {
super(api, abi, decorateMethod);
this.address = this.registry.createType('AccountId', address);
this.exec = createWithId(this.#exec);
this.read = createWithId(this.#read);
this.abi.messages.forEach((m): void => {
const messageName = stringCamelCase(m.identifier);
if (isUndefined(this.#tx[messageName])) {
this.#tx[messageName] = (value: BigInt | BN | string | number, gasLimit: BigInt | BN | string | number, ...params: CodecArg[]) =>
this.#exec(m, value, gasLimit, params);
this.#tx[messageName] = createTx((o, p) => this.#exec(m, o, p));
}
if (isUndefined(this.#query[messageName])) {
this.#query[messageName] = (origin: string | AccountId | Uint8Array, value: BigInt | BN | string | number, gasLimit: BigInt | BN | string | number, ...params: CodecArg[]) =>
this.#read(m, value, gasLimit, params).send(origin);
this.#query[messageName] = createQuery((f, o, p) => this.#read(m, o, p).send(f));
}
});
}
@@ -50,29 +128,47 @@ export default class Contract<ApiType extends ApiTypes> extends Base<ApiType> {
return isFunction(this.api.rx.rpc.contracts?.call);
}
public get query (): MapMessageRead<ApiType> {
public get query (): MapMessageQuery<ApiType> {
assert(this.hasRpcContractsCall, ERROR_NO_CALL);
return this.#query;
}
public get tx (): MapMessageExec<ApiType> {
public get tx (): MapMessageTx<ApiType> {
return this.#tx;
}
#getGas = (_gasLimit: BigInt | BN | string | number): BN => {
#getGas = (_gasLimit: BigInt | BN | string | number, isCall = false): BN => {
const gasLimit = bnToBn(_gasLimit);
return gasLimit.lten(0)
? this.api.consts.system.maximumBlockWeight.muln(64).divn(100)
? isCall
? MAX_CALL_GAS
: this.api.consts.system.maximumBlockWeight.muln(64).divn(100)
: gasLimit;
}
#exec = (messageOrId: AbiMessage | string | number, value: BigInt | BN | string | number, gasLimit: BigInt | BN | string | number, params: CodecArg[]): SubmittableExtrinsic<ApiType> => {
return this.api.tx.contracts.call(this.address, value, this.#getGas(gasLimit), this.abi.findMessage(messageOrId).toU8a(params));
#exec = (messageOrId: AbiMessage | string | number, { gasLimit = 0, value = 0 }: ContractOptions, params: CodecArg[]): SubmittableExtrinsic<ApiType> => {
return this.api.tx.contracts
.call(this.address, value, this.#getGas(gasLimit), this.abi.findMessage(messageOrId).toU8a(params))
.withResultTransform((result: ISubmittableResult) =>
new ContractSubmittableResult(result, applyOnEvent(result, 'ContractExecution', (records: EventRecord[]) =>
records
.map(({ event: { data: [, data] } }): DecodedEvent | null => {
try {
return this.abi.decodeEvent(data as Bytes);
} catch (error) {
l.error(`Unable to decode contract event: ${(error as Error).message}`);
return null;
}
})
.filter((decoded): decoded is DecodedEvent => !!decoded)
))
);
}
#read = (messageOrId: AbiMessage | string | number, value: BigInt | BN | string | number, gasLimit: BigInt | BN | string | number, params: CodecArg[]): ContractRead<ApiType> => {
#read = (messageOrId: AbiMessage | string | number, { gasLimit = 0, value = 0 }: ContractOptions, params: CodecArg[]): ContractCallSend<ApiType> => {
assert(this.hasRpcContractsCall, ERROR_NO_CALL);
const message = this.abi.findMessage(messageOrId);
@@ -80,29 +176,25 @@ export default class Contract<ApiType extends ApiTypes> extends Base<ApiType> {
return {
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
send: this._decorateMethod((origin: string | AccountId | Uint8Array) =>
this.api.rx.rpc.contracts.call({
this.api.rx.rpc.contracts.call.json({
dest: this.address,
gasLimit: this.#getGas(gasLimit),
gasLimit: this.#getGas(gasLimit, true),
inputData: message.toU8a(params),
origin,
value
}).pipe(
map((result: ContractExecResult): ContractCallOutcome => ({
output: result.isSuccess && message.returnType
? formatData(this.registry, result.asSuccess.data, message.returnType)
}).pipe(map((json): ContractCallOutcome => {
const { debugMessage, gasConsumed, result } = mapExecResult(this.registry, json.toJSON());
return {
debugMessage,
gasConsumed,
output: result.isOk && message.returnType
? formatData(this.registry, result.asOk.data, message.returnType)
: null,
result
}))
)
};
}))
)
};
}
public exec (messageOrId: AbiMessage | string | number, value: BigInt | BN | string | number, gasLimit: BigInt | BN | string | number, ...params: CodecArg[]): SubmittableExtrinsic<ApiType> {
return this.#exec(messageOrId, value, gasLimit, params);
}
public read (messageOrId: AbiMessage | string | number, value: BigInt | BN | string | number, gasLimit: BigInt | BN | string | number, ...params: CodecArg[]): ContractRead<ApiType> {
return this.#read(messageOrId, value, gasLimit, params);
}
}
+3 -3
View File
@@ -1,6 +1,6 @@
// Copyright 2017-2020 @polkadot/api authors & contributors
// SPDX-License-Identifier: Apache-2.0
export { default as Blueprint, BlueprintSubmittableResult } from './Blueprint';
export { default as Code, CodeSubmittableResult } from './Code';
export { default as Contract } from './Contract';
export { Blueprint, BlueprintSubmittableResult } from './Blueprint';
export { Code, CodeSubmittableResult } from './Code';
export { Contract } from './Contract';
+20
View File
@@ -0,0 +1,20 @@
// Copyright 2017-2020 @polkadot/api-contract authors & contributors
// SPDX-License-Identifier: Apache-2.0
import { ApiBase } from '@polkadot/api/base';
import { TypeRegistry } from '@polkadot/types';
const registry = new TypeRegistry();
export const mockApi = {
registry,
rx: {
tx: {
contracts: {
putCode: (): never => {
throw new Error('mock');
}
}
}
}
} as unknown as ApiBase<'promise'>;
+28 -8
View File
@@ -5,27 +5,47 @@ import { ApiTypes, ObsInnerType } from '@polkadot/api/types';
import { SubmittableExtrinsic } from '@polkadot/api/submittable/types';
import { AccountId } from '@polkadot/types/interfaces';
import { CodecArg } from '@polkadot/types/types';
import { ContractCallOutcome } from '../types';
import { AbiMessage, BlueprintOptions, ContractCallOutcome, ContractOptions } from '../types';
import BN from 'bn.js';
import { Observable } from 'rxjs';
type ContractCallResult<ApiType extends ApiTypes, T> = ApiType extends 'rxjs'
export interface BlueprintDeploy<ApiType extends ApiTypes> {
(options: BlueprintOptions, ...params: CodecArg[]): SubmittableExtrinsic<ApiType>;
(value: BigInt | string | number | BN, gasLimit: BigInt | string | number | BN, ...params: CodecArg[]): SubmittableExtrinsic<ApiType>;
}
export interface ContractQuery<ApiType extends ApiTypes> {
(origin: AccountId | string | Uint8Array, options: ContractOptions, ...params: CodecArg[]): ContractCallResult<ApiType, ContractCallOutcome>;
(origin: AccountId | string | Uint8Array, value: BigInt | BN | string | number, gasLimit: BigInt | BN | string | number, ...params: CodecArg[]): ContractCallResult<ApiType, ContractCallOutcome>;
}
export interface ContractTx<ApiType extends ApiTypes> {
(options: ContractOptions, ...params: CodecArg[]): SubmittableExtrinsic<ApiType>;
(value: BigInt | BN | string | number, gasLimit: BigInt | BN | string | number, ...params: CodecArg[]): SubmittableExtrinsic<ApiType>;
}
export interface ContractGeneric<O, T> {
(messageOrId: AbiMessage | string | number, options: O, ...params: CodecArg[]): T;
(messageOrId: AbiMessage | string | number, value: BigInt | BN | string | number, gasLimit: BigInt | BN | string | number, ...params: CodecArg[]): T;
}
export type ContractCallResult<ApiType extends ApiTypes, T> = ApiType extends 'rxjs'
? Observable<Observable<T>>
: Promise<ObsInnerType<Observable<T>>>;
export interface ContractRead<ApiType extends ApiTypes> {
export interface ContractCallSend<ApiType extends ApiTypes> {
send (account: string | AccountId | Uint8Array): ContractCallResult<ApiType, ContractCallOutcome>;
}
export interface MapConstructorExec<ApiType extends ApiTypes> {
[message: string]: (endowment: BigInt | string | number | BN, gasLimit: BigInt | string | number | BN, ...params: CodecArg[]) => SubmittableExtrinsic<ApiType>;
[message: string]: BlueprintDeploy<ApiType>;
}
export interface MapMessageExec<ApiType extends ApiTypes> {
[message: string]: (value: BigInt | BN | string | number, gasLimit: BigInt | BN | string | number, ...params: CodecArg[]) => SubmittableExtrinsic<ApiType>;
export interface MapMessageTx<ApiType extends ApiTypes> {
[message: string]: ContractTx<ApiType>;
}
export interface MapMessageRead<ApiType extends ApiTypes> {
[message: string]: (origin: AccountId | string | Uint8Array, value: BigInt | BN | string | number, gasLimit: BigInt | BN | string | number, ...params: CodecArg[]) => ContractCallResult<ApiType, ContractCallOutcome>;
export interface MapMessageQuery<ApiType extends ApiTypes> {
[message: string]: ContractQuery<ApiType>;
}
@@ -0,0 +1,51 @@
// Copyright 2017-2020 @polkadot/api-contract authors & contributors
// SPDX-License-Identifier: Apache-2.0
// Simple non-runnable checks to test type definitions in the editor itself
import { ApiPromise } from '@polkadot/api';
import { TestKeyringMap, createTestPairs } from '@polkadot/keyring/testingPairs';
import abiIncrementer from '../test/contracts/ink/incrementer.json';
import { BlueprintPromise, ContractPromise } from '.';
async function checkBlueprint (api: ApiPromise, pairs: TestKeyringMap): Promise<void> {
const blueprint = new BlueprintPromise(api, abiIncrementer, '0x1234');
// new style
await blueprint.tx.new({ gasLimit: 456, salt: '0x1234', value: 123 }, 42).signAndSend(pairs.bob);
await blueprint.tx.new({ gasLimit: 456, value: 123 }, 42).signAndSend(pairs.bob);
// old style
await blueprint.tx.new(123, 456, 42).signAndSend(pairs.bob);
}
async function checkContract (api: ApiPromise, pairs: TestKeyringMap): Promise<void> {
const contract = new ContractPromise(api, abiIncrementer, '0x1234');
// queries
await contract.query.get(pairs.alice.address, {});
await contract.query.get(pairs.alice.address, 0, 0);
// execute
await contract.tx.inc({ gasLimit: 1234 }, 123).signAndSend(pairs.eve);
await contract.tx.inc(123, 456, 69).signAndSend(pairs.eve);
// deprecated
await contract.read('get', {}).send(pairs.eve.address);
await contract.exec('inc', {}, 123).signAndSend(pairs.dave);
}
async function main (): Promise<void> {
const api = await ApiPromise.create();
const pairs = createTestPairs();
// eslint-disable-next-line @typescript-eslint/no-floating-promises
Promise.all([
checkBlueprint(api, pairs),
checkContract(api, pairs)
]);
}
// eslint-disable-next-line @typescript-eslint/unbound-method
main().catch(console.error);
+1 -1
View File
@@ -1,7 +1,7 @@
// Copyright 2017-2020 @polkadot/api-contract authors & contributors
// SPDX-License-Identifier: Apache-2.0
export { default as Abi } from './Abi';
export { Abi } from './Abi';
export { Blueprint as BlueprintRx, Code as CodeRx, Contract as ContractRx } from './rx';
export { Blueprint as BlueprintPromise, Code as CodePromise, Contract as ContractPromise } from './promise';
@@ -7,10 +7,10 @@ import { AnyJson } from '@polkadot/types/types';
import { ApiPromise } from '@polkadot/api';
import { decorateMethod } from '@polkadot/api/promise';
import Abi from '../Abi';
import BaseBlueprint from '../base/Blueprint';
import { Abi } from '../Abi';
import { Blueprint as BaseBlueprint } from '../base';
export default class Blueprint extends BaseBlueprint<'promise'> {
export class Blueprint extends BaseBlueprint<'promise'> {
constructor (api: ApiPromise, abi: AnyJson | Abi, codeHash: string | Hash) {
super(api, abi, codeHash, decorateMethod);
}
+4 -4
View File
@@ -5,11 +5,11 @@ import { ApiPromise } from '@polkadot/api';
import { decorateMethod } from '@polkadot/api/promise';
import { AnyJson } from '@polkadot/types/types';
import Abi from '../Abi';
import BaseCode from '../base/Code';
import { Abi } from '../Abi';
import { Code as BaseCode } from '../base';
export default class Code extends BaseCode<'promise'> {
constructor (api: ApiPromise, abi: AnyJson | Abi, wasm: Uint8Array | string | Buffer) {
export class Code extends BaseCode<'promise'> {
constructor (api: ApiPromise, abi: AnyJson | Abi, wasm: Uint8Array | string | Buffer | null | undefined) {
super(api, abi, wasm, decorateMethod);
}
}
@@ -7,10 +7,10 @@ import { AnyJson } from '@polkadot/types/types';
import { ApiPromise } from '@polkadot/api';
import { decorateMethod } from '@polkadot/api/promise';
import Abi from '../Abi';
import BaseContract from '../base/Contract';
import { Abi } from '../Abi';
import { Contract as BaseContract } from '../base';
export default class Contract extends BaseContract<'promise'> {
export class Contract extends BaseContract<'promise'> {
constructor (api: ApiPromise, abi: AnyJson | Abi, address: string | AccountId) {
super(api, abi, address, decorateMethod);
}
+3 -3
View File
@@ -1,6 +1,6 @@
// Copyright 2017-2020 @polkadot/api-contract authors & contributors
// SPDX-License-Identifier: Apache-2.0
export { default as Blueprint } from './Blueprint';
export { default as Code } from './Code';
export { default as Contract } from './Contract';
export { Blueprint } from './Blueprint';
export { Code } from './Code';
export { Contract } from './Contract';
+3 -3
View File
@@ -7,10 +7,10 @@ import { AnyJson } from '@polkadot/types/types';
import { ApiRx } from '@polkadot/api';
import { decorateMethod } from '@polkadot/api/rx';
import Abi from '../Abi';
import BaseBlueprint from '../base/Blueprint';
import { Abi } from '../Abi';
import { Blueprint as BaseBlueprint } from '../base';
export default class Blueprint extends BaseBlueprint<'rxjs'> {
export class Blueprint extends BaseBlueprint<'rxjs'> {
constructor (api: ApiRx, abi: AnyJson | Abi, codeHash: string | Hash) {
super(api, abi, codeHash, decorateMethod);
}
+4 -4
View File
@@ -6,11 +6,11 @@ import { AnyJson } from '@polkadot/types/types';
import { ApiRx } from '@polkadot/api';
import { decorateMethod } from '@polkadot/api/rx';
import Abi from '../Abi';
import BaseCode from '../base/Code';
import { Abi } from '../Abi';
import { Code as BaseCode } from '../base';
export default class Code extends BaseCode<'rxjs'> {
constructor (api: ApiRx, abi: AnyJson | Abi, wasm: Uint8Array | string | Buffer) {
export class Code extends BaseCode<'rxjs'> {
constructor (api: ApiRx, abi: AnyJson | Abi, wasm: Uint8Array | string | Buffer | null | undefined) {
super(api, abi, wasm, decorateMethod);
}
}
+3 -3
View File
@@ -7,10 +7,10 @@ import { AnyJson } from '@polkadot/types/types';
import { ApiRx } from '@polkadot/api';
import { decorateMethod } from '@polkadot/api/rx';
import Abi from '../Abi';
import BaseContract from '../base/Contract';
import { Abi } from '../Abi';
import { Contract as BaseContract } from '../base';
export default class Contract extends BaseContract<'rxjs'> {
export class Contract extends BaseContract<'rxjs'> {
constructor (api: ApiRx, abi: AnyJson | Abi, address: string | AccountId) {
super(api, abi, address, decorateMethod);
}
+3 -3
View File
@@ -1,6 +1,6 @@
// Copyright 2017-2020 @polkadot/api-contract authors & contributors
// SPDX-License-Identifier: Apache-2.0
export { default as Blueprint } from './Blueprint';
export { default as Code } from './Code';
export { default as Contract } from './Contract';
export { Blueprint } from './Blueprint';
export { Code } from './Code';
export { Contract } from './Contract';
+21 -5
View File
@@ -2,11 +2,14 @@
// SPDX-License-Identifier: Apache-2.0
import { ApiTypes } from '@polkadot/api/types';
import { ContractExecResult, ContractSelector } from '@polkadot/types/interfaces';
import { ContractExecResultResult, ContractSelector } from '@polkadot/types/interfaces';
import { Codec, CodecArg, TypeDef } from '@polkadot/types/types';
import ApiBase from '@polkadot/api/base';
import Abi from './Abi';
import BN from 'bn.js';
import { ApiBase } from '@polkadot/api/base';
import { Text, u64 } from '@polkadot/types';
import { Abi } from '.';
export interface ContractBase<ApiType extends ApiTypes> {
readonly abi: Abi;
@@ -40,7 +43,7 @@ export interface AbiMessage {
isPayable?: boolean;
returnType?: TypeDef | null;
selector: ContractSelector;
toU8a: (params: CodecArg[]) => Uint8Array;
toU8a: (params: CodecArg[], additional?: Uint8Array) => Uint8Array;
}
export type AbiConstructor = AbiMessage;
@@ -51,8 +54,10 @@ export interface InterfaceContractCalls {
}
export interface ContractCallOutcome {
debugMessage: Text;
gasConsumed: u64;
output: Codec | null;
result: ContractExecResult;
result: ContractExecResultResult;
}
export interface DecodedEvent {
@@ -64,3 +69,14 @@ export interface DecodedMessage {
args: Codec[];
message: AbiMessage;
}
export interface BlueprintOptions {
gasLimit?: BigInt | string | number | BN;
salt?: Uint8Array | string | null;
value?: BigInt | string | number | BN;
}
export interface ContractOptions {
gasLimit?: BigInt | BN | string | number;
value?: BigInt | BN | string | number;
}
+25 -7
View File
@@ -1,24 +1,42 @@
// Copyright 2017-2020 @polkadot/rpc-core authors & contributors
// Copyright 2017-2020 @polkadot/rpc-contract authors & contributors
// SPDX-License-Identifier: Apache-2.0
import { SubmittableResult } from '@polkadot/api';
import { EventRecord } from '@polkadot/types/interfaces';
import { Codec, Registry, TypeDef } from '@polkadot/types/types';
import { Codec, CodecArg, Registry, TypeDef } from '@polkadot/types/types';
import { BlueprintOptions, ContractOptions } from './types';
import { Raw, createTypeUnsafe } from '@polkadot/types';
import BN from 'bn.js';
import { Raw } from '@polkadot/types';
import { createTypeUnsafe } from '@polkadot/types/create';
import { isBn, isBigInt, isNumber, isString } from '@polkadot/util';
type ContractEvents = 'CodeStored' | 'ContractExecution' | 'Instantiated';
type TOptions = BlueprintOptions | ContractOptions;
export function formatData (registry: Registry, data: Raw, { type }: TypeDef): Codec {
return createTypeUnsafe(registry, type, [data], true);
}
export function applyOnEvent <T> (result: SubmittableResult, type: 'CodeStored' | 'Instantiated', fn: (record: EventRecord) => T): T | undefined {
export function applyOnEvent <T> (result: SubmittableResult, type: ContractEvents, fn: (records: EventRecord[]) => T): T | undefined {
if (result.isInBlock || result.isFinalized) {
const record = result.findRecord('contracts', type);
const records = result.filterRecords('contracts', type);
if (record) {
return fn(record);
if (records.length) {
return fn(records);
}
}
return undefined;
}
export function isOptions <T> (options: BigInt | string | number | BN | T): options is T {
return !(isBn(options) || isBigInt(options) || isNumber(options) || isString(options));
}
export function extractOptions <T extends TOptions> (value: BigInt | string | number | BN, params: CodecArg[]): [T, CodecArg[]] {
const gasLimit = params.shift() as BN;
return [{ gasLimit, value } as T, params];
}
@@ -29,15 +29,6 @@
{
"displayName": "Entry",
"namespace": "ink_storage::collections::stash",
"params": [
{
"displayName": "Hash",
"namespace": "ink_env::types",
"info": 6,
"type": "Hash"
}
],
"info": 3,
"sub": [
{
"displayName": "VacantEntry",
@@ -66,6 +57,7 @@
"name": "Occupied"
}
],
"info": 3,
"type": "{\"_enum\":{\"Vacant\":\"VacantEntry\",\"Occupied\":\"Hash\"}}"
},
{
@@ -108,15 +100,6 @@
{
"displayName": "ValueEntry",
"namespace": "ink_storage::collections::hashmap",
"params": [
{
"displayName": "AccountId",
"namespace": "ink_env::types",
"info": 6,
"type": "AccountId"
}
],
"info": 9,
"sub": [
{
"displayName": "AccountId",
@@ -131,6 +114,7 @@
"name": "key_index"
}
],
"info": 9,
"type": "{\"value\":\"AccountId\",\"key_index\":\"u32\"}"
},
{
@@ -141,38 +125,6 @@
},
{
"displayName": "Result",
"params": [
{
"info": 10,
"sub": [],
"type": "()"
},
{
"displayName": "Error",
"namespace": "dns::dns",
"info": 3,
"sub": [
{
"ext": {
"discriminant": 0
},
"info": 6,
"name": "NameAlreadyExists",
"type": "Null"
},
{
"ext": {
"discriminant": 1
},
"info": 6,
"name": "CallerIsNotOwner",
"type": "Null"
}
],
"type": "{ _enum: [\"NameAlreadyExists\", \"CallerIsNotOwner\"] }"
}
],
"info": 7,
"sub": [
{
"name": "Ok",
@@ -203,9 +155,10 @@
"type": "Null"
}
],
"type": "{ _enum: [\"NameAlreadyExists\", \"CallerIsNotOwner\"] }"
"type": "{\"_enum\":[\"NameAlreadyExists\",\"CallerIsNotOwner\"]}"
}
],
"info": 7,
"type": "Result<(), Error>"
},
{
@@ -235,25 +188,17 @@
"type": "Null"
}
],
"type": "{ _enum: [\"NameAlreadyExists\", \"CallerIsNotOwner\"] }"
"type": "{\"_enum\":[\"NameAlreadyExists\",\"CallerIsNotOwner\"]}"
},
{
"displayName": "Option",
"params": [
{
"displayName": "AccountId",
"namespace": "ink_env::types",
"info": 6,
"type": "AccountId"
}
],
"info": 5,
"sub": {
"displayName": "AccountId",
"namespace": "ink_env::types",
"info": 6,
"type": "AccountId"
},
"info": 5,
"type": "Option<AccountId>"
}
]
@@ -33,15 +33,6 @@
{
"displayName": "Entry",
"namespace": "ink_storage::collections::stash",
"params": [
{
"displayName": "AccountId",
"namespace": "ink_env::types",
"info": 6,
"type": "AccountId"
}
],
"info": 3,
"sub": [
{
"displayName": "VacantEntry",
@@ -70,6 +61,7 @@
"name": "Occupied"
}
],
"info": 3,
"type": "{\"_enum\":{\"Vacant\":\"VacantEntry\",\"Occupied\":\"AccountId\"}}"
},
{
@@ -112,13 +104,6 @@
{
"displayName": "ValueEntry",
"namespace": "ink_storage::collections::hashmap",
"params": [
{
"info": 6,
"type": "u128"
}
],
"info": 9,
"sub": [
{
"info": 6,
@@ -131,32 +116,12 @@
"name": "key_index"
}
],
"info": 9,
"type": "{\"value\":\"u128\",\"key_index\":\"u32\"}"
},
{
"displayName": "Entry",
"namespace": "ink_storage::collections::stash",
"params": [
{
"info": 10,
"sub": [
{
"displayName": "AccountId",
"namespace": "ink_env::types",
"info": 6,
"type": "AccountId"
},
{
"displayName": "AccountId",
"namespace": "ink_env::types",
"info": 6,
"type": "AccountId"
}
],
"type": "(AccountId, AccountId)"
}
],
"info": 3,
"sub": [
{
"displayName": "VacantEntry",
@@ -197,6 +162,7 @@
"name": "Occupied"
}
],
"info": 3,
"type": "{\"_enum\":{\"Vacant\":\"VacantEntry\",\"Occupied\":\"(AccountId, AccountId)\"}}"
},
{
@@ -223,21 +189,13 @@
},
{
"displayName": "Option",
"params": [
{
"displayName": "AccountId",
"namespace": "ink_env::types",
"info": 6,
"type": "AccountId"
}
],
"info": 5,
"sub": {
"displayName": "AccountId",
"namespace": "ink_env::types",
"info": 6,
"type": "AccountId"
},
"info": 5,
"type": "Option<AccountId>"
}
]
@@ -29,13 +29,6 @@
{
"displayName": "Entry",
"namespace": "ink_storage::collections::stash",
"params": [
{
"info": 6,
"type": "u32"
}
],
"info": 3,
"sub": [
{
"displayName": "VacantEntry",
@@ -62,6 +55,7 @@
"name": "Occupied"
}
],
"info": 3,
"type": "{\"_enum\":{\"Vacant\":\"VacantEntry\",\"Occupied\":\"u32\"}}"
},
{
@@ -85,15 +79,6 @@
{
"displayName": "ValueEntry",
"namespace": "ink_storage::collections::hashmap",
"params": [
{
"displayName": "AccountId",
"namespace": "ink_env::types",
"info": 6,
"type": "AccountId"
}
],
"info": 9,
"sub": [
{
"displayName": "AccountId",
@@ -108,6 +93,7 @@
"name": "key_index"
}
],
"info": 9,
"type": "{\"value\":\"AccountId\",\"key_index\":\"u32\"}"
},
{
@@ -132,15 +118,6 @@
{
"displayName": "Entry",
"namespace": "ink_storage::collections::stash",
"params": [
{
"displayName": "AccountId",
"namespace": "ink_env::types",
"info": 6,
"type": "AccountId"
}
],
"info": 3,
"sub": [
{
"displayName": "VacantEntry",
@@ -169,18 +146,12 @@
"name": "Occupied"
}
],
"info": 3,
"type": "{\"_enum\":{\"Vacant\":\"VacantEntry\",\"Occupied\":\"AccountId\"}}"
},
{
"displayName": "ValueEntry",
"namespace": "ink_storage::collections::hashmap",
"params": [
{
"info": 6,
"type": "u32"
}
],
"info": 9,
"sub": [
{
"info": 6,
@@ -193,32 +164,12 @@
"name": "key_index"
}
],
"info": 9,
"type": "{\"value\":\"u32\",\"key_index\":\"u32\"}"
},
{
"displayName": "Entry",
"namespace": "ink_storage::collections::stash",
"params": [
{
"info": 10,
"sub": [
{
"displayName": "AccountId",
"namespace": "ink_env::types",
"info": 6,
"type": "AccountId"
},
{
"displayName": "AccountId",
"namespace": "ink_env::types",
"info": 6,
"type": "AccountId"
}
],
"type": "(AccountId, AccountId)"
}
],
"info": 3,
"sub": [
{
"displayName": "VacantEntry",
@@ -259,6 +210,7 @@
"name": "Occupied"
}
],
"info": 3,
"type": "{\"_enum\":{\"Vacant\":\"VacantEntry\",\"Occupied\":\"(AccountId, AccountId)\"}}"
},
{
@@ -282,13 +234,6 @@
{
"displayName": "ValueEntry",
"namespace": "ink_storage::collections::hashmap",
"params": [
{
"info": 6,
"type": "bool"
}
],
"info": 9,
"sub": [
{
"info": 6,
@@ -301,6 +246,7 @@
"name": "key_index"
}
],
"info": 9,
"type": "{\"value\":\"bool\",\"key_index\":\"u32\"}"
},
{
@@ -309,105 +255,17 @@
},
{
"displayName": "Option",
"params": [
{
"displayName": "AccountId",
"namespace": "ink_env::types",
"info": 6,
"type": "AccountId"
}
],
"info": 5,
"sub": {
"displayName": "AccountId",
"namespace": "ink_env::types",
"info": 6,
"type": "AccountId"
},
"info": 5,
"type": "Option<AccountId>"
},
{
"displayName": "Result",
"params": [
{
"info": 10,
"sub": [],
"type": "()"
},
{
"displayName": "Error",
"namespace": "erc721::erc721",
"info": 3,
"sub": [
{
"ext": {
"discriminant": 0
},
"info": 6,
"name": "NotOwner",
"type": "Null"
},
{
"ext": {
"discriminant": 1
},
"info": 6,
"name": "NotApproved",
"type": "Null"
},
{
"ext": {
"discriminant": 2
},
"info": 6,
"name": "TokenExists",
"type": "Null"
},
{
"ext": {
"discriminant": 3
},
"info": 6,
"name": "TokenNotFound",
"type": "Null"
},
{
"ext": {
"discriminant": 4
},
"info": 6,
"name": "CannotInsert",
"type": "Null"
},
{
"ext": {
"discriminant": 5
},
"info": 6,
"name": "CannotRemove",
"type": "Null"
},
{
"ext": {
"discriminant": 6
},
"info": 6,
"name": "CannotFetchValue",
"type": "Null"
},
{
"ext": {
"discriminant": 7
},
"info": 6,
"name": "NotAllowed",
"type": "Null"
}
],
"type": "{ _enum: [\"NotOwner\", \"NotApproved\", \"TokenExists\", \"TokenNotFound\", \"CannotInsert\", \"CannotRemove\", \"CannotFetchValue\", \"NotAllowed\"] }"
}
],
"info": 7,
"sub": [
{
"name": "Ok",
@@ -486,9 +344,10 @@
"type": "Null"
}
],
"type": "{ _enum: [\"NotOwner\", \"NotApproved\", \"TokenExists\", \"TokenNotFound\", \"CannotInsert\", \"CannotRemove\", \"CannotFetchValue\", \"NotAllowed\"] }"
"type": "{\"_enum\":[\"NotOwner\",\"NotApproved\",\"TokenExists\",\"TokenNotFound\",\"CannotInsert\",\"CannotRemove\",\"CannotFetchValue\",\"NotAllowed\"]}"
}
],
"info": 7,
"type": "Result<(), Error>"
},
{
@@ -566,6 +425,6 @@
"type": "Null"
}
],
"type": "{ _enum: [\"NotOwner\", \"NotApproved\", \"TokenExists\", \"TokenNotFound\", \"CannotInsert\", \"CannotRemove\", \"CannotFetchValue\", \"NotAllowed\"] }"
"type": "{\"_enum\":[\"NotOwner\",\"NotApproved\",\"TokenExists\",\"TokenNotFound\",\"CannotInsert\",\"CannotRemove\",\"CannotFetchValue\",\"NotAllowed\"]}"
}
]
@@ -29,25 +29,6 @@
{
"displayName": "Entry",
"namespace": "ink_storage::collections::stash",
"params": [
{
"info": 10,
"sub": [
{
"info": 6,
"type": "u32"
},
{
"displayName": "AccountId",
"namespace": "ink_env::types",
"info": 6,
"type": "AccountId"
}
],
"type": "(u32, AccountId)"
}
],
"info": 3,
"sub": [
{
"displayName": "VacantEntry",
@@ -86,6 +67,7 @@
"name": "Occupied"
}
],
"info": 3,
"type": "{\"_enum\":{\"Vacant\":\"VacantEntry\",\"Occupied\":\"(u32, AccountId)\"}}"
},
{
@@ -144,14 +126,6 @@
{
"displayName": "ValueEntry",
"namespace": "ink_storage::collections::hashmap",
"params": [
{
"info": 10,
"sub": [],
"type": "()"
}
],
"info": 9,
"sub": [
{
"info": 10,
@@ -165,6 +139,7 @@
"name": "key_index"
}
],
"info": 9,
"type": "{\"value\":\"()\",\"key_index\":\"u32\"}"
},
{
@@ -175,13 +150,6 @@
{
"displayName": "Entry",
"namespace": "ink_storage::collections::stash",
"params": [
{
"info": 6,
"type": "u32"
}
],
"info": 3,
"sub": [
{
"displayName": "VacantEntry",
@@ -208,18 +176,12 @@
"name": "Occupied"
}
],
"info": 3,
"type": "{\"_enum\":{\"Vacant\":\"VacantEntry\",\"Occupied\":\"u32\"}}"
},
{
"displayName": "ValueEntry",
"namespace": "ink_storage::collections::hashmap",
"params": [
{
"info": 6,
"type": "u32"
}
],
"info": 9,
"sub": [
{
"info": 6,
@@ -232,58 +194,12 @@
"name": "key_index"
}
],
"info": 9,
"type": "{\"value\":\"u32\",\"key_index\":\"u32\"}"
},
{
"displayName": "Entry",
"namespace": "ink_storage::collections::stash",
"params": [
{
"displayName": "Transaction",
"namespace": "multisig_plain::multisig_plain",
"info": 9,
"sub": [
{
"displayName": "AccountId",
"namespace": "ink_env::types",
"info": 6,
"type": "AccountId",
"name": "callee"
},
{
"info": 12,
"length": 4,
"sub": {
"info": 6,
"type": "u8"
},
"type": "[u8;4]",
"name": "selector"
},
{
"info": 11,
"sub": {
"info": 6,
"type": "u8"
},
"type": "Vec<u8>",
"name": "input"
},
{
"info": 6,
"type": "u128",
"name": "transferred_value"
},
{
"info": 6,
"type": "u64",
"name": "gas_limit"
}
],
"type": "{\"callee\":\"AccountId\",\"selector\":\"[u8;4]\",\"input\":\"Vec<u8>\",\"transferred_value\":\"u128\",\"gas_limit\":\"u64\"}"
}
],
"info": 3,
"sub": [
{
"displayName": "VacantEntry",
@@ -350,6 +266,7 @@
"name": "Occupied"
}
],
"info": 3,
"type": "{\"_enum\":{\"Vacant\":\"VacantEntry\",\"Occupied\":\"Transaction\"}}"
},
{
@@ -424,15 +341,6 @@
{
"displayName": "Entry",
"namespace": "ink_storage::collections::stash",
"params": [
{
"displayName": "AccountId",
"namespace": "ink_env::types",
"info": 6,
"type": "AccountId"
}
],
"info": 3,
"sub": [
{
"displayName": "VacantEntry",
@@ -461,6 +369,7 @@
"name": "Occupied"
}
],
"info": 3,
"type": "{\"_enum\":{\"Vacant\":\"VacantEntry\",\"Occupied\":\"AccountId\"}}"
},
{
@@ -523,19 +432,6 @@
},
{
"displayName": "Result",
"params": [
{
"info": 10,
"sub": [],
"type": "()"
},
{
"info": 10,
"sub": [],
"type": "()"
}
],
"info": 7,
"sub": [
{
"name": "Ok",
@@ -550,26 +446,11 @@
"type": "()"
}
],
"info": 7,
"type": "Result<(), ()>"
},
{
"displayName": "Result",
"params": [
{
"info": 11,
"sub": {
"info": 6,
"type": "u8"
},
"type": "Vec<u8>"
},
{
"info": 10,
"sub": [],
"type": "()"
}
],
"info": 7,
"sub": [
{
"name": "Ok",
@@ -587,56 +468,15 @@
"type": "()"
}
],
"info": 7,
"type": "Result<Vec<u8>, ()>"
},
{
"displayName": "Result",
"params": [
{
"displayName": "Option",
"params": [
{
"info": 11,
"sub": {
"info": 6,
"type": "u8"
},
"type": "Vec<u8>"
}
],
"info": 5,
"sub": {
"info": 11,
"sub": {
"info": 6,
"type": "u8"
},
"type": "Vec<u8>"
},
"type": "Option<Vec<u8>>"
},
{
"info": 10,
"sub": [],
"type": "()"
}
],
"info": 7,
"sub": [
{
"name": "Ok",
"displayName": "Option",
"params": [
{
"info": 11,
"sub": {
"info": 6,
"type": "u8"
},
"type": "Vec<u8>"
}
],
"info": 5,
"sub": {
"info": 11,
"sub": {
@@ -645,6 +485,7 @@
},
"type": "Vec<u8>"
},
"info": 5,
"type": "Option<Vec<u8>>"
},
{
@@ -654,21 +495,11 @@
"type": "()"
}
],
"info": 7,
"type": "Result<Option<Vec<u8>>, ()>"
},
{
"displayName": "Option",
"params": [
{
"info": 11,
"sub": {
"info": 6,
"type": "u8"
},
"type": "Vec<u8>"
}
],
"info": 5,
"sub": {
"info": 11,
"sub": {
@@ -677,6 +508,7 @@
},
"type": "Vec<u8>"
},
"info": 5,
"type": "Option<Vec<u8>>"
}
]
]
@@ -0,0 +1,28 @@
[
{
"info": 6,
"type": "u256"
},
{
"info": 6,
"type": "u8"
},
{
"info": 12,
"length": 32,
"sub": {
"info": 6,
"type": "u8"
},
"type": "[u8;32]"
},
{
"displayName": "AccountId",
"info": 6,
"type": "AccountId"
},
{
"info": 6,
"type": "Text"
}
]
@@ -0,0 +1,422 @@
[
{
"info": 6,
"type": "i32"
},
{
"info": 6,
"type": "u32"
},
{
"info": 6,
"type": "u8"
},
{
"displayName": "Variant",
"namespace": "enum_example::enum_example",
"info": 3,
"sub": [
{
"info": 10,
"sub": [],
"name": "None",
"type": "()"
},
{
"displayName": "Weekday",
"namespace": "enum_example::enum_example",
"info": 3,
"sub": [
{
"ext": {
"discriminant": 0
},
"info": 6,
"name": "Monday",
"type": "Null"
},
{
"ext": {
"discriminant": 1
},
"info": 6,
"name": "Tuesday",
"type": "Null"
},
{
"ext": {
"discriminant": 2
},
"info": 6,
"name": "Wednesday",
"type": "Null"
},
{
"ext": {
"discriminant": 3
},
"info": 6,
"name": "Thursday",
"type": "Null"
},
{
"ext": {
"discriminant": 4
},
"info": 6,
"name": "Friday",
"type": "Null"
},
{
"ext": {
"discriminant": 5
},
"info": 6,
"name": "Saturday",
"type": "Null"
},
{
"ext": {
"discriminant": 6
},
"info": 6,
"name": "Sunday",
"type": "Null"
}
],
"type": "{\"_enum\":[\"Monday\",\"Tuesday\",\"Wednesday\",\"Thursday\",\"Friday\",\"Saturday\",\"Sunday\"]}",
"name": "Weekday"
},
{
"displayName": "TupleMaybeSigned",
"namespace": "enum_example::enum_example",
"info": 3,
"sub": [
{
"info": 6,
"type": "i32",
"name": "Signed"
},
{
"info": 6,
"type": "u32",
"name": "Unsigned"
}
],
"type": "{\"_enum\":{\"Signed\":\"i32\",\"Unsigned\":\"u32\"}}",
"name": "TupleMaybeSigned"
},
{
"displayName": "NamedMaybeSigned",
"namespace": "enum_example::enum_example",
"info": 3,
"sub": [
{
"info": 9,
"sub": [
{
"info": 6,
"type": "i32",
"name": "value"
}
],
"name": "Signed",
"type": "{\"value\":\"i32\"}"
},
{
"info": 9,
"sub": [
{
"info": 6,
"type": "u32",
"name": "value"
}
],
"name": "Unsigned",
"type": "{\"value\":\"u32\"}"
}
],
"type": "{\"_enum\":{\"Signed\":\"{\\\"value\\\":\\\"i32\\\"}\",\"Unsigned\":\"{\\\"value\\\":\\\"u32\\\"}\"}}",
"name": "NamedMaybeSigned"
},
{
"displayName": "Color",
"namespace": "enum_example::enum_example",
"info": 3,
"sub": [
{
"info": 10,
"sub": [],
"name": "Red",
"type": "()"
},
{
"info": 10,
"sub": [],
"name": "Blue",
"type": "()"
},
{
"info": 10,
"sub": [],
"name": "Green",
"type": "()"
},
{
"info": 10,
"sub": [],
"name": "Yellow",
"type": "()"
},
{
"info": 9,
"sub": [
{
"info": 6,
"type": "u8",
"name": "r"
},
{
"info": 6,
"type": "u8",
"name": "g"
},
{
"info": 6,
"type": "u8",
"name": "b"
}
],
"name": "Rgb",
"type": "{\"r\":\"u8\",\"g\":\"u8\",\"b\":\"u8\"}"
},
{
"info": 9,
"sub": [
{
"info": 6,
"type": "u8",
"name": "r"
},
{
"info": 6,
"type": "u8",
"name": "g"
},
{
"info": 6,
"type": "u8",
"name": "b"
},
{
"info": 6,
"type": "u8",
"name": "a"
}
],
"name": "Rgba",
"type": "{\"r\":\"u8\",\"g\":\"u8\",\"b\":\"u8\",\"a\":\"u8\"}"
}
],
"type": "{\"_enum\":{\"Red\":\"()\",\"Blue\":\"()\",\"Green\":\"()\",\"Yellow\":\"()\",\"Rgb\":\"{\\\"r\\\":\\\"u8\\\",\\\"g\\\":\\\"u8\\\",\\\"b\\\":\\\"u8\\\"}\",\"Rgba\":\"{\\\"r\\\":\\\"u8\\\",\\\"g\\\":\\\"u8\\\",\\\"b\\\":\\\"u8\\\",\\\"a\\\":\\\"u8\\\"}\"}}",
"name": "Color"
}
],
"type": "{\"_enum\":{\"None\":\"()\",\"Weekday\":\"Weekday\",\"TupleMaybeSigned\":\"TupleMaybeSigned\",\"NamedMaybeSigned\":\"NamedMaybeSigned\",\"Color\":\"Color\"}}"
},
{
"displayName": "Weekday",
"namespace": "enum_example::enum_example",
"info": 3,
"sub": [
{
"ext": {
"discriminant": 0
},
"info": 6,
"name": "Monday",
"type": "Null"
},
{
"ext": {
"discriminant": 1
},
"info": 6,
"name": "Tuesday",
"type": "Null"
},
{
"ext": {
"discriminant": 2
},
"info": 6,
"name": "Wednesday",
"type": "Null"
},
{
"ext": {
"discriminant": 3
},
"info": 6,
"name": "Thursday",
"type": "Null"
},
{
"ext": {
"discriminant": 4
},
"info": 6,
"name": "Friday",
"type": "Null"
},
{
"ext": {
"discriminant": 5
},
"info": 6,
"name": "Saturday",
"type": "Null"
},
{
"ext": {
"discriminant": 6
},
"info": 6,
"name": "Sunday",
"type": "Null"
}
],
"type": "{\"_enum\":[\"Monday\",\"Tuesday\",\"Wednesday\",\"Thursday\",\"Friday\",\"Saturday\",\"Sunday\"]}"
},
{
"displayName": "TupleMaybeSigned",
"namespace": "enum_example::enum_example",
"info": 3,
"sub": [
{
"info": 6,
"type": "i32",
"name": "Signed"
},
{
"info": 6,
"type": "u32",
"name": "Unsigned"
}
],
"type": "{\"_enum\":{\"Signed\":\"i32\",\"Unsigned\":\"u32\"}}"
},
{
"displayName": "NamedMaybeSigned",
"namespace": "enum_example::enum_example",
"info": 3,
"sub": [
{
"info": 9,
"sub": [
{
"info": 6,
"type": "i32",
"name": "value"
}
],
"name": "Signed",
"type": "{\"value\":\"i32\"}"
},
{
"info": 9,
"sub": [
{
"info": 6,
"type": "u32",
"name": "value"
}
],
"name": "Unsigned",
"type": "{\"value\":\"u32\"}"
}
],
"type": "{\"_enum\":{\"Signed\":\"{\\\"value\\\":\\\"i32\\\"}\",\"Unsigned\":\"{\\\"value\\\":\\\"u32\\\"}\"}}"
},
{
"displayName": "Color",
"namespace": "enum_example::enum_example",
"info": 3,
"sub": [
{
"info": 10,
"sub": [],
"name": "Red",
"type": "()"
},
{
"info": 10,
"sub": [],
"name": "Blue",
"type": "()"
},
{
"info": 10,
"sub": [],
"name": "Green",
"type": "()"
},
{
"info": 10,
"sub": [],
"name": "Yellow",
"type": "()"
},
{
"info": 9,
"sub": [
{
"info": 6,
"type": "u8",
"name": "r"
},
{
"info": 6,
"type": "u8",
"name": "g"
},
{
"info": 6,
"type": "u8",
"name": "b"
}
],
"name": "Rgb",
"type": "{\"r\":\"u8\",\"g\":\"u8\",\"b\":\"u8\"}"
},
{
"info": 9,
"sub": [
{
"info": 6,
"type": "u8",
"name": "r"
},
{
"info": 6,
"type": "u8",
"name": "g"
},
{
"info": 6,
"type": "u8",
"name": "b"
},
{
"info": 6,
"type": "u8",
"name": "a"
}
],
"name": "Rgba",
"type": "{\"r\":\"u8\",\"g\":\"u8\",\"b\":\"u8\",\"a\":\"u8\"}"
}
],
"type": "{\"_enum\":{\"Red\":\"()\",\"Blue\":\"()\",\"Green\":\"()\",\"Yellow\":\"()\",\"Rgb\":\"{\\\"r\\\":\\\"u8\\\",\\\"g\\\":\\\"u8\\\",\\\"b\\\":\\\"u8\\\"}\",\"Rgba\":\"{\\\"r\\\":\\\"u8\\\",\\\"g\\\":\\\"u8\\\",\\\"b\\\":\\\"u8\\\",\\\"a\\\":\\\"u8\\\"}\"}}"
}
]
@@ -33,15 +33,6 @@
{
"displayName": "Entry",
"namespace": "ink_storage::collections::stash",
"params": [
{
"displayName": "AccountId",
"namespace": "ink_env::types",
"info": 6,
"type": "AccountId"
}
],
"info": 3,
"sub": [
{
"displayName": "VacantEntry",
@@ -70,6 +61,7 @@
"name": "Occupied"
}
],
"info": 3,
"type": "{\"_enum\":{\"Vacant\":\"VacantEntry\",\"Occupied\":\"AccountId\"}}"
},
{
@@ -112,13 +104,6 @@
{
"displayName": "ValueEntry",
"namespace": "ink_storage::collections::hashmap",
"params": [
{
"info": 6,
"type": "u128"
}
],
"info": 9,
"sub": [
{
"info": 6,
@@ -131,32 +116,12 @@
"name": "key_index"
}
],
"info": 9,
"type": "{\"value\":\"u128\",\"key_index\":\"u32\"}"
},
{
"displayName": "Entry",
"namespace": "ink_storage::collections::stash",
"params": [
{
"info": 10,
"sub": [
{
"displayName": "AccountId",
"namespace": "ink_env::types",
"info": 6,
"type": "AccountId"
},
{
"displayName": "AccountId",
"namespace": "ink_env::types",
"info": 6,
"type": "AccountId"
}
],
"type": "(AccountId, AccountId)"
}
],
"info": 3,
"sub": [
{
"displayName": "VacantEntry",
@@ -197,6 +162,7 @@
"name": "Occupied"
}
],
"info": 3,
"type": "{\"_enum\":{\"Vacant\":\"VacantEntry\",\"Occupied\":\"(AccountId, AccountId)\"}}"
},
{
@@ -227,21 +193,13 @@
},
{
"displayName": "Option",
"params": [
{
"displayName": "AccountId",
"namespace": "ink_env::types",
"info": 6,
"type": "AccountId"
}
],
"info": 5,
"sub": {
"displayName": "AccountId",
"namespace": "ink_env::types",
"info": 6,
"type": "AccountId"
},
"info": 5,
"type": "Option<AccountId>"
}
]
]
+18 -3
View File
@@ -1,6 +1,21 @@
// Copyright 2017-2020 @polkadot/api-contract authors & contributors
// SPDX-License-Identifier: Apache-2.0
export * from './ink';
export * from './solang';
export * from './user';
import * as ink from './ink';
import * as solang from './solang';
import * as user from './user';
const all: Record<string, any> = {};
function addExport (type: string, abis: Record<string, any>): void {
Object.keys(abis).forEach((key): void => {
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
all[`${type}_${key}`] = abis[key];
});
}
addExport('ink', ink);
addExport('solang', solang);
addExport('user', user);
export default all;
@@ -0,0 +1,107 @@
{
"metadataVersion": "0.1.0",
"source": {
"hash": "0x98086d5ccadd437459b812682380250f51a3034272cd1108e499acc0cafe9f42",
"language": "ink! 3.0.0-rc2",
"compiler": "rustc 1.49.0-nightly",
"wasm": "0x0061736d01000000012c0860027f7f0060037f7f7f0060017f017f60017f006000017f60037f7f7f017f60047f7f7f7f0060017f017e02880106057365616c30107365616c5f6765745f73746f726167650005057365616c30107365616c5f7365745f73746f726167650001057365616c30167365616c5f76616c75655f7472616e736665727265640000057365616c300a7365616c5f696e7075740000057365616c300b7365616c5f72657475726e000103656e76066d656d6f72790201021003121102020002000100070303060402040503010608017f01418080040b071102066465706c6f7900100463616c6c00120a8e1111c90101017f230041406a22012400200141206a200041186a290300370300200141186a200041106a290300370300200141106a200041086a2903003703002001420037032820012000290300370308200141086a1006200141808001360234200141a4800436023020014180800136023841a48004200141386a10002100200141306a20012802381007024002400240024020000e0401000002000b000b20012001290330370338200141386a100841ff017122004102470d01000b000b200141406b240020004100470b6001037e200029032021012000420137032020002001200029030022027c22013703002000200029030822032001200254ad7c22013703082000200029031022022001200354ad7c2201370310200020002903182001200254ad7c37031820000b4901037f230041106b22022400200028020421032000410036020420002802002104200041a48004360200200241086a200120042003100f20002002290308370200200241106a24000b4201027f230041106b22012400200141086a2000100b20012d0009210020012d00082102200141106a240041024101410220004101461b410020001b20024101711b0b8f0101017f230041406a22022400200241206a200141186a290300370300200241186a200141106a290300370300200241106a200141086a2903003703002002420037032820022001290300370308200241086a1006200241386a41808001360200200241a48004360234200241003602302002200241306a2000100a200228020020022802041001200241406b24000b9d0101037f230041106b22032400200141086a220428020021052004410036020020012802042104200141a48004360204200320023a000f2003410120042005100f024020032802044101460440200328020020032d000f3a000020014100360208200141a480043602042005450d0120012005417f6a3602082001200441016a3602042000410136020420002004360200200341106a24000f0b000b000b4801027f230041106b22022400200241003a000f024020012002410f6a4101101345044020022d000f21010c010b410121030b200020013a0001200020033a0000200241106a24000b890101027f230041106b22012400200142003c000c200142003e0208027f0340200241044604402001280208210241000c020b20012000100b20012d0000410171450440200141086a20026a20012d00013a00002001200241016a22023a000c0c010b0b200241ff01710440200141003a000c0b4100210241010b200141106a2400ad2002ad420886840b2201017f230041106b220124002001200036020c2001410c6a2802002d0000100e000b4601017f230041206b22012400200141186a41808001360200200141a4800436021420014100360210200141086a200141106a2000100a41002001280208200128020c1004000b2300410020014d0440200320014f044020002001360204200020023602000f0b000b000b15004100101141ff0171410274418080046a2802000bd80502057f017e230041306b220124000240027f024002402000044020014180800136020c200141a48004360208200141086a10142001200129030837031041012103200141106a100c2206a722054101710440410121020c030b200642ffffffffff1f832206422088a721002006421888a721042006421088a72102200541087641ff01712205411e470440200541c00147200041f3014772200241ff017141960147720d0241002102200441ff017141a501460d030c020b200041d60047200241ff017141dc0047720d014100210241002103200441ff017141a401470d010c020b20014180800136020c200141a48004360208200141086a101420012001290308370310410321020240200141106a100c2206a722044101710d00200642ffffffffff1f832206422088a721002006421888a721032006421088a7210202400240200441087641ff0171220441ea00470440200441d101472000412b4772200241ff017141830147720d02200341ff017141d100460d010c020b200041e20147200241ff0171413747720d0141022102200341ff01714112470d010c020b41032102200141106a100841ff017122004102460d01200041004721020c010b410321020b4106200241034622030d021a4106200220031b22024102460440200141286a4200370300200141206a4200370300200141186a4200370300200142003703104100200141106a100941080c030b200141286a4200370300200141206a4200370300200141186a4200370300200142003703102002410171200141106a100941080c020b41012102410121030b410620020d001a2003450d01200141286a4200370300200141206a4200370300200141186a420037030020014200370310200141106a1005410173200141106a100941080b200141306a24000f0b200141286a4200370300200141206a4200370300200141186a4200370300200142003703102001200141106a10053a0008200141086a100d000ba90102027f027e230041206b22002400200041808001360204200041a4800436020020004180800136021041a48004200041106a100220002000280210100720002000290300370308200041186a2201420037030020004200370310027f4101200041086a200041106a411010130d001a200129030021022000290310210341000b200220038450457245044041011011200041206a240041ff0171410274418080046a2802000f0b000b45000240200028020420024f047f2001200028020020021015200028020422012002490d012000200120026b3602042000200028020020026a36020041000541010b0f0b000b3301017f230041106b220124002001200028020436020c20002802002001410c6a10032000200128020c1007200141106a24000b2c01017f037f2002200346047f200005200020036a200120036a2d00003a0000200341016a21030c010b0b1a0b0b250100418080040b1d0100000002000000030000000400000005000000060000000700000008"
},
"contract": {
"name": "flipper",
"version": "3.0.0-rc2",
"authors": [
"Parity Technologies <admin@parity.io>"
]
},
"spec": {
"constructors": [
{
"args": [
{
"name": "init_value",
"type": {
"displayName": [
"bool"
],
"type": 1
}
}
],
"docs": [
" Creates a new flipper smart contract initialized with the given value."
],
"name": [
"new"
],
"selector": "0xd183512b"
},
{
"args": [],
"docs": [
" Creates a new flipper smart contract initialized to `false`."
],
"name": [
"default"
],
"selector": "0x6a3712e2"
}
],
"docs": [],
"events": [],
"messages": [
{
"args": [],
"docs": [
" Flips the current value of the Flipper's bool."
],
"mutates": true,
"name": [
"flip"
],
"payable": false,
"returnType": null,
"selector": "0xc096a5f3"
},
{
"args": [],
"docs": [
" Returns the current value of the Flipper's bool."
],
"mutates": false,
"name": [
"get"
],
"payable": false,
"returnType": {
"displayName": [
"bool"
],
"type": 1
},
"selector": "0x1e5ca456"
}
]
},
"storage": {
"struct": {
"fields": [
{
"layout": {
"cell": {
"key": "0x0000000000000000000000000000000000000000000000000000000000000000",
"ty": 1
}
},
"name": "value"
}
]
}
},
"types": [
{
"def": {
"primitive": "bool"
}
}
]
}
@@ -0,0 +1,299 @@
{
"contract": {
"authors": [
"unknown"
],
"name": "AssetTransfer",
"version": "0.0.1"
},
"metadataVersion": "0.1.0",
"source": {
"compiler": "solang 0.1.4",
"hash": "0x7d163f445bec3d33e90d0f60bda40acd42f2760dbc1b731616af70a6001e05c7",
"language": "Solidity 0.1.4"
},
"spec": {
"constructors": [
{
"args": [],
"docs": [
""
],
"name": "new",
"selector": "0x861731d5"
}
],
"events": [
{
"args": [
{
"indexed": false,
"name": "_newUser",
"type": {
"display_name": [
"AccountId"
],
"type": 4
}
}
],
"docs": [
""
],
"name": "successfulRegistration"
},
{
"args": [
{
"indexed": false,
"name": "sender",
"type": {
"display_name": [
"AccountId"
],
"type": 4
}
},
{
"indexed": false,
"name": "_hexAsset",
"type": {
"display_name": [
"String"
],
"type": 5
}
}
],
"docs": [
""
],
"name": "addedAsset"
},
{
"args": [
{
"indexed": false,
"name": "sender",
"type": {
"display_name": [
"AccountId"
],
"type": 4
}
},
{
"indexed": false,
"name": "receiver",
"type": {
"display_name": [
"AccountId"
],
"type": 4
}
},
{
"indexed": false,
"name": "hexOfAsset",
"type": {
"display_name": [
"String"
],
"type": 5
}
}
],
"docs": [
""
],
"name": "assetSent"
}
],
"messages": [
{
"args": [
{
"name": "_user",
"type": {
"display_name": [
"AccountId"
],
"type": 4
}
}
],
"docs": [
""
],
"mutates": false,
"name": "viewBalance",
"payable": false,
"return_type": {
"display_name": [
"u256"
],
"type": 1
},
"selector": "0xc1a13d1a"
},
{
"args": [
{
"name": "_assetHex",
"type": {
"display_name": [
"String"
],
"type": 5
}
}
],
"docs": [
""
],
"mutates": false,
"name": "findOwner",
"payable": false,
"return_type": {
"display_name": [
"AccountId"
],
"type": 4
},
"selector": "0x63560a8e"
},
{
"args": [
{
"name": "_hexAsset",
"type": {
"display_name": [
"String"
],
"type": 5
}
}
],
"docs": [
""
],
"mutates": true,
"name": "addAsset",
"payable": false,
"return_type": null,
"selector": "0xa7c6b52e"
},
{
"args": [],
"docs": [
""
],
"mutates": true,
"name": "receiveAsset",
"payable": false,
"return_type": {
"display_name": [
"String"
],
"type": 5
},
"selector": "0xb2f3b5bc"
},
{
"args": [
{
"name": "_assetHex",
"type": {
"display_name": [
"String"
],
"type": 5
}
},
{
"name": "_receiver",
"type": {
"display_name": [
"AccountId"
],
"type": 4
}
}
],
"docs": [
""
],
"mutates": true,
"name": "sendAsset",
"payable": false,
"return_type": null,
"selector": "0xd6e5288f"
},
{
"args": [
{
"name": "_newUser",
"type": {
"display_name": [
"AccountId"
],
"type": 4
}
}
],
"docs": [
""
],
"mutates": true,
"name": "register",
"payable": false,
"return_type": null,
"selector": "0x4420e486"
}
]
},
"storage": {
"struct": {
"fields": []
}
},
"types": [
{
"def": {
"primitive": "u256"
}
},
{
"def": {
"primitive": "u8"
}
},
{
"def": {
"array": {
"len": 32,
"type": 2
}
}
},
{
"def": {
"composite": {
"fields": [
{
"type": 3
}
]
}
},
"path": [
"AccountId"
]
},
{
"def": {
"primitive": "str"
}
}
]
}
@@ -0,0 +1,528 @@
{
"metadataVersion": "0.1.0",
"source": {
"hash": "0x1a37c380fe02fe3b670480dff1393b0401788955315d092e39fcc06047f1413c",
"language": "ink! 3.0.0-rc2",
"compiler": "rustc 1.49.0-nightly"
},
"contract": {
"name": "enum_example",
"version": "0.1.0",
"authors": [
"[your_name] <[your_email]>"
]
},
"spec": {
"constructors": [
{
"args": [],
"docs": [],
"name": [
"new"
],
"selector": "0xd183512b"
}
],
"docs": [],
"events": [],
"messages": [
{
"args": [
{
"name": "variant",
"type": {
"displayName": [
"Variant"
],
"type": 4
}
}
],
"docs": [],
"mutates": true,
"name": [
"set_variant"
],
"payable": false,
"returnType": null,
"selector": "0x4fa6b9cf"
},
{
"args": [],
"docs": [],
"mutates": false,
"name": [
"get_variant"
],
"payable": false,
"returnType": {
"displayName": [
"Variant"
],
"type": 4
},
"selector": "0x1d5962d1"
}
]
},
"storage": {
"struct": {
"fields": [
{
"layout": {
"enum": {
"dispatchKey": "0x0000000000000000000000000000000000000000000000000000000000000000",
"variants": {
"0": {
"fields": []
},
"1": {
"fields": [
{
"layout": {
"enum": {
"dispatchKey": "0x0100000000000000000000000000000000000000000000000000000000000000",
"variants": {
"0": {
"fields": []
},
"1": {
"fields": []
},
"2": {
"fields": []
},
"3": {
"fields": []
},
"4": {
"fields": []
},
"5": {
"fields": []
},
"6": {
"fields": []
}
}
}
},
"name": null
}
]
},
"2": {
"fields": [
{
"layout": {
"enum": {
"dispatchKey": "0x0100000000000000000000000000000000000000000000000000000000000000",
"variants": {
"0": {
"fields": [
{
"layout": {
"cell": {
"key": "0x0200000000000000000000000000000000000000000000000000000000000000",
"ty": 1
}
},
"name": null
}
]
},
"1": {
"fields": [
{
"layout": {
"cell": {
"key": "0x0200000000000000000000000000000000000000000000000000000000000000",
"ty": 2
}
},
"name": null
}
]
}
}
}
},
"name": null
}
]
},
"3": {
"fields": [
{
"layout": {
"enum": {
"dispatchKey": "0x0100000000000000000000000000000000000000000000000000000000000000",
"variants": {
"0": {
"fields": [
{
"layout": {
"cell": {
"key": "0x0200000000000000000000000000000000000000000000000000000000000000",
"ty": 1
}
},
"name": "value"
}
]
},
"1": {
"fields": [
{
"layout": {
"cell": {
"key": "0x0200000000000000000000000000000000000000000000000000000000000000",
"ty": 2
}
},
"name": "value"
}
]
}
}
}
},
"name": null
}
]
},
"4": {
"fields": [
{
"layout": {
"enum": {
"dispatchKey": "0x0100000000000000000000000000000000000000000000000000000000000000",
"variants": {
"0": {
"fields": []
},
"1": {
"fields": []
},
"2": {
"fields": []
},
"3": {
"fields": []
},
"4": {
"fields": [
{
"layout": {
"cell": {
"key": "0x0200000000000000000000000000000000000000000000000000000000000000",
"ty": 3
}
},
"name": "r"
},
{
"layout": {
"cell": {
"key": "0x0300000000000000000000000000000000000000000000000000000000000000",
"ty": 3
}
},
"name": "g"
},
{
"layout": {
"cell": {
"key": "0x0400000000000000000000000000000000000000000000000000000000000000",
"ty": 3
}
},
"name": "b"
}
]
},
"5": {
"fields": [
{
"layout": {
"cell": {
"key": "0x0200000000000000000000000000000000000000000000000000000000000000",
"ty": 3
}
},
"name": "r"
},
{
"layout": {
"cell": {
"key": "0x0300000000000000000000000000000000000000000000000000000000000000",
"ty": 3
}
},
"name": "g"
},
{
"layout": {
"cell": {
"key": "0x0400000000000000000000000000000000000000000000000000000000000000",
"ty": 3
}
},
"name": "b"
},
{
"layout": {
"cell": {
"key": "0x0500000000000000000000000000000000000000000000000000000000000000",
"ty": 3
}
},
"name": "a"
}
]
}
}
}
},
"name": null
}
]
}
}
}
},
"name": "last"
}
]
}
},
"types": [
{
"def": {
"primitive": "i32"
}
},
{
"def": {
"primitive": "u32"
}
},
{
"def": {
"primitive": "u8"
}
},
{
"def": {
"variant": {
"variants": [
{
"name": "None"
},
{
"fields": [
{
"type": 5
}
],
"name": "Weekday"
},
{
"fields": [
{
"type": 6
}
],
"name": "TupleMaybeSigned"
},
{
"fields": [
{
"type": 7
}
],
"name": "NamedMaybeSigned"
},
{
"fields": [
{
"type": 8
}
],
"name": "Color"
}
]
}
},
"path": [
"enum_example",
"enum_example",
"Variant"
]
},
{
"def": {
"variant": {
"variants": [
{
"discriminant": 0,
"name": "Monday"
},
{
"discriminant": 1,
"name": "Tuesday"
},
{
"discriminant": 2,
"name": "Wednesday"
},
{
"discriminant": 3,
"name": "Thursday"
},
{
"discriminant": 4,
"name": "Friday"
},
{
"discriminant": 5,
"name": "Saturday"
},
{
"discriminant": 6,
"name": "Sunday"
}
]
}
},
"path": [
"enum_example",
"enum_example",
"Weekday"
]
},
{
"def": {
"variant": {
"variants": [
{
"fields": [
{
"type": 1
}
],
"name": "Signed"
},
{
"fields": [
{
"type": 2
}
],
"name": "Unsigned"
}
]
}
},
"path": [
"enum_example",
"enum_example",
"TupleMaybeSigned"
]
},
{
"def": {
"variant": {
"variants": [
{
"fields": [
{
"name": "value",
"type": 1
}
],
"name": "Signed"
},
{
"fields": [
{
"name": "value",
"type": 2
}
],
"name": "Unsigned"
}
]
}
},
"path": [
"enum_example",
"enum_example",
"NamedMaybeSigned"
]
},
{
"def": {
"variant": {
"variants": [
{
"name": "Red"
},
{
"name": "Blue"
},
{
"name": "Green"
},
{
"name": "Yellow"
},
{
"fields": [
{
"name": "r",
"type": 3
},
{
"name": "g",
"type": 3
},
{
"name": "b",
"type": 3
}
],
"name": "Rgb"
},
{
"fields": [
{
"name": "r",
"type": 3
},
{
"name": "g",
"type": 3
},
{
"name": "b",
"type": 3
},
{
"name": "a",
"type": 3
}
],
"name": "Rgba"
}
]
}
},
"path": [
"enum_example",
"enum_example",
"Color"
]
}
]
}
@@ -1,4 +1,6 @@
// Copyright 2017-2020 @polkadot/api-contract authors & contributors
// SPDX-License-Identifier: Apache-2.0
export { default as assetTransfer } from './assetTransfer.json';
export { default as enumExample } from './enumExample.json';
export { default as withString } from './withString.json';
+13 -23
View File
@@ -1,44 +1,34 @@
{
"name": "@polkadot/api-derive",
"version": "2.4.1",
"version": "2.7.1",
"description": "Common functions used across Polkadot, derived from RPC calls and storage queries.",
"main": "index.js",
"sideEffects": false,
"keywords": [
"Polkadot",
"Promise",
"RxJs"
],
"author": "Jaco Greeff <jacogr@gmail.com>",
"maintainers": [
"Jaco Greeff <jacogr@gmail.com>"
],
"maintainers": [],
"contributors": [],
"license": "Apache-2.0",
"publishConfig": {
"access": "public",
"registry": "https://registry.npmjs.org"
},
"repository": {
"type": "git",
"url": "git+https://github.com/polkadot-js/api.git"
},
"bugs": {
"url": "https://github.com/polkadot-js/api/issues"
},
"repository": "github:polkadot-js/api",
"bugs": "https://github.com/polkadot-js/api/issues",
"homepage": "https://github.com/polkadot-js/api/tree/master/packages/api-derive#readme",
"dependencies": {
"@babel/runtime": "^7.12.1",
"@polkadot/api": "^2.4.1",
"@polkadot/rpc-core": "^2.4.1",
"@polkadot/rpc-provider": "^2.4.1",
"@polkadot/types": "^2.4.1",
"@polkadot/util": "^3.6.1",
"@polkadot/util-crypto": "^3.6.1",
"@babel/runtime": "^7.12.5",
"@polkadot/api": "2.7.1",
"@polkadot/rpc-core": "2.7.1",
"@polkadot/types": "2.7.1",
"@polkadot/util": "^4.1.1",
"@polkadot/util-crypto": "^4.1.1",
"bn.js": "^5.1.3",
"memoizee": "^0.4.14",
"rxjs": "^6.6.3"
},
"devDependencies": {
"@polkadot/keyring": "^3.6.1"
"@polkadot/keyring": "^4.1.1",
"@polkadot/rpc-provider": "2.7.1"
}
}
@@ -6,7 +6,7 @@ import { AccountId, AccountIndex, Address } from '@polkadot/types/interfaces';
import { Observable, of } from 'rxjs';
import { map } from 'rxjs/operators';
import { ApiInterfaceRx } from '@polkadot/api/types';
import { isU8a, assert } from '@polkadot/util';
import { isU8a, assertReturn } from '@polkadot/util';
import { decodeAddress } from '@polkadot/util-crypto';
import { memo } from '../util';
@@ -16,18 +16,14 @@ function retrieve (api: ApiInterfaceRx, address: Address | AccountId | AccountIn
? address
: decodeAddress((address || '').toString());
if (decoded.length === 32) {
if (decoded.length > 8) {
return of(api.registry.createType('AccountId', decoded));
}
const accountIndex = api.registry.createType('AccountIndex', decoded);
return api.derive.accounts.indexToId(accountIndex.toString()).pipe(
map((accountId) => {
assert(accountId, 'Unable to retrieve accountId');
return accountId;
})
map((accountId) => assertReturn(accountId, 'Unable to retrieve accountId'))
);
}
+29 -32
View File
@@ -20,9 +20,17 @@ type FlagsIntermediate = [
AccountId | undefined
];
function isIncludedFn (accountId: AccountId | Address | string): (_: AccountId | Address |string) => boolean {
return function (id: AccountId | Address | string): boolean {
return id.toString() === accountId.toString();
function parseFlags (address: AccountId | Address | string | null | undefined, [electionsMembers, councilMembers, technicalCommitteeMembers, societyMembers, sudoKey]: FlagsIntermediate): DeriveAccountFlags {
const isIncluded = (id: AccountId | Address | string) =>
address
? id.toString() === address.toString()
: false;
return {
isCouncil: (electionsMembers?.map(([id]: ITuple<[AccountId, Balance]>) => id) || councilMembers || []).some(isIncluded),
isSociety: (societyMembers || []).some(isIncluded),
isSudo: sudoKey?.toString() === address?.toString(),
isTechCommittee: (technicalCommitteeMembers || []).some(isIncluded)
};
}
@@ -34,35 +42,24 @@ export function flags (instanceId: string, api: ApiInterfaceRx): (address?: Acco
return memo(instanceId, (address?: AccountId | Address | string | null): Observable<DeriveAccountFlags> => {
const councilSection = api.query.electionsPhragmen ? 'electionsPhragmen' : 'elections';
return (
combineLatest([
address && api.query[councilSection]?.members
? api.query[councilSection].members()
: of(undefined),
address && api.query.council?.members
? api.query.council.members()
: of([]),
address && api.query.technicalCommittee?.members
? api.query.technicalCommittee.members()
: of([]),
address && api.query.society?.members
? api.query.society.members()
: of([]),
address && api.query.sudo?.key
? api.query.sudo.key()
: of(undefined)
]) as Observable<FlagsIntermediate>
).pipe(
map(([electionsMembers, councilMembers, technicalCommitteeMembers, societyMembers, sudoKey]): DeriveAccountFlags => {
const isIncluded = address ? isIncludedFn(address) : (): boolean => false;
return {
isCouncil: (electionsMembers?.map(([id]: ITuple<[AccountId, Balance]>) => id) || councilMembers || []).some(isIncluded),
isSociety: (societyMembers || []).some(isIncluded),
isSudo: sudoKey?.toString() === address?.toString(),
isTechCommittee: (technicalCommitteeMembers || []).some(isIncluded)
};
})
return combineLatest<FlagsIntermediate>([
address && api.query[councilSection]?.members
? api.query[councilSection].members()
: of(undefined),
address && api.query.council?.members
? api.query.council.members()
: of([]),
address && api.query.technicalCommittee?.members
? api.query.technicalCommittee.members()
: of([]),
address && api.query.society?.members
? api.query.society.members()
: of([]),
address && api.query.sudo?.key
? api.query.sudo.key()
: of(undefined)
]).pipe(
map((result) => parseFlags(address, result))
);
});
}
@@ -19,7 +19,7 @@ function retrieve (api: ApiInterfaceRx, address: Address | AccountId | AccountIn
? address
: decodeAddress((address || '').toString());
if (decoded.length === 32) {
if (decoded.length > 8) {
const accountId = api.registry.createType('AccountId', decoded);
return api.derive.accounts.idToIndex(accountId).pipe(
+21 -23
View File
@@ -2,7 +2,7 @@
// SPDX-License-Identifier: Apache-2.0
import { ApiInterfaceRx } from '@polkadot/api/types';
import { AccountId, AccountIndex, Address, Balance, Registration } from '@polkadot/types/interfaces';
import { AccountId, AccountIndex, Address, Balance, IdentityInfoAdditional, Registration } from '@polkadot/types/interfaces';
import { ITuple } from '@polkadot/types/types';
import { DeriveAccountInfo, DeriveAccountRegistration } from '../types';
@@ -13,6 +13,8 @@ import { u8aToString } from '@polkadot/util';
import { memo } from '../util';
const UNDEF_HEX = { toHex: () => undefined };
function dataAsString (data: Data): string | undefined {
return data.isRaw
? u8aToString(data.asRaw.toU8a(true))
@@ -35,6 +37,19 @@ function retrieveNick (api: ApiInterfaceRx, accountId?: AccountId): Observable<s
);
}
function extractOther (additional: IdentityInfoAdditional[]): Record<string, string> {
return additional.reduce((other: Record<string, string>, [_key, _value]): Record<string, string> => {
const key = dataAsString(_key);
const value = dataAsString(_value);
if (key && value) {
other[key] = value;
}
return other;
}, {});
}
function extractIdentity (identityOfOpt?: Option<Registration>, superOf?: [AccountId, Data]): DeriveAccountRegistration {
if (!identityOfOpt?.isSome) {
return { judgements: [] };
@@ -44,32 +59,15 @@ function extractIdentity (identityOfOpt?: Option<Registration>, superOf?: [Accou
const topDisplay = dataAsString(info.display);
return {
display: superOf
? dataAsString(superOf[1]) || topDisplay
: topDisplay,
displayParent: superOf
? topDisplay
: undefined,
display: (superOf && dataAsString(superOf[1])) || topDisplay,
displayParent: superOf && topDisplay,
email: dataAsString(info.email),
image: dataAsString(info.image),
judgements,
legal: dataAsString(info.legal),
other: info.additional.reduce((other: Record<string, string>, [_key, _value]): Record<string, string> => {
const key = dataAsString(_key);
const value = dataAsString(_value);
if (key && value) {
other[key] = value;
}
return other;
}, {}),
parent: superOf
? superOf[0]
: undefined,
pgp: info.pgpFingerprint.isSome
? info.pgpFingerprint.unwrap().toHex()
: undefined,
other: extractOther(info.additional),
parent: superOf && superOf[0],
pgp: info.pgpFingerprint.unwrapOr(UNDEF_HEX).toHex(),
riot: dataAsString(info.riot),
twitter: dataAsString(info.twitter),
web: dataAsString(info.web)
+15 -4
View File
@@ -16,9 +16,16 @@ import { memo } from '../util';
type ResultBalance = [VestingInfo | null, (BalanceLock | BalanceLockTo212)[]];
type Result = [DeriveBalancesAccount, BlockNumber, ResultBalance];
interface AllLocked {
allLocked: boolean,
lockedBalance: Balance,
lockedBreakdown: (BalanceLock | BalanceLockTo212)[],
vestingLocked: Balance
}
const VESTING_ID = '0x76657374696e6720';
function calcBalances (api: ApiInterfaceRx, [{ accountId, accountNonce, freeBalance, frozenFee, frozenMisc, reservedBalance, votingBalance }, bestNumber, [vesting, locks]]: Result): DeriveBalancesAll {
function calcLocked (api: ApiInterfaceRx, bestNumber: BlockNumber, locks: (BalanceLock | BalanceLockTo212)[]): AllLocked {
let lockedBalance = api.registry.createType('Balance');
let lockedBreakdown: (BalanceLock | BalanceLockTo212)[] = [];
let vestingLocked = api.registry.createType('Balance');
@@ -27,18 +34,22 @@ function calcBalances (api: ApiInterfaceRx, [{ accountId, accountNonce, freeBala
if (Array.isArray(locks)) {
// only get the locks that are valid until passed the current block
lockedBreakdown = (locks as BalanceLockTo212[]).filter(({ until }): boolean => !until || (bestNumber && until.gt(bestNumber)));
const notAll = lockedBreakdown.filter(({ amount }) => !amount.isMax());
allLocked = lockedBreakdown.some(({ amount }) => amount.isMax());
vestingLocked = api.registry.createType('Balance', lockedBreakdown.filter(({ id }) => id.eq(VESTING_ID)).reduce((result: BN, { amount }) => result.iadd(amount), new BN(0)));
// get the maximum of the locks according to https://github.com/paritytech/substrate/blob/master/srml/balances/src/lib.rs#L699
const notAll = lockedBreakdown.filter(({ amount }) => !amount.isMax());
if (notAll.length) {
lockedBalance = api.registry.createType('Balance', bnMax(...notAll.map(({ amount }): Balance => amount)));
}
}
return { allLocked, lockedBalance, lockedBreakdown, vestingLocked };
}
function calcBalances (api: ApiInterfaceRx, [{ accountId, accountNonce, freeBalance, frozenFee, frozenMisc, reservedBalance, votingBalance }, bestNumber, [vesting, locks]]: Result): DeriveBalancesAll {
const { allLocked, lockedBalance, lockedBreakdown, vestingLocked } = calcLocked(api, bestNumber, locks);
// Calculate the vesting balances,
// - offset = balance locked at startingBlock
// - perBlock is the unlock amount
+41 -16
View File
@@ -6,20 +6,20 @@ import { Hash, Proposal, Votes } from '@polkadot/types/interfaces';
import { DeriveCollectiveProposal } from '../types';
import { Observable, combineLatest, of } from 'rxjs';
import { map, switchMap } from 'rxjs/operators';
import { catchError, map, switchMap } from 'rxjs/operators';
import { Option } from '@polkadot/types';
import { isFunction } from '@polkadot/util';
import { memo } from '../util';
type Result = [Hash[], Option<Proposal>[], Option<Votes>[]];
type Result = [(Hash | Uint8Array | string)[], (Option<Proposal> | null)[], Option<Votes>[]];
function parse ([hashes, proposals, votes]: Result): DeriveCollectiveProposal[] {
function parse (api: ApiInterfaceRx, [hashes, proposals, votes]: Result): DeriveCollectiveProposal[] {
return proposals
.map((proposalOpt, index): DeriveCollectiveProposal | null =>
proposalOpt.isSome
proposalOpt && proposalOpt.isSome
? {
hash: hashes[index],
hash: api.registry.createType('Hash', hashes[index]),
proposal: proposalOpt.unwrap(),
votes: votes[index].unwrapOr(null)
}
@@ -28,21 +28,46 @@ function parse ([hashes, proposals, votes]: Result): DeriveCollectiveProposal[]
.filter((proposal): proposal is DeriveCollectiveProposal => !!proposal);
}
export function proposals (instanceId: string, api: ApiInterfaceRx, section: 'council' | 'technicalCommittee'): () => Observable<DeriveCollectiveProposal[]> {
function _proposalsFrom (instanceId: string, api: ApiInterfaceRx, section: 'council' | 'technicalCommittee' = 'council'): (hashes: (Hash | Uint8Array | string)[]) => Observable<DeriveCollectiveProposal[]> {
return memo(instanceId, (hashes: (Hash | Uint8Array | string)[]): Observable<DeriveCollectiveProposal[]> =>
(isFunction(api.query[section]?.proposals) && hashes.length
? combineLatest<Result>([
of(hashes),
combineLatest(hashes.map((hash) =>
// this should simply be api.query[section].proposalOf.multi<Option<Proposal>>(hashes),
// however we have had cases on Edgeware where the indices have moved around after an
// upgrade, which results in invalid on-chain data
api.query[section].proposalOf(hash).pipe(catchError(() => of(null)))
)),
api.query[section].voting.multi<Option<Votes>>(hashes)
])
: of([[], [], []] as Result)
).pipe(
map((result) => parse(api, result))
)
);
}
export function proposals (instanceId: string, api: ApiInterfaceRx, section: 'council' | 'technicalCommittee' = 'council'): () => Observable<DeriveCollectiveProposal[]> {
const proposalsFrom = _proposalsFrom(instanceId, api, section);
return memo(instanceId, (): Observable<DeriveCollectiveProposal[]> =>
isFunction(api.query[section]?.proposals)
? api.query[section].proposals().pipe(
switchMap((hashes: Hash[]): Observable<Result> =>
hashes.length
? combineLatest([
of(hashes),
api.query[section].proposalOf.multi<Option<Proposal>>(hashes),
api.query[section].voting.multi<Option<Votes>>(hashes)
])
: of([[], [], []])
),
map(parse)
switchMap(proposalsFrom)
)
: of([] as DeriveCollectiveProposal[])
);
}
export function proposal (instanceId: string, api: ApiInterfaceRx, section: 'council' | 'technicalCommittee' = 'council'): (hash: Hash | Uint8Array | string) => Observable<DeriveCollectiveProposal | null> {
const proposalsFrom = _proposalsFrom(instanceId, api, section);
return memo(instanceId, (hash: Hash | Uint8Array | string): Observable<DeriveCollectiveProposal | null> =>
isFunction(api.query[section]?.proposals)
? proposalsFrom([hash]).pipe(
map(([proposal]) => proposal)
)
: of(null)
);
}
+9 -4
View File
@@ -2,12 +2,17 @@
// SPDX-License-Identifier: Apache-2.0
import { ApiInterfaceRx } from '@polkadot/api/types';
import { DeriveCollectiveProposals } from '../types';
import { Hash } from '@polkadot/types/interfaces';
import { DeriveCollectiveProposal } from '../types';
import { Observable } from 'rxjs';
import { proposals as collectiveProposals } from '../collective';
import { proposal as collectiveProposal, proposals as collectiveProposals } from '../collective';
import { memo } from '../util';
export function proposals (instanceId: string, api: ApiInterfaceRx): () => Observable<DeriveCollectiveProposals> {
return memo(instanceId, collectiveProposals(instanceId, api, 'council'));
export function proposal (instanceId: string, api: ApiInterfaceRx): (hash: Hash | Uint8Array | string) => Observable<DeriveCollectiveProposal | null> {
return memo(instanceId, collectiveProposal(instanceId, api));
}
export function proposals (instanceId: string, api: ApiInterfaceRx): () => Observable<DeriveCollectiveProposal[]> {
return memo(instanceId, collectiveProposals(instanceId, api));
}
+14 -15
View File
@@ -1,7 +1,7 @@
// Copyright 2017-2020 @polkadot/api-derive authors & contributors
// SPDX-License-Identifier: Apache-2.0
import { AccountId, ReferendumInfo, ReferendumInfoTo239, VotingDelegating, VotingDirect, VotingDirectVote } from '@polkadot/types/interfaces';
import { AccountId, ReferendumInfo, ReferendumInfoFinished, ReferendumInfoTo239, Vote, VotingDelegating, VotingDirect, VotingDirectVote } from '@polkadot/types/interfaces';
import { ApiInterfaceRx } from '@polkadot/api/types';
import { DeriveDemocracyLock } from '../types';
@@ -9,27 +9,26 @@ import BN from 'bn.js';
import { Observable, of } from 'rxjs';
import { map, switchMap } from 'rxjs/operators';
import { Option } from '@polkadot/types';
import { isUndefined } from '@polkadot/util';
import { BN_ZERO, isUndefined } from '@polkadot/util';
import { memo } from '../util';
const LOCKUPS = [0, 1, 2, 4, 8, 16, 32];
const ZERO = new BN(0);
function parseEnd (api: ApiInterfaceRx, vote: Vote, { approved, end }: ReferendumInfoFinished): [BN, BN] {
return [
end,
(approved.isTrue && vote.isAye) || (approved.isFalse && vote.isNay)
? end.add(api.consts.democracy.enactmentPeriod.muln(LOCKUPS[vote.conviction.index]))
: BN_ZERO
];
}
function parseLock (api: ApiInterfaceRx, [referendumId, accountVote]: VotingDirectVote, referendum: ReferendumInfo): DeriveDemocracyLock {
const { balance, vote } = accountVote.asStandard;
let unlockAt = ZERO;
let referendumEnd = ZERO;
if (referendum.isFinished) {
const { approved, end } = referendum.asFinished;
referendumEnd = end;
if ((approved.isTrue && vote.isAye) || (approved.isFalse && vote.isNay)) {
unlockAt = end.add(api.consts.democracy.enactmentPeriod.muln(LOCKUPS[vote.conviction.index]));
}
}
const [referendumEnd, unlockAt] = referendum.isFinished
? parseEnd(api, vote, referendum.asFinished)
: [BN_ZERO, BN_ZERO];
return { balance, isDelegated: false, isFinished: referendum.isFinished, referendumEnd, referendumId, unlockAt, vote };
}
@@ -40,31 +40,35 @@ function votesPrev (api: ApiInterfaceRx, referendumId: BN): Observable<DeriveRef
);
}
function extractVotes (mapped: [AccountId, Voting][], referendumId: BN): DeriveReferendumVote[] {
return mapped
.filter(([, voting]) => voting.isDirect)
.map(([accountId, voting]): [AccountId, VotingDirectVote[]] => [
accountId,
voting.asDirect.votes.filter(([idx]) => idx.eq(referendumId))
])
.filter(([, directVotes]) => !!directVotes.length)
.reduce((result: DeriveReferendumVote[], [accountId, votes]) =>
// FIXME We are ignoring split votes
votes.reduce((result: DeriveReferendumVote[], [, vote]): DeriveReferendumVote[] => {
if (vote.isStandard) {
result.push({
accountId,
isDelegating: false,
...vote.asStandard
});
}
return result;
}, result), []
);
}
function votesCurr (api: ApiInterfaceRx, referendumId: BN): Observable<DeriveReferendumVote[]> {
return api.query.democracy.votingOf.entries<Voting>().pipe(
map((allVoting): DeriveReferendumVote[] => {
const mapped = allVoting.map(([key, voting]): [AccountId, Voting] => [key.args[0] as AccountId, voting]);
const votes = mapped
.filter(([, voting]) => voting.isDirect)
.map(([accountId, voting]): [AccountId, VotingDirectVote[]] => [
accountId,
voting.asDirect.votes.filter(([idx]) => idx.eq(referendumId))
])
.filter(([, directVotes]) => !!directVotes.length)
.reduce((result: DeriveReferendumVote[], [accountId, votes]) =>
// FIXME We are ignoring split votes
votes.reduce((result: DeriveReferendumVote[], [, vote]): DeriveReferendumVote[] => {
if (vote.isStandard) {
result.push({
accountId,
isDelegating: false,
...vote.asStandard
});
}
return result;
}, result), []
);
const votes = extractVotes(mapped, referendumId);
const delegations = mapped
.filter(([, voting]) => voting.isDelegating)
.map(([accountId, voting]): [AccountId, VotingDelegating] => [accountId, voting.asDelegating]);
+11 -16
View File
@@ -58,16 +58,20 @@ export function compareRationals (n1: BN, d1: BN, n2: BN, d2: BN): boolean {
}
}
export function calcPassing (threshold: VoteThreshold, sqrtElectorate: BN, { votedAye, votedNay, votedTotal }: ApproxState): boolean {
function calcPassingOther (threshold: VoteThreshold, sqrtElectorate: BN, { votedAye, votedNay, votedTotal }: ApproxState): boolean {
const sqrtVoters = bnSqrt(votedTotal);
return sqrtVoters.isZero()
? false
: threshold.isSimplemajority
? votedAye.gt(votedNay)
: threshold.isSupermajorityapproval
? compareRationals(votedNay, sqrtVoters, votedAye, sqrtElectorate)
: compareRationals(votedNay, sqrtElectorate, votedAye, sqrtVoters);
: threshold.isSupermajorityapproval
? compareRationals(votedNay, sqrtVoters, votedAye, sqrtElectorate)
: compareRationals(votedNay, sqrtElectorate, votedAye, sqrtVoters);
}
export function calcPassing (threshold: VoteThreshold, sqrtElectorate: BN, state: ApproxState): boolean {
return threshold.isSimplemajority
? state.votedAye.gt(state.votedNay)
: calcPassingOther(threshold, sqrtElectorate, state);
}
function calcVotesPrev (votesFor: DeriveReferendumVote[]): DeriveReferendumVoteState {
@@ -92,16 +96,7 @@ function calcVotesPrev (votesFor: DeriveReferendumVote[]): DeriveReferendumVoteS
state.votedTotal.iadd(counted);
return state;
}, {
allAye: [],
allNay: [],
voteCount: 0,
voteCountAye: 0,
voteCountNay: 0,
votedAye: new BN(0),
votedNay: new BN(0),
votedTotal: new BN(0)
});
}, { allAye: [], allNay: [], voteCount: 0, voteCountAye: 0, voteCountNay: 0, votedAye: new BN(0), votedNay: new BN(0), votedTotal: new BN(0) });
}
function calcVotesCurrent (tally: Tally, votes: DeriveReferendumVote[]): DeriveReferendumVoteState {
+3 -3
View File
@@ -6,9 +6,9 @@
/* eslint-disable @typescript-eslint/restrict-template-expressions */
import { Observable, from } from 'rxjs';
import ApiRx from '@polkadot/api/rx/Api';
import MockProvider from '@polkadot/rpc-provider/mock';
import { TypeRegistry } from '@polkadot/types';
import { ApiRx } from '@polkadot/api/rx';
import { MockProvider } from '@polkadot/rpc-provider/mock';
import { TypeRegistry } from '@polkadot/types/create';
import { ExactDerive } from '.';
+1 -1
View File
@@ -92,7 +92,7 @@ function injectFunctions<AllSections> (instanceId: string, api: ApiInterfaceRx,
// FIXME The return type of this function should be {...ExactDerive, ...DeriveCustom}
// For now we just drop the custom derive typings
/** @internal */
export default function decorateDerive (instanceId: string, api: ApiInterfaceRx, custom: DeriveCustom = {}): ExactDerive {
export function decorateDerive (instanceId: string, api: ApiInterfaceRx, custom: DeriveCustom = {}): ExactDerive {
return {
...injectFunctions(instanceId, api, derive),
...injectFunctions(instanceId, api, custom)
+7 -9
View File
@@ -10,6 +10,7 @@ import { map } from 'rxjs/operators';
import { ApiInterfaceRx } from '@polkadot/api/types';
import { memo } from '../util';
import { didUpdateToBool } from './util';
type Result = [
Active,
@@ -23,7 +24,7 @@ type Result = [
];
function parseActive (id: ParaId, active: Active): DeriveParachainActive | null {
const found = active.find(([paraId]): boolean => paraId === id);
const found = active.find(([paraId]) => paraId === id);
if (found && found[1].isSome) {
const [collatorId, retriable] = found[1].unwrap();
@@ -48,12 +49,11 @@ function parseActive (id: ParaId, active: Active): DeriveParachainActive | null
}
function parseCollators (id: ParaId, collatorQueue: SelectedThreads | RetryQueue): (CollatorId | null)[] {
return collatorQueue
.map((queue): CollatorId | null => {
const found = queue.find(([paraId]): boolean => paraId === id);
return collatorQueue.map((queue): CollatorId | null => {
const found = queue.find(([paraId]) => paraId === id);
return found ? found[1] : null;
});
return found ? found[1] : null;
});
}
function parse (id: ParaId, [active, retryQueue, selectedThreads, didUpdate, info, pendingSwap, heads, relayDispatchQueue]: Result): DeriveParachainFull | null {
@@ -63,9 +63,7 @@ function parse (id: ParaId, [active, retryQueue, selectedThreads, didUpdate, inf
return {
active: parseActive(id, active),
didUpdate: didUpdate.isSome
? !!didUpdate.unwrap().some((paraId): boolean => paraId.eq(id))
: false,
didUpdate: didUpdateToBool(didUpdate, id),
heads,
id,
info: { id, ...info.unwrap() } as DeriveParachainInfo,
+9 -14
View File
@@ -10,6 +10,7 @@ import { map, switchMap } from 'rxjs/operators';
import { ApiInterfaceRx } from '@polkadot/api/types';
import { memo } from '../util';
import { didUpdateToBool } from './util';
type Result = [
ParaId[],
@@ -20,17 +21,13 @@ type Result = [
];
function parse ([ids, didUpdate, infos, pendingSwaps, relayDispatchQueueSizes]: Result): DeriveParachain[] {
return ids.map((id, index): DeriveParachain => {
return {
didUpdate: didUpdate.isSome
? !!didUpdate.unwrap().some((paraId): boolean => paraId.eq(id))
: false,
id,
info: { id, ...infos[index].unwrapOr(null) } as DeriveParachainInfo,
pendingSwapId: pendingSwaps[index].unwrapOr(null),
relayDispatchQueueSize: relayDispatchQueueSizes[index][0].toNumber()
};
});
return ids.map((id, index): DeriveParachain => ({
didUpdate: didUpdateToBool(didUpdate, id),
id,
info: { id, ...infos[index].unwrapOr(null) } as DeriveParachainInfo,
pendingSwapId: pendingSwaps[index].unwrapOr(null),
relayDispatchQueueSize: relayDispatchQueueSizes[index][0].toNumber()
}));
}
export function overview (instanceId: string, api: ApiInterfaceRx): () => Observable<DeriveParachain[]> {
@@ -46,9 +43,7 @@ export function overview (instanceId: string, api: ApiInterfaceRx): () => Observ
api.query.parachains.relayDispatchQueueSize.multi<RelayDispatchQueueSize>(paraIds)
])
),
map((result: Result): DeriveParachain[] =>
parse(result)
)
map(parse)
)
: of([] as DeriveParachain[])
);
@@ -0,0 +1,11 @@
// Copyright 2017-2020 @polkadot/api-derive authors & contributors
// SPDX-License-Identifier: Apache-2.0
import { ParaId } from '@polkadot/types/interfaces';
import { DidUpdate } from './types';
export function didUpdateToBool (didUpdate: DidUpdate, id: ParaId): boolean {
return didUpdate.isSome
? didUpdate.unwrap().some((paraId) => paraId.eq(id))
: false;
}
@@ -10,6 +10,7 @@ import { map, switchMap } from 'rxjs/operators';
import { BN_ZERO } from '@polkadot/util';
import { deriveCache, memo } from '../util';
import { filterEras } from './util';
const CACHE_KEY = 'eraPoints';
@@ -42,7 +43,7 @@ export function _erasPoints (instanceId: string, api: ApiInterfaceRx): (eras: Er
: eras
.map((era) => deriveCache.get<DeriveEraPoints>(`${CACHE_KEY}-${era.toString()}`))
.filter((value): value is DeriveEraPoints => !!value);
const remaining = eras.filter((era) => !cached.some((cached) => era.eq(cached.era)));
const remaining = filterEras(eras, cached);
return !remaining.length
? of(cached)
@@ -10,6 +10,7 @@ import { map, switchMap } from 'rxjs/operators';
import { Option } from '@polkadot/types';
import { deriveCache, memo } from '../util';
import { filterEras } from './util';
const CACHE_KEY = 'eraRewards';
@@ -31,7 +32,7 @@ export function _erasRewards (instanceId: string, api: ApiInterfaceRx): (eras: E
: eras
.map((era) => deriveCache.get<DeriveEraRewards>(`${CACHE_KEY}-${era.toString()}`))
.filter((value): value is DeriveEraRewards => !!value);
const remaining = eras.filter((era) => !cached.some((cached) => era.eq(cached.era)));
const remaining = filterEras(eras, cached);
if (!remaining.length) {
return of(cached);
@@ -12,6 +12,7 @@ import { Option } from '@polkadot/types';
import { isFunction } from '@polkadot/util';
import { memo } from '../util';
import { DeriveStakingQuery } from './types';
type ErasResult = [{ unwrapOr: (value: BN) => BN }, DeriveEraPoints[], DeriveEraPrefs[], DeriveEraRewards[]];
@@ -99,24 +100,37 @@ function filterEras (eras: EraIndex[], stakingLedger: StakingLedger): EraIndex[]
return eras.filter((era) => filterEra(era, stakingLedger));
}
function filterRewards (api: ApiInterfaceRx, eras: EraIndex[], migrateEra: BN, rewards: DeriveStakerReward[], stakingLedger: StakingLedger, withActive: boolean): Observable<DeriveStakerReward[]> {
if (withActive) {
return of(rewards);
}
function removeClaimed (validators: string[], queryValidators: DeriveStakingQuery[], reward: DeriveStakerReward): void {
const rm: string[] = [];
Object.keys(reward.validators).forEach((validatorId): void => {
const index = validators.indexOf(validatorId);
if (index !== -1) {
const valLedger = queryValidators[index].stakingLedger;
if (valLedger?.claimedRewards.some((era) => reward.era.eq(era))) {
rm.push(validatorId);
}
}
});
rm.forEach((validatorId): void => {
delete reward.validators[validatorId];
});
}
function filterRewards (api: ApiInterfaceRx, eras: EraIndex[], { migrateEra, rewards, stakingLedger }: { migrateEra: BN, rewards: DeriveStakerReward[]; stakingLedger: StakingLedger }): Observable<DeriveStakerReward[]> {
const validators = uniqValidators(rewards);
const filter = filterEras(eras, stakingLedger);
return (
isFunction(api.tx.staking.payoutStakers)
? api.derive.staking.queryMulti(validators)
: of([])
).pipe(
map((queryValidators): DeriveStakerReward[] => {
const filter = withActive
? eras
: filterEras(eras, stakingLedger);
return rewards
map((queryValidators): DeriveStakerReward[] =>
rewards
.filter(({ isEmpty }) => !isEmpty)
.filter((reward): boolean => {
if (!filter.some((filter) => reward.era.eq(filter))) {
@@ -128,32 +142,16 @@ function filterRewards (api: ApiInterfaceRx, eras: EraIndex[], migrateEra: BN, r
reward.isStakerPayout = true;
const rm: string[] = [];
Object.keys(reward.validators).forEach((validatorId): void => {
const index = validators.indexOf(validatorId);
if (index !== -1) {
const valLedger = queryValidators[index].stakingLedger;
if (valLedger?.claimedRewards.some((era) => reward.era.eq(era))) {
rm.push(validatorId);
}
}
});
rm.forEach((validatorId): void => {
delete reward.validators[validatorId];
});
removeClaimed(validators, queryValidators, reward);
return true;
})
.filter(({ validators }) => Object.keys(validators).length !== 0)
.map((reward) => ({
...reward,
nominators: reward.nominating.filter(({ validatorId }) => !!reward.validators[validatorId])
}));
})
nominators: reward.nominating.filter((n) => !!reward.validators[n.validatorId])
}))
)
);
}
@@ -178,13 +176,15 @@ export function _stakerRewards (instanceId: string, api: ApiInterfaceRx): (accou
api.derive.staking._stakerRewardsEras(eras, withActive)
]).pipe(
switchMap(([{ stakingLedger, stashId }, exposures, erasResult]): Observable<DeriveStakerReward[]> => {
const migrateEra: BN = erasResult[0].unwrapOr(ZERO);
if (!stashId || !stakingLedger) {
return of([]);
}
return filterRewards(api, eras, migrateEra, parseRewards(api, stashId, erasResult, exposures), stakingLedger, withActive);
const rewards = parseRewards(api, stashId, erasResult, exposures);
return withActive
? of(rewards)
: filterRewards(api, eras, { migrateEra: erasResult[0].unwrapOr(ZERO), rewards, stakingLedger });
})
)
);
+8
View File
@@ -0,0 +1,8 @@
// Copyright 2017-2020 @polkadot/api-derive authors & contributors
// SPDX-License-Identifier: Apache-2.0
import { EraIndex } from '@polkadot/types/interfaces';
export function filterEras <T extends { era: EraIndex }> (eras: EraIndex[], list: T[]): EraIndex[] {
return eras.filter((era) => !list.some((entry) => era.eq(entry.era)));
}
@@ -2,12 +2,12 @@
// SPDX-License-Identifier: Apache-2.0
import { ApiInterfaceRx } from '@polkadot/api/types';
import { DeriveCollectiveProposals } from '../types';
import { DeriveCollectiveProposal } from '../types';
import { Observable } from 'rxjs';
import { proposals as collectiveProposals } from '../collective';
import { memo } from '../util';
export function proposals (instanceId: string, api: ApiInterfaceRx): () => Observable<DeriveCollectiveProposals> {
export function proposals (instanceId: string, api: ApiInterfaceRx): () => Observable<DeriveCollectiveProposal[]> {
return memo(instanceId, collectiveProposals(instanceId, api, 'technicalCommittee'));
}
@@ -3,7 +3,7 @@
import { ApiInterfaceRx } from '@polkadot/api/types';
import { ProposalIndex, TreasuryProposal } from '@polkadot/types/interfaces';
import { DeriveCollectiveProposals, DeriveTreasuryProposal, DeriveTreasuryProposals } from '../types';
import { DeriveCollectiveProposal, DeriveTreasuryProposal, DeriveTreasuryProposals } from '../types';
import { Observable, combineLatest, of } from 'rxjs';
import { map, switchMap } from 'rxjs/operators';
@@ -15,7 +15,7 @@ interface Result {
allIds: ProposalIndex[];
allProposals: Option<TreasuryProposal>[];
approvalIds: ProposalIndex[];
councilProposals: DeriveCollectiveProposals;
councilProposals: DeriveCollectiveProposal[];
proposalCount: ProposalIndex;
}
@@ -51,9 +51,7 @@ function retrieveProposals (api: ApiInterfaceRx, proposalCount: ProposalIndex, a
const count = proposalCount.toNumber();
for (let index = 0; index < count; index++) {
const isApproval = approvalIds.some((id): boolean => id.eqn(index));
if (!isApproval) {
if (!approvalIds.some((id) => id.eqn(index))) {
proposalIds.push(api.registry.createType('ProposalIndex', index));
}
}
@@ -64,7 +62,7 @@ function retrieveProposals (api: ApiInterfaceRx, proposalCount: ProposalIndex, a
api.query.treasury.proposals.multi<Option<TreasuryProposal>>(allIds),
api.derive.council.proposals()
]).pipe(
map(([allProposals, councilProposals]: [Option<TreasuryProposal>[], DeriveCollectiveProposals]): DeriveTreasuryProposals =>
map(([allProposals, councilProposals]: [Option<TreasuryProposal>[], DeriveCollectiveProposal[]]): DeriveTreasuryProposals =>
parseResult(api, { allIds, allProposals, approvalIds, councilProposals, proposalCount })
)
);
@@ -17,7 +17,7 @@ const _Header = Struct.with(runtimeTypes.types.Header as any) as Constructor<Hea
* @description
* A [[Block]] header with an additional `author` field that indicates the block author
*/
export default class HeaderExtended extends _Header {
export class HeaderExtended extends _Header {
readonly #author?: AccountId;
constructor (registry: Registry, header?: Header, sessionValidators?: AccountId[]) {
@@ -36,9 +36,9 @@ export default class HeaderExtended extends _Header {
/**
* @description Creates a human-friendly JSON representation
*/
public toHuman (isExtended?: boolean): AnyJson {
public toHuman (isExtended?: boolean): Record<string, AnyJson> {
return {
...super.toHuman(isExtended) as { [index: string]: AnyJson },
...super.toHuman(isExtended),
author: this.author
? this.author.toHuman()
: undefined
@@ -48,9 +48,9 @@ export default class HeaderExtended extends _Header {
/**
* @description Creates the JSON representation
*/
public toJSON (): AnyJson {
public toJSON (): Record<string, AnyJson> {
return {
...super.toJSON() as { [index: string]: AnyJson },
...super.toJSON(),
author: this.author
? this.author.toJSON()
: undefined
@@ -17,7 +17,7 @@ const _SignedBlock = Struct.with(runtimeTypes.types.SignedBlock as any) as Const
* @description
* A [[Block]] header with an additional `author` field that indicates the block author
*/
export default class BlockExtended extends _SignedBlock {
export class SignedBlockExtended extends _SignedBlock {
readonly #author?: AccountId;
constructor (registry: Registry, block?: SignedBlock, sessionValidators?: AccountId[]) {
@@ -36,9 +36,9 @@ export default class BlockExtended extends _SignedBlock {
/**
* @description Creates a human-friendly JSON representation
*/
public toHuman (isExtended?: boolean): AnyJson {
public toHuman (isExtended?: boolean): Record<string, AnyJson> {
return {
...super.toHuman(isExtended) as { [index: string]: AnyJson },
...super.toHuman(isExtended),
author: this.author
? this.author.toHuman()
: undefined
@@ -48,9 +48,9 @@ export default class BlockExtended extends _SignedBlock {
/**
* @description Creates the JSON representation
*/
public toJSON (): AnyJson {
public toJSON (): Record<string, AnyJson> {
return {
...super.toJSON() as { [index: string]: AnyJson },
...super.toJSON(),
author: this.author
? this.author.toJSON()
: undefined
+2 -2
View File
@@ -1,5 +1,5 @@
// Copyright 2017-2020 @polkadot/api-derive authors & contributors
// SPDX-License-Identifier: Apache-2.0
export { default as HeaderExtended } from './HeaderExtended';
export { default as SignedBlockExtended } from './SignedBlockExtended';
export { HeaderExtended } from './HeaderExtended';
export { SignedBlockExtended } from './SignedBlockExtended';
-2
View File
@@ -60,8 +60,6 @@ export interface DeriveCollectiveProposal {
votes: Votes | null;
}
export type DeriveCollectiveProposals = DeriveCollectiveProposal[];
export interface DeriveFees {
creationFee: Balance;
existentialDeposit: Balance;
@@ -3,7 +3,7 @@
import { ApprovalFlag } from '@polkadot/types/interfaces';
import { TypeRegistry } from '@polkadot/types';
import { TypeRegistry } from '@polkadot/types/create';
import { approvalFlagsToBools } from './approvalFlagsToBools';
+1 -3
View File
@@ -1,11 +1,9 @@
// Copyright 2017-2020 @polkadot/api-derive authors & contributors
// SPDX-License-Identifier: Apache-2.0
import { drr } from '@polkadot/rpc-core/rxjs';
export { drr } from '@polkadot/rpc-core/util';
export * from './approvalFlagsToBools';
export * from './cache';
export * from './cacheImpl';
export * from './memo';
export { drr };
+1 -2
View File
@@ -3,8 +3,7 @@
import createMemo from 'memoizee';
import { Observable, Observer, TeardownLogic } from 'rxjs';
import { drr } from '@polkadot/rpc-core/rxjs';
import normalizer from '@polkadot/rpc-core/normalizer';
import { drr, normalizer } from '@polkadot/rpc-core/util';
type ObsFn <T> = (...params: any[]) => Observable<T>;
+15 -28
View File
@@ -1,46 +1,33 @@
{
"name": "@polkadot/api",
"version": "2.4.1",
"version": "2.7.1",
"description": "Promise and RxJS wrappers around the Polkadot JS RPC",
"main": "index.js",
"sideEffects": false,
"keywords": [
"Polkadot",
"RxJs"
],
"author": "Jaco Greeff <jacogr@gmail.com>",
"maintainers": [
"Jaco Greeff <jacogr@gmail.com>"
],
"maintainers": [],
"contributors": [],
"license": "Apache-2.0",
"publishConfig": {
"access": "public",
"registry": "https://registry.npmjs.org"
},
"repository": {
"type": "git",
"url": "git+https://github.com/polkadot-js/api.git"
},
"bugs": {
"url": "https://github.com/polkadot-js/api/issues"
},
"repository": "github:polkadot-js/api",
"bugs": "https://github.com/polkadot-js/api/issues",
"homepage": "https://github.com/polkadot-js/api/tree/master/packages/api#readme",
"dependencies": {
"@babel/runtime": "^7.12.1",
"@polkadot/api-derive": "^2.4.1",
"@polkadot/keyring": "^3.6.1",
"@polkadot/metadata": "^2.4.1",
"@polkadot/rpc-core": "^2.4.1",
"@polkadot/rpc-provider": "^2.4.1",
"@polkadot/types": "^2.4.1",
"@polkadot/types-known": "^2.4.1",
"@polkadot/util": "^3.6.1",
"@polkadot/util-crypto": "^3.6.1",
"@babel/runtime": "^7.12.5",
"@polkadot/api-derive": "2.7.1",
"@polkadot/keyring": "^4.1.1",
"@polkadot/metadata": "2.7.1",
"@polkadot/rpc-core": "2.7.1",
"@polkadot/rpc-provider": "2.7.1",
"@polkadot/types": "2.7.1",
"@polkadot/types-known": "2.7.1",
"@polkadot/util": "^4.1.1",
"@polkadot/util-crypto": "^4.1.1",
"bn.js": "^5.1.3",
"eventemitter3": "^4.0.7",
"rxjs": "^6.6.3"
},
"devDependencies": {
"@polkadot/keyring": "^3.6.1"
}
}
+7 -19
View File
@@ -1,14 +1,13 @@
// Auto-generated via `yarn polkadot-types-from-chain`, do not edit
/* eslint-disable */
import { Codec } from '@polkadot/types/types';
import { Vec } from '@polkadot/types/codec';
import { u16, u32, u64 } from '@polkadot/types/primitive';
import { Balance, BalanceOf, BlockNumber, LockIdentifier, ModuleId, Moment, Perbill, Percent, Permill, RuntimeDbWeight, Weight } from '@polkadot/types/interfaces/runtime';
import { SessionIndex } from '@polkadot/types/interfaces/session';
import { EraIndex } from '@polkadot/types/interfaces/staking';
import { WeightToFeeCoefficient } from '@polkadot/types/interfaces/support';
import { ApiTypes } from '@polkadot/api/types';
import type { Vec, u16, u32, u64 } from '@polkadot/types';
import type { Codec } from '@polkadot/types/types';
import type { Balance, BalanceOf, BlockNumber, LockIdentifier, ModuleId, Moment, Perbill, Percent, Permill, RuntimeDbWeight, Weight } from '@polkadot/types/interfaces/runtime';
import type { SessionIndex } from '@polkadot/types/interfaces/session';
import type { EraIndex } from '@polkadot/types/interfaces/staking';
import type { WeightToFeeCoefficient } from '@polkadot/types/interfaces/support';
import type { ApiTypes } from '@polkadot/api/types';
declare module '@polkadot/api/types/consts' {
export interface AugmentedConsts<ApiType> {
@@ -134,17 +133,6 @@ declare module '@polkadot/api/types/consts' {
termDuration: BlockNumber & AugmentedConst<ApiType>;
votingBond: BalanceOf & AugmentedConst<ApiType>;
};
finalityTracker: {
[key: string]: Codec;
/**
* The delay after which point things become suspicious. Default is 1000.
**/
reportLatency: BlockNumber & AugmentedConst<ApiType>;
/**
* The number of recent samples to keep from this chain. Default is 101.
**/
windowSize: BlockNumber & AugmentedConst<ApiType>;
};
identity: {
[key: string]: Codec;
/**
+33 -28
View File
@@ -1,34 +1,33 @@
// Auto-generated via `yarn polkadot-types-from-chain`, do not edit
/* eslint-disable */
import { AnyNumber, ITuple, Observable } 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 { BabeAuthorityWeight, MaybeRandomness, NextConfigDescriptor, Randomness } from '@polkadot/types/interfaces/babe';
import { AccountData, BalanceLock } from '@polkadot/types/interfaces/balances';
import { ProposalIndex, Votes } from '@polkadot/types/interfaces/collective';
import { AuthorityId } from '@polkadot/types/interfaces/consensus';
import { CodeHash, ContractInfo, PrefabWasmModule, Schedule } from '@polkadot/types/interfaces/contracts';
import { PreimageStatus, PropIndex, Proposal, ReferendumIndex, ReferendumInfo, Voting } from '@polkadot/types/interfaces/democracy';
import { VoteThreshold } from '@polkadot/types/interfaces/elections';
import { SetId, StoredPendingChange, StoredState } from '@polkadot/types/interfaces/grandpa';
import { RegistrarInfo, Registration } from '@polkadot/types/interfaces/identity';
import { AuthIndex } from '@polkadot/types/interfaces/imOnline';
import { DeferredOffenceOf, Kind, OffenceDetails, OpaqueTimeSlot, ReportIdOf } from '@polkadot/types/interfaces/offences';
import { ProxyAnnouncement, ProxyDefinition } from '@polkadot/types/interfaces/proxy';
import { ActiveRecovery, RecoveryConfig } from '@polkadot/types/interfaces/recovery';
import { AccountId, AccountIndex, Balance, BalanceOf, BlockNumber, ExtrinsicsWeight, Hash, KeyTypeId, Moment, OpaqueCall, Perbill, Releases, ValidatorId } from '@polkadot/types/interfaces/runtime';
import { Scheduled, TaskAddress } from '@polkadot/types/interfaces/scheduler';
import { Keys, SessionIndex } from '@polkadot/types/interfaces/session';
import { Bid, BidKind, SocietyVote, StrikeCount, VouchingStatus } from '@polkadot/types/interfaces/society';
import { ActiveEraInfo, ElectionResult, ElectionScore, ElectionStatus, EraIndex, EraRewardPoints, Exposure, Forcing, Nominations, RewardDestination, SlashingSpans, SpanIndex, SpanRecord, StakingLedger, UnappliedSlash, ValidatorPrefs } from '@polkadot/types/interfaces/staking';
import { AccountInfo, DigestOf, EventIndex, EventRecord, LastRuntimeUpgradeInfo, Phase } from '@polkadot/types/interfaces/system';
import { Bounty, BountyIndex, OpenTip, TreasuryProposal } from '@polkadot/types/interfaces/treasury';
import { Multiplier } from '@polkadot/types/interfaces/txpayment';
import { Multisig } from '@polkadot/types/interfaces/utility';
import { VestingInfo } from '@polkadot/types/interfaces/vesting';
import { ApiTypes } from '@polkadot/api/types';
import type { Bytes, Data, Option, U8aFixed, Vec, bool, u32, u64 } from '@polkadot/types';
import type { AnyNumber, ITuple, Observable } from '@polkadot/types/types';
import type { UncleEntryItem } from '@polkadot/types/interfaces/authorship';
import type { BabeAuthorityWeight, MaybeRandomness, NextConfigDescriptor, Randomness } from '@polkadot/types/interfaces/babe';
import type { AccountData, BalanceLock } from '@polkadot/types/interfaces/balances';
import type { ProposalIndex, Votes } from '@polkadot/types/interfaces/collective';
import type { AuthorityId } from '@polkadot/types/interfaces/consensus';
import type { CodeHash, ContractInfo, PrefabWasmModule, Schedule } from '@polkadot/types/interfaces/contracts';
import type { PreimageStatus, PropIndex, Proposal, ReferendumIndex, ReferendumInfo, Voting } from '@polkadot/types/interfaces/democracy';
import type { VoteThreshold } from '@polkadot/types/interfaces/elections';
import type { SetId, StoredPendingChange, StoredState } from '@polkadot/types/interfaces/grandpa';
import type { RegistrarInfo, Registration } from '@polkadot/types/interfaces/identity';
import type { AuthIndex } from '@polkadot/types/interfaces/imOnline';
import type { DeferredOffenceOf, Kind, OffenceDetails, OpaqueTimeSlot, ReportIdOf } from '@polkadot/types/interfaces/offences';
import type { ProxyAnnouncement, ProxyDefinition } from '@polkadot/types/interfaces/proxy';
import type { ActiveRecovery, RecoveryConfig } from '@polkadot/types/interfaces/recovery';
import type { AccountId, AccountIndex, Balance, BalanceOf, BlockNumber, ExtrinsicsWeight, Hash, KeyTypeId, Moment, OpaqueCall, Perbill, Releases, ValidatorId } from '@polkadot/types/interfaces/runtime';
import type { Scheduled, TaskAddress } from '@polkadot/types/interfaces/scheduler';
import type { Keys, SessionIndex } from '@polkadot/types/interfaces/session';
import type { Bid, BidKind, SocietyVote, StrikeCount, VouchingStatus } from '@polkadot/types/interfaces/society';
import type { ActiveEraInfo, ElectionResult, ElectionScore, ElectionStatus, EraIndex, EraRewardPoints, Exposure, Forcing, Nominations, RewardDestination, SlashingSpans, SpanIndex, SpanRecord, StakingLedger, UnappliedSlash, ValidatorPrefs } from '@polkadot/types/interfaces/staking';
import type { AccountInfo, DigestOf, EventIndex, EventRecord, LastRuntimeUpgradeInfo, Phase } from '@polkadot/types/interfaces/system';
import type { Bounty, BountyIndex, OpenTip, TreasuryProposal } from '@polkadot/types/interfaces/treasury';
import type { Multiplier } from '@polkadot/types/interfaces/txpayment';
import type { Multisig } from '@polkadot/types/interfaces/utility';
import type { VestingInfo } from '@polkadot/types/interfaces/vesting';
import type { ApiTypes } from '@polkadot/api/types';
declare module '@polkadot/api/types/storage' {
export interface AugmentedQueries<ApiType> {
@@ -53,6 +52,12 @@ declare module '@polkadot/api/types/storage' {
* Current epoch authorities.
**/
authorities: AugmentedQuery<ApiType, () => Observable<Vec<ITuple<[AuthorityId, BabeAuthorityWeight]>>>> & QueryableStorageEntry<ApiType>;
/**
* Temporary value (cleared at block finalization) that includes the VRF output generated
* at this block. This field should always be populated during block processing unless
* secondary plain slots are enabled (which don't contain a VRF output).
**/
authorVrfRandomness: AugmentedQuery<ApiType, () => Observable<MaybeRandomness>> & QueryableStorageEntry<ApiType>;
/**
* Current slot number.
**/
+30 -21
View File
@@ -1,25 +1,24 @@
// Auto-generated via `yarn polkadot-types-from-chain`, do not edit
/* eslint-disable */
import { AnyNumber, Codec, IExtrinsic, Observable } from '@polkadot/types/types';
import { HashMap, Option, Vec } from '@polkadot/types/codec';
import { Bytes, Null, StorageKey, Text, bool, u32, u64 } from '@polkadot/types/primitive';
import { Metadata } from '@polkadot/types';
import { ExtrinsicOrHash, ExtrinsicStatus } from '@polkadot/types/interfaces/author';
import { EpochAuthorship } from '@polkadot/types/interfaces/babe';
import { BlockHash } from '@polkadot/types/interfaces/chain';
import { PrefixedStorageKey } from '@polkadot/types/interfaces/childstate';
import { AuthorityId } from '@polkadot/types/interfaces/consensus';
import { ContractCallRequest, ContractExecResult } from '@polkadot/types/interfaces/contracts';
import { CreatedBlock } from '@polkadot/types/interfaces/engine';
import { Extrinsic } from '@polkadot/types/interfaces/extrinsics';
import { EncodedFinalityProofs, JustificationNotification, ReportedRoundStates } from '@polkadot/types/interfaces/grandpa';
import { StorageKind } from '@polkadot/types/interfaces/offchain';
import { RuntimeDispatchInfo } from '@polkadot/types/interfaces/payment';
import { RpcMethods } from '@polkadot/types/interfaces/rpc';
import { AccountId, BlockNumber, H256, Hash, Header, Index, Justification, KeyValue, SignedBlock, StorageData } from '@polkadot/types/interfaces/runtime';
import { ReadProof, RuntimeVersion } from '@polkadot/types/interfaces/state';
import { ApplyExtrinsicResult, ChainProperties, ChainType, Health, NetworkState, NodeRole, PeerInfo } from '@polkadot/types/interfaces/system';
import type { Metadata } from '@polkadot/metadata';
import type { Bytes, HashMap, Json, Null, Option, StorageKey, Text, Vec, bool, u32, u64 } from '@polkadot/types';
import type { AnyNumber, Codec, IExtrinsic, Observable } from '@polkadot/types/types';
import type { ExtrinsicOrHash, ExtrinsicStatus } from '@polkadot/types/interfaces/author';
import type { EpochAuthorship } from '@polkadot/types/interfaces/babe';
import type { BlockHash } from '@polkadot/types/interfaces/chain';
import type { PrefixedStorageKey } from '@polkadot/types/interfaces/childstate';
import type { AuthorityId } from '@polkadot/types/interfaces/consensus';
import type { ContractCallRequest, ContractExecResult } from '@polkadot/types/interfaces/contracts';
import type { CreatedBlock } from '@polkadot/types/interfaces/engine';
import type { Extrinsic } from '@polkadot/types/interfaces/extrinsics';
import type { EncodedFinalityProofs, JustificationNotification, ReportedRoundStates } from '@polkadot/types/interfaces/grandpa';
import type { StorageKind } from '@polkadot/types/interfaces/offchain';
import type { RuntimeDispatchInfo } from '@polkadot/types/interfaces/payment';
import type { RpcMethods } from '@polkadot/types/interfaces/rpc';
import type { AccountId, BlockNumber, H256, Hash, Header, Index, Justification, KeyValue, SignedBlock, StorageData } from '@polkadot/types/interfaces/runtime';
import type { ReadProof, RuntimeVersion } from '@polkadot/types/interfaces/state';
import type { ApplyExtrinsicResult, ChainProperties, ChainType, Health, NetworkState, NodeRole, PeerInfo, SyncState } from '@polkadot/types/interfaces/system';
declare module '@polkadot/rpc-core/types.jsonrpc' {
export interface RpcInterface {
@@ -153,11 +152,11 @@ declare module '@polkadot/rpc-core/types.jsonrpc' {
/**
* Get offchain local storage under given key and prefix
**/
localStorageGet: AugmentedRpc<(kind: StorageKind | '__UNUSED'|'PERSISTENT'|'LOCAL' | number | Uint8Array, key: Bytes | string | Uint8Array) => Observable<Option<Bytes>>>;
localStorageGet: AugmentedRpc<(kind: StorageKind | '__UNUSED' | 'PERSISTENT' | 'LOCAL' | number | Uint8Array, key: Bytes | string | Uint8Array) => Observable<Option<Bytes>>>;
/**
* Set offchain local storage under given key and prefix
**/
localStorageSet: AugmentedRpc<(kind: StorageKind | '__UNUSED'|'PERSISTENT'|'LOCAL' | number | Uint8Array, key: Bytes | string | Uint8Array, value: Bytes | string | Uint8Array) => Observable<Null>>;
localStorageSet: AugmentedRpc<(kind: StorageKind | '__UNUSED' | 'PERSISTENT' | 'LOCAL' | number | Uint8Array, key: Bytes | string | Uint8Array, value: Bytes | string | Uint8Array) => Observable<Null>>;
};
payment: {
/**
@@ -245,6 +244,12 @@ declare module '@polkadot/rpc-core/types.jsonrpc' {
**/
subscribeStorage: AugmentedRpc<<T = Codec[]>(keys?: Vec<StorageKey> | (StorageKey | string | Uint8Array | any)[]) => Observable<T>>;
};
syncstate: {
/**
* Returns the json-serialized chainspec running the node, with a sync state.
**/
genSyncSpec: AugmentedRpc<(raw: bool | boolean | Uint8Array) => Observable<Json>>;
};
system: {
/**
* Retrieves the next accountIndex as available on the node
@@ -302,6 +307,10 @@ declare module '@polkadot/rpc-core/types.jsonrpc' {
* Remove a reserved peer
**/
removeReservedPeer: AugmentedRpc<(peerId: Text | string) => Observable<Text>>;
/**
* Returns the state of the syncing of the node
**/
syncState: AugmentedRpc<() => Observable<SyncState>>;
/**
* Retrieves the version of the node
**/
+71 -66
View File
@@ -1,29 +1,28 @@
// Auto-generated via `yarn polkadot-types-from-chain`, do not edit
/* eslint-disable */
import { AnyNumber, ITuple } from '@polkadot/types/types';
import { Compact, Option, U8aFixed, Vec } from '@polkadot/types/codec';
import { Bytes, Data, bool, u16, u32, u64 } from '@polkadot/types/primitive';
import { BabeEquivocationProof } from '@polkadot/types/interfaces/babe';
import { MemberCount, ProposalIndex } from '@polkadot/types/interfaces/collective';
import { CodeHash, Gas, Schedule } from '@polkadot/types/interfaces/contracts';
import { AccountVote, Conviction, PropIndex, Proposal, ReferendumIndex } from '@polkadot/types/interfaces/democracy';
import { DefunctVoter, Renouncing } from '@polkadot/types/interfaces/elections';
import { Extrinsic, Signature } from '@polkadot/types/interfaces/extrinsics';
import { GrandpaEquivocationProof, KeyOwnerProof } from '@polkadot/types/interfaces/grandpa';
import { IdentityFields, IdentityInfo, IdentityJudgement, RegistrarIndex } from '@polkadot/types/interfaces/identity';
import { Heartbeat } from '@polkadot/types/interfaces/imOnline';
import { ProxyType } from '@polkadot/types/interfaces/proxy';
import { AccountId, AccountIndex, Address, Balance, BalanceOf, BlockNumber, Call, CallHashOf, ChangesTrieConfiguration, Hash, Header, KeyValue, LookupSource, Moment, OpaqueCall, Perbill, Percent, Weight } from '@polkadot/types/interfaces/runtime';
import { Period, Priority } from '@polkadot/types/interfaces/scheduler';
import { Keys } from '@polkadot/types/interfaces/session';
import { SocietyJudgement } from '@polkadot/types/interfaces/society';
import { CompactAssignments, ElectionScore, ElectionSize, EraIndex, RewardDestination, ValidatorIndex, ValidatorPrefs } from '@polkadot/types/interfaces/staking';
import { Key } from '@polkadot/types/interfaces/system';
import { BountyIndex } from '@polkadot/types/interfaces/treasury';
import { Timepoint } from '@polkadot/types/interfaces/utility';
import { VestingInfo } from '@polkadot/types/interfaces/vesting';
import { ApiTypes, SubmittableExtrinsic } from '@polkadot/api/types';
import type { Bytes, Compact, Data, Option, U8aFixed, Vec, bool, u16, u32, u64 } from '@polkadot/types';
import type { AnyNumber, ITuple } from '@polkadot/types/types';
import type { BabeEquivocationProof } from '@polkadot/types/interfaces/babe';
import type { MemberCount, ProposalIndex } from '@polkadot/types/interfaces/collective';
import type { CodeHash, Gas, Schedule } from '@polkadot/types/interfaces/contracts';
import type { AccountVote, Conviction, PropIndex, Proposal, ReferendumIndex } from '@polkadot/types/interfaces/democracy';
import type { DefunctVoter, Renouncing } from '@polkadot/types/interfaces/elections';
import type { Extrinsic, Signature } from '@polkadot/types/interfaces/extrinsics';
import type { GrandpaEquivocationProof, KeyOwnerProof } from '@polkadot/types/interfaces/grandpa';
import type { IdentityFields, IdentityInfo, IdentityJudgement, RegistrarIndex } from '@polkadot/types/interfaces/identity';
import type { Heartbeat } from '@polkadot/types/interfaces/imOnline';
import type { ProxyType } from '@polkadot/types/interfaces/proxy';
import type { AccountId, AccountIndex, Address, Balance, BalanceOf, BlockNumber, Call, CallHashOf, ChangesTrieConfiguration, Hash, Header, KeyValue, LookupSource, Moment, OpaqueCall, Perbill, Percent, Weight } from '@polkadot/types/interfaces/runtime';
import type { Period, Priority } from '@polkadot/types/interfaces/scheduler';
import type { Keys } from '@polkadot/types/interfaces/session';
import type { SocietyJudgement } from '@polkadot/types/interfaces/society';
import type { CompactAssignments, ElectionScore, ElectionSize, EraIndex, RewardDestination, ValidatorIndex, ValidatorPrefs } from '@polkadot/types/interfaces/staking';
import type { Key } from '@polkadot/types/interfaces/system';
import type { BountyIndex } from '@polkadot/types/interfaces/treasury';
import type { Timepoint } from '@polkadot/types/interfaces/utility';
import type { VestingInfo } from '@polkadot/types/interfaces/vesting';
import type { ApiTypes, SubmittableExtrinsic } from '@polkadot/api/types';
declare module '@polkadot/api/types/submittable' {
export interface AugmentedSubmittables<ApiType> {
@@ -65,7 +64,7 @@ declare module '@polkadot/api/types/submittable' {
* not assumed to be in the overlay.
* # </weight>
**/
forceTransfer: AugmentedSubmittable<(source: LookupSource | Address | AccountId | AccountIndex | LookupSource | string | Uint8Array, dest: LookupSource | Address | AccountId | AccountIndex | LookupSource | string | Uint8Array, value: Compact<Balance> | AnyNumber | Uint8Array) => SubmittableExtrinsic<ApiType>>;
forceTransfer: AugmentedSubmittable<(source: LookupSource | Address | AccountId | AccountIndex | string | Uint8Array, dest: LookupSource | Address | AccountId | AccountIndex | string | Uint8Array, value: Compact<Balance> | AnyNumber | Uint8Array) => SubmittableExtrinsic<ApiType>>;
/**
* Set the balances of a given account.
*
@@ -86,7 +85,7 @@ declare module '@polkadot/api/types/submittable' {
* - DB Weight: 1 Read, 1 Write to `who`
* # </weight>
**/
setBalance: AugmentedSubmittable<(who: LookupSource | Address | AccountId | AccountIndex | LookupSource | string | Uint8Array, newFree: Compact<Balance> | AnyNumber | Uint8Array, newReserved: Compact<Balance> | AnyNumber | Uint8Array) => SubmittableExtrinsic<ApiType>>;
setBalance: AugmentedSubmittable<(who: LookupSource | Address | AccountId | AccountIndex | string | Uint8Array, newFree: Compact<Balance> | AnyNumber | Uint8Array, newReserved: Compact<Balance> | AnyNumber | Uint8Array) => SubmittableExtrinsic<ApiType>>;
/**
* Transfer some liquid free balance to another account.
*
@@ -116,7 +115,7 @@ declare module '@polkadot/api/types/submittable' {
* - Origin account is already in memory, so no DB operations for them.
* # </weight>
**/
transfer: AugmentedSubmittable<(dest: LookupSource | Address | AccountId | AccountIndex | LookupSource | string | Uint8Array, value: Compact<Balance> | AnyNumber | Uint8Array) => SubmittableExtrinsic<ApiType>>;
transfer: AugmentedSubmittable<(dest: LookupSource | Address | AccountId | AccountIndex | string | Uint8Array, value: Compact<Balance> | AnyNumber | Uint8Array) => SubmittableExtrinsic<ApiType>>;
/**
* Same as the [`transfer`] call, but with a check that the transfer will not kill the
* origin account.
@@ -130,7 +129,7 @@ declare module '@polkadot/api/types/submittable' {
* - DB Weight: 1 Read and 1 Write to dest (sender is in overlay already)
* #</weight>
**/
transferKeepAlive: AugmentedSubmittable<(dest: LookupSource | Address | AccountId | AccountIndex | LookupSource | string | Uint8Array, value: Compact<Balance> | AnyNumber | Uint8Array) => SubmittableExtrinsic<ApiType>>;
transferKeepAlive: AugmentedSubmittable<(dest: LookupSource | Address | AccountId | AccountIndex | string | Uint8Array, value: Compact<Balance> | AnyNumber | Uint8Array) => SubmittableExtrinsic<ApiType>>;
};
contracts: {
[key: string]: SubmittableExtrinsicFunction<ApiType>;
@@ -143,7 +142,7 @@ declare module '@polkadot/api/types/submittable' {
* * 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.
**/
call: AugmentedSubmittable<(dest: LookupSource | Address | AccountId | AccountIndex | LookupSource | string | Uint8Array, value: Compact<BalanceOf> | AnyNumber | Uint8Array, gasLimit: Compact<Gas> | AnyNumber | Uint8Array, data: Bytes | string | Uint8Array) => SubmittableExtrinsic<ApiType>>;
call: AugmentedSubmittable<(dest: LookupSource | Address | AccountId | AccountIndex | string | Uint8Array, value: Compact<BalanceOf> | AnyNumber | Uint8Array, gasLimit: Compact<Gas> | AnyNumber | Uint8Array, data: Bytes | string | Uint8Array) => SubmittableExtrinsic<ApiType>>;
/**
* Allows block producers to claim a small reward for evicting a contract. If a block producer
* fails to do so, a regular users will be allowed to claim the reward.
@@ -175,7 +174,7 @@ declare module '@polkadot/api/types/submittable' {
*
* The schedule must have a greater version than the stored schedule.
**/
updateSchedule: AugmentedSubmittable<(schedule: Schedule | { version?: any; instructionWeights?: any; hostFnWeights?: any; enablePrintln?: any; maxEventTopics?: any; maxStackHeight?: any; maxMemoryPages?: any; maxTableSize?: any; maxSubjectLen?: any; maxCodeSize?: any } | string | Uint8Array) => SubmittableExtrinsic<ApiType>>;
updateSchedule: AugmentedSubmittable<(schedule: Schedule | { version?: any; enablePrintln?: any; limits?: any; instructionWeights?: any; hostFnWeights?: any } | string | Uint8Array) => SubmittableExtrinsic<ApiType>>;
};
council: {
[key: string]: SubmittableExtrinsicFunction<ApiType>;
@@ -391,7 +390,7 @@ declare module '@polkadot/api/types/submittable' {
* Weight: `O(R)` where R is the number of referendums the voter delegating to has
* voted on. Weight is charged as if maximum votes.
**/
delegate: AugmentedSubmittable<(to: AccountId | string | Uint8Array, conviction: Conviction | 'None'|'Locked1x'|'Locked2x'|'Locked3x'|'Locked4x'|'Locked5x'|'Locked6x' | number | Uint8Array, balance: BalanceOf | AnyNumber | Uint8Array) => SubmittableExtrinsic<ApiType>>;
delegate: AugmentedSubmittable<(to: AccountId | string | Uint8Array, conviction: Conviction | 'None' | 'Locked1x' | 'Locked2x' | 'Locked3x' | 'Locked4x' | 'Locked5x' | 'Locked6x' | number | Uint8Array, balance: BalanceOf | AnyNumber | Uint8Array) => SubmittableExtrinsic<ApiType>>;
/**
* Schedule an emergency cancellation of a referendum. Cannot happen twice to the same
* referendum.
@@ -666,7 +665,7 @@ declare module '@polkadot/api/types/submittable' {
* Else, since this is a root call and will go into phragmen, we assume full block for now.
* # </weight>
**/
removeMember: AugmentedSubmittable<(who: LookupSource | Address | AccountId | AccountIndex | LookupSource | string | Uint8Array, hasReplacement: bool | boolean | Uint8Array) => SubmittableExtrinsic<ApiType>>;
removeMember: AugmentedSubmittable<(who: LookupSource | Address | AccountId | AccountIndex | string | Uint8Array, hasReplacement: bool | boolean | Uint8Array) => SubmittableExtrinsic<ApiType>>;
/**
* Remove `origin` as a voter. This removes the lock and returns the bond.
*
@@ -805,14 +804,6 @@ declare module '@polkadot/api/types/submittable' {
**/
vote: AugmentedSubmittable<(votes: Vec<AccountId> | (AccountId | string | Uint8Array)[], value: Compact<BalanceOf> | AnyNumber | Uint8Array) => SubmittableExtrinsic<ApiType>>;
};
finalityTracker: {
[key: string]: SubmittableExtrinsicFunction<ApiType>;
/**
* Hint that the author of this block thinks the best finalized
* block is the given number.
**/
finalHint: AugmentedSubmittable<(hint: Compact<BlockNumber> | AnyNumber | Uint8Array) => SubmittableExtrinsic<ApiType>>;
};
grandpa: {
[key: string]: SubmittableExtrinsicFunction<ApiType>;
/**
@@ -872,7 +863,7 @@ declare module '@polkadot/api/types/submittable' {
* The dispatch origin for this call must be _Signed_ and the sender must have a registered
* sub identity of `sub`.
**/
addSub: AugmentedSubmittable<(sub: LookupSource | Address | AccountId | AccountIndex | LookupSource | string | Uint8Array, data: Data | { None: any } | { Raw: any } | { BlakeTwo256: any } | { Sha256: any } | { Keccak256: any } | { ShaThree256: any } | string | Uint8Array) => SubmittableExtrinsic<ApiType>>;
addSub: AugmentedSubmittable<(sub: LookupSource | Address | AccountId | AccountIndex | string | Uint8Array, data: Data | { None: any } | { Raw: any } | { BlakeTwo256: any } | { Sha256: any } | { Keccak256: any } | { ShaThree256: any } | string | Uint8Array) => SubmittableExtrinsic<ApiType>>;
/**
* Cancel a previous request.
*
@@ -935,7 +926,7 @@ declare module '@polkadot/api/types/submittable' {
* - One event.
* # </weight>
**/
killIdentity: AugmentedSubmittable<(target: LookupSource | Address | AccountId | AccountIndex | LookupSource | string | Uint8Array) => SubmittableExtrinsic<ApiType>>;
killIdentity: AugmentedSubmittable<(target: LookupSource | Address | AccountId | AccountIndex | string | Uint8Array) => SubmittableExtrinsic<ApiType>>;
/**
* Provide a judgement for an account's identity.
*
@@ -957,7 +948,7 @@ declare module '@polkadot/api/types/submittable' {
* - One event.
* # </weight>
**/
provideJudgement: AugmentedSubmittable<(regIndex: Compact<RegistrarIndex> | AnyNumber | Uint8Array, target: LookupSource | Address | AccountId | AccountIndex | LookupSource | string | Uint8Array, judgement: IdentityJudgement | { Unknown: any } | { FeePaid: any } | { Reasonable: any } | { KnownGood: any } | { OutOfDate: any } | { LowQuality: any } | { Erroneous: any } | string | Uint8Array) => SubmittableExtrinsic<ApiType>>;
provideJudgement: AugmentedSubmittable<(regIndex: Compact<RegistrarIndex> | AnyNumber | Uint8Array, target: LookupSource | Address | AccountId | AccountIndex | string | Uint8Array, judgement: IdentityJudgement | { Unknown: any } | { FeePaid: any } | { Reasonable: any } | { KnownGood: any } | { OutOfDate: any } | { LowQuality: any } | { Erroneous: any } | string | Uint8Array) => SubmittableExtrinsic<ApiType>>;
/**
* Remove the sender as a sub-account.
*
@@ -980,14 +971,14 @@ declare module '@polkadot/api/types/submittable' {
* The dispatch origin for this call must be _Signed_ and the sender must have a registered
* sub identity of `sub`.
**/
removeSub: AugmentedSubmittable<(sub: LookupSource | Address | AccountId | AccountIndex | LookupSource | string | Uint8Array) => SubmittableExtrinsic<ApiType>>;
removeSub: AugmentedSubmittable<(sub: LookupSource | Address | AccountId | AccountIndex | string | Uint8Array) => SubmittableExtrinsic<ApiType>>;
/**
* Alter the associated name of the given sub-account.
*
* The dispatch origin for this call must be _Signed_ and the sender must have a registered
* sub identity of `sub`.
**/
renameSub: AugmentedSubmittable<(sub: LookupSource | Address | AccountId | AccountIndex | LookupSource | string | Uint8Array, data: Data | { None: any } | { Raw: any } | { BlakeTwo256: any } | { Sha256: any } | { Keccak256: any } | { ShaThree256: any } | string | Uint8Array) => SubmittableExtrinsic<ApiType>>;
renameSub: AugmentedSubmittable<(sub: LookupSource | Address | AccountId | AccountIndex | string | Uint8Array, data: Data | { None: any } | { Raw: any } | { BlakeTwo256: any } | { Sha256: any } | { Keccak256: any } | { ShaThree256: any } | string | Uint8Array) => SubmittableExtrinsic<ApiType>>;
/**
* Request a judgement from a registrar.
*
@@ -1392,7 +1383,7 @@ declare module '@polkadot/api/types/submittable' {
* Weight is a function of the number of proxies the user has (P).
* # </weight>
**/
addProxy: AugmentedSubmittable<(delegate: AccountId | string | Uint8Array, proxyType: ProxyType | 'Any'|'NonTransfer'|'Governance'|'Staking' | number | Uint8Array, delay: BlockNumber | AnyNumber | Uint8Array) => SubmittableExtrinsic<ApiType>>;
addProxy: AugmentedSubmittable<(delegate: AccountId | string | Uint8Array, proxyType: ProxyType | 'Any' | 'NonTransfer' | 'Governance' | 'Staking' | number | Uint8Array, delay: BlockNumber | AnyNumber | Uint8Array) => SubmittableExtrinsic<ApiType>>;
/**
* Publish the hash of a proxy-call that will be made in the future.
*
@@ -1442,7 +1433,7 @@ declare module '@polkadot/api/types/submittable' {
* # </weight>
* TODO: Might be over counting 1 read
**/
anonymous: AugmentedSubmittable<(proxyType: ProxyType | 'Any'|'NonTransfer'|'Governance'|'Staking' | number | Uint8Array, delay: BlockNumber | AnyNumber | Uint8Array, index: u16 | AnyNumber | Uint8Array) => SubmittableExtrinsic<ApiType>>;
anonymous: AugmentedSubmittable<(proxyType: ProxyType | 'Any' | 'NonTransfer' | 'Governance' | 'Staking' | number | Uint8Array, delay: BlockNumber | AnyNumber | Uint8Array, index: u16 | AnyNumber | Uint8Array) => SubmittableExtrinsic<ApiType>>;
/**
* Removes a previously spawned anonymous proxy.
*
@@ -1465,7 +1456,7 @@ declare module '@polkadot/api/types/submittable' {
* Weight is a function of the number of proxies the user has (P).
* # </weight>
**/
killAnonymous: AugmentedSubmittable<(spawner: AccountId | string | Uint8Array, proxyType: ProxyType | 'Any'|'NonTransfer'|'Governance'|'Staking' | number | Uint8Array, index: u16 | AnyNumber | Uint8Array, height: Compact<BlockNumber> | AnyNumber | Uint8Array, extIndex: Compact<u32> | AnyNumber | Uint8Array) => SubmittableExtrinsic<ApiType>>;
killAnonymous: AugmentedSubmittable<(spawner: AccountId | string | Uint8Array, proxyType: ProxyType | 'Any' | 'NonTransfer' | 'Governance' | 'Staking' | number | Uint8Array, index: u16 | AnyNumber | Uint8Array, height: Compact<BlockNumber> | AnyNumber | Uint8Array, extIndex: Compact<u32> | AnyNumber | Uint8Array) => SubmittableExtrinsic<ApiType>>;
/**
* Dispatch the given `call` from an account that the sender is authorised for through
* `add_proxy`.
@@ -1568,7 +1559,7 @@ declare module '@polkadot/api/types/submittable' {
* Weight is a function of the number of proxies the user has (P).
* # </weight>
**/
removeProxy: AugmentedSubmittable<(delegate: AccountId | string | Uint8Array, proxyType: ProxyType | 'Any'|'NonTransfer'|'Governance'|'Staking' | number | Uint8Array, delay: BlockNumber | AnyNumber | Uint8Array) => SubmittableExtrinsic<ApiType>>;
removeProxy: AugmentedSubmittable<(delegate: AccountId | string | Uint8Array, proxyType: ProxyType | 'Any' | 'NonTransfer' | 'Governance' | 'Staking' | number | Uint8Array, delay: BlockNumber | AnyNumber | Uint8Array) => SubmittableExtrinsic<ApiType>>;
};
recovery: {
[key: string]: SubmittableExtrinsicFunction<ApiType>;
@@ -1999,7 +1990,7 @@ declare module '@polkadot/api/types/submittable' {
* Total Complexity: O(M + logM + B + X)
* # </weight>
**/
judgeSuspendedCandidate: AugmentedSubmittable<(who: AccountId | string | Uint8Array, judgement: SocietyJudgement | 'Rebid'|'Reject'|'Approve' | number | Uint8Array) => SubmittableExtrinsic<ApiType>>;
judgeSuspendedCandidate: AugmentedSubmittable<(who: AccountId | string | Uint8Array, judgement: SocietyJudgement | 'Rebid' | 'Reject' | 'Approve' | number | Uint8Array) => SubmittableExtrinsic<ApiType>>;
/**
* Allow suspension judgement origin to make judgement on a suspended member.
*
@@ -2149,7 +2140,7 @@ declare module '@polkadot/api/types/submittable' {
* Total Complexity: O(M + logM + C)
* # </weight>
**/
vote: AugmentedSubmittable<(candidate: LookupSource | Address | AccountId | AccountIndex | LookupSource | string | Uint8Array, approve: bool | boolean | Uint8Array) => SubmittableExtrinsic<ApiType>>;
vote: AugmentedSubmittable<(candidate: LookupSource | Address | AccountId | AccountIndex | string | Uint8Array, approve: bool | boolean | Uint8Array) => SubmittableExtrinsic<ApiType>>;
/**
* As a member, vouch for someone to join society by placing a bid on their behalf.
*
@@ -2224,7 +2215,7 @@ declare module '@polkadot/api/types/submittable' {
* - Write: Bonded, Payee, [Origin Account], Locks, Ledger
* # </weight>
**/
bond: AugmentedSubmittable<(controller: LookupSource | Address | AccountId | AccountIndex | LookupSource | string | Uint8Array, value: Compact<BalanceOf> | AnyNumber | Uint8Array, payee: RewardDestination | { Staked: any } | { Stash: any } | { Controller: any } | { Account: any } | string | Uint8Array) => SubmittableExtrinsic<ApiType>>;
bond: AugmentedSubmittable<(controller: LookupSource | Address | AccountId | AccountIndex | string | Uint8Array, value: Compact<BalanceOf> | AnyNumber | Uint8Array, payee: RewardDestination | { Staked: any } | { Stash: any } | { Controller: any } | { Account: any } | string | Uint8Array) => SubmittableExtrinsic<ApiType>>;
/**
* Add some extra amount that have appeared in the stash `free_balance` into the balance up
* for staking.
@@ -2365,7 +2356,7 @@ declare module '@polkadot/api/types/submittable' {
* - Writes: Validators, Nominators
* # </weight>
**/
nominate: AugmentedSubmittable<(targets: Vec<LookupSource> | (LookupSource | Address | AccountId | AccountIndex | LookupSource | string | Uint8Array)[]) => SubmittableExtrinsic<ApiType>>;
nominate: AugmentedSubmittable<(targets: Vec<LookupSource> | (LookupSource | Address | AccountId | AccountIndex | string | Uint8Array)[]) => SubmittableExtrinsic<ApiType>>;
/**
* Pay out all the stakers behind a single validator for a single era.
*
@@ -2460,7 +2451,7 @@ declare module '@polkadot/api/types/submittable' {
* - Write: Bonded, Ledger New Controller, Ledger Old Controller
* # </weight>
**/
setController: AugmentedSubmittable<(controller: LookupSource | Address | AccountId | AccountIndex | LookupSource | string | Uint8Array) => SubmittableExtrinsic<ApiType>>;
setController: AugmentedSubmittable<(controller: LookupSource | Address | AccountId | AccountIndex | string | Uint8Array) => SubmittableExtrinsic<ApiType>>;
/**
* Set `HistoryDepth` value. This function will delete any history information
* when `HistoryDepth` is reduced.
@@ -2693,7 +2684,7 @@ declare module '@polkadot/api/types/submittable' {
* - One DB change.
* # </weight>
**/
setKey: AugmentedSubmittable<(updated: LookupSource | Address | AccountId | AccountIndex | LookupSource | string | Uint8Array) => SubmittableExtrinsic<ApiType>>;
setKey: AugmentedSubmittable<(updated: LookupSource | Address | AccountId | AccountIndex | string | Uint8Array) => SubmittableExtrinsic<ApiType>>;
/**
* Authenticates the sudo key and dispatches a function call with `Root` origin.
*
@@ -2720,7 +2711,7 @@ declare module '@polkadot/api/types/submittable' {
* - Weight of derivative `call` execution + 10,000.
* # </weight>
**/
sudoAs: AugmentedSubmittable<(who: LookupSource | Address | AccountId | AccountIndex | LookupSource | string | Uint8Array, call: Call | { callIndex?: any; args?: any } | string | Uint8Array) => SubmittableExtrinsic<ApiType>>;
sudoAs: AugmentedSubmittable<(who: LookupSource | Address | AccountId | AccountIndex | string | Uint8Array, call: Call | { callIndex?: any; args?: any } | string | Uint8Array) => SubmittableExtrinsic<ApiType>>;
/**
* Authenticates the sudo key and dispatches a function call with `Root` origin.
* This function does not check the weight of the call, and instead allows the
@@ -3047,9 +3038,9 @@ declare module '@polkadot/api/types/submittable' {
* The dispatch origin for this call must be `Inherent`.
*
* # <weight>
* - `O(T)` where `T` complexity of `on_timestamp_set`
* - `O(1)` (Note that implementations of `OnTimestampSet` must also be `O(1)`)
* - 1 storage read and 1 storage mutation (codec `O(1)`). (because of `DidUpdate::take` in `on_finalize`)
* - 1 event handler `on_timestamp_set` `O(T)`.
* - 1 event handler `on_timestamp_set`. Must be `O(1)`.
* # </weight>
**/
set: AugmentedSubmittable<(now: Compact<Moment> | AnyNumber | Uint8Array) => SubmittableExtrinsic<ApiType>>;
@@ -3103,7 +3094,7 @@ declare module '@polkadot/api/types/submittable' {
* - `bounty_id`: Bounty ID to award.
* - `beneficiary`: The beneficiary account whom will receive the payout.
**/
awardBounty: AugmentedSubmittable<(bountyId: Compact<ProposalIndex> | AnyNumber | Uint8Array, beneficiary: LookupSource | Address | AccountId | AccountIndex | LookupSource | string | Uint8Array) => SubmittableExtrinsic<ApiType>>;
awardBounty: AugmentedSubmittable<(bountyId: Compact<ProposalIndex> | AnyNumber | Uint8Array, beneficiary: LookupSource | Address | AccountId | AccountIndex | string | Uint8Array) => SubmittableExtrinsic<ApiType>>;
/**
* Claim the payout from an awarded bounty after payout delay.
*
@@ -3176,7 +3167,7 @@ declare module '@polkadot/api/types/submittable' {
* - One DB change.
* # </weight>
**/
proposeCurator: AugmentedSubmittable<(bountyId: Compact<ProposalIndex> | AnyNumber | Uint8Array, curator: LookupSource | Address | AccountId | AccountIndex | LookupSource | string | Uint8Array, fee: Compact<BalanceOf> | AnyNumber | Uint8Array) => SubmittableExtrinsic<ApiType>>;
proposeCurator: AugmentedSubmittable<(bountyId: Compact<ProposalIndex> | AnyNumber | Uint8Array, curator: LookupSource | Address | AccountId | AccountIndex | string | Uint8Array, fee: Compact<BalanceOf> | AnyNumber | Uint8Array) => SubmittableExtrinsic<ApiType>>;
/**
* 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
@@ -3188,7 +3179,7 @@ declare module '@polkadot/api/types/submittable' {
* - DbWrites: `ProposalCount`, `Proposals`, `origin account`
* # </weight>
**/
proposeSpend: AugmentedSubmittable<(value: Compact<BalanceOf> | AnyNumber | Uint8Array, beneficiary: LookupSource | Address | AccountId | AccountIndex | LookupSource | string | Uint8Array) => SubmittableExtrinsic<ApiType>>;
proposeSpend: AugmentedSubmittable<(value: Compact<BalanceOf> | AnyNumber | Uint8Array, beneficiary: LookupSource | Address | AccountId | AccountIndex | string | Uint8Array) => SubmittableExtrinsic<ApiType>>;
/**
* Reject a proposed spend. The original deposit will be slashed.
*
@@ -3351,9 +3342,7 @@ declare module '@polkadot/api/types/submittable' {
* bypassing `frame_system::Trait::BaseCallFilter`).
*
* # <weight>
* - Base weight: 14.39 + .987 * c µs
* - Plus the sum of the weights of the `calls`.
* - Plus one additional event. (repeat read/write)
* - Complexity: O(C) where C is the number of calls to be batched.
* # </weight>
*
* This will return `Ok` in all circumstances. To determine the success of the batch, an
@@ -3363,6 +3352,22 @@ declare module '@polkadot/api/types/submittable' {
* event is deposited.
**/
batch: AugmentedSubmittable<(calls: Vec<Call> | (Call | { callIndex?: any; args?: any } | string | Uint8Array)[]) => SubmittableExtrinsic<ApiType>>;
/**
* Send a batch of dispatch calls and atomically execute them.
* The whole transaction will rollback and fail if any of the calls failed.
*
* May be called from any origin.
*
* - `calls`: The calls to be dispatched from the same origin.
*
* If origin is root then call are dispatch without checking origin filter. (This includes
* bypassing `frame_system::Trait::BaseCallFilter`).
*
* # <weight>
* - Complexity: O(C) where C is the number of calls to be batched.
* # </weight>
**/
batchAll: AugmentedSubmittable<(calls: Vec<Call> | (Call | { callIndex?: any; args?: any } | string | Uint8Array)[]) => SubmittableExtrinsic<ApiType>>;
};
vesting: {
[key: string]: SubmittableExtrinsicFunction<ApiType>;
@@ -3385,7 +3390,7 @@ declare module '@polkadot/api/types/submittable' {
* - Writes: Vesting Storage, Balances Locks, Target Account, Source Account
* # </weight>
**/
forceVestedTransfer: AugmentedSubmittable<(source: LookupSource | Address | AccountId | AccountIndex | LookupSource | string | Uint8Array, target: LookupSource | Address | AccountId | AccountIndex | LookupSource | string | Uint8Array, schedule: VestingInfo | { locked?: any; perBlock?: any; startingBlock?: any } | string | Uint8Array) => SubmittableExtrinsic<ApiType>>;
forceVestedTransfer: AugmentedSubmittable<(source: LookupSource | Address | AccountId | AccountIndex | string | Uint8Array, target: LookupSource | Address | AccountId | AccountIndex | string | Uint8Array, schedule: VestingInfo | { locked?: any; perBlock?: any; startingBlock?: any } | string | Uint8Array) => SubmittableExtrinsic<ApiType>>;
/**
* Unlock any vested funds of the sender account.
*
@@ -3419,7 +3424,7 @@ declare module '@polkadot/api/types/submittable' {
* - Writes: Vesting Storage, Balances Locks, Target Account
* # </weight>
**/
vestOther: AugmentedSubmittable<(target: LookupSource | Address | AccountId | AccountIndex | LookupSource | string | Uint8Array) => SubmittableExtrinsic<ApiType>>;
vestOther: AugmentedSubmittable<(target: LookupSource | Address | AccountId | AccountIndex | string | Uint8Array) => SubmittableExtrinsic<ApiType>>;
/**
* Create a vested transfer.
*
@@ -3438,7 +3443,7 @@ declare module '@polkadot/api/types/submittable' {
* - Writes: Vesting Storage, Balances Locks, Target Account, [Sender Account]
* # </weight>
**/
vestedTransfer: AugmentedSubmittable<(target: LookupSource | Address | AccountId | AccountIndex | LookupSource | string | Uint8Array, schedule: VestingInfo | { locked?: any; perBlock?: any; startingBlock?: any } | string | Uint8Array) => SubmittableExtrinsic<ApiType>>;
vestedTransfer: AugmentedSubmittable<(target: LookupSource | Address | AccountId | AccountIndex | string | Uint8Array, schedule: VestingInfo | { locked?: any; perBlock?: any; startingBlock?: any } | string | Uint8Array) => SubmittableExtrinsic<ApiType>>;
};
}
+38 -32
View File
@@ -1,31 +1,33 @@
// Copyright 2017-2020 @polkadot/api authors & contributors
// SPDX-License-Identifier: Apache-2.0
import { Constants, Storage } from '@polkadot/metadata/Decorated/types';
import { Constants, DecoratedMeta } from '@polkadot/metadata/decorate/types';
import { RpcInterface } from '@polkadot/rpc-core/types';
import { Call, Hash, RuntimeVersion } from '@polkadot/types/interfaces';
import { AnyFunction, CallFunction, Codec, CodecArg as Arg, InterfaceTypes, ModulesWithCalls, Registry, RegistryTypes } from '@polkadot/types/types';
import { StorageEntry } from '@polkadot/types/primitive/types';
import { AnyFunction, CallFunction, Codec, CodecArg as Arg, InterfaceTypes, Registry, RegistryTypes } from '@polkadot/types/types';
import { SubmittableExtrinsic } from '../submittable/types';
import { ApiInterfaceRx, ApiOptions, ApiTypes, DecorateMethod, DecoratedRpc, DecoratedRpcSection, PaginationOptions, QueryableConsts, QueryableModuleStorage, QueryableStorage, QueryableStorageEntry, QueryableStorageMulti, QueryableStorageMultiArg, SubmittableExtrinsicFunction, SubmittableExtrinsics, SubmittableModuleExtrinsics } from '../types';
import BN from 'bn.js';
import { BehaviorSubject, Observable, combineLatest, of } from 'rxjs';
import { map, switchMap, take, tap, toArray } from 'rxjs/operators';
import decorateDerive, { ExactDerive } from '@polkadot/api-derive';
import { ExactDerive, decorateDerive } from '@polkadot/api-derive';
import { memo } from '@polkadot/api-derive/util';
import DecoratedMeta from '@polkadot/metadata/Decorated';
import RpcCore from '@polkadot/rpc-core';
import { Metadata, expandMetadata } from '@polkadot/metadata';
import { RpcCore } from '@polkadot/rpc-core';
import { WsProvider } from '@polkadot/rpc-provider';
import { Metadata, Option, Raw, Text, TypeRegistry, u64 } from '@polkadot/types';
import { Option, Raw, StorageKey, Text, u64 } from '@polkadot/types';
import { DEFAULT_VERSION as EXTRINSIC_DEFAULT_VERSION } from '@polkadot/types/extrinsic/constants';
import StorageKey, { StorageEntry, unwrapStorageType } from '@polkadot/types/primitive/StorageKey';
import { TypeRegistry } from '@polkadot/types/create';
import { unwrapStorageType } from '@polkadot/types/primitive/StorageKey';
import { assert, compactStripLength, logger, u8aToHex } from '@polkadot/util';
import { createSubmittable } from '../submittable';
import augmentObject from '../util/augmentObject';
import { augmentObject } from '../util/augmentObject';
import { decorateSections, DeriveAllSections } from '../util/decorate';
import { extractStorageArgs } from '../util/validate';
import Events from './Events';
import { Events } from './Events';
interface MetaDecoration {
callIndex?: Uint8Array;
@@ -42,7 +44,7 @@ const l = logger('api/init');
let instanceCounter = 0;
export default abstract class Decorate<ApiType extends ApiTypes> extends Events {
export abstract class Decorate<ApiType extends ApiTypes> extends Events {
readonly #instanceId: string;
#registry: Registry;
@@ -172,22 +174,22 @@ export default abstract class Decorate<ApiType extends ApiTypes> extends Events
}
public injectMetadata (metadata: Metadata, fromEmpty?: boolean, registry?: Registry): void {
const decoratedMeta = new DecoratedMeta(registry || this.#registry, metadata);
const decoratedMeta = expandMetadata(registry || this.#registry, metadata);
if (fromEmpty || !this._extrinsics) {
this._extrinsics = this._decorateExtrinsics(decoratedMeta.tx, this._decorateMethod);
this._rx.tx = this._decorateExtrinsics(decoratedMeta.tx, this._rxDecorateMethod);
this._extrinsics = this._decorateExtrinsics(decoratedMeta, this._decorateMethod);
this._rx.tx = this._decorateExtrinsics(decoratedMeta, this._rxDecorateMethod);
} else {
augmentObject('tx', this._decorateExtrinsics(decoratedMeta.tx, this._decorateMethod), this._extrinsics, false);
augmentObject(null, this._decorateExtrinsics(decoratedMeta.tx, this._rxDecorateMethod), this._rx.tx, false);
augmentObject('tx', this._decorateExtrinsics(decoratedMeta, this._decorateMethod), this._extrinsics, false);
augmentObject(null, this._decorateExtrinsics(decoratedMeta, this._rxDecorateMethod), this._rx.tx, false);
}
// this API
augmentObject('query', this._decorateStorage(decoratedMeta.query, this._decorateMethod), this._query, fromEmpty);
augmentObject('query', this._decorateStorage(decoratedMeta, this._decorateMethod), this._query, fromEmpty);
augmentObject('consts', decoratedMeta.consts, this._consts, fromEmpty);
// rx
augmentObject(null, this._decorateStorage(decoratedMeta.query, this._rxDecorateMethod), this._rx.query, fromEmpty);
augmentObject(null, this._decorateStorage(decoratedMeta, this._rxDecorateMethod), this._rx.query, fromEmpty);
augmentObject(null, decoratedMeta.consts, this._rx.consts, fromEmpty);
}
@@ -225,7 +227,7 @@ export default abstract class Decorate<ApiType extends ApiTypes> extends Events
protected _filterRpcMethods (exposed: string[]): void {
const hasResults = exposed.length !== 0;
const allKnown = [...this._rpcCore.mapping.entries()];
const allKeys = allKnown.reduce((allKeys: string[], [, { alias, method, pubsub, section }]): string[] => {
const allKeys = allKnown.reduce((allKeys: string[], [, { alias, endpoint, method, pubsub, section }]): string[] => {
allKeys.push(`${section}_${method}`);
if (pubsub) {
@@ -237,6 +239,10 @@ export default abstract class Decorate<ApiType extends ApiTypes> extends Events
allKeys.push(...alias);
}
if (endpoint) {
allKeys.push(endpoint);
}
return allKeys;
}, []);
const unknown = exposed.filter((key) => !allKeys.includes(key));
@@ -270,6 +276,8 @@ export default abstract class Decorate<ApiType extends ApiTypes> extends Events
if (this.hasSubscriptions || !(methodName.startsWith('subscribe') || methodName.startsWith('unsubscribe'))) {
(section as Record<string, unknown>)[methodName] = decorateMethod(method, { methodName }) as unknown;
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
(section as Record<string, { json: unknown }>)[methodName].json = decorateMethod(method.json, { methodName }) as unknown;
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
(section as Record<string, { raw: unknown }>)[methodName].raw = decorateMethod(method.raw, { methodName }) as unknown;
}
@@ -284,18 +292,16 @@ export default abstract class Decorate<ApiType extends ApiTypes> extends Events
// eslint-disable-next-line @typescript-eslint/no-unsafe-return
return decorateMethod((calls: QueryableStorageMultiArg<ApiType>[]): Observable<Codec[]> =>
this._rpcCore.state.subscribeStorage(
calls.map((arg: QueryableStorageMultiArg<ApiType>): [QueryableStorageEntry<ApiType>, ...Arg[]] =>
// the input is a QueryableStorageEntry, convert to StorageEntry
// eslint-disable-next-line @typescript-eslint/no-unsafe-return
calls.map((arg: QueryableStorageMultiArg<ApiType>) =>
Array.isArray(arg)
? [arg[0].creator, ...arg.slice(1)]
: [arg.creator] as any)));
: [arg.creator])));
}
protected _decorateExtrinsics<ApiType extends ApiTypes> (extrinsics: ModulesWithCalls, decorateMethod: DecorateMethod<ApiType>): SubmittableExtrinsics<ApiType> {
protected _decorateExtrinsics<ApiType extends ApiTypes> ({ tx }: DecoratedMeta, decorateMethod: DecorateMethod<ApiType>): SubmittableExtrinsics<ApiType> {
const creator = createSubmittable(this._type, this._rx, decorateMethod);
return Object.entries(extrinsics).reduce((out, [name, section]): SubmittableExtrinsics<ApiType> => {
return Object.entries(tx).reduce((out, [name, section]): SubmittableExtrinsics<ApiType> => {
out[name] = Object.entries(section).reduce((out, [name, method]): SubmittableModuleExtrinsics<ApiType> => {
out[name] = this._decorateExtrinsicEntry(method, creator);
@@ -314,8 +320,8 @@ export default abstract class Decorate<ApiType extends ApiTypes> extends Events
return this._decorateFunctionMeta(method as any, decorated as any) as unknown as SubmittableExtrinsicFunction<ApiType>;
}
protected _decorateStorage<ApiType extends ApiTypes> (storage: Storage, decorateMethod: DecorateMethod<ApiType>): QueryableStorage<ApiType> {
return Object.entries(storage).reduce((out, [name, section]): QueryableStorage<ApiType> => {
protected _decorateStorage<ApiType extends ApiTypes> ({ query }: DecoratedMeta, decorateMethod: DecorateMethod<ApiType>): QueryableStorage<ApiType> {
return Object.entries(query).reduce((out, [name, section]): QueryableStorage<ApiType> => {
out[name] = Object.entries(section).reduce((out, [name, method]): QueryableModuleStorage<ApiType> => {
out[name] = this._decorateStorageEntry(method, decorateMethod);
@@ -424,7 +430,7 @@ export default abstract class Decorate<ApiType extends ApiTypes> extends Events
));
}
private _retrieveMapKeys ({ iterKey, meta }: StorageEntry, at: Hash | Uint8Array | string | null, arg?: Arg): Observable<StorageKey[]> {
private _retrieveMapKeys ({ iterKey, meta, method, section }: StorageEntry, at: Hash | Uint8Array | string | null, arg?: Arg): Observable<StorageKey[]> {
assert(iterKey && (meta.type.isMap || meta.type.isDoubleMap), 'keys can only be retrieved on maps, linked maps and double maps');
const headKey = iterKey(arg).toHex();
@@ -436,7 +442,7 @@ export default abstract class Decorate<ApiType extends ApiTypes> extends Events
return startSubject.pipe(
switchMap((startKey) =>
query(startKey).pipe(
map((keys) => keys.map((key) => key.setMeta(meta)))
map((keys) => keys.map((key) => key.setMeta(meta, section, method)))
)
),
tap((keys): void => {
@@ -449,19 +455,19 @@ export default abstract class Decorate<ApiType extends ApiTypes> extends Events
);
}
private _retrieveMapKeysPaged ({ iterKey, meta }: StorageEntry, opts: PaginationOptions): Observable<StorageKey[]> {
private _retrieveMapKeysPaged ({ iterKey, meta, method, section }: StorageEntry, opts: PaginationOptions): Observable<StorageKey[]> {
assert(iterKey && (meta.type.isMap || meta.type.isDoubleMap), 'keys can only be retrieved on maps, linked maps and double maps');
const headKey = iterKey(opts.arg).toHex();
return this._rpcCore.state.getKeysPaged(headKey, opts.pageSize, opts.startKey || headKey).pipe(
map((keys) => keys.map((key) => key.setMeta(meta)))
map((keys) => keys.map((key) => key.setMeta(meta, section, method)))
);
}
private _retrieveMapEntries (entry: StorageEntry, at: Hash | Uint8Array | string | null, arg?: Arg): Observable<[StorageKey, Codec][]> {
const query = at
? this._rpcCore.state.queryStorageAt
const query = this._rpcCore.state.queryStorageAt
? at
? (keyset: StorageKey[]) => this._rpcCore.state.queryStorageAt<Codec[]>(keyset, at)
: (keyset: StorageKey[]) => this._rpcCore.state.queryStorageAt<Codec[]>(keyset)
// this is horrible, but need older support (which now doesn't work with at)
+1 -1
View File
@@ -5,7 +5,7 @@ import { ApiInterfaceEvents } from '../types';
import EventEmitter from 'eventemitter3';
export default class Events {
export class Events {
#eventemitter = new EventEmitter();
protected emit (type: ApiInterfaceEvents, ...args: any[]): boolean {
+215
View File
@@ -0,0 +1,215 @@
// Copyright 2017-2020 @polkadot/api authors & contributors
// SPDX-License-Identifier: Apache-2.0
import { RpcInterface } from '@polkadot/rpc-core/types';
import { Hash, RuntimeVersion } from '@polkadot/types/interfaces';
import { ApiInterfaceRx, ApiTypes, DecoratedRpc, QueryableConsts, QueryableStorage, QueryableStorageMulti, SubmittableExtrinsics } from '../types';
import { Metadata } from '@polkadot/metadata';
import { Text } from '@polkadot/types';
import { assertReturn } from '@polkadot/util';
import { Init } from './Init';
interface PkgJson {
name: string;
version: string;
}
let pkgJson: PkgJson = { name: '@polkadot/api', version: '-' };
import('../package.json')
.then((_pkgJson: unknown): void => {
pkgJson = _pkgJson as PkgJson;
})
.catch((): void => {
// ignore
});
function assertResult<T> (value: T | undefined): T {
return assertReturn(value, 'Api needs to be initialized before using, listen on \'ready\'');
}
export abstract class Getters<ApiType extends ApiTypes> extends Init<ApiType> {
/**
* @description Contains the parameter types (constants) of all modules.
*
* The values are instances of the appropriate type and are accessible using `section`.`constantName`,
*
* @example
* <BR>
*
* ```javascript
* console.log(api.consts.democracy.enactmentPeriod.toString())
* ```
*/
public get consts (): QueryableConsts<ApiType> {
return assertResult(this._consts);
}
/**
* @description Derived results that are injected into the API, allowing for combinations of various query results.
*
* @example
* <BR>
*
* ```javascript
* api.derive.chain.bestNumber((number) => {
* console.log('best number', number);
* });
* ```
*/
public get derive (): ReturnType<Getters<ApiType>['_decorateDerive']> {
return assertResult(this._derive);
}
/**
* @description Returns the version of extrinsics in-use on this chain
*/
public get extrinsicVersion (): number {
return this._extrinsicType;
}
/**
* @description Contains the genesis Hash of the attached chain. Apart from being useful to determine the actual chain, it can also be used to sign immortal transactions.
*/
public get genesisHash (): Hash {
return assertResult(this._genesisHash);
}
/**
* @description `true` when subscriptions are supported
*/
public get hasSubscriptions (): boolean {
return this._rpcCore.provider.hasSubscriptions;
}
/**
* @description true is the underlying provider is connected
*/
public get isConnected (): boolean {
return this._isConnected.getValue();
}
/**
* @description The library information name & version (from package.json)
*/
public get libraryInfo (): string {
return `${pkgJson.name} v${pkgJson.version}`;
}
/**
* @description Contains all the chain state modules and their subsequent methods in the API. These are attached dynamically from the runtime metadata.
*
* All calls inside the namespace, is denoted by `section`.`method` and may take an optional query parameter. As an example, `api.query.timestamp.now()` (current block timestamp) does not take parameters, while `api.query.system.account(<accountId>)` (retrieving the associated nonce & balances for an account), takes the `AccountId` as a parameter.
*
* @example
* <BR>
*
* ```javascript
* api.query.system.account(<accountId>, ([nonce, balance]) => {
* console.log('new free balance', balance.free, 'new nonce', nonce);
* });
* ```
*/
public get query (): QueryableStorage<ApiType> {
return assertResult(this._query);
}
/**
* @description Allows for the querying of multiple storage entries and the combination thereof into a single result. This is a very optimal way to make multiple queries since it only makes a single connection to the node and retrieves the data over one subscription.
*
* @example
* <BR>
*
* ```javascript
* const unsub = await api.queryMulti(
* [
* // you can include the storage without any parameters
* api.query.balances.totalIssuance,
* // or you can pass parameters to the storage query
* [api.query.system.account, '5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY']
* ],
* ([existential, [, { free }]]) => {
* console.log(`You have ${free.sub(existential)} more than the existential deposit`);
*
* unsub();
* }
* );
* ```
*/
public get queryMulti (): QueryableStorageMulti<ApiType> {
return assertResult(this._queryMulti);
}
/**
* @description Contains all the raw rpc sections and their subsequent methods in the API as defined by the jsonrpc interface definitions. Unlike the dynamic `api.query` and `api.tx` sections, these methods are fixed (although extensible with node upgrades) and not determined by the runtime.
*
* RPC endpoints available here allow for the query of chain, node and system information, in addition to providing interfaces for the raw queries of state (using known keys) and the submission of transactions.
*
* @example
* <BR>
*
* ```javascript
* api.rpc.chain.subscribeNewHeads((header) => {
* console.log('new header', header);
* });
* ```
*/
public get rpc (): DecoratedRpc<ApiType, RpcInterface> {
return assertResult(this._rpc);
}
/**
* @description Contains the chain information for the current node.
*/
public get runtimeChain (): Text {
return assertResult(this._runtimeChain);
}
/**
* @description Yields the current attached runtime metadata. Generally this is only used to construct extrinsics & storage, but is useful for current runtime inspection.
*/
public get runtimeMetadata (): Metadata {
return assertResult(this._runtimeMetadata);
}
/**
* @description Contains the version information for the current runtime.
*/
public get runtimeVersion (): RuntimeVersion {
return assertResult(this._runtimeVersion);
}
/**
* @description The underlying Rx API interface
*/
public get rx (): Pick<ApiInterfaceRx, 'tx' | 'rpc'> {
return assertResult(this._rx as Pick<ApiInterfaceRx, 'tx' | 'rpc'>);
}
/**
* @description The type of this API instance, either 'rxjs' or 'promise'
*/
public get type (): ApiTypes {
return this._type;
}
/**
* @description Contains all the extrinsic modules and their subsequent methods in the API. It allows for the construction of transactions and the submission thereof. These are attached dynamically from the runtime metadata.
*
* @example
* <BR>
*
* ```javascript
* api.tx.balances
* .transfer(<recipientId>, <balance>)
* .signAndSend(<keyPair>, ({status}) => {
* console.log('tx status', status.asFinalized.toHex());
* });
* ```
*/
public get tx (): SubmittableExtrinsics<ApiType> {
return assertResult(this._extrinsics);
}
}
+6 -3
View File
@@ -9,20 +9,22 @@ import { VersionedRegistry } from './types';
import BN from 'bn.js';
import { Observable, Subscription, of } from 'rxjs';
import { map, switchMap } from 'rxjs/operators';
import { Metadata, Text, TypeRegistry } from '@polkadot/types';
import { Metadata } from '@polkadot/metadata';
import { Text } from '@polkadot/types';
import { TypeRegistry } from '@polkadot/types/create';
import { LATEST_EXTRINSIC_VERSION } from '@polkadot/types/extrinsic/Extrinsic';
import { getSpecAlias, getSpecTypes, getUpgradeVersion } from '@polkadot/types-known';
import { BN_ZERO, assert, logger, u8aEq, u8aToU8a } from '@polkadot/util';
import { cryptoWaitReady } from '@polkadot/util-crypto';
import Decorate from './Decorate';
import { Decorate } from './Decorate';
const KEEPALIVE_INTERVAL = 15000;
const DEFAULT_BLOCKNUMBER = { unwrap: () => BN_ZERO };
const l = logger('api/init');
export default abstract class Init<ApiType extends ApiTypes> extends Decorate<ApiType> {
export abstract class Init<ApiType extends ApiTypes> extends Decorate<ApiType> {
#healthTimer: NodeJS.Timeout | null = null;
#registries: VersionedRegistry[] = [];
@@ -317,6 +319,7 @@ export default abstract class Init<ApiType extends ApiTypes> extends Decorate<Ap
const error = new Error(`FATAL: Unable to initialize the API: ${(_error as Error).message}`);
l.error(error);
l.error(_error);
this.emit('error', error);
}
+4 -210
View File
@@ -1,15 +1,12 @@
// Copyright 2017-2020 @polkadot/api authors & contributors
// SPDX-License-Identifier: Apache-2.0
import { RpcInterface } from '@polkadot/rpc-core/types';
import { Hash, RuntimeVersion } from '@polkadot/types/interfaces';
import { CallFunction, RegistryError, SignerPayloadRawBase } from '@polkadot/types/types';
import { ApiInterfaceRx, ApiOptions, ApiTypes, DecoratedRpc, DecorateMethod, QueryableConsts, QueryableStorage, QueryableStorageMulti, SubmittableExtrinsics, Signer } from '../types';
import { ApiOptions, ApiTypes, DecorateMethod, Signer } from '../types';
import { Metadata, Text } from '@polkadot/types';
import { assert, isString, isUndefined, u8aToHex, u8aToU8a } from '@polkadot/util';
import { assert, isString, u8aToHex, u8aToU8a } from '@polkadot/util';
import Init from './Init';
import { Getters } from './Getters';
interface KeyringSigner {
sign (message: Uint8Array): Uint8Array;
@@ -19,28 +16,7 @@ interface SignerRawOptions {
signer?: Signer;
}
interface PkgJson {
name: string;
version: string;
}
let pkgJson: PkgJson = { name: '@polkadot/api', version: '-' };
import('../package.json')
.then((_pkgJson: unknown): void => {
pkgJson = _pkgJson as PkgJson;
})
.catch((): void => {
// ignore
});
function assertResult<T> (value: T | undefined): T {
assert(!isUndefined(value), 'Api needs to be initialized before using, listen on \'ready\'');
return value;
}
export default abstract class ApiBase<ApiType extends ApiTypes> extends Init<ApiType> {
export abstract class ApiBase<ApiType extends ApiTypes> extends Getters<ApiType> {
/**
* @description Create an instance of the class
*
@@ -63,188 +39,6 @@ export default abstract class ApiBase<ApiType extends ApiTypes> extends Init<Api
super(options, type, decorateMethod);
}
/**
* @description Contains the parameter types (constants) of all modules.
*
* The values are instances of the appropriate type and are accessible using `section`.`constantName`,
*
* @example
* <BR>
*
* ```javascript
* console.log(api.consts.democracy.enactmentPeriod.toString())
* ```
*/
public get consts (): QueryableConsts<ApiType> {
return assertResult(this._consts);
}
/**
* @description Derived results that are injected into the API, allowing for combinations of various query results.
*
* @example
* <BR>
*
* ```javascript
* api.derive.chain.bestNumber((number) => {
* console.log('best number', number);
* });
* ```
*/
public get derive (): ReturnType<ApiBase<ApiType>['_decorateDerive']> {
return assertResult(this._derive);
}
/**
* @description Returns the version of extrinsics in-use on this chain
*/
public get extrinsicVersion (): number {
return this._extrinsicType;
}
/**
* @description Contains the genesis Hash of the attached chain. Apart from being useful to determine the actual chain, it can also be used to sign immortal transactions.
*/
public get genesisHash (): Hash {
return assertResult(this._genesisHash);
}
/**
* @description `true` when subscriptions are supported
*/
public get hasSubscriptions (): boolean {
return this._rpcCore.provider.hasSubscriptions;
}
/**
* @description true is the underlying provider is connected
*/
public get isConnected (): boolean {
return this._isConnected.getValue();
}
/**
* @description The library information name & version (from package.json)
*/
public get libraryInfo (): string {
return `${pkgJson.name} v${pkgJson.version}`;
}
/**
* @description Contains all the chain state modules and their subsequent methods in the API. These are attached dynamically from the runtime metadata.
*
* All calls inside the namespace, is denoted by `section`.`method` and may take an optional query parameter. As an example, `api.query.timestamp.now()` (current block timestamp) does not take parameters, while `api.query.system.account(<accountId>)` (retrieving the associated nonce & balances for an account), takes the `AccountId` as a parameter.
*
* @example
* <BR>
*
* ```javascript
* api.query.system.account(<accountId>, ([nonce, balance]) => {
* console.log('new free balance', balance.free, 'new nonce', nonce);
* });
* ```
*/
public get query (): QueryableStorage<ApiType> {
return assertResult(this._query);
}
/**
* @description Allows for the querying of multiple storage entries and the combination thereof into a single result. This is a very optimal way to make multiple queries since it only makes a single connection to the node and retrieves the data over one subscription.
*
* @example
* <BR>
*
* ```javascript
* const unsub = await api.queryMulti(
* [
* // you can include the storage without any parameters
* api.query.balances.totalIssuance,
* // or you can pass parameters to the storage query
* [api.query.system.account, '5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY']
* ],
* ([existential, [, { free }]]) => {
* console.log(`You have ${free.sub(existential)} more than the existential deposit`);
*
* unsub();
* }
* );
* ```
*/
public get queryMulti (): QueryableStorageMulti<ApiType> {
return assertResult(this._queryMulti);
}
/**
* @description Contains all the raw rpc sections and their subsequent methods in the API as defined by the jsonrpc interface definitions. Unlike the dynamic `api.query` and `api.tx` sections, these methods are fixed (although extensible with node upgrades) and not determined by the runtime.
*
* RPC endpoints available here allow for the query of chain, node and system information, in addition to providing interfaces for the raw queries of state (using known keys) and the submission of transactions.
*
* @example
* <BR>
*
* ```javascript
* api.rpc.chain.subscribeNewHeads((header) => {
* console.log('new header', header);
* });
* ```
*/
public get rpc (): DecoratedRpc<ApiType, RpcInterface> {
return assertResult(this._rpc);
}
/**
* @description Contains the chain information for the current node.
*/
public get runtimeChain (): Text {
return assertResult(this._runtimeChain);
}
/**
* @description Yields the current attached runtime metadata. Generally this is only used to construct extrinsics & storage, but is useful for current runtime inspection.
*/
public get runtimeMetadata (): Metadata {
return assertResult(this._runtimeMetadata);
}
/**
* @description Contains the version information for the current runtime.
*/
public get runtimeVersion (): RuntimeVersion {
return assertResult(this._runtimeVersion);
}
/**
* @description The underlying Rx API interface
*/
public get rx (): Pick<ApiInterfaceRx, 'tx' | 'rpc'> {
return assertResult(this._rx as Pick<ApiInterfaceRx, 'tx' | 'rpc'>);
}
/**
* @description The type of this API instance, either 'rxjs' or 'promise'
*/
public get type (): ApiTypes {
return this._type;
}
/**
* @description Contains all the extrinsic modules and their subsequent methods in the API. It allows for the construction of transactions and the submission thereof. These are attached dynamically from the runtime metadata.
*
* @example
* <BR>
*
* ```javascript
* api.tx.balances
* .transfer(<recipientId>, <balance>)
* .signAndSend(<keyPair>, ({status}) => {
* console.log('tx status', status.asFinalized.toHex());
* });
* ```
*/
public get tx (): SubmittableExtrinsics<ApiType> {
return assertResult(this._extrinsics);
}
/**
* @description Connect from the underlying provider, halting all network traffic
*/
+2 -2
View File
@@ -1,8 +1,8 @@
// Copyright 2017-2020 @polkadot/api authors & contributors
// SPDX-License-Identifier: Apache-2.0
import { Constants } from '@polkadot/metadata/Decorated/types';
import { Metadata } from '@polkadot/types';
import { Constants } from '@polkadot/metadata/decorate/types';
import { Metadata } from '@polkadot/metadata';
import { Registry } from '@polkadot/types/types';
import BN from 'bn.js';
+31 -33
View File
@@ -8,8 +8,8 @@ import { IExtrinsic, IMethod } from '@polkadot/types/types';
import { ApiPromise } from '@polkadot/api';
import { HeaderExtended } from '@polkadot/api-derive';
import testKeyring, { TestKeyringMap } from '@polkadot/keyring/testingPairs';
import { createTypeUnsafe, TypeRegistry } from '@polkadot/types';
import { TestKeyringMap, createTestPairs } from '@polkadot/keyring/testingPairs';
import { createTypeUnsafe, TypeRegistry } from '@polkadot/types/create';
import { SubmittableResult } from './';
@@ -34,7 +34,7 @@ async function derive (api: ApiPromise): Promise<void> {
console.log('fees', fees);
}
async function query (api: ApiPromise, keyring: TestKeyringMap): Promise<void> {
async function query (api: ApiPromise, pairs: TestKeyringMap): Promise<void> {
const intentions = await api.query.staking.bonded();
console.log('intentions:', intentions);
@@ -47,15 +47,14 @@ async function query (api: ApiPromise, keyring: TestKeyringMap): Promise<void> {
const oldBal = await api.query.balances.totalIssuance.at('abcd');
// It's hard to correctly type .multi. Expected: `Balance[]`, actual: Codec[].
// In the meantime, we can case with `<Balance>` (this is not available on recent chains)
const multi = await api.query.balances.freeBalance.multi<Balance>([keyring.alice.address, keyring.bob.address]);
const multi = await api.query.balances.freeBalance.multi<Balance>([pairs.alice.address, pairs.bob.address]);
console.log('query types:', bar, bal, bal2, override, oldBal, multi);
// check multi for unsub
const multiUnsub = await api.queryMulti([
[api.query.system.account, keyring.eve.address],
// older chains only
[api.query.system.accountNonce, keyring.bob.address]
[api.query.staking.validators],
[api.query.system.events]
], (values): void => {
console.log('values', values);
@@ -64,13 +63,15 @@ async function query (api: ApiPromise, keyring: TestKeyringMap): Promise<void> {
// check multi , Promise result
const multiRes = await api.queryMulti([
[api.query.system.account, keyring.eve.address],
[api.query.system.account, pairs.eve.address],
// older chains only
[api.query.system.accountNonce, keyring.bob.address]
[api.query.system.accountNonce, pairs.eve.address]
]);
console.log(multiRes);
}
async function queryExtra (api: ApiPromise, pairs: TestKeyringMap): Promise<void> {
// events destructing
await api.query.system.events((records): void => {
records.forEach(({ event, phase }): void => {
@@ -95,7 +96,7 @@ async function query (api: ApiPromise, keyring: TestKeyringMap): Promise<void> {
await api.query.staking.nominatorSlashInEra.entries(123); // should take a param
// check range
await api.query.balances.freeBalance.range<Balance>(['0x1234'], keyring.bob.address);
await api.query.balances.freeBalance.range<Balance>(['0x1234'], pairs.bob.address);
// check range types
const entries = await api.query.system.events.range(['0x12345', '0x7890']);
@@ -114,7 +115,8 @@ async function rpc (api: ApiPromise): Promise<void> {
console.log('current balance:', balance.toString());
});
// using raw
// using json & raw
await api.rpc.chain.getBlock.json('0x123456');
await api.rpc.chain.getBlock.raw('0x123456');
// using raw subs
@@ -137,36 +139,33 @@ function types (api: ApiPromise): void {
console.log(balance, gas, compact, gasUnsafe, overriddenUnsafe, api.createType('AccountData'));
}
async function tx (api: ApiPromise, keyring: TestKeyringMap): Promise<void> {
async function tx (api: ApiPromise, pairs: TestKeyringMap): Promise<void> {
// transfer, also allows for BigInt inputs here
const transfer = api.tx.balances.transfer(keyring.bob.address, 123456789n);
const transfer = api.tx.balances.transfer(pairs.bob.address, 123456789n);
console.log('transfer as Call', transfer as IMethod);
console.log('transfer as Extrinsic', transfer as IExtrinsic);
console.log('transfer casted', transfer as IMethod, transfer as IExtrinsic);
// simple "return the hash" variant
console.log('hash:', (await transfer.signAndSend(keyring.alice)).toHex());
console.log('hash:', (await transfer.signAndSend(pairs.alice)).toHex());
// passing options, but waiting for hash
const nonce = await api.query.system.accountNonce<Index>(keyring.alice.address);
const nonce = await api.query.system.accountNonce<Index>(pairs.alice.address);
(await api.tx.balances
.transfer(keyring.bob.address, 12345)
.signAndSend(keyring.alice, { nonce })
.transfer(pairs.bob.address, 12345)
.signAndSend(pairs.alice, { nonce })
).toHex();
// just with the callback
await api.tx.balances
.transfer(keyring.bob.address, 12345)
.signAndSend(keyring.alice, ({ status }: SubmittableResult): void => {
console.log('transfer status:', status.type);
});
.transfer(pairs.bob.address, 12345)
.signAndSend(pairs.alice, ({ status }: SubmittableResult) => console.log(status.type));
// with options and the callback
const nonce2 = await api.query.system.accountNonce(keyring.alice.address);
const nonce2 = await api.query.system.accountNonce(pairs.alice.address);
const unsub2 = await api.tx.balances
.transfer(keyring.bob.address, 12345)
.signAndSend(keyring.alice, { nonce: nonce2 }, ({ status }: SubmittableResult): void => {
.transfer(pairs.bob.address, 12345)
.signAndSend(pairs.alice, { nonce: nonce2 }, ({ status }: SubmittableResult): void => {
console.log('transfer status:', status.type);
unsub2();
@@ -176,26 +175,25 @@ async function tx (api: ApiPromise, keyring: TestKeyringMap): Promise<void> {
const second = api.tx.democracy.second(123, 5);
// eslint-disable-next-line @typescript-eslint/no-floating-promises
second.signAndSend('123', (result): void => {
console.log(result);
});
await second.signAndSend('123', (result) => console.log(result));
// it handles enum inputs correctly
await api.tx.democracy.proxyVote(123, { Split: { nay: 456, yay: 123 } }).signAndSend(keyring.alice);
await api.tx.democracy.proxyVote(123, { Split: { nay: 456, yay: 123 } }).signAndSend(pairs.alice);
}
async function main (): Promise<void> {
const api = await ApiPromise.create();
const keyring = testKeyring();
const pairs = createTestPairs();
// eslint-disable-next-line @typescript-eslint/no-floating-promises
Promise.all([
consts(api),
derive(api),
query(api, keyring),
query(api, pairs),
queryExtra(api, pairs),
rpc(api),
types(api),
tx(api, keyring)
tx(api, pairs)
]);
}
+8
View File
@@ -0,0 +1,8 @@
// Copyright 2017-2020 @polkadot/api authors & contributors
// SPDX-License-Identifier: Apache-2.0
import { detectPackage } from '@polkadot/util';
// FIXME This really should be `import(...).then(...)`, but need to check rejections
// eslint-disable-next-line @typescript-eslint/no-var-requires
detectPackage(require('./package.json'), typeof __dirname !== 'undefined' && __dirname);
+6 -9
View File
@@ -1,15 +1,12 @@
// Copyright 2017-2020 @polkadot/api authors & contributors
// SPDX-License-Identifier: Apache-2.0
import { detectPackage } from '@polkadot/util';
// FIXME This really should be `import(...).then(...)`, but need to check rejections
// eslint-disable-next-line @typescript-eslint/no-var-requires
detectPackage(require('./package.json'), typeof __dirname !== 'undefined' && __dirname);
import './detectPackage';
export { Keyring } from '@polkadot/keyring';
export { WsProvider } from '@polkadot/rpc-provider';
export { WsProvider } from '@polkadot/rpc-provider/ws';
export { default as ApiPromise } from './promise';
export { default as ApiRx } from './rx';
export * from './submittable';
export { ApiPromise } from './promise';
export { ApiRx } from './rx';
export { SubmittableResult } from './submittable';

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