Compare commits

...
106 Commits
Author SHA1 Message Date
Github Actions d1a1be49c5 [CI Skip] release/stable 3.11.1
skip-checks: true
2021-02-28 12:49:45 +00:00
Jaco Greeff 4b6ad647a2 3.11 (#3242) 2021-02-28 13:39:57 +01:00
Jaco Greeff 04f656cafa Ensure metadata.toJSON applies type aliasses (#3243) 2021-02-28 13:35:25 +01:00
Github Actions 09bbd5f6c9 [CI Skip] release/beta 3.10.3-19
skip-checks: true
2021-02-28 10:51:08 +00:00
Jaco Greeff dbc3df6d09 Bump common (#3241) 2021-02-28 11:42:16 +01:00
Github Actions 26865f92e3 [CI Skip] release/beta 3.10.3-18
skip-checks: true
2021-02-28 09:40:56 +00:00
Jaco Greeff 73045de73d Fix election candidate derive (#3239) 2021-02-28 10:33:16 +01:00
Github Actions 6d3491b9f1 [CI Skip] release/beta 3.10.3-17
skip-checks: true
2021-02-28 09:21:56 +00:00
Jaco Greeff 886f3a3c08 Revert "modified api-derive balances to allow use of custom balance storages … (#3223)" (#3238)
This reverts commit ab8b381d8b.
2021-02-28 10:12:54 +01:00
Github Actions c72f976895 [CI Skip] release/beta 3.10.3-16
skip-checks: true
2021-02-28 09:02:15 +00:00
Alex D ab8b381d8b modified api-derive balances to allow use of custom balance storages … (#3223)
* modified api-derive balances to allow use of custom balance storages via derives; current implementation only works with standard call signatures

* type predicate as filter value
2021-02-28 09:53:35 +01:00
Github Actions 443e29a3be [CI Skip] release/beta 3.10.3-15
skip-checks: true
2021-02-28 08:25:59 +00:00
Jaco Greeff 117bb5717a Bump common (#3236) 2021-02-28 09:16:54 +01:00
Github Actions 5fb76baa16 [CI Skip] release/beta 3.10.3-14
skip-checks: true
2021-02-28 07:32:13 +00:00
Jaco Greeff 274b3498d4 Gilt types (#3229) 2021-02-28 08:23:16 +01:00
Github Actions fa9e1c53e1 [CI Skip] release/beta 3.10.3-13
skip-checks: true
2021-02-27 14:34:11 +00:00
Jaco Greeff 3ebf7eb424 Adjust detectPackage for direct dependencies (#3227)
* Dependency detection

* packageInfo imports

* Dependency array

* Bump common

* Remove detectPackage comments (available in util)

* Bump
2021-02-27 15:25:05 +01:00
Github Actions 7d11e6f9a5 [CI Skip] release/beta 3.10.3-12
skip-checks: true
2021-02-27 12:24:59 +00:00
Jaco Greeff a0d6384b01 Cleanup exports (less indirection) (#3226)
* Cleanup exports (less indirection)

* packageInfo import
2021-02-27 13:17:07 +01:00
Github Actions 47afe2cfc6 [CI Skip] release/beta 3.10.3-11
skip-checks: true
2021-02-26 16:49:27 +00:00
Jaco Greeff c37a2fc756 Bump deps (#3224) 2021-02-26 17:39:59 +01:00
Github Actions e2545276bb [CI Skip] release/beta 3.10.3-10
skip-checks: true
2021-02-26 11:59:32 +00:00
Jaco Greeff 4219409ef8 Update to latest substrate metadata (#3220)
* Update to latest substrate metadata

* ExtendedBalance type
2021-02-26 12:49:19 +01:00
Github Actions c9e64d2a32 [CI Skip] release/beta 3.10.3-9
skip-checks: true
2021-02-26 07:50:31 +00:00
Jaco Greeff 41db3b2e35 Bump deps (#3219) 2021-02-26 08:40:39 +01:00
Github Actions ebe15dada6 [CI Skip] release/beta 3.10.3-8
skip-checks: true
2021-02-25 14:40:29 +00:00
Jaco Greeff c2cb5dc574 Bump deps (#3218) 2021-02-25 15:31:52 +01:00
Github Actions ba451348c0 [CI Skip] release/beta 3.10.3-7
skip-checks: true
2021-02-25 14:08:25 +00:00
Jaco Greeff ec76b11666 Only inject tx version from metadata (metadata 4+) (#3217)
* Only inject tx version from metadata (metadata 4+)

* No need for extra var
2021-02-25 14:58:32 +01:00
Jaco Greeff 7603f9e6c1 Fix MultiAddress decoding from raw publicKey (#3215)
* Fix Multiddress decoding from raw publicKey

* Full decoding on empty

* Update
2021-02-25 12:14:00 +01:00
Github Actions b50eab11c0 [CI Skip] release/beta 3.10.3-6
skip-checks: true
2021-02-25 10:02:34 +00:00
Jaco Greeff 66d05c1771 Bump common (elliptic imports fix for Node) (#3214) 2021-02-25 10:53:42 +01:00
Github Actions fd7c3d7e10 [CI Skip] release/beta 3.10.3-5
skip-checks: true
2021-02-24 17:11:53 +00:00
Jaco Greeff 28d4c7d808 Update .123trigger 2021-02-24 18:02:57 +01:00
Github Actions 43d36fbcf6 [CI Skip] release/beta 3.10.3-4
skip-checks: true
2021-02-24 16:59:57 +00:00
Jaco Greeff e54eef2369 Bump deps (#3212)
* Bump deps

* autolint
2021-02-24 17:51:51 +01:00
Github Actions 296842858f [CI Skip] release/beta 3.10.3-3
skip-checks: true
2021-02-24 09:26:06 +00:00
Jaco Greeff ba8849a3e9 Allow for CodecHash override & hasher option (#3206)
* Allow for CodecHash override & hasher option

* Adjust

* CodecHash maps to Hash
2021-02-24 10:17:29 +01:00
Github Actions e333c3d8d9 [CI Skip] release/beta 3.10.3-2
skip-checks: true
2021-02-23 15:19:38 +00:00
Jaco Greeff 0fe6a21624 Indexed enums (#3194)
* Indexed enums

* Type generation updates

* Cleanup createType

* Empty bytes default

* output tests

* Explicit entryIndex
2021-02-23 16:09:47 +01:00
Github Actions 0abedb81c6 [CI Skip] release/beta 3.10.3-1
skip-checks: true
2021-02-23 14:46:56 +00:00
Ian He 08eda72d4b clean ws-provider's states on disconnected (#3197)
* clean ws-provider's states on disconnected

* per comments
2021-02-23 15:36:10 +01:00
Github Actions 70d4126c84 [CI Skip] release/beta 3.10.3-0
skip-checks: true
2021-02-23 14:34:49 +00:00
Jaco Greeff dcccab705c Additional MultiAddress testing paths (#3205)
* Additional MultiAddress testing paths

* Update packages/types/src/generic/MultiAddress.ts
2021-02-23 15:25:48 +01:00
Github Actions e45ff6d026 [CI Skip] release/stable 3.10.2
skip-checks: true
2021-02-23 08:23:24 +00:00
Jaco Greeff b49c2314e7 Fix variable-length MultiAddress decoding (only detect 32 & 20) (#3204)
* Fix variable-length MultiAddress decoding (only detect 32 & 20)

* Decoding tests

* Fix Call test

* patch-only

* Update CHANGELOG.md
2021-02-23 09:13:47 +01:00
Github Actions 0ac085756a [CI Skip] release/beta 3.10.2-0
skip-checks: true
2021-02-22 16:00:25 +00:00
Jaco Greeff 542a690c89 Update contracts host weights (#3199)
* Update contracts host weights

* Update Limits
2021-02-22 16:50:16 +01:00
Github Actions ff23ead797 [CI Skip] release/stable 3.10.1
skip-checks: true
2021-02-22 08:45:21 +00:00
Jaco Greeff ae55e4fbf7 3.10 (#3198) 2021-02-22 09:36:29 +01:00
Github Actions b17412163d [CI Skip] release/beta 3.9.4-4
skip-checks: true
2021-02-21 12:18:23 +00:00
Jaco Greeff 46dcbf9a42 Bump common (#3196) 2021-02-21 13:09:51 +01:00
Github Actions 193dfcc32f [CI Skip] release/beta 3.9.4-3
skip-checks: true
2021-02-21 09:42:58 +00:00
Jaco Greeff a81011cf94 Adjust ConsumedWeight (#3195) 2021-02-21 10:34:07 +01:00
Github Actions d43a8b2e11 [CI Skip] release/beta 3.9.4-2
skip-checks: true
2021-02-20 11:47:18 +00:00
Jaco Greeff dff859ba68 Don't send unsubscribe when already disconnected (#3192)
* Don't send unsubscribe when already disconnected

* Small cleanups
2021-02-20 12:37:05 +01:00
Github Actions 5169b6ee69 [CI Skip] release/beta 3.9.4-1
skip-checks: true
2021-02-20 10:59:13 +00:00
Jaco Greeff f4405667fe Adjust use of staking derive multi (#3173)
* Adjust use of staking derive multi

* Remove migrateEra

* Flatten rewards
2021-02-20 11:51:48 +01:00
Github Actions 49ff636305 [CI Skip] release/beta 3.9.4-0
skip-checks: true
2021-02-16 12:00:27 +00:00
Jaco Greeff d77d686c76 Update detectPackage to use packgeInfo.ts (#3182) 2021-02-16 12:50:45 +01:00
Github Actions 502c6a3451 [CI Skip] release/stable 3.9.3
skip-checks: true
2021-02-16 06:47:07 +00:00
Jaco Greeff b58c77683d 3.9.3 PersistedValidationData (#3180) 2021-02-16 07:39:29 +01:00
Github Actions b9f82fc549 [CI Skip] release/stable 3.9.2
skip-checks: true
2021-02-15 09:05:52 +00:00
Jaco Greeff 25b8dba607 3.9.2 (#3176)
* 3.9.2

* Update CHANGELOG.md
2021-02-15 09:56:14 +01:00
Github Actions 1bc4f2c334 [CI Skip] release/beta 3.9.2-0
skip-checks: true
2021-02-15 06:47:13 +00:00
Nikos Kontakis aee8ac6b0a Update README.md (#3175)
Minor url link fixes (documentation portal and JSON-RPC methods link)
2021-02-15 07:37:11 +01:00
Github Actions aa7e30070f [CI Skip] release/stable 3.9.1
skip-checks: true
2021-02-14 17:46:51 +00:00
Jaco Greeff 64b5855f65 3.8 (#3174) 2021-02-14 18:39:44 +01:00
Github Actions d7ff9e706e [CI Skip] release/beta 3.8.2-5
skip-checks: true
2021-02-14 08:53:37 +00:00
Jaco Greeff 15ba6f6261 Adjust Result for Rust-compatible Err (w/ deprecation of is/asError) (#3172)
* Adjust Result for Rust-compatible Err (w/ deprecation of is/asError)

* Jsdoc comments

* test updates
2021-02-14 09:43:37 +01:00
Github Actions 8c88a880c6 [CI Skip] release/beta 3.8.2-4
skip-checks: true
2021-02-11 17:27:04 +00:00
Jaco Greeff 74566cce7b Update Rococo types (drop v0) (#3167) 2021-02-11 18:17:05 +01:00
Github Actions 16f6deed5e [CI Skip] release/beta 3.8.2-3
skip-checks: true
2021-02-10 12:14:16 +00:00
Jaco Greeff 40edc131fe Allow geneic args for keys/entries (#3165) 2021-02-10 13:04:23 +01:00
Github Actions 3e014b38e6 [CI Skip] release/beta 3.8.2-2
skip-checks: true
2021-02-10 08:49:29 +00:00
Jaco Greeff b4cfdbffab Fix council derives for seatholders (#3163)
* Fix council derives for setholders

* Fix vote retreival
2021-02-10 09:41:47 +01:00
Github Actions cbfb6f8f59 [CI Skip] release/beta 3.8.2-1
skip-checks: true
2021-02-09 19:00:05 +00:00
Jaco Greeff b5bc15ab8b Last Kusama upgrade block (#3160) 2021-02-09 19:50:24 +01:00
Github Actions 0b343fc0f8 [CI Skip] release/beta 3.8.2-0
skip-checks: true
2021-02-08 15:55:08 +00:00
Jaco Greeff e7f9693873 Add ParaLifecycle type (#3159) 2021-02-08 16:47:02 +01:00
Github Actions a0a5c3185d [CI Skip] release/stable 3.8.1
skip-checks: true
2021-02-07 13:05:43 +00:00
Jaco Greeff 151d4693a9 3.8 (#3158) 2021-02-07 13:56:10 +01:00
Github Actions cdb27d8ec2 [CI Skip] release/beta 3.7.4-8
skip-checks: true
2021-02-07 12:14:25 +00:00
Jaco Greeff 055e4d1261 Bump to common stable (#3157) 2021-02-07 13:06:46 +01:00
Github Actions bf753255ab [CI Skip] release/beta 3.7.4-7
skip-checks: true
2021-02-07 08:59:19 +00:00
Jaco Greeff e2230ef454 Bump common (#3155)
* Bump common

* Adjust (some) tests

* Adjust tests
2021-02-07 09:49:48 +01:00
Github Actions 0f5b01b856 [CI Skip] release/beta 3.7.4-6
skip-checks: true
2021-02-06 13:45:59 +00:00
Jaco Greeff 82787c96c6 Single put_code/deploy (new & backwards compat.) (#3143)
* Single put_code/deploy (new & backwards compat.)

* new-style

* old-style deploy?

* notice

* Cleanups

* linting

* grrr... Mac case-sensistivity

* Add createContract on BluePrint

* Adjust contracts check

* Adjust

* Adjust tests
2021-02-06 14:36:42 +01:00
Github Actions f89028d5fe [CI Skip] release/beta 3.7.4-5
skip-checks: true
2021-02-06 12:09:28 +00:00
Jaco Greeff ba24a2e917 Bump latest Substrate meta (#3154) 2021-02-06 13:00:26 +01:00
Github Actions b549bbf46b [CI Skip] release/beta 3.7.4-4
skip-checks: true
2021-02-06 07:58:57 +00:00
Jaco Greeff 1e87f58f36 Allow extensions on typesBundle (#3142)
* Allow extensions on typesBundle

* User extension take precedence
2021-02-06 08:49:11 +01:00
Github Actions f643426067 [CI Skip] release/beta 3.7.4-3
skip-checks: true
2021-02-05 21:12:04 +00:00
Jaco Greeff 94d26c76ec Check for autoConnectMs on reconnect (#3151)
* Check for autoConnectMs on reconnect

* Update packages/rpc-provider/src/ws/index.ts
2021-02-05 22:03:31 +01:00
Github Actions 8fe262a712 [CI Skip] release/beta 3.7.4-2
skip-checks: true
2021-02-05 15:55:13 +00:00
Jake Naviasky 122ee968cb Add eth filter RPC endpoints and FilterChanges type. (#3150) 2021-02-05 16:45:31 +01:00
Github Actions d2ff350db9 [CI Skip] release/beta 3.7.4-1
skip-checks: true
2021-02-05 07:34:46 +00:00
Nantian 9100aabbac fix signedExtensions type (#3148) 2021-02-05 08:25:17 +01:00
Github Actions 1e73f69253 [CI Skip] release/beta 3.7.4-0
skip-checks: true
2021-02-04 16:16:08 +00:00
Jaco Greeff 7153cb4158 Extend ProxyType with CancelProxy (#3147) 2021-02-04 17:05:56 +01:00
Github Actions 999dc6f8a5 [CI Skip] release/stable 3.7.3
skip-checks: true
2021-02-02 16:37:56 +00:00
Jaco Greeff 724574afe7 3.7.3 (w/ Polkadot 27 upgrade blocks) (#3139) 2021-02-02 17:29:43 +01:00
Github Actions 0352a30b6b [CI Skip] release/beta 3.7.3-1
skip-checks: true
2021-02-02 10:14:04 +00:00
Jaco Greeff 41b4cd5c55 Adjust known-types to use @polkadot/networks (#3138) 2021-02-02 11:06:52 +01:00
Github Actions 89f16f3123 [CI Skip] release/beta 3.7.3-0
skip-checks: true
2021-02-02 09:22:19 +00:00
Jaco Greeff 261a4eede3 Add 26 checkpoint for Polkadot (#3137) 2021-02-02 10:15:17 +01:00
159 changed files with 3823 additions and 1988 deletions
+5 -2
View File
@@ -1,4 +1,4 @@
25 26
1.4.2 1.4.2
1.6.2 1.6.2
1.11.2 1.11.2
@@ -8,9 +8,12 @@
2.8.2 2.8.2
3.2.2 3.2.2
3.2.3 3.2.3
3.3.2 3.3.2
3.6.2 3.6.2
3.6.3 3.6.3
3.6.4 3.6.4
3.7.2 3.7.2
3.7.3
3.9.2
3.9.3
3.10.2
-2
View File
@@ -24,8 +24,6 @@ module.exports = {
...base.rules, ...base.rules,
// add override for any (a metric ton of them, initial conversion) // add override for any (a metric ton of them, initial conversion)
'@typescript-eslint/no-explicit-any': 'off', '@typescript-eslint/no-explicit-any': 'off',
// these should be removed, there are 8 of them as errors
'@typescript-eslint/no-non-null-assertion': 'off',
// this seems very broken atm, false positives // this seems very broken atm, false positives
'@typescript-eslint/unbound-method': 'off' '@typescript-eslint/unbound-method': 'off'
} }
+111
View File
@@ -1,5 +1,116 @@
# CHANGELOG # CHANGELOG
## 3.11.1 Feb 28, 2021
Upgrade priority: Low. Recommended for users wanting to keep updated with chain changes.
Contributed:
- Clean Websocket states on disconnects (Thanks to https://github.com/ianhe8x)
- Support for C-like indexed enums (Thanks to https://github.com/xlc)
Changes:
- Adjust council derives to cater for current-generation candidate mapping
- Allow for override of codec hasher (& output type)
- Adjust submittables to submit hex-encoded addresses to queries
- Adjust initialization to always retrieve tx version from Metadata only
- Update election types as per latest Substrate
- Add types for the new gilt module
- Upgrade to the latest Substrate metadata
- Adjust package detection to check for local monorepo dependencies
- Ensure that metadata `.toJSON()` does apply type aliasses
## 3.10.2 Feb 23, 2021
Upgrade priority: Medium. Recommended for users of chains where `MultiAddress` is in-use and blocks are decoded.
Changes:
- Fix decoding for `MultiAddress` enum where non-`AccountId` variable-lengths are provided as part of a stream
- Added known Polkadot 28 upgrade block
- Update for latest Substrate contracts `Schedule` types
## 3.10.1 Feb 22, 2021
Upgrade priority: Low.
Changes:
- Adjust ConsumedWeight types to align with Rust module code
- Check for connection status in subscription unsubscribe
- Adjust staking reward derives ordering for better performance
- Adapt detection imports to remove `.json` dependencies (Better behavior using Node.js with ESM)
## 3.9.3 Feb 16, 2021
Upgrade priority: Low. Recommended for parachain builders since it contains the updated parachain types.
Changes:
- Adjusted parachain `PersistedValidationData` structure
## 3.9.2 Feb 15, 2021
Upgrade priority: Low. Recommended for parachain builders since it contains the latest parachain types.
Contributed:
- Update README links (Thanks to https://github.com/wirednkod)
Changes:
- Added missing Culmulus `ParachainInherentData` & `MessageQueueChain` types
- Add alias for `system_unstable_networkState` RPC
## 3.9.1 Feb 14, 2021
Upgrade priority: Low.
- **Important** The `Result<T, E>` has been updated in the generation and the base types to follow the Rust version 100%. This means `{as, is}Error` is now available as `{as, is}Err` on the `Result` type. The older versions can still be used, but the `*Error` interfaces are now marked as deprecated.
Changes:
- Adjust `Result<T, E>` interface to be 100% compatible with the Rust version
- Add the `2028` upgrade to the known upgrades (optimizing certain `.at` queries)
- Adjust council derives to cater for latest Substrate & Polkadot
- Adjust Rococo know type definitions to cater for the latest update
- Update types for latest Polkadot/Substrate
- Add generic arguments for TypeScript users to `.entries/.keys` to deal with the key typings
## 3.8.1 Feb 7, 2021
Upgrade priority: Low. Recommended for users of the latest Substrate master, especially using contracts.
- **Important** The `api-contract` `Code` now supports deploying the code and a contract in on operation. This aligns with the latest Substrate where code cannot be uploaded with a contract. The `createBlueprint` is therefore deprecated, use `code.tx.<constructor>(...)` to deploy code. (Compatible with both old and new versions of Substrate)
Contributed:
- Add support for latest Frontier RPCs (Thanks to https://github.com/jnaviask)
- Fix user-supplied signed extensions type signature (Thanks to https://github.com/ntduan)
Changes:
- Expand `api-contract` to allow for `Code` to deploy contract alongside code. `createBlueprint` is now deprecated, replaced by `createContract` or the preferred `code.tx.<constructor>`, which uploads and deploys the code in one operation. This aligns with the current Substrate master contracts implementation.
- Allow for signed extensions to be supplied inside type bundles
- Ensure that the auto-connect state is checked on auto-connections (respecting disconnect)
- Added `CancelProxy` to `ProxyTypes on Polkadot, Kusama & Westend
- Updated to latest Substrate metadata
## 3.7.3 Feb 2, 2021
Changes:
- Added Polkadot upgrade block for runtime 27 (known checkpoint optimization)
## 3.7.2 Feb 2, 2021 ## 3.7.2 Feb 2, 2021
Changes: Changes:
+2 -2
View File
@@ -7,7 +7,7 @@
# @polkadot/api # @polkadot/api
This library provides a clean wrapper around all the methods exposed by a Polkadot/Substrate network client and defines all the types exposed by a node. For complete documentation around the classes, interfaces and their use, visit the [documentation portal](https://polkadot.js.org/api/). This library provides a clean wrapper around all the methods exposed by a Polkadot/Substrate network client and defines all the types exposed by a node. For complete documentation around the classes, interfaces and their use, visit the [documentation portal](https://polkadot.js.org/docs/api/).
If you are an existing user, please be sure to track the [CHANGELOG](CHANGELOG.md) and [UPGRADING](UPGRADING.md) guides when changing versions. If you are an existing user, please be sure to track the [CHANGELOG](CHANGELOG.md) and [UPGRADING](UPGRADING.md) guides when changing versions.
@@ -22,7 +22,7 @@ The API is split up into a number of internal packages -
- [@polkadot/api](packages/api/) The API library, providing both Promise and RxJS Observable-based interfaces. This is the main user-facing entry point. - [@polkadot/api](packages/api/) The API library, providing both Promise and RxJS Observable-based interfaces. This is the main user-facing entry point.
- [@polkadot/api-derive](packages/api-derive/) Derived results that are injected into the API, allowing for combinations of various query results (only used internally and exposed on the Api instances via `api.derive.*`) - [@polkadot/api-derive](packages/api-derive/) Derived results that are injected into the API, allowing for combinations of various query results (only used internally and exposed on the Api instances via `api.derive.*`)
- [@polkadot/api-metadata](packages/api-metadata/) Base extrinsic, storage and constant injectors for injection - [@polkadot/api-metadata](packages/api-metadata/) Base extrinsic, storage and constant injectors for injection
- [@polkadot/rpc-core](packages/rpc-core/) Wrapper around all [JSON-RPC methods](https://polkadot.js.org/api/substrate/rpc.html) exposed by a Polkadot network client - [@polkadot/rpc-core](packages/rpc-core/) Wrapper around all [JSON-RPC methods](https://polkadot.js.org/docs/substrate/rpc) exposed by a Polkadot network client
- [@polkadot/rpc-provider](packages/rpc-provider/) Providers for connecting to nodes, including WebSockets and Http - [@polkadot/rpc-provider](packages/rpc-provider/) Providers for connecting to nodes, including WebSockets and Http
Type definitions for interfaces as exposed by Polkadot & Substrate clients - Type definitions for interfaces as exposed by Polkadot & Substrate clients -
+6 -6
View File
@@ -8,7 +8,7 @@
"packages/*" "packages/*"
], ],
"resolutions": { "resolutions": {
"typescript": "^4.1.3" "typescript": "^4.1.5"
}, },
"scripts": { "scripts": {
"build": "yarn build:interfaces && polkadot-dev-build-ts", "build": "yarn build:interfaces && polkadot-dev-build-ts",
@@ -25,14 +25,14 @@
"test:watch": "polkadot-dev-run-test --watch" "test:watch": "polkadot-dev-run-test --watch"
}, },
"devDependencies": { "devDependencies": {
"@babel/core": "^7.12.10", "@babel/core": "^7.13.8",
"@babel/register": "^7.12.10", "@babel/register": "^7.13.8",
"@babel/runtime": "^7.12.5", "@babel/runtime": "^7.13.8",
"@polkadot/dev": "^0.61.24", "@polkadot/dev": "^0.61.30",
"@polkadot/ts": "^0.3.59", "@polkadot/ts": "^0.3.59",
"@polkadot/typegen": "workspace:packages/typegen", "@polkadot/typegen": "workspace:packages/typegen",
"@types/jest": "^26.0.20", "@types/jest": "^26.0.20",
"copyfiles": "^2.4.1" "copyfiles": "^2.4.1"
}, },
"version": "3.7.2" "version": "3.11.1"
} }
+10 -7
View File
@@ -1,9 +1,12 @@
{ {
"name": "@polkadot/api-contract", "name": "@polkadot/api-contract",
"version": "3.7.2", "version": "3.11.1",
"description": "Interfaces for interacting with contracts and contract ABIs", "description": "Interfaces for interacting with contracts and contract ABIs",
"main": "index.js", "main": "index.js",
"sideEffects": false, "sideEffects": [
"./detectPackage.js",
"./detectPackage.mjs"
],
"author": "Jaco Greeff <jacogr@gmail.com>", "author": "Jaco Greeff <jacogr@gmail.com>",
"maintainers": [], "maintainers": [],
"contributors": [], "contributors": [],
@@ -12,11 +15,11 @@
"bugs": "https://github.com/polkadot-js/api/issues", "bugs": "https://github.com/polkadot-js/api/issues",
"homepage": "https://github.com/polkadot-js/api/tree/master/packages/api-contract#readme", "homepage": "https://github.com/polkadot-js/api/tree/master/packages/api-contract#readme",
"dependencies": { "dependencies": {
"@babel/runtime": "^7.12.5", "@babel/runtime": "^7.13.8",
"@polkadot/api": "3.7.2", "@polkadot/api": "3.11.1",
"@polkadot/types": "3.7.2", "@polkadot/types": "3.11.1",
"@polkadot/util": "^5.5.1", "@polkadot/util": "^5.9.2",
"@polkadot/x-rxjs": "^5.5.1", "@polkadot/x-rxjs": "^5.9.2",
"bn.js": "^4.11.9" "bn.js": "^4.11.9"
} }
} }
+1 -1
View File
@@ -26,6 +26,6 @@ export abstract class Base<ApiType extends ApiTypes> {
this.registry = this.abi.registry; this.registry = this.abi.registry;
this._decorateMethod = decorateMethod; this._decorateMethod = decorateMethod;
assert(this.api.rx.tx.contracts && this.api.rx.tx.contracts.putCode, 'You need to connect to a node with the contracts module, the metadata does not enable api.tx.contracts on this instance'); assert(api.rx.tx.contracts?.instantiate, 'You need to connect to a node with the contracts module, the metadata does not enable api.tx.contracts on this instance');
} }
} }
+8 -35
View File
@@ -6,44 +6,17 @@ import type { ApiTypes, DecorateMethod } from '@polkadot/api/types';
import type { AccountId, EventRecord, Hash } from '@polkadot/types/interfaces'; import type { AccountId, EventRecord, Hash } from '@polkadot/types/interfaces';
import type { AnyJson, CodecArg, ISubmittableResult } from '@polkadot/types/types'; import type { AnyJson, CodecArg, ISubmittableResult } from '@polkadot/types/types';
import type { AbiConstructor, BlueprintOptions } from '../types'; import type { AbiConstructor, BlueprintOptions } from '../types';
import type { BlueprintDeploy, ContractGeneric, MapConstructorExec } from './types'; import type { ContractGeneric, MapConstructorExec } from './types';
import BN from 'bn.js';
import { SubmittableResult } from '@polkadot/api'; import { SubmittableResult } from '@polkadot/api';
import { ApiBase } from '@polkadot/api/base'; import { ApiBase } from '@polkadot/api/base';
import { Bytes } from '@polkadot/types'; import { isUndefined, stringCamelCase } from '@polkadot/util';
import { compactAddLength, isUndefined, stringCamelCase, u8aToU8a } from '@polkadot/util';
import { randomAsU8a } from '@polkadot/util-crypto';
import { Abi } from '../Abi'; import { Abi } from '../Abi';
import { applyOnEvent, extractOptions, isOptions } from '../util'; import { applyOnEvent } from '../util';
import { Base } from './Base'; import { Base } from './Base';
import { Contract } from './Contract'; import { Contract } from './Contract';
import { createBluePrintTx, createBluePrintWithId, EMPTY_SALT, encodeSalt } from './util';
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 { export class BlueprintSubmittableResult<ApiType extends ApiTypes> extends SubmittableResult {
public readonly contract?: Contract<ApiType>; public readonly contract?: Contract<ApiType>;
@@ -73,13 +46,13 @@ export class Blueprint<ApiType extends ApiTypes> extends Base<ApiType> {
super(api, abi, decorateMethod); super(api, abi, decorateMethod);
this.codeHash = this.registry.createType('Hash', codeHash); this.codeHash = this.registry.createType('Hash', codeHash);
this.createContract = createWithId(this.#deploy); this.createContract = createBluePrintWithId(this.#deploy);
this.abi.constructors.forEach((c): void => { this.abi.constructors.forEach((c): void => {
const messageName = stringCamelCase(c.identifier); const messageName = stringCamelCase(c.identifier);
if (isUndefined(this.#tx[messageName])) { if (isUndefined(this.#tx[messageName])) {
this.#tx[messageName] = createTx((o, p) => this.#deploy(c, o, p)); this.#tx[messageName] = createBluePrintTx((o, p) => this.#deploy(c, o, p));
} }
}); });
} }
@@ -88,7 +61,7 @@ export class Blueprint<ApiType extends ApiTypes> extends Base<ApiType> {
return this.#tx; return this.#tx;
} }
#deploy = (constructorOrId: AbiConstructor | string| number, { gasLimit = 0, salt, value = 0 }: BlueprintOptions, params: CodecArg[]): SubmittableExtrinsic<ApiType, BlueprintSubmittableResult<ApiType>> => { #deploy = (constructorOrId: AbiConstructor | string | number, { gasLimit = 0, salt, value = 0 }: BlueprintOptions, params: CodecArg[]): SubmittableExtrinsic<ApiType, BlueprintSubmittableResult<ApiType>> => {
const encodedSalt = encodeSalt(salt); const encodedSalt = encodeSalt(salt);
const withSalt = this.api.tx.contracts.instantiate.meta.args.length === 5; const withSalt = this.api.tx.contracts.instantiate.meta.args.length === 5;
const encoded = this.abi.findConstructor(constructorOrId).toU8a(params, withSalt ? EMPTY_SALT : encodedSalt); const encoded = this.abi.findConstructor(constructorOrId).toU8a(params, withSalt ? EMPTY_SALT : encodedSalt);
@@ -99,7 +72,7 @@ export class Blueprint<ApiType extends ApiTypes> extends Base<ApiType> {
: this.api.tx.contracts.instantiate(value, gasLimit, this.codeHash, encoded); : this.api.tx.contracts.instantiate(value, gasLimit, this.codeHash, encoded);
return tx.withResultTransform((result: ISubmittableResult) => return tx.withResultTransform((result: ISubmittableResult) =>
new BlueprintSubmittableResult(result, applyOnEvent(result, 'Instantiated', ([record]: EventRecord[]) => new BlueprintSubmittableResult(result, applyOnEvent(result, ['Instantiated'], ([record]: EventRecord[]) =>
new Contract<ApiType>(this.api, this.abi, record.event.data[1] as AccountId, this._decorateMethod) new Contract<ApiType>(this.api, this.abi, record.event.data[1] as AccountId, this._decorateMethod)
)) ))
); );
+74 -4
View File
@@ -4,30 +4,39 @@
import type { SubmittableExtrinsic } from '@polkadot/api/submittable/types'; import type { SubmittableExtrinsic } from '@polkadot/api/submittable/types';
import type { ApiTypes, DecorateMethod } from '@polkadot/api/types'; import type { ApiTypes, DecorateMethod } from '@polkadot/api/types';
import type { EventRecord, Hash } from '@polkadot/types/interfaces'; import type { EventRecord, Hash } from '@polkadot/types/interfaces';
import type { AnyJson, ISubmittableResult } from '@polkadot/types/types'; import type { AnyJson, CodecArg, ISubmittableResult } from '@polkadot/types/types';
import type { AbiConstructor, BlueprintOptions } from '../types';
import type { MapConstructorExec } from './types';
import { SubmittableResult } from '@polkadot/api'; import { SubmittableResult } from '@polkadot/api';
import { ApiBase } from '@polkadot/api/base'; import { ApiBase } from '@polkadot/api/base';
import { assert, compactAddLength, isWasm, u8aToU8a } from '@polkadot/util'; import { assert, compactAddLength, isFunction, isUndefined, isWasm, stringCamelCase, u8aToU8a } from '@polkadot/util';
import { blake2AsU8a } from '@polkadot/util-crypto';
import { Abi } from '../Abi'; import { Abi } from '../Abi';
import { applyOnEvent } from '../util'; import { applyOnEvent } from '../util';
import { Base } from './Base'; import { Base } from './Base';
import { Blueprint } from './Blueprint'; import { Blueprint } from './Blueprint';
import { Contract } from './Contract';
import { createBluePrintTx, EMPTY_SALT, encodeSalt } from './util';
export class CodeSubmittableResult<ApiType extends ApiTypes> extends SubmittableResult { export class CodeSubmittableResult<ApiType extends ApiTypes> extends SubmittableResult {
public readonly blueprint?: Blueprint<ApiType>; public readonly blueprint?: Blueprint<ApiType>;
public readonly contract?: Contract<ApiType>;
constructor (result: ISubmittableResult, blueprint?: Blueprint<ApiType>) { constructor (result: ISubmittableResult, blueprint?: Blueprint<ApiType>, contract?: Contract<ApiType>) {
super(result); super(result);
this.blueprint = blueprint; this.blueprint = blueprint;
this.contract = contract;
} }
} }
export class Code<ApiType extends ApiTypes> extends Base<ApiType> { export class Code<ApiType extends ApiTypes> extends Base<ApiType> {
public readonly code: Uint8Array; public readonly code: Uint8Array;
readonly #tx: MapConstructorExec<ApiType> = {};
constructor (api: ApiBase<ApiType>, abi: AnyJson | Abi, wasm: Uint8Array | string | Buffer | null | undefined, decorateMethod: DecorateMethod<ApiType>) { constructor (api: ApiBase<ApiType>, abi: AnyJson | Abi, wasm: Uint8Array | string | Buffer | null | undefined, decorateMethod: DecorateMethod<ApiType>) {
super(api, abi, decorateMethod); super(api, abi, decorateMethod);
@@ -36,18 +45,79 @@ export class Code<ApiType extends ApiTypes> extends Base<ApiType> {
: u8aToU8a(wasm); : u8aToU8a(wasm);
assert(isWasm(this.code), 'No WASM code provided'); assert(isWasm(this.code), 'No WASM code provided');
this.abi.constructors.forEach((c): void => {
const messageName = stringCamelCase(c.identifier);
if (isUndefined(this.#tx[messageName])) {
this.#tx[messageName] = createBluePrintTx((o, p) => this.#instantiate(c, o, p));
}
});
} }
/** /**
* @description Deploy the code bundle, creating a Blueprint. * @description Deploy the code bundle, creating a Blueprint.
* @deprecated Use the `code.tx.<constructor>(...) format to put code and deploy
*/ */
public createBlueprint (): SubmittableExtrinsic<ApiType, CodeSubmittableResult<ApiType>> { public createBlueprint (): SubmittableExtrinsic<ApiType, CodeSubmittableResult<ApiType>> {
return this.api.tx.contracts return this.api.tx.contracts
.putCode(compactAddLength(this.code)) .putCode(compactAddLength(this.code))
.withResultTransform((result: ISubmittableResult) => .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) new Blueprint<ApiType>(this.api, this.abi, record.event.data[0] as Hash, this._decorateMethod)
)) ))
); );
} }
/**
* @description Deploy the code bundle and the contract, creating a Blueprint.
* @deprecated Use the `code.tx.<constructor>(...) format to put code and deploy
*/
public createContract (constructorOrId: AbiConstructor | string | number, options: BlueprintOptions, params: CodecArg[]): SubmittableExtrinsic<ApiType, CodeSubmittableResult<ApiType>> {
return this.#instantiate(constructorOrId, options, params);
}
public get tx (): MapConstructorExec<ApiType> {
return this.#tx;
}
#instantiate = (constructorOrId: AbiConstructor | string | number, options: BlueprintOptions, params: CodecArg[]): SubmittableExtrinsic<ApiType, CodeSubmittableResult<ApiType>> => {
return isFunction(this.api.tx.contracts.instantiateWithCode)
? this.#instantiateSingle(constructorOrId, options, params)
: this.#instantiateBatch(constructorOrId, options, params);
}
#instantiateSingle = (constructorOrId: AbiConstructor | string | number, { gasLimit = 0, salt, value = 0 }: BlueprintOptions, params: CodecArg[]): SubmittableExtrinsic<ApiType, CodeSubmittableResult<ApiType>> => {
return this.api.tx.contracts
.instantiateWithCode(value, gasLimit, compactAddLength(this.code), this.abi.findConstructor(constructorOrId).toU8a(params), encodeSalt(salt))
.withResultTransform(this.#transformEvents);
}
#instantiateBatch = (constructorOrId: AbiConstructor | string | number, { gasLimit = 0, salt, value = 0 }: BlueprintOptions, params: CodecArg[]): SubmittableExtrinsic<ApiType, CodeSubmittableResult<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 codeHash = blake2AsU8a(this.code);
return this.api.tx.utility.batch([
this.api.tx.contracts.putCode(compactAddLength(this.code)),
withSalt
? this.api.tx.contracts.instantiate(value, gasLimit, codeHash, encoded, encodedSalt)
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore old style with salt included in the params itself
: this.api.tx.contracts.instantiate(value, gasLimit, codeHash, encoded)
]).withResultTransform(this.#transformEvents);
}
#transformEvents = (result: ISubmittableResult): CodeSubmittableResult<ApiType> => {
return new CodeSubmittableResult(result, ...(applyOnEvent(result, ['CodeStored', 'Instantiated'], (records: EventRecord[]) =>
records.reduce(([blueprint, contract], { event }): [Blueprint<ApiType>?, Contract<ApiType>?] =>
this.api.events.contracts.Instantiated.is(event)
? [blueprint, new Contract<ApiType>(this.api, this.abi, event.data[1], this._decorateMethod)]
: this.api.events.contracts.CodeStored.is(event)
? [new Blueprint<ApiType>(this.api, this.abi, event.data[0], this._decorateMethod), contract]
: [blueprint, contract],
[] as [Blueprint<ApiType>?, Contract<ApiType>?])
) || []));
}
} }
+1 -1
View File
@@ -156,7 +156,7 @@ export class Contract<ApiType extends ApiTypes> extends Base<ApiType> {
return this.api.tx.contracts return this.api.tx.contracts
.call(this.address, value, this.#getGas(gasLimit), this.abi.findMessage(messageOrId).toU8a(params)) .call(this.address, value, this.#getGas(gasLimit), this.abi.findMessage(messageOrId).toU8a(params))
.withResultTransform((result: ISubmittableResult) => .withResultTransform((result: ISubmittableResult) =>
new ContractSubmittableResult(result, applyOnEvent(result, 'ContractExecution', (records: EventRecord[]) => new ContractSubmittableResult(result, applyOnEvent(result, ['ContractExecution'], (records: EventRecord[]) =>
records records
.map(({ event: { data: [, data] } }): DecodedEvent | null => { .map(({ event: { data: [, data] } }): DecodedEvent | null => {
try { try {
+3
View File
@@ -11,6 +11,9 @@ export const mockApi = {
rx: { rx: {
tx: { tx: {
contracts: { contracts: {
instantiate: (): never => {
throw new Error('mock');
},
putCode: (): never => { putCode: (): never => {
throw new Error('mock'); throw new Error('mock');
} }
+41
View File
@@ -0,0 +1,41 @@
// Copyright 2017-2021 @polkadot/api-contract authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { SubmittableResult } from '@polkadot/api';
import type { SubmittableExtrinsic } from '@polkadot/api/submittable/types';
import type { ApiTypes } from '@polkadot/api/types';
import type { CodecArg } from '@polkadot/types/types';
import type { AbiConstructor, BlueprintOptions } from '../types';
import type { BlueprintDeploy, ContractGeneric } from './types';
import BN from 'bn.js';
import { Bytes } from '@polkadot/types';
import { compactAddLength, u8aToU8a } from '@polkadot/util';
import { randomAsU8a } from '@polkadot/util-crypto';
import { extractOptions, isOptions } from '../util';
export const EMPTY_SALT = new Uint8Array();
export function createBluePrintTx <ApiType extends ApiTypes, R extends SubmittableResult> (fn: (options: BlueprintOptions, params: CodecArg[]) => SubmittableExtrinsic<ApiType, R>): BlueprintDeploy<ApiType> {
return (options: BigInt | string | number | BN | BlueprintOptions, ...params: CodecArg[]): SubmittableExtrinsic<ApiType, R> =>
isOptions(options)
? fn(options, params)
: fn(...extractOptions(options, params));
}
export function createBluePrintWithId <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));
}
export function encodeSalt (salt: Uint8Array | string | null = randomAsU8a()): Uint8Array {
return salt instanceof Bytes
? salt
: salt && salt.length
? compactAddLength(u8aToU8a(salt))
: EMPTY_SALT;
}
@@ -0,0 +1,10 @@
// Copyright 2017-2021 @polkadot/api-contract authors & contributors
// SPDX-License-Identifier: Apache-2.0
import { packageInfo as apiInfo } from '@polkadot/api/packageInfo';
import { packageInfo as typesInfo } from '@polkadot/types/packageInfo';
import { detectPackage } from '@polkadot/util';
import { packageInfo } from './packageInfo';
detectPackage(packageInfo, typeof __dirname !== 'undefined' && __dirname, [apiInfo, typesInfo]);
+4 -2
View File
@@ -1,7 +1,9 @@
// Copyright 2017-2021 @polkadot/api-contract authors & contributors // Copyright 2017-2021 @polkadot/api-contract authors & contributors
// SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: Apache-2.0
export { Abi } from './Abi'; import './detectPackage';
export { Blueprint as BlueprintRx, Code as CodeRx, Contract as ContractRx } from './rx'; export { Abi } from './Abi';
export { packageInfo } from './packageInfo';
export { Blueprint as BlueprintPromise, Code as CodePromise, Contract as ContractPromise } from './promise'; export { Blueprint as BlueprintPromise, Code as CodePromise, Contract as ContractPromise } from './promise';
export { Blueprint as BlueprintRx, Code as CodeRx, Contract as ContractRx } from './rx';
+6
View File
@@ -0,0 +1,6 @@
// Copyright 2017-2021 @polkadot/dev authors & contributors
// SPDX-License-Identifier: Apache-2.0
// Auto-generated by @polkadot/dev, do not edit
export const packageInfo = { name: '@polkadot/api-contract', version: '3.11.1' };
+2 -2
View File
@@ -20,9 +20,9 @@ export function formatData (registry: Registry, data: Raw, { type }: TypeDef): C
return createTypeUnsafe(registry, type, [data], { isPedantic: true }); return createTypeUnsafe(registry, type, [data], { isPedantic: true });
} }
export function applyOnEvent <T> (result: SubmittableResult, type: ContractEvents, fn: (records: EventRecord[]) => T): T | undefined { export function applyOnEvent <T> (result: SubmittableResult, types: ContractEvents[], fn: (records: EventRecord[]) => T): T | undefined {
if (result.isInBlock || result.isFinalized) { if (result.isInBlock || result.isFinalized) {
const records = result.filterRecords('contracts', type); const records = result.filterRecords('contracts', types);
if (records.length) { if (records.length) {
return fn(records); return fn(records);
+14 -11
View File
@@ -1,9 +1,12 @@
{ {
"name": "@polkadot/api-derive", "name": "@polkadot/api-derive",
"version": "3.7.2", "version": "3.11.1",
"description": "Common functions used across Polkadot, derived from RPC calls and storage queries.", "description": "Common functions used across Polkadot, derived from RPC calls and storage queries.",
"main": "index.js", "main": "index.js",
"sideEffects": false, "sideEffects": [
"./detectPackage.js",
"./detectPackage.mjs"
],
"author": "Jaco Greeff <jacogr@gmail.com>", "author": "Jaco Greeff <jacogr@gmail.com>",
"maintainers": [], "maintainers": [],
"contributors": [], "contributors": [],
@@ -12,17 +15,17 @@
"bugs": "https://github.com/polkadot-js/api/issues", "bugs": "https://github.com/polkadot-js/api/issues",
"homepage": "https://github.com/polkadot-js/api/tree/master/packages/api-derive#readme", "homepage": "https://github.com/polkadot-js/api/tree/master/packages/api-derive#readme",
"dependencies": { "dependencies": {
"@babel/runtime": "^7.12.5", "@babel/runtime": "^7.13.8",
"@polkadot/api": "3.7.2", "@polkadot/api": "3.11.1",
"@polkadot/rpc-core": "3.7.2", "@polkadot/rpc-core": "3.11.1",
"@polkadot/types": "3.7.2", "@polkadot/types": "3.11.1",
"@polkadot/util": "^5.5.1", "@polkadot/util": "^5.9.2",
"@polkadot/util-crypto": "^5.5.1", "@polkadot/util-crypto": "^5.9.2",
"@polkadot/x-rxjs": "^5.5.1", "@polkadot/x-rxjs": "^5.9.2",
"bn.js": "^4.11.9" "bn.js": "^4.11.9"
}, },
"devDependencies": { "devDependencies": {
"@polkadot/keyring": "^5.5.1", "@polkadot/keyring": "^5.9.2",
"@polkadot/rpc-provider": "3.7.2" "@polkadot/rpc-provider": "3.11.1"
} }
} }
@@ -23,7 +23,7 @@ describe('bounties derive', () => {
let storageKey: (index: number) => StorageKey; let storageKey: (index: number) => StorageKey;
let defaultBounty: () => Bounty; let defaultBounty: () => Bounty;
let emptyOption: <T extends Codec> (typeName: keyof InterfaceTypes) => Option<T>; let emptyOption: <T extends Codec> (typeName: keyof InterfaceTypes) => Option<T>;
let optionOf: <T extends Codec> (value: T)=> Option<T>; let optionOf: <T extends Codec> (value: T) => Option<T>;
let bountyIndex: (index: number) => BountyIndex; let bountyIndex: (index: number) => BountyIndex;
let proposalIndex: (index: number) => ProposalIndex; let proposalIndex: (index: number) => ProposalIndex;
let bytes: (value: string) => Bytes; let bytes: (value: string) => Bytes;
+4 -4
View File
@@ -3,7 +3,7 @@
import type { ApiInterfaceRx } from '@polkadot/api/types'; import type { ApiInterfaceRx } from '@polkadot/api/types';
import type { DeriveBounties, DeriveCollectiveProposal } from '@polkadot/api-derive/types'; import type { DeriveBounties, DeriveCollectiveProposal } from '@polkadot/api-derive/types';
import type { Bytes, Option, StorageKey } from '@polkadot/types'; import type { Bytes, Option } from '@polkadot/types';
import type { Bounty, BountyIndex, ProposalIndex } from '@polkadot/types/interfaces'; import type { Bounty, BountyIndex, ProposalIndex } from '@polkadot/types/interfaces';
import { memo } from '@polkadot/api-derive/util'; import { memo } from '@polkadot/api-derive/util';
@@ -32,7 +32,7 @@ function parseResult ([maybeBounties, maybeDescriptions, ids, bountyProposals]:
} }
export function bounties (instanceId: string, api: ApiInterfaceRx): () => Observable<DeriveBounties> { export function bounties (instanceId: string, api: ApiInterfaceRx): () => Observable<DeriveBounties> {
const bountyBase = api.query.bounties ? api.query.bounties : api.query.treasury; const bountyBase = api.query.bounties || api.query.treasury;
return memo(instanceId, (): Observable<DeriveBounties> => return memo(instanceId, (): Observable<DeriveBounties> =>
combineLatest([ combineLatest([
@@ -41,12 +41,12 @@ export function bounties (instanceId: string, api: ApiInterfaceRx): () => Observ
]).pipe( ]).pipe(
switchMap(() => switchMap(() =>
combineLatest([ combineLatest([
bountyBase.bounties.keys(), bountyBase.bounties.keys<[BountyIndex]>(),
api.derive.council ? api.derive.council.proposals() : of([]) api.derive.council ? api.derive.council.proposals() : of([])
]) ])
), ),
switchMap(([keys, proposals]): Observable<Result> => { switchMap(([keys, proposals]): Observable<Result> => {
const ids = (keys as StorageKey<[BountyIndex]>[]).map(({ args: [id] }) => id); const ids = keys.map(({ args: [id] }) => id);
return combineLatest([ return combineLatest([
bountyBase.bounties.multi<Option<Bounty>>(ids), bountyBase.bounties.multi<Option<Bounty>>(ids),
+19 -9
View File
@@ -3,7 +3,7 @@
import type { ApiInterfaceRx } from '@polkadot/api/types'; import type { ApiInterfaceRx } from '@polkadot/api/types';
import type { Vec } from '@polkadot/types'; import type { Vec } from '@polkadot/types';
import type { AccountId, Balance } from '@polkadot/types/interfaces'; import type { AccountId, Balance, Voter } from '@polkadot/types/interfaces';
import type { ITuple } from '@polkadot/types/types'; import type { ITuple } from '@polkadot/types/types';
import type { Observable } from '@polkadot/x-rxjs'; import type { Observable } from '@polkadot/x-rxjs';
import type { DeriveCouncilVote, DeriveCouncilVotes } from '../types'; import type { DeriveCouncilVote, DeriveCouncilVotes } from '../types';
@@ -13,18 +13,25 @@ import { map } from '@polkadot/x-rxjs/operators';
import { memo } from '../util'; import { memo } from '../util';
// Voter is current tuple is 2.x-era
type VoteEntry = Voter | ITuple<[Balance, Vec<AccountId>]>;
function isVoter (value: VoteEntry): value is Voter {
return !Array.isArray(value);
}
function retrieveStakeOf (api: ApiInterfaceRx): Observable<[AccountId, Balance][]> { function retrieveStakeOf (api: ApiInterfaceRx): Observable<[AccountId, Balance][]> {
return (api.query.electionsPhragmen || api.query.elections).stakeOf.entries<Balance>().pipe( return (api.query.electionsPhragmen || api.query.elections).stakeOf.entries<Balance, [AccountId]>().pipe(
map((entries) => map((entries) =>
entries.map(([key, stake]) => [key.args[0] as AccountId, stake]) entries.map(([{ args: [accountId] }, stake]) => [accountId, stake])
) )
); );
} }
function retrieveVoteOf (api: ApiInterfaceRx): Observable<[AccountId, AccountId[]][]> { function retrieveVoteOf (api: ApiInterfaceRx): Observable<[AccountId, AccountId[]][]> {
return (api.query.electionsPhragmen || api.query.elections).votesOf.entries<Vec<AccountId>>().pipe( return (api.query.electionsPhragmen || api.query.elections).votesOf.entries<Vec<AccountId>, [AccountId]>().pipe(
map((entries) => map((entries) =>
entries.map(([key, votes]) => [key.args[0] as AccountId, votes]) entries.map(([{ args: [accountId] }, votes]) => [accountId, votes])
) )
); );
} }
@@ -56,11 +63,14 @@ function retrievePrev (api: ApiInterfaceRx): Observable<DeriveCouncilVotes> {
function retrieveCurrent (api: ApiInterfaceRx): Observable<DeriveCouncilVotes> { function retrieveCurrent (api: ApiInterfaceRx): Observable<DeriveCouncilVotes> {
const elections = (api.query.electionsPhragmen || api.query.elections); const elections = (api.query.electionsPhragmen || api.query.elections);
return elections.voting.entries<ITuple<[Balance, Vec<AccountId>]>>().pipe( return elections.voting.entries<VoteEntry, [AccountId]>().pipe(
map((entries): DeriveCouncilVotes => map((entries): DeriveCouncilVotes =>
entries.map(([key, [stake, votes]]): [AccountId, DeriveCouncilVote] => entries.map(([{ args: [accountId] }, value]): [AccountId, DeriveCouncilVote] => [
[key.args[0] as AccountId, { stake, votes }] accountId,
) isVoter(value)
? { stake: value.stake, votes: value.votes }
: { stake: value[0], votes: value[1] }
])
) )
); );
} }
@@ -51,7 +51,7 @@ function schedulerEntries (api: ApiInterfaceRx): Observable<[BlockNumber[], Opti
api.query.scheduler.agenda.keys() api.query.scheduler.agenda.keys()
), ),
switchMap((keys) => { switchMap((keys) => {
const blockNumbers = keys.map((key) => key.args[0]); const blockNumbers = keys.map(({ args: [blockNumber] }) => blockNumber);
return combineLatest([ return combineLatest([
of(blockNumbers), of(blockNumbers),
@@ -67,9 +67,9 @@ function extractVotes (mapped: [AccountId, Voting][], referendumId: BN): DeriveR
} }
function votesCurr (api: ApiInterfaceRx, referendumId: BN): Observable<DeriveReferendumVote[]> { function votesCurr (api: ApiInterfaceRx, referendumId: BN): Observable<DeriveReferendumVote[]> {
return api.query.democracy.votingOf.entries<Voting>().pipe( return api.query.democracy.votingOf.entries<Voting, [AccountId]>().pipe(
map((allVoting): DeriveReferendumVote[] => { map((allVoting): DeriveReferendumVote[] => {
const mapped = allVoting.map(([key, voting]): [AccountId, Voting] => [key.args[0], voting]); const mapped = allVoting.map(([{ args: [accountId] }, voting]): [AccountId, Voting] => [accountId, voting]);
const votes = extractVotes(mapped, referendumId); const votes = extractVotes(mapped, referendumId);
const delegations = mapped const delegations = mapped
.filter(([, voting]) => voting.isDelegating) .filter(([, voting]) => voting.isDelegating)
+11
View File
@@ -0,0 +1,11 @@
// Copyright 2017-2021 @polkadot/api-derive authors & contributors
// SPDX-License-Identifier: Apache-2.0
import { packageInfo as apiInfo } from '@polkadot/api/packageInfo';
import { packageInfo as coreInfo } from '@polkadot/rpc-core/packageInfo';
import { packageInfo as typesInfo } from '@polkadot/types/packageInfo';
import { detectPackage } from '@polkadot/util';
import { packageInfo } from './packageInfo';
detectPackage(packageInfo, typeof __dirname !== 'undefined' && __dirname, [apiInfo, coreInfo, typesInfo]);
+31 -6
View File
@@ -3,7 +3,7 @@
import type { ApiInterfaceRx } from '@polkadot/api/types'; import type { ApiInterfaceRx } from '@polkadot/api/types';
import type { u32, Vec } from '@polkadot/types'; import type { u32, Vec } from '@polkadot/types';
import type { AccountId, Balance, BlockNumber } from '@polkadot/types/interfaces'; import type { AccountId, Balance, BlockNumber, SeatHolder } from '@polkadot/types/interfaces';
import type { ITuple } from '@polkadot/types/types'; import type { ITuple } from '@polkadot/types/types';
import type { Observable } from '@polkadot/x-rxjs'; import type { Observable } from '@polkadot/x-rxjs';
import type { DeriveElectionsInfo } from './types'; import type { DeriveElectionsInfo } from './types';
@@ -12,14 +12,39 @@ import { map } from '@polkadot/x-rxjs/operators';
import { memo } from '../util'; import { memo } from '../util';
function sortAccounts ([, balanceA]: ITuple<[AccountId, Balance]>, [, balanceB]: ITuple<[AccountId, Balance]>): number { // SeatHolder is current tuple is 2.x-era Substrate
type Member = SeatHolder | ITuple<[AccountId, Balance]>;
type Candidate = AccountId | ITuple<[AccountId, Balance]>;
function isSeatHolder (value: Member): value is SeatHolder {
return !Array.isArray(value);
}
function isCandidateTuple (value: Candidate): value is ITuple<[AccountId, Balance]> {
return Array.isArray(value);
}
function getAccountTuple (value: Member): [AccountId, Balance] {
return isSeatHolder(value)
? [value.who, value.stake]
: value;
}
function getCandidate (value: Candidate): AccountId {
return isCandidateTuple(value)
? value[0]
: value;
}
function sortAccounts ([, balanceA]: [AccountId, Balance], [, balanceB]: [AccountId, Balance]): number {
return balanceB.cmp(balanceA); return balanceB.cmp(balanceA);
} }
function queryElections (api: ApiInterfaceRx): Observable<DeriveElectionsInfo> { function queryElections (api: ApiInterfaceRx): Observable<DeriveElectionsInfo> {
const section = api.query.electionsPhragmen ? 'electionsPhragmen' : 'elections'; const section = api.query.electionsPhragmen ? 'electionsPhragmen' : 'elections';
return api.queryMulti<[Vec<AccountId>, Vec<AccountId>, Vec<ITuple<[AccountId, Balance]>>, Vec<ITuple<[AccountId, Balance]>>]>([ return api.queryMulti<[Vec<AccountId>, Vec<Candidate>, Vec<Member>, Vec<Member>]>([
api.query.council.members, api.query.council.members,
api.query[section].candidates, api.query[section].candidates,
api.query[section].members, api.query[section].members,
@@ -28,13 +53,13 @@ function queryElections (api: ApiInterfaceRx): Observable<DeriveElectionsInfo> {
map(([councilMembers, candidates, members, runnersUp]): DeriveElectionsInfo => ({ map(([councilMembers, candidates, members, runnersUp]): DeriveElectionsInfo => ({
candidacyBond: api.consts[section].candidacyBond as Balance, candidacyBond: api.consts[section].candidacyBond as Balance,
candidateCount: api.registry.createType('u32', candidates.length), candidateCount: api.registry.createType('u32', candidates.length),
candidates, candidates: candidates.map(getCandidate),
desiredRunnersUp: api.consts[section].desiredRunnersUp as u32, desiredRunnersUp: api.consts[section].desiredRunnersUp as u32,
desiredSeats: api.consts[section].desiredMembers as u32, desiredSeats: api.consts[section].desiredMembers as u32,
members: members.length members: members.length
? members.sort(sortAccounts) ? members.map(getAccountTuple).sort(sortAccounts)
: councilMembers.map((accountId): [AccountId, Balance] => [accountId, api.registry.createType('Balance')]), : councilMembers.map((accountId): [AccountId, Balance] => [accountId, api.registry.createType('Balance')]),
runnersUp: runnersUp.sort(sortAccounts), runnersUp: runnersUp.map(getAccountTuple).sort(sortAccounts),
termDuration: api.consts[section].termDuration as BlockNumber, termDuration: api.consts[section].termDuration as BlockNumber,
votingBond: api.consts[section].votingBond as Balance votingBond: api.consts[section].votingBond as Balance
})) }))
+3
View File
@@ -1,6 +1,8 @@
// Copyright 2017-2021 @polkadot/api-derive authors & contributors // Copyright 2017-2021 @polkadot/api-derive authors & contributors
// SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: Apache-2.0
import './detectPackage';
import type { ApiInterfaceRx } from '@polkadot/api/types'; import type { ApiInterfaceRx } from '@polkadot/api/types';
import type { AnyFunction } from '@polkadot/types/types'; import type { AnyFunction } from '@polkadot/types/types';
import type { Observable } from '@polkadot/x-rxjs'; import type { Observable } from '@polkadot/x-rxjs';
@@ -22,6 +24,7 @@ import * as technicalCommittee from './technicalCommittee';
import * as treasury from './treasury'; import * as treasury from './treasury';
import * as tx from './tx'; import * as tx from './tx';
export { packageInfo } from './packageInfo';
export * from './type'; export * from './type';
export const derive = { accounts, balances, bounties, chain, contracts, council, democracy, elections, imOnline, parachains, session, society, staking, technicalCommittee, treasury, tx }; export const derive = { accounts, balances, bounties, chain, contracts, council, democracy, elections, imOnline, parachains, session, society, staking, technicalCommittee, treasury, tx };
+6
View File
@@ -0,0 +1,6 @@
// Copyright 2017-2021 @polkadot/dev authors & contributors
// SPDX-License-Identifier: Apache-2.0
// Auto-generated by @polkadot/dev, do not edit
export const packageInfo = { name: '@polkadot/api-derive', version: '3.11.1' };
@@ -3,7 +3,7 @@
import type { ApiInterfaceRx } from '@polkadot/api/types'; import type { ApiInterfaceRx } from '@polkadot/api/types';
import type { StorageKey } from '@polkadot/types'; import type { StorageKey } from '@polkadot/types';
import type { EraIndex, Exposure } from '@polkadot/types/interfaces'; import type { AccountId, EraIndex, Exposure } from '@polkadot/types/interfaces';
import type { Observable } from '@polkadot/x-rxjs'; import type { Observable } from '@polkadot/x-rxjs';
import type { DeriveEraExposure, DeriveEraNominatorExposure, DeriveEraValidatorExposure } from '../types'; import type { DeriveEraExposure, DeriveEraNominatorExposure, DeriveEraValidatorExposure } from '../types';
@@ -12,7 +12,7 @@ import { map, switchMap } from '@polkadot/x-rxjs/operators';
import { deriveCache, memo } from '../util'; import { deriveCache, memo } from '../util';
type KeysAndExposures = [StorageKey, Exposure][]; type KeysAndExposures = [StorageKey<[EraIndex, AccountId]>, Exposure][];
const CACHE_KEY = 'eraExposure'; const CACHE_KEY = 'eraExposure';
+17 -35
View File
@@ -1,55 +1,37 @@
// Copyright 2017-2021 @polkadot/api-derive authors & contributors // Copyright 2017-2021 @polkadot/api-derive authors & contributors
// SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: Apache-2.0
import type { ApiInterfaceRx } from '@polkadot/api/types'; import type { ApiInterfaceRx, QueryableStorageMultiArg } from '@polkadot/api/types';
import type { EraIndex, Exposure } from '@polkadot/types/interfaces'; import type { EraIndex, Exposure } from '@polkadot/types/interfaces';
import type { Observable } from '@polkadot/x-rxjs'; import type { Observable } from '@polkadot/x-rxjs';
import type { DeriveOwnExposure } from '../types'; import type { DeriveOwnExposure } from '../types';
import { combineLatest, of } from '@polkadot/x-rxjs'; import { of } from '@polkadot/x-rxjs';
import { map, switchMap } from '@polkadot/x-rxjs/operators'; import { map, switchMap } from '@polkadot/x-rxjs/operators';
import { deriveCache, memo } from '../util'; import { memo } from '../util';
const CACHE_KEY = 'ownExposure'; export function _ownExposures (instanceId: string, api: ApiInterfaceRx): (accountId: Uint8Array | string, eras: EraIndex[], withActive: boolean) => Observable<DeriveOwnExposure[]> {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
export function _ownExposure (instanceId: string, api: ApiInterfaceRx): (accountId: Uint8Array | string, era: EraIndex, withActive: boolean) => Observable<DeriveOwnExposure> { return memo(instanceId, (accountId: Uint8Array | string, eras: EraIndex[], _withActive: boolean): Observable<DeriveOwnExposure[]> =>
return memo(instanceId, (accountId: Uint8Array | string, era: EraIndex, withActive: boolean): Observable<DeriveOwnExposure> => { eras.length
const cacheKey = `${CACHE_KEY}-${era.toString()}-${accountId.toString()}`; ? api.queryMulti<Exposure[]>([
const cached = withActive ...eras.map((era): QueryableStorageMultiArg<'rxjs'> => [api.query.staking.erasStakersClipped, [era, accountId]]),
? undefined ...eras.map((era): QueryableStorageMultiArg<'rxjs'> => [api.query.staking.erasStakers, [era, accountId]])
: deriveCache.get<DeriveOwnExposure>(cacheKey);
return cached
? of(cached)
: api.queryMulti<[Exposure, Exposure]>([
[api.query.staking.erasStakersClipped, [era, accountId]],
[api.query.staking.erasStakers, [era, accountId]]
]).pipe( ]).pipe(
map(([clipped, exposure]): DeriveOwnExposure => { map((all): DeriveOwnExposure[] =>
const value = { clipped, era, exposure }; eras.map((era, index) => ({ clipped: all[index], era, exposure: all[eras.length + index] }))
)
!withActive && deriveCache.set(cacheKey, value); )
: of([])
return value;
})
); );
});
} }
export function ownExposure (instanceId: string, api: ApiInterfaceRx): (accountId: Uint8Array | string, era: EraIndex) => Observable<DeriveOwnExposure> { export function ownExposure (instanceId: string, api: ApiInterfaceRx): (accountId: Uint8Array | string, era: EraIndex) => Observable<DeriveOwnExposure> {
return memo(instanceId, (accountId: Uint8Array | string, era: EraIndex): Observable<DeriveOwnExposure> => return memo(instanceId, (accountId: Uint8Array | string, era: EraIndex): Observable<DeriveOwnExposure> =>
api.derive.staking._ownExposure(accountId, era, true) api.derive.staking._ownExposures(accountId, [era], true).pipe(
); map(([first]) => first)
}
export function _ownExposures (instanceId: string, api: ApiInterfaceRx): (accountId: Uint8Array | string, eras: EraIndex[], withActive: boolean) => Observable<DeriveOwnExposure[]> {
return memo(instanceId, (accountId: Uint8Array | string, eras: EraIndex[], withActive: boolean): Observable<DeriveOwnExposure[]> =>
eras.length
? combineLatest(
eras.map((era) => api.derive.staking._ownExposure(accountId, era, withActive))
) )
: of([])
); );
} }
+21 -39
View File
@@ -1,62 +1,44 @@
// Copyright 2017-2021 @polkadot/api-derive authors & contributors // Copyright 2017-2021 @polkadot/api-derive authors & contributors
// SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: Apache-2.0
import type { ApiInterfaceRx } from '@polkadot/api/types'; import type { ApiInterfaceRx, QueryableStorageMultiArg } from '@polkadot/api/types';
import type { Option } from '@polkadot/types'; import type { Option } from '@polkadot/types';
import type { BalanceOf, EraIndex, Perbill } from '@polkadot/types/interfaces'; import type { BalanceOf, EraIndex, Perbill } from '@polkadot/types/interfaces';
import type { ITuple } from '@polkadot/types/types'; import type { ITuple } from '@polkadot/types/types';
import type { Observable } from '@polkadot/x-rxjs'; import type { Observable } from '@polkadot/x-rxjs';
import type { DeriveStakerSlashes } from '../types'; import type { DeriveStakerSlashes } from '../types';
import { combineLatest, of } from '@polkadot/x-rxjs'; import { of } from '@polkadot/x-rxjs';
import { map, switchMap } from '@polkadot/x-rxjs/operators'; import { map, switchMap } from '@polkadot/x-rxjs/operators';
import { deriveCache, memo } from '../util'; import { memo } from '../util';
const CACHE_KEY = 'ownSlash'; export function _ownSlashes (instanceId: string, api: ApiInterfaceRx): (accountId: Uint8Array | string, eras: EraIndex[], withActive: boolean) => Observable<DeriveStakerSlashes[]> {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
export function _ownSlash (instanceId: string, api: ApiInterfaceRx): (accountId: Uint8Array | string, era: EraIndex, withActive: boolean) => Observable<DeriveStakerSlashes> { return memo(instanceId, (accountId: Uint8Array | string, eras: EraIndex[], _withActive: boolean): Observable<DeriveStakerSlashes[]> =>
return memo(instanceId, (accountId: Uint8Array | string, era: EraIndex, withActive: boolean): Observable<DeriveStakerSlashes> => { eras.length
const cacheKey = `${CACHE_KEY}-${era.toString()}-${accountId.toString()}`; ? api.queryMulti<(Option<ITuple<[Perbill, BalanceOf]>> | Option<BalanceOf>)[]>([
const cached = withActive ...eras.map((era): QueryableStorageMultiArg<'rxjs'> => [api.query.staking.validatorSlashInEra, [era, accountId]]),
? undefined ...eras.map((era): QueryableStorageMultiArg<'rxjs'> => [api.query.staking.nominatorSlashInEra, [era, accountId]])
: deriveCache.get<DeriveStakerSlashes>(cacheKey);
return cached
? of(cached)
: api.queryMulti<[Option<BalanceOf>, Option<ITuple<[Perbill, BalanceOf]>>]>([
[api.query.staking.nominatorSlashInEra, [era, accountId]],
[api.query.staking.validatorSlashInEra, [era, accountId]]
]).pipe( ]).pipe(
map(([optNom, optVal]): DeriveStakerSlashes => { map((values): DeriveStakerSlashes[] =>
const value = { eras.map((era, index) => ({
era, era,
total: optVal.isSome total: values[index].isSome
? optVal.unwrap()[1] ? (values[index].unwrap() as ITuple<[Perbill, BalanceOf]>)[1]
: optNom.unwrapOrDefault() : (values[index + eras.length].unwrapOrDefault() as BalanceOf)
}; }))
)
!withActive && deriveCache.set(cacheKey, value); )
: of([])
return value;
})
); );
});
} }
export function ownSlash (instanceId: string, api: ApiInterfaceRx): (accountId: Uint8Array | string, era: EraIndex) => Observable<DeriveStakerSlashes> { export function ownSlash (instanceId: string, api: ApiInterfaceRx): (accountId: Uint8Array | string, era: EraIndex) => Observable<DeriveStakerSlashes> {
return memo(instanceId, (accountId: Uint8Array | string, era: EraIndex): Observable<DeriveStakerSlashes> => return memo(instanceId, (accountId: Uint8Array | string, era: EraIndex): Observable<DeriveStakerSlashes> =>
api.derive.staking._ownSlash(accountId, era, true) api.derive.staking._ownSlashes(accountId, [era], true).pipe(
); map(([first]) => first)
}
export function _ownSlashes (instanceId: string, api: ApiInterfaceRx): (accountId: Uint8Array | string, eras: EraIndex[], withActive: boolean) => Observable<DeriveStakerSlashes[]> {
return memo(instanceId, (accountId: Uint8Array | string, eras: EraIndex[], withActive: boolean): Observable<DeriveStakerSlashes[]> =>
eras.length
? combineLatest(
eras.map((era) => api.derive.staking._ownSlash(accountId, era, withActive))
) )
: of([])
); );
} }
@@ -10,12 +10,13 @@ import { map, switchMap } from '@polkadot/x-rxjs/operators';
import { memo } from '../util'; import { memo } from '../util';
export function _stakerExposure (instanceId: string, api: ApiInterfaceRx): (accountId: Uint8Array | string, eras: EraIndex[], withActive: boolean) => Observable<DeriveStakerExposure[]> { export function _stakerExposures (instanceId: string, api: ApiInterfaceRx): (accountIds: (Uint8Array | string)[], eras: EraIndex[], withActive: boolean) => Observable<DeriveStakerExposure[][]> {
return memo(instanceId, (accountId: Uint8Array | string, eras: EraIndex[], withActive: boolean): Observable<DeriveStakerExposure[]> => { return memo(instanceId, (accountIds: (Uint8Array | string)[], eras: EraIndex[], withActive: boolean): Observable<DeriveStakerExposure[][]> => {
const stakerId = api.registry.createType('AccountId', accountId).toString(); const stakerIds = accountIds.map((a) => api.registry.createType('AccountId', a).toString());
return api.derive.staking._erasExposure(eras, withActive).pipe( return api.derive.staking._erasExposure(eras, withActive).pipe(
map((exposures): DeriveStakerExposure[] => map((exposures): DeriveStakerExposure[][] =>
stakerIds.map((stakerId) =>
exposures.map(({ era, nominators: allNominators, validators: allValidators }): DeriveStakerExposure => { exposures.map(({ era, nominators: allNominators, validators: allValidators }): DeriveStakerExposure => {
const isValidator = !!allValidators[stakerId]; const isValidator = !!allValidators[stakerId];
const validators: DeriveEraValidatorExposure = {}; const validators: DeriveEraValidatorExposure = {};
@@ -32,14 +33,23 @@ export function _stakerExposure (instanceId: string, api: ApiInterfaceRx): (acco
return { era, isEmpty: !Object.keys(validators).length, isValidator, nominating, validators }; return { era, isEmpty: !Object.keys(validators).length, isValidator, nominating, validators };
}) })
) )
)
); );
}); });
} }
export function stakerExposure (instanceId: string, api: ApiInterfaceRx): (accountId: Uint8Array | string, withActive?: boolean) => Observable<DeriveStakerExposure[]> { export function stakerExposures (instanceId: string, api: ApiInterfaceRx): (accountIds: (Uint8Array | string)[], withActive?: boolean) => Observable<DeriveStakerExposure[][]> {
return memo(instanceId, (accountId: Uint8Array | string, withActive = false): Observable<DeriveStakerExposure[]> => return memo(instanceId, (accountIds: (Uint8Array | string)[], withActive = false): Observable<DeriveStakerExposure[][]> =>
api.derive.staking.erasHistoric(withActive).pipe( api.derive.staking.erasHistoric(withActive).pipe(
switchMap((eras) => api.derive.staking._stakerExposure(accountId, eras, withActive)) switchMap((eras) => api.derive.staking._stakerExposures(accountIds, eras, withActive))
)
);
}
export function stakerExposure (instanceId: string, api: ApiInterfaceRx): (accountId: Uint8Array | string, withActive?: boolean) => Observable<DeriveStakerExposure[]> {
return memo(instanceId, (accountId: Uint8Array | string, withActive = false): Observable<DeriveStakerExposure[]> =>
api.derive.staking.stakerExposures([accountId, withActive]).pipe(
map(([first]) => first)
) )
); );
} }
@@ -2,45 +2,40 @@
// SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: Apache-2.0
import type { ApiInterfaceRx } from '@polkadot/api/types'; import type { ApiInterfaceRx } from '@polkadot/api/types';
import type { Option } from '@polkadot/types'; import type { AccountId, EraIndex, StakingLedger } from '@polkadot/types/interfaces';
import type { AccountId, EraIndex, StakingLedger, StakingLedgerTo240 } from '@polkadot/types/interfaces';
import type { Observable } from '@polkadot/x-rxjs'; import type { Observable } from '@polkadot/x-rxjs';
import type { DeriveEraPoints, DeriveEraPrefs, DeriveEraRewards, DeriveEraValPrefs, DeriveStakerExposure, DeriveStakerReward, DeriveStakerRewardValidator } from '../types'; import type { DeriveEraPoints, DeriveEraPrefs, DeriveEraRewards, DeriveEraValPrefs, DeriveStakerExposure, DeriveStakerReward, DeriveStakerRewardValidator } from '../types';
import type { DeriveStakingQuery } from './types'; import type { DeriveStakingQuery } from './types';
import BN from 'bn.js'; import BN from 'bn.js';
import { isFunction } from '@polkadot/util'; import { BN_BILLION, BN_ZERO } from '@polkadot/util';
import { combineLatest, of } from '@polkadot/x-rxjs'; import { combineLatest, of } from '@polkadot/x-rxjs';
import { map, switchMap } from '@polkadot/x-rxjs/operators'; import { map, switchMap } from '@polkadot/x-rxjs/operators';
import { memo } from '../util'; import { memo } from '../util';
type ErasResult = [{ unwrapOr: (value: BN) => BN }, DeriveEraPoints[], DeriveEraPrefs[], DeriveEraRewards[]]; type ErasResult = [DeriveEraPoints[], DeriveEraPrefs[], DeriveEraRewards[]];
const ZERO = new BN(0); function parseRewards (api: ApiInterfaceRx, stashId: AccountId, [erasPoints, erasPrefs, erasRewards]: ErasResult, exposures: DeriveStakerExposure[]): DeriveStakerReward[] {
const MIN_ONE = new BN(-1);
const COMM_DIV = new BN(1_000_000_000);
function parseRewards (api: ApiInterfaceRx, stashId: AccountId, [, erasPoints, erasPrefs, erasRewards]: ErasResult, exposures: DeriveStakerExposure[]): DeriveStakerReward[] {
return exposures.map(({ era, isEmpty, isValidator, nominating, validators: eraValidators }): DeriveStakerReward => { return exposures.map(({ era, isEmpty, isValidator, nominating, validators: eraValidators }): DeriveStakerReward => {
const { eraPoints, validators: allValPoints } = erasPoints.find((p) => p.era.eq(era)) || { eraPoints: ZERO, validators: {} }; const { eraPoints, validators: allValPoints } = erasPoints.find((p) => p.era.eq(era)) || { eraPoints: BN_ZERO, validators: {} };
const { eraReward } = erasRewards.find((r) => r.era.eq(era)) || { eraReward: api.registry.createType('Balance') }; const { eraReward } = erasRewards.find((r) => r.era.eq(era)) || { eraReward: api.registry.createType('Balance') };
const { validators: allValPrefs } = erasPrefs.find((p) => p.era.eq(era)) || { validators: {} as DeriveEraValPrefs }; const { validators: allValPrefs } = erasPrefs.find((p) => p.era.eq(era)) || { validators: {} as DeriveEraValPrefs };
const validators: Record<string, DeriveStakerRewardValidator> = {}; const validators: Record<string, DeriveStakerRewardValidator> = {};
const stakerId = stashId.toString(); const stakerId = stashId.toString();
Object.entries(eraValidators).forEach(([validatorId, exposure]): void => { Object.entries(eraValidators).forEach(([validatorId, exposure]): void => {
const valPoints = allValPoints[validatorId] || ZERO; const valPoints = allValPoints[validatorId] || BN_ZERO;
const valComm = allValPrefs[validatorId]?.commission.unwrap() || ZERO; const valComm = allValPrefs[validatorId]?.commission.unwrap() || BN_ZERO;
const expTotal = exposure.total.unwrap(); const expTotal = exposure.total.unwrap();
let avail = ZERO; let avail = BN_ZERO;
let value: BN | undefined; let value: BN | undefined;
if (!(expTotal.isZero() || valPoints.isZero() || eraPoints.isZero())) { if (!(expTotal.isZero() || valPoints.isZero() || eraPoints.isZero())) {
avail = eraReward.mul(valPoints).div(eraPoints); avail = eraReward.mul(valPoints).div(eraPoints);
const valCut = valComm.mul(avail).div(COMM_DIV); const valCut = valComm.mul(avail).div(BN_BILLION);
let staked: BN; let staked: BN;
if (validatorId === stakerId) { if (validatorId === stakerId) {
@@ -50,10 +45,10 @@ function parseRewards (api: ApiInterfaceRx, stashId: AccountId, [, erasPoints, e
staked = stakerExp staked = stakerExp
? stakerExp.value.unwrap() ? stakerExp.value.unwrap()
: ZERO; : BN_ZERO;
} }
value = avail.sub(valCut).imul(staked).div(expTotal).iadd(validatorId === stakerId ? valCut : ZERO); value = avail.sub(valCut).imul(staked).div(expTotal).iadd(validatorId === stakerId ? valCut : BN_ZERO);
} }
validators[validatorId] = { validators[validatorId] = {
@@ -73,32 +68,25 @@ function parseRewards (api: ApiInterfaceRx, stashId: AccountId, [, erasPoints, e
}); });
} }
function uniqValidators (rewards: DeriveStakerReward[]): string[] { function allUniqValidators (rewards: DeriveStakerReward[][]): [string[], string[][]] {
return rewards.reduce(([all, perStash]: [string[], string[][]], rewards) => {
const uniq: string[] = []; const uniq: string[] = [];
rewards.forEach(({ validators }): void => { perStash.push(uniq);
rewards.forEach(({ validators }) =>
Object.keys(validators).forEach((validatorId): void => { Object.keys(validators).forEach((validatorId): void => {
if (!uniq.includes(validatorId)) { if (!uniq.includes(validatorId)) {
uniq.push(validatorId); uniq.push(validatorId);
if (!all.includes(validatorId)) {
all.push(validatorId);
} }
}); }
}); })
);
return uniq; return [all, perStash];
} }, [[], []]);
function isOldLedger (ledger?: StakingLedger | StakingLedgerTo240): ledger is StakingLedgerTo240 {
return !!(ledger as StakingLedgerTo240)?.lastReward;
}
function filterEra (era: EraIndex, stakingLedger: StakingLedger): boolean {
return isOldLedger(stakingLedger)
? era.gt(stakingLedger.lastReward.unwrapOr(MIN_ONE))
: !stakingLedger.claimedRewards.some((e) => e.eq(era));
}
function filterEras (eras: EraIndex[], stakingLedger: StakingLedger): EraIndex[] {
return eras.filter((era) => filterEra(era, stakingLedger));
} }
function removeClaimed (validators: string[], queryValidators: DeriveStakingQuery[], reward: DeriveStakerReward): void { function removeClaimed (validators: string[], queryValidators: DeriveStakingQuery[], reward: DeriveStakerReward): void {
@@ -121,20 +109,16 @@ function removeClaimed (validators: string[], queryValidators: DeriveStakingQuer
}); });
} }
function filterRewards (api: ApiInterfaceRx, eras: EraIndex[], { migrateEra, rewards, stakingLedger }: { migrateEra: BN, rewards: DeriveStakerReward[]; stakingLedger: StakingLedger }): Observable<DeriveStakerReward[]> { function filterRewards (eras: EraIndex[], valInfo: [string, DeriveStakingQuery][], { rewards, stakingLedger }: { rewards: DeriveStakerReward[]; stakingLedger: StakingLedger }): DeriveStakerReward[] {
const validators = uniqValidators(rewards); const filter = eras.filter((era) => !stakingLedger.claimedRewards.some((e) => e.eq(era)));
const filter = filterEras(eras, stakingLedger); const validators = valInfo.map(([v]) => v);
const queryValidators = valInfo.map(([, q]) => q);
return api.derive.staking.queryMulti(validators, { withLedger: true }).pipe( return rewards
map((queryValidators): DeriveStakerReward[] =>
rewards
.filter(({ isEmpty }) => !isEmpty) .filter(({ isEmpty }) => !isEmpty)
.filter((reward): boolean => { .filter((reward): boolean => {
if (!filter.some((filter) => reward.era.eq(filter))) { if (!filter.some((filter) => reward.era.eq(filter))) {
return false; return false;
} else if (reward.era.lt(migrateEra)) {
// we filter again here, the actual ledger may have changed, e.g. something has been claimed
return filterEra(reward.era, stakingLedger);
} }
reward.isStakerPayout = true; reward.isStakerPayout = true;
@@ -147,17 +131,12 @@ function filterRewards (api: ApiInterfaceRx, eras: EraIndex[], { migrateEra, rew
.map((reward) => ({ .map((reward) => ({
...reward, ...reward,
nominators: reward.nominating.filter((n) => reward.validators[n.validatorId]) nominators: reward.nominating.filter((n) => reward.validators[n.validatorId])
})) }));
)
);
} }
export function _stakerRewardsEras (instanceId: string, api: ApiInterfaceRx): (eras: EraIndex[], withActive: boolean) => Observable<ErasResult> { export function _stakerRewardsEras (instanceId: string, api: ApiInterfaceRx): (eras: EraIndex[], withActive: boolean) => Observable<ErasResult> {
return memo(instanceId, (eras: EraIndex[], withActive: boolean): Observable<ErasResult> => return memo(instanceId, (eras: EraIndex[], withActive: boolean): Observable<ErasResult> =>
combineLatest([ combineLatest([
isFunction(api.query.staking.migrateEra)
? api.query.staking.migrateEra<Option<EraIndex>>()
: of(api.registry.createType('Option<EraIndex>')),
api.derive.staking._erasPoints(eras, withActive), api.derive.staking._erasPoints(eras, withActive),
api.derive.staking._erasPrefs(eras, withActive), api.derive.staking._erasPrefs(eras, withActive),
api.derive.staking._erasRewards(eras, withActive) api.derive.staking._erasRewards(eras, withActive)
@@ -165,23 +144,39 @@ export function _stakerRewardsEras (instanceId: string, api: ApiInterfaceRx): (e
); );
} }
export function _stakerRewards (instanceId: string, api: ApiInterfaceRx): (accountId: Uint8Array | string, eras: EraIndex[], withActive: boolean) => Observable<DeriveStakerReward[]> { export function _stakerRewards (instanceId: string, api: ApiInterfaceRx): (accountIds: (Uint8Array | string)[], eras: EraIndex[], withActive: boolean) => Observable<DeriveStakerReward[][]> {
return memo(instanceId, (accountId: Uint8Array | string, eras: EraIndex[], withActive: boolean): Observable<DeriveStakerReward[]> => return memo(instanceId, (accountIds: (Uint8Array | string)[], eras: EraIndex[], withActive: boolean): Observable<DeriveStakerReward[][]> =>
combineLatest([ combineLatest([
api.derive.staking.query(accountId, { withLedger: true }), api.derive.staking.queryMulti(accountIds, { withLedger: true }),
api.derive.staking._stakerExposure(accountId, eras, withActive), api.derive.staking._stakerExposures(accountIds, eras, withActive),
api.derive.staking._stakerRewardsEras(eras, withActive) api.derive.staking._stakerRewardsEras(eras, withActive)
]).pipe( ]).pipe(
switchMap(([{ stakingLedger, stashId }, exposures, erasResult]): Observable<DeriveStakerReward[]> => { switchMap(([queries, exposures, erasResult]): Observable<DeriveStakerReward[][]> => {
if (!stashId || !stakingLedger) { const allRewards = queries.map(({ stakingLedger, stashId }, index): DeriveStakerReward[] =>
return of([]); (!stashId || !stakingLedger)
? []
: parseRewards(api, stashId, erasResult, exposures[index])
);
if (withActive) {
return of(allRewards);
} }
const rewards = parseRewards(api, stashId, erasResult, exposures); const [allValidators, stashValidators] = allUniqValidators(allRewards);
return withActive return api.derive.staking.queryMulti(allValidators, { withLedger: true }).pipe(
? of(rewards) map((queriedVals): DeriveStakerReward[][] => {
: filterRewards(api, eras, { migrateEra: erasResult[0].unwrapOr(ZERO), rewards, stakingLedger }); return queries.map(({ stakingLedger }, index): DeriveStakerReward[] => {
const rewards = allRewards[index];
const ownValidators = stashValidators[index].map((validatorId): [string, DeriveStakingQuery] => [
validatorId,
queriedVals.find((q) => q.accountId.eq(validatorId)) as DeriveStakingQuery
]);
return filterRewards(eras, ownValidators, { rewards, stakingLedger });
});
})
);
}) })
) )
); );
@@ -190,7 +185,8 @@ export function _stakerRewards (instanceId: string, api: ApiInterfaceRx): (accou
export function stakerRewards (instanceId: string, api: ApiInterfaceRx): (accountId: Uint8Array | string, withActive?: boolean) => Observable<DeriveStakerReward[]> { export function stakerRewards (instanceId: string, api: ApiInterfaceRx): (accountId: Uint8Array | string, withActive?: boolean) => Observable<DeriveStakerReward[]> {
return memo(instanceId, (accountId: Uint8Array | string, withActive = false): Observable<DeriveStakerReward[]> => return memo(instanceId, (accountId: Uint8Array | string, withActive = false): Observable<DeriveStakerReward[]> =>
api.derive.staking.erasHistoric(withActive).pipe( api.derive.staking.erasHistoric(withActive).pipe(
switchMap((eras) => api.derive.staking._stakerRewards(accountId, eras, withActive)) switchMap((eras) => api.derive.staking._stakerRewards([accountId], eras, withActive)),
map(([first]) => first)
) )
); );
} }
@@ -198,7 +194,7 @@ export function stakerRewards (instanceId: string, api: ApiInterfaceRx): (accoun
export function stakerRewardsMultiEras (instanceId: string, api: ApiInterfaceRx): (accountIds: (Uint8Array | string)[], eras: EraIndex[]) => Observable<DeriveStakerReward[][]> { export function stakerRewardsMultiEras (instanceId: string, api: ApiInterfaceRx): (accountIds: (Uint8Array | string)[], eras: EraIndex[]) => Observable<DeriveStakerReward[][]> {
return memo(instanceId, (accountIds: (Uint8Array | string)[], eras: EraIndex[]): Observable<DeriveStakerReward[][]> => return memo(instanceId, (accountIds: (Uint8Array | string)[], eras: EraIndex[]): Observable<DeriveStakerReward[][]> =>
accountIds.length && eras.length accountIds.length && eras.length
? combineLatest(accountIds.map((acc) => api.derive.staking._stakerRewards(acc, eras, false))) ? api.derive.staking._stakerRewards(accountIds, eras, false)
: of([]) : of([])
); );
} }
+1 -1
View File
@@ -15,7 +15,7 @@ import { memo } from '../util';
export function stashes (instanceId: string, api: ApiInterfaceRx): () => Observable<AccountId[]> { export function stashes (instanceId: string, api: ApiInterfaceRx): () => Observable<AccountId[]> {
return memo(instanceId, (): Observable<AccountId[]> => return memo(instanceId, (): Observable<AccountId[]> =>
api.query.staking.validators.keys().pipe( api.query.staking.validators.keys().pipe(
map((keys) => keys.map((key) => key.args[0]).filter((a) => a)) map((keys) => keys.map(({ args: [validatorId] }) => validatorId).filter((a) => a))
) )
); );
} }
@@ -18,7 +18,7 @@ export function nextElected (instanceId: string, api: ApiInterfaceRx): () => Obs
// only populate for next era in the last session, so track both here - entries are not // only populate for next era in the last session, so track both here - entries are not
// subscriptions, so we need a trigger - currentIndex acts as that trigger to refresh // subscriptions, so we need a trigger - currentIndex acts as that trigger to refresh
switchMap(({ currentEra }) => api.query.staking.erasStakers.keys(currentEra)), switchMap(({ currentEra }) => api.query.staking.erasStakers.keys(currentEra)),
map((keys) => keys.map((key) => key.args[1])) map((keys) => keys.map(({ args: [, accountId] }) => accountId))
) )
: api.query.staking.currentElected<AccountId[]>() : api.query.staking.currentElected<AccountId[]>()
); );
+2 -4
View File
@@ -5,7 +5,7 @@ import type { DeriveCache } from './types';
const mapCache = new Map<string, any>(); const mapCache = new Map<string, any>();
const deriveMapCache: DeriveCache = { export const deriveMapCache: DeriveCache = {
del: (key: string): void => { del: (key: string): void => {
mapCache.delete(key); mapCache.delete(key);
}, },
@@ -24,11 +24,9 @@ const deriveMapCache: DeriveCache = {
} }
}; };
const deriveNoopCache: DeriveCache = { export const deriveNoopCache: DeriveCache = {
del: (): void => undefined, del: (): void => undefined,
forEach: () => undefined, forEach: () => undefined,
get: (): undefined => undefined, get: (): undefined => undefined,
set: (_: string, value: unknown): unknown => value set: (_: string, value: unknown): unknown => value
}; };
export { deriveMapCache, deriveNoopCache };
+12 -12
View File
@@ -1,6 +1,6 @@
{ {
"name": "@polkadot/api", "name": "@polkadot/api",
"version": "3.7.2", "version": "3.11.1",
"description": "Promise and RxJS wrappers around the Polkadot JS RPC", "description": "Promise and RxJS wrappers around the Polkadot JS RPC",
"main": "index.js", "main": "index.js",
"sideEffects": [ "sideEffects": [
@@ -15,17 +15,17 @@
"bugs": "https://github.com/polkadot-js/api/issues", "bugs": "https://github.com/polkadot-js/api/issues",
"homepage": "https://github.com/polkadot-js/api/tree/master/packages/api#readme", "homepage": "https://github.com/polkadot-js/api/tree/master/packages/api#readme",
"dependencies": { "dependencies": {
"@babel/runtime": "^7.12.5", "@babel/runtime": "^7.13.8",
"@polkadot/api-derive": "3.7.2", "@polkadot/api-derive": "3.11.1",
"@polkadot/keyring": "^5.5.1", "@polkadot/keyring": "^5.9.2",
"@polkadot/metadata": "3.7.2", "@polkadot/metadata": "3.11.1",
"@polkadot/rpc-core": "3.7.2", "@polkadot/rpc-core": "3.11.1",
"@polkadot/rpc-provider": "3.7.2", "@polkadot/rpc-provider": "3.11.1",
"@polkadot/types": "3.7.2", "@polkadot/types": "3.11.1",
"@polkadot/types-known": "3.7.2", "@polkadot/types-known": "3.11.1",
"@polkadot/util": "^5.5.1", "@polkadot/util": "^5.9.2",
"@polkadot/util-crypto": "^5.5.1", "@polkadot/util-crypto": "^5.9.2",
"@polkadot/x-rxjs": "^5.5.1", "@polkadot/x-rxjs": "^5.9.2",
"bn.js": "^4.11.9", "bn.js": "^4.11.9",
"eventemitter3": "^4.0.7" "eventemitter3": "^4.0.7"
} }
+24 -3
View File
@@ -107,12 +107,17 @@ declare module '@polkadot/api/types/consts' {
**/ **/
depositPerStorageItem: BalanceOf & AugmentedConst<ApiType>; depositPerStorageItem: BalanceOf & AugmentedConst<ApiType>;
/** /**
* The maximum nesting level of a call/instantiate stack. A reasonable default * The maximum length of a contract code in bytes. This limit applies to the instrumented
* value is 100. * version of the code. Therefore `instantiate_with_code` can fail even when supplying
* a wasm binary below this maximum size.
**/
maxCodeSize: u32 & AugmentedConst<ApiType>;
/**
* The maximum nesting level of a call/instantiate stack.
**/ **/
maxDepth: u32 & AugmentedConst<ApiType>; maxDepth: u32 & AugmentedConst<ApiType>;
/** /**
* The maximum size of a storage value in bytes. A reasonable default is 16 KiB. * The maximum size of a storage value and event payload in bytes.
**/ **/
maxValueSize: u32 & AugmentedConst<ApiType>; maxValueSize: u32 & AugmentedConst<ApiType>;
/** /**
@@ -179,6 +184,22 @@ declare module '@polkadot/api/types/consts' {
**/ **/
votingPeriod: BlockNumber & AugmentedConst<ApiType>; votingPeriod: BlockNumber & AugmentedConst<ApiType>;
}; };
electionProviderMultiPhase: {
[key: string]: Codec;
/**
* Duration of the signed phase.
**/
signedPhase: BlockNumber & AugmentedConst<ApiType>;
/**
* The minimum amount of improvement to the solution score that defines a solution as
* "better" (in any phase).
**/
solutionImprovementThreshold: Perbill & AugmentedConst<ApiType>;
/**
* Duration of the unsigned phase.
**/
unsignedPhase: BlockNumber & AugmentedConst<ApiType>;
};
elections: { elections: {
[key: string]: Codec; [key: string]: Codec;
candidacyBond: BalanceOf & AugmentedConst<ApiType>; candidacyBond: BalanceOf & AugmentedConst<ApiType>;
+27 -7
View File
@@ -184,13 +184,14 @@ declare module '@polkadot/api/types/errors' {
**/ **/
CodeNotFound: AugmentedError<ApiType>; CodeNotFound: AugmentedError<ApiType>;
/** /**
* The code supplied to `put_code` exceeds the limit specified in the current schedule. * The code supplied to `instantiate_with_code` exceeds the limit specified in the
* current schedule.
**/ **/
CodeTooLarge: AugmentedError<ApiType>; CodeTooLarge: AugmentedError<ApiType>;
/** /**
* A contract could not be evicted because it has enough balance to pay rent. * A contract could not be evicted because it has enough balance to pay rent.
* *
* This can be returned from [`Module::claim_surcharge`] because the target * This can be returned from [`Pallet::claim_surcharge`] because the target
* contract has enough balance to pay for its rent. * contract has enough balance to pay for its rent.
**/ **/
ContractNotEvictable: AugmentedError<ApiType>; ContractNotEvictable: AugmentedError<ApiType>;
@@ -205,11 +206,15 @@ declare module '@polkadot/api/types/errors' {
/** /**
* Removal of a contract failed because the deletion queue is full. * Removal of a contract failed because the deletion queue is full.
* *
* This can happen when either calling [`Module::claim_surcharge`] or `seal_terminate`. * This can happen when either calling [`Pallet::claim_surcharge`] or `seal_terminate`.
* The queue is filled by deleting contracts and emptied by a fixed amount each block. * The queue is filled by deleting contracts and emptied by a fixed amount each block.
* Trying again during another block is the only way to resolve this issue. * Trying again during another block is the only way to resolve this issue.
**/ **/
DeletionQueueFull: AugmentedError<ApiType>; DeletionQueueFull: AugmentedError<ApiType>;
/**
* A contract with the same AccountId already exists.
**/
DuplicateContract: AugmentedError<ApiType>;
/** /**
* The topics passed to `seal_deposit_events` contains at least one duplicate. * The topics passed to `seal_deposit_events` contains at least one duplicate.
**/ **/
@@ -494,6 +499,21 @@ declare module '@polkadot/api/types/errors' {
**/ **/
WrongUpperBound: AugmentedError<ApiType>; WrongUpperBound: AugmentedError<ApiType>;
}; };
electionProviderMultiPhase: {
[key: string]: AugmentedError<ApiType>;
/**
* Submission was too early.
**/
PreDispatchEarlySubmission: AugmentedError<ApiType>;
/**
* Submission was too weak, score-wise.
**/
PreDispatchWeakSubmission: AugmentedError<ApiType>;
/**
* Wrong number of winners presented.
**/
PreDispatchWrongWinnerCount: AugmentedError<ApiType>;
};
elections: { elections: {
[key: string]: AugmentedError<ApiType>; [key: string]: AugmentedError<ApiType>;
/** /**
@@ -686,6 +706,10 @@ declare module '@polkadot/api/types/errors' {
* The data to be stored is already stored. * The data to be stored is already stored.
**/ **/
AlreadyStored: AugmentedError<ApiType>; AlreadyStored: AugmentedError<ApiType>;
/**
* The maximum weight information provided was too low.
**/
MaxWeightTooLow: AugmentedError<ApiType>;
/** /**
* Threshold must be 2 or greater. * Threshold must be 2 or greater.
**/ **/
@@ -726,10 +750,6 @@ declare module '@polkadot/api/types/errors' {
* A timepoint was given, yet no multisig operation is underway. * A timepoint was given, yet no multisig operation is underway.
**/ **/
UnexpectedTimepoint: AugmentedError<ApiType>; UnexpectedTimepoint: AugmentedError<ApiType>;
/**
* The maximum weight information provided was too low.
**/
WeightTooLow: AugmentedError<ApiType>;
/** /**
* A different timepoint was given to the multisig operation that is underway. * A different timepoint was given to the multisig operation that is underway.
**/ **/
+76 -19
View File
@@ -160,45 +160,71 @@ declare module '@polkadot/api/types/events' {
contracts: { contracts: {
[key: string]: AugmentedEvent<ApiType>; [key: string]: AugmentedEvent<ApiType>;
/** /**
* Code with the specified hash has been stored. * A code with the specified hash was removed.
* \[code_hash\] * \[code_hash\]
*
* This happens when the last contract that uses this code hash was removed or evicted.
**/
CodeRemoved: AugmentedEvent<ApiType, [Hash]>;
/**
* Code with the specified hash has been stored. \[code_hash\]
**/ **/
CodeStored: AugmentedEvent<ApiType, [Hash]>; CodeStored: AugmentedEvent<ApiType, [Hash]>;
/** /**
* An event deposited upon execution of a contract from the account. * A custom event emitted by the contract.
* \[account, data\] * \[contract, data\]
**/
ContractExecution: AugmentedEvent<ApiType, [AccountId, Bytes]>;
/**
* Contract has been evicted and is now in tombstone state.
* \[contract, tombstone\]
* *
* # Params * # Params
* *
* - `contract`: `AccountId`: The account ID of the evicted contract. * - `contract`: The contract that emitted the event.
* - `tombstone`: `bool`: True if the evicted contract left behind a tombstone. * - `data`: Data supplied by the contract. Metadata generated during contract
* compilation is needed to decode it.
**/ **/
Evicted: AugmentedEvent<ApiType, [AccountId, bool]>; ContractEmitted: AugmentedEvent<ApiType, [AccountId, Bytes]>;
/** /**
* Contract deployed by address at the specified address. \[owner, contract\] * Contract has been evicted and is now in tombstone state. \[contract\]
**/
Evicted: AugmentedEvent<ApiType, [AccountId]>;
/**
* Contract deployed by address at the specified address. \[deployer, contract\]
**/ **/
Instantiated: AugmentedEvent<ApiType, [AccountId, AccountId]>; Instantiated: AugmentedEvent<ApiType, [AccountId, AccountId]>;
/** /**
* Restoration for a contract has been successful. * Restoration of a contract has been successful.
* \[donor, dest, code_hash, rent_allowance\] * \[restorer, dest, code_hash, rent_allowance\]
* *
* # Params * # Params
* *
* - `donor`: `AccountId`: Account ID of the restoring contract * - `restorer`: Account ID of the restoring contract.
* - `dest`: `AccountId`: Account ID of the restored contract * - `dest`: Account ID of the restored contract.
* - `code_hash`: `Hash`: Code hash of the restored contract * - `code_hash`: Code hash of the restored contract.
* - `rent_allowance: `Balance`: Rent allowance of the restored contract * - `rent_allowance`: Rent allowance of the restored contract.
**/ **/
Restored: AugmentedEvent<ApiType, [AccountId, AccountId, Hash, Balance]>; Restored: AugmentedEvent<ApiType, [AccountId, AccountId, Hash, Balance]>;
/** /**
* Triggered when the current \[schedule\] is updated. * Triggered when the current schedule is updated.
* \[version\]
*
* # Params
*
* - `version`: The version of the newly set schedule.
**/ **/
ScheduleUpdated: AugmentedEvent<ApiType, [u32]>; ScheduleUpdated: AugmentedEvent<ApiType, [u32]>;
/**
* Contract has been terminated without leaving a tombstone.
* \[contract, beneficiary\]
*
* # Params
*
* - `contract`: The contract that was terminated.
* - `beneficiary`: The account that received the contracts remaining balance.
*
* # Note
*
* The only way for a contract to be removed without a tombstone and emitting
* this event is by calling `seal_terminate`.
**/
Terminated: AugmentedEvent<ApiType, [AccountId, AccountId]>;
}; };
council: { council: {
[key: string]: AugmentedEvent<ApiType>; [key: string]: AugmentedEvent<ApiType>;
@@ -319,6 +345,37 @@ declare module '@polkadot/api/types/events' {
**/ **/
Vetoed: AugmentedEvent<ApiType, [AccountId, Hash, BlockNumber]>; Vetoed: AugmentedEvent<ApiType, [AccountId, Hash, BlockNumber]>;
}; };
electionProviderMultiPhase: {
[key: string]: AugmentedEvent<ApiType>;
/**
* The election has been finalized, with `Some` of the given computation, or else if the
* election failed, `None`.
**/
ElectionFinalized: AugmentedEvent<ApiType, [Option<ElectionCompute>]>;
/**
* An account has been rewarded for their signed submission being finalized.
**/
Rewarded: AugmentedEvent<ApiType, [AccountId]>;
/**
* The signed phase of the given round has started.
**/
SignedPhaseStarted: AugmentedEvent<ApiType, [u32]>;
/**
* An account has been slashed for submitting an invalid signed submission.
**/
Slashed: AugmentedEvent<ApiType, [AccountId]>;
/**
* A solution was stored with the given compute.
*
* If the solution is signed, this means that it hasn't yet been processed. If the
* solution is unsigned, this means that it has also been processed.
**/
SolutionStored: AugmentedEvent<ApiType, [ElectionCompute]>;
/**
* The unsigned phase of the given round has started.
**/
UnsignedPhaseStarted: AugmentedEvent<ApiType, [u32]>;
};
elections: { elections: {
[key: string]: AugmentedEvent<ApiType>; [key: string]: AugmentedEvent<ApiType>;
/** /**
+62 -6
View File
@@ -19,11 +19,11 @@ import type { CallIndex, LotteryConfig } from '@polkadot/types/interfaces/lotter
import type { DeferredOffenceOf, Kind, OffenceDetails, OpaqueTimeSlot, ReportIdOf } from '@polkadot/types/interfaces/offences'; import type { DeferredOffenceOf, Kind, OffenceDetails, OpaqueTimeSlot, ReportIdOf } from '@polkadot/types/interfaces/offences';
import type { ProxyAnnouncement, ProxyDefinition } from '@polkadot/types/interfaces/proxy'; import type { ProxyAnnouncement, ProxyDefinition } from '@polkadot/types/interfaces/proxy';
import type { ActiveRecovery, RecoveryConfig } from '@polkadot/types/interfaces/recovery'; import type { ActiveRecovery, RecoveryConfig } from '@polkadot/types/interfaces/recovery';
import type { AccountId, AccountIndex, AssetId, Balance, BalanceOf, BlockNumber, Hash, KeyTypeId, Moment, OpaqueCall, Perbill, Releases, ValidatorId } from '@polkadot/types/interfaces/runtime'; import type { AccountId, AccountIndex, AssetId, Balance, BalanceOf, BlockNumber, Hash, KeyTypeId, Moment, OpaqueCall, Perbill, Releases, Slot, ValidatorId } from '@polkadot/types/interfaces/runtime';
import type { Scheduled, TaskAddress } from '@polkadot/types/interfaces/scheduler'; import type { Scheduled, TaskAddress } from '@polkadot/types/interfaces/scheduler';
import type { Keys, SessionIndex } from '@polkadot/types/interfaces/session'; import type { Keys, SessionIndex } from '@polkadot/types/interfaces/session';
import type { Bid, BidKind, SocietyVote, StrikeCount, VouchingStatus } from '@polkadot/types/interfaces/society'; import type { Bid, BidKind, SocietyVote, StrikeCount, VouchingStatus } from '@polkadot/types/interfaces/society';
import type { ActiveEraInfo, ElectionResult, ElectionScore, ElectionStatus, EraIndex, EraRewardPoints, Exposure, Forcing, Nominations, RewardDestination, SeatHolder, SlashingSpans, SpanIndex, SpanRecord, StakingLedger, UnappliedSlash, ValidatorPrefs, Voter } from '@polkadot/types/interfaces/staking'; import type { ActiveEraInfo, ElectionResult, ElectionScore, ElectionStatus, EraIndex, EraRewardPoints, Exposure, Forcing, Nominations, ReadySolution, RewardDestination, RoundSnapshot, SeatHolder, SlashingSpans, SolutionOrSnapshotSize, SpanIndex, SpanRecord, StakingLedger, UnappliedSlash, ValidatorPrefs, Voter } from '@polkadot/types/interfaces/staking';
import type { AccountInfo, ConsumedWeight, DigestOf, EventIndex, EventRecord, LastRuntimeUpgradeInfo, Phase } from '@polkadot/types/interfaces/system'; import type { AccountInfo, ConsumedWeight, DigestOf, EventIndex, EventRecord, LastRuntimeUpgradeInfo, Phase } from '@polkadot/types/interfaces/system';
import type { Bounty, BountyIndex, OpenTip, TreasuryProposal } from '@polkadot/types/interfaces/treasury'; import type { Bounty, BountyIndex, OpenTip, TreasuryProposal } from '@polkadot/types/interfaces/treasury';
import type { Multiplier } from '@polkadot/types/interfaces/txpayment'; import type { Multiplier } from '@polkadot/types/interfaces/txpayment';
@@ -78,7 +78,7 @@ declare module '@polkadot/api/types/storage' {
/** /**
* Current slot number. * Current slot number.
**/ **/
currentSlot: AugmentedQuery<ApiType, () => Observable<u64>, []> & QueryableStorageEntry<ApiType, []>; currentSlot: AugmentedQuery<ApiType, () => Observable<Slot>, []> & QueryableStorageEntry<ApiType, []>;
/** /**
* Current epoch index. * Current epoch index.
**/ **/
@@ -87,7 +87,7 @@ declare module '@polkadot/api/types/storage' {
* The slot at which the first epoch actually started. This is 0 * The slot at which the first epoch actually started. This is 0
* until the first block of the chain. * until the first block of the chain.
**/ **/
genesisSlot: AugmentedQuery<ApiType, () => Observable<u64>, []> & QueryableStorageEntry<ApiType, []>; genesisSlot: AugmentedQuery<ApiType, () => Observable<Slot>, []> & QueryableStorageEntry<ApiType, []>;
/** /**
* Temporary value (cleared at block finalization) which is `Some` * Temporary value (cleared at block finalization) which is `Some`
* if per-block initialization has already been called for current block. * if per-block initialization has already been called for current block.
@@ -148,7 +148,7 @@ declare module '@polkadot/api/types/storage' {
/** /**
* The balance of an account. * The balance of an account.
* *
* NOTE: This is only used in the case that this module is used to store balances. * NOTE: This is only used in the case that this pallet is used to store balances.
**/ **/
account: AugmentedQuery<ApiType, (arg: AccountId | string | Uint8Array) => Observable<AccountData>, [AccountId]> & QueryableStorageEntry<ApiType, [AccountId]>; account: AugmentedQuery<ApiType, (arg: AccountId | string | Uint8Array) => Observable<AccountData>, [AccountId]> & QueryableStorageEntry<ApiType, [AccountId]>;
/** /**
@@ -323,6 +323,44 @@ declare module '@polkadot/api/types/storage' {
**/ **/
votingOf: AugmentedQuery<ApiType, (arg: AccountId | string | Uint8Array) => Observable<Voting>, [AccountId]> & QueryableStorageEntry<ApiType, [AccountId]>; votingOf: AugmentedQuery<ApiType, (arg: AccountId | string | Uint8Array) => Observable<Voting>, [AccountId]> & QueryableStorageEntry<ApiType, [AccountId]>;
}; };
electionProviderMultiPhase: {
[key: string]: QueryableStorageEntry<ApiType>;
/**
* Current phase.
**/
currentPhase: AugmentedQuery<ApiType, () => Observable<Phase>, []> & QueryableStorageEntry<ApiType, []>;
/**
* Desired number of targets to elect for this round.
*
* Only exists when [`Snapshot`] is present.
**/
desiredTargets: AugmentedQuery<ApiType, () => Observable<Option<u32>>, []> & QueryableStorageEntry<ApiType, []>;
/**
* Current best solution, signed or unsigned, queued to be returned upon `elect`.
**/
queuedSolution: AugmentedQuery<ApiType, () => Observable<Option<ReadySolution>>, []> & QueryableStorageEntry<ApiType, []>;
/**
* Internal counter for the number of rounds.
*
* This is useful for de-duplication of transactions submitted to the pool, and general
* diagnostics of the pallet.
*
* This is merely incremented once per every time that an upstream `elect` is called.
**/
round: AugmentedQuery<ApiType, () => Observable<u32>, []> & QueryableStorageEntry<ApiType, []>;
/**
* Snapshot data of the round.
*
* This is created at the beginning of the signed phase and cleared upon calling `elect`.
**/
snapshot: AugmentedQuery<ApiType, () => Observable<Option<RoundSnapshot>>, []> & QueryableStorageEntry<ApiType, []>;
/**
* The metadata of the [`RoundSnapshot`]
*
* Only exists when [`Snapshot`] is present.
**/
snapshotMetadata: AugmentedQuery<ApiType, () => Observable<Option<SolutionOrSnapshotSize>>, []> & QueryableStorageEntry<ApiType, []>;
};
elections: { elections: {
[key: string]: QueryableStorageEntry<ApiType>; [key: string]: QueryableStorageEntry<ApiType>;
/** /**
@@ -421,7 +459,7 @@ declare module '@polkadot/api/types/storage' {
imOnline: { imOnline: {
[key: string]: QueryableStorageEntry<ApiType>; [key: string]: QueryableStorageEntry<ApiType>;
/** /**
* For each session index, we keep a mapping of `T::ValidatorId` to the * For each session index, we keep a mapping of `ValidatorId<T>` to the
* number of blocks authored by the given authority. * number of blocks authored by the given authority.
**/ **/
authoredBlocks: AugmentedQueryDoubleMap<ApiType, (key1: SessionIndex | AnyNumber | Uint8Array, key2: ValidatorId | string | Uint8Array) => Observable<u32>, [SessionIndex, ValidatorId]> & QueryableStorageEntry<ApiType, [SessionIndex, ValidatorId]>; authoredBlocks: AugmentedQueryDoubleMap<ApiType, (key1: SessionIndex | AnyNumber | Uint8Array, key2: ValidatorId | string | Uint8Array) => Observable<u32>, [SessionIndex, ValidatorId]> & QueryableStorageEntry<ApiType, [SessionIndex, ValidatorId]>;
@@ -723,6 +761,12 @@ declare module '@polkadot/api/types/storage' {
* set, it might be active or not. * set, it might be active or not.
**/ **/
currentEra: AugmentedQuery<ApiType, () => Observable<Option<EraIndex>>, []> & QueryableStorageEntry<ApiType, []>; currentEra: AugmentedQuery<ApiType, () => Observable<Option<EraIndex>>, []> & QueryableStorageEntry<ApiType, []>;
/**
* The last planned session scheduled by the session pallet.
*
* This is basically in sync with the call to [`SessionManager::new_session`].
**/
currentPlannedSession: AugmentedQuery<ApiType, () => Observable<SessionIndex>, []> & QueryableStorageEntry<ApiType, []>;
/** /**
* The earliest era for which we have a pending, unapplied slash. * The earliest era for which we have a pending, unapplied slash.
**/ **/
@@ -730,6 +774,8 @@ declare module '@polkadot/api/types/storage' {
/** /**
* Flag to control the execution of the offchain election. When `Open(_)`, we accept * Flag to control the execution of the offchain election. When `Open(_)`, we accept
* solutions to be submitted. * solutions to be submitted.
*
* TWO_PHASE_NOTE: should be removed once we switch to multi-phase.
**/ **/
eraElectionStatus: AugmentedQuery<ApiType, () => Observable<ElectionStatus>, []> & QueryableStorageEntry<ApiType, []>; eraElectionStatus: AugmentedQuery<ApiType, () => Observable<ElectionStatus>, []> & QueryableStorageEntry<ApiType, []>;
/** /**
@@ -809,6 +855,8 @@ declare module '@polkadot/api/types/storage' {
/** /**
* True if the current **planned** session is final. Note that this does not take era * True if the current **planned** session is final. Note that this does not take era
* forcing into account. * forcing into account.
*
* TWO_PHASE_NOTE: should be removed once we switch to multi-phase.
**/ **/
isCurrentSessionFinal: AugmentedQuery<ApiType, () => Observable<bool>, []> & QueryableStorageEntry<ApiType, []>; isCurrentSessionFinal: AugmentedQuery<ApiType, () => Observable<bool>, []> & QueryableStorageEntry<ApiType, []>;
/** /**
@@ -835,10 +883,14 @@ declare module '@polkadot/api/types/storage' {
* The next validator set. At the end of an era, if this is available (potentially from the * The next validator set. At the end of an era, if this is available (potentially from the
* result of an offchain worker), it is immediately used. Otherwise, the on-chain election * result of an offchain worker), it is immediately used. Otherwise, the on-chain election
* is executed. * is executed.
*
* TWO_PHASE_NOTE: should be removed once we switch to multi-phase.
**/ **/
queuedElected: AugmentedQuery<ApiType, () => Observable<Option<ElectionResult>>, []> & QueryableStorageEntry<ApiType, []>; queuedElected: AugmentedQuery<ApiType, () => Observable<Option<ElectionResult>>, []> & QueryableStorageEntry<ApiType, []>;
/** /**
* The score of the current [`QueuedElected`]. * The score of the current [`QueuedElected`].
*
* TWO_PHASE_NOTE: should be removed once we switch to multi-phase.
**/ **/
queuedScore: AugmentedQuery<ApiType, () => Observable<Option<ElectionScore>>, []> & QueryableStorageEntry<ApiType, []>; queuedScore: AugmentedQuery<ApiType, () => Observable<Option<ElectionScore>>, []> & QueryableStorageEntry<ApiType, []>;
/** /**
@@ -854,11 +906,15 @@ declare module '@polkadot/api/types/storage' {
/** /**
* Snapshot of nominators at the beginning of the current election window. This should only * Snapshot of nominators at the beginning of the current election window. This should only
* have a value when [`EraElectionStatus`] == `ElectionStatus::Open(_)`. * have a value when [`EraElectionStatus`] == `ElectionStatus::Open(_)`.
*
* TWO_PHASE_NOTE: should be removed once we switch to multi-phase.
**/ **/
snapshotNominators: AugmentedQuery<ApiType, () => Observable<Option<Vec<AccountId>>>, []> & QueryableStorageEntry<ApiType, []>; snapshotNominators: AugmentedQuery<ApiType, () => Observable<Option<Vec<AccountId>>>, []> & QueryableStorageEntry<ApiType, []>;
/** /**
* Snapshot of validators at the beginning of the current election window. This should only * Snapshot of validators at the beginning of the current election window. This should only
* have a value when [`EraElectionStatus`] == `ElectionStatus::Open(_)`. * have a value when [`EraElectionStatus`] == `ElectionStatus::Open(_)`.
*
* TWO_PHASE_NOTE: should be removed once we switch to multi-phase.
**/ **/
snapshotValidators: AugmentedQuery<ApiType, () => Observable<Option<Vec<AccountId>>>, []> & QueryableStorageEntry<ApiType, []>; snapshotValidators: AugmentedQuery<ApiType, () => Observable<Option<Vec<AccountId>>>, []> & QueryableStorageEntry<ApiType, []>;
/** /**
+27 -3
View File
@@ -11,7 +11,7 @@ import type { PrefixedStorageKey } from '@polkadot/types/interfaces/childstate';
import type { AuthorityId } from '@polkadot/types/interfaces/consensus'; import type { AuthorityId } from '@polkadot/types/interfaces/consensus';
import type { ContractCallRequest, ContractExecResult } from '@polkadot/types/interfaces/contracts'; import type { ContractCallRequest, ContractExecResult } from '@polkadot/types/interfaces/contracts';
import type { CreatedBlock } from '@polkadot/types/interfaces/engine'; import type { CreatedBlock } from '@polkadot/types/interfaces/engine';
import type { EthAccount, EthCallRequest, EthFilter, EthLog, EthReceipt, EthRichBlock, EthSubKind, EthSubParams, EthSyncStatus, EthTransaction, EthTransactionRequest, EthWork } from '@polkadot/types/interfaces/eth'; import type { EthAccount, EthCallRequest, EthFilter, EthFilterChanges, EthLog, EthReceipt, EthRichBlock, EthSubKind, EthSubParams, EthSyncStatus, EthTransaction, EthTransactionRequest, EthWork } from '@polkadot/types/interfaces/eth';
import type { Extrinsic } from '@polkadot/types/interfaces/extrinsics'; import type { Extrinsic } from '@polkadot/types/interfaces/extrinsics';
import type { EncodedFinalityProofs, JustificationNotification, ReportedRoundStates } from '@polkadot/types/interfaces/grandpa'; import type { EncodedFinalityProofs, JustificationNotification, ReportedRoundStates } from '@polkadot/types/interfaces/grandpa';
import type { StorageKind } from '@polkadot/types/interfaces/offchain'; import type { StorageKind } from '@polkadot/types/interfaces/offchain';
@@ -188,6 +188,14 @@ declare module '@polkadot/rpc-core/types.jsonrpc' {
* Returns the code at given address at given time (block number). * Returns the code at given address at given time (block number).
**/ **/
getCode: AugmentedRpc<(address: H160 | string | Uint8Array, number?: BlockNumber | AnyNumber | Uint8Array) => Observable<Bytes>>; getCode: AugmentedRpc<(address: H160 | string | Uint8Array, number?: BlockNumber | AnyNumber | Uint8Array) => Observable<Bytes>>;
/**
* Returns filter changes since last poll.
**/
getFilterChanges: AugmentedRpc<(index: U256 | AnyNumber | Uint8Array) => Observable<EthFilterChanges>>;
/**
* Returns all logs matching given filter (in a range 'from' - 'to').
**/
getFilterLogs: AugmentedRpc<(index: U256 | AnyNumber | Uint8Array) => Observable<Vec<EthLog>>>;
/** /**
* Returns logs matching given filter object. * Returns logs matching given filter object.
**/ **/
@@ -248,6 +256,18 @@ declare module '@polkadot/rpc-core/types.jsonrpc' {
* Returns true if client is actively mining new blocks. * Returns true if client is actively mining new blocks.
**/ **/
mining: AugmentedRpc<() => Observable<bool>>; mining: AugmentedRpc<() => Observable<bool>>;
/**
* Returns id of new block filter.
**/
newBlockFilter: AugmentedRpc<() => Observable<U256>>;
/**
* Returns id of new filter.
**/
newFilter: AugmentedRpc<(filter: EthFilter | { fromBlock?: any; toBlock?: any; blockHash?: any; address?: any; topics?: any } | string | Uint8Array) => Observable<U256>>;
/**
* Returns id of new block filter.
**/
newPendingTransactionFilter: AugmentedRpc<() => Observable<U256>>;
/** /**
* Returns protocol version encoded as a string (quotes are necessary). * Returns protocol version encoded as a string (quotes are necessary).
**/ **/
@@ -276,6 +296,10 @@ declare module '@polkadot/rpc-core/types.jsonrpc' {
* Returns an object with data about the sync status or false. * Returns an object with data about the sync status or false.
**/ **/
syncing: AugmentedRpc<() => Observable<EthSyncStatus>>; syncing: AugmentedRpc<() => Observable<EthSyncStatus>>;
/**
* Uninstalls filter.
**/
uninstallFilter: AugmentedRpc<(index: U256 | AnyNumber | Uint8Array) => Observable<bool>>;
}; };
grandpa: { grandpa: {
/** /**
@@ -309,11 +333,11 @@ declare module '@polkadot/rpc-core/types.jsonrpc' {
/** /**
* Get offchain local storage under given key and prefix * 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 | 'PERSISTENT' | 'LOCAL' | number | Uint8Array, key: Bytes | string | Uint8Array) => Observable<Option<Bytes>>>;
/** /**
* Set offchain local storage under given key and prefix * 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 | 'PERSISTENT' | 'LOCAL' | number | Uint8Array, key: Bytes | string | Uint8Array, value: Bytes | string | Uint8Array) => Observable<Null>>;
}; };
payment: { payment: {
/** /**
+48 -17
View File
@@ -6,7 +6,7 @@ import type { AnyNumber, ITuple } from '@polkadot/types/types';
import type { TAssetBalance } from '@polkadot/types/interfaces/assets'; import type { TAssetBalance } from '@polkadot/types/interfaces/assets';
import type { BabeEquivocationProof } from '@polkadot/types/interfaces/babe'; import type { BabeEquivocationProof } from '@polkadot/types/interfaces/babe';
import type { MemberCount, ProposalIndex } from '@polkadot/types/interfaces/collective'; import type { MemberCount, ProposalIndex } from '@polkadot/types/interfaces/collective';
import type { CodeHash, Gas, Schedule } from '@polkadot/types/interfaces/contracts'; import type { CodeHash, Schedule } from '@polkadot/types/interfaces/contracts';
import type { AccountVote, Conviction, PropIndex, Proposal, ReferendumIndex } from '@polkadot/types/interfaces/democracy'; import type { AccountVote, Conviction, PropIndex, Proposal, ReferendumIndex } from '@polkadot/types/interfaces/democracy';
import type { Renouncing } from '@polkadot/types/interfaces/elections'; import type { Renouncing } from '@polkadot/types/interfaces/elections';
import type { Extrinsic, Signature } from '@polkadot/types/interfaces/extrinsics'; import type { Extrinsic, Signature } from '@polkadot/types/interfaces/extrinsics';
@@ -18,7 +18,7 @@ import type { AccountId, AccountIndex, AssetId, Balance, BalanceOf, BlockNumber,
import type { Period, Priority } from '@polkadot/types/interfaces/scheduler'; import type { Period, Priority } from '@polkadot/types/interfaces/scheduler';
import type { Keys } from '@polkadot/types/interfaces/session'; import type { Keys } from '@polkadot/types/interfaces/session';
import type { SocietyJudgement } from '@polkadot/types/interfaces/society'; import type { SocietyJudgement } from '@polkadot/types/interfaces/society';
import type { CompactAssignments, ElectionScore, ElectionSize, EraIndex, RewardDestination, ValidatorIndex, ValidatorPrefs } from '@polkadot/types/interfaces/staking'; import type { CompactAssignments, ElectionScore, ElectionSize, EraIndex, RawSolution, RewardDestination, SolutionOrSnapshotSize, ValidatorIndex, ValidatorPrefs } from '@polkadot/types/interfaces/staking';
import type { Key } from '@polkadot/types/interfaces/system'; import type { Key } from '@polkadot/types/interfaces/system';
import type { BountyIndex } from '@polkadot/types/interfaces/treasury'; import type { BountyIndex } from '@polkadot/types/interfaces/treasury';
import type { Timepoint } from '@polkadot/types/interfaces/utility'; import type { Timepoint } from '@polkadot/types/interfaces/utility';
@@ -396,7 +396,7 @@ declare module '@polkadot/api/types/submittable' {
* *
* 99% of the time you want [`transfer`] instead. * 99% of the time you want [`transfer`] instead.
* *
* [`transfer`]: struct.Module.html#method.transfer * [`transfer`]: struct.Pallet.html#method.transfer
* # <weight> * # <weight>
* - Cheaper than transfer because account cannot be killed. * - Cheaper than transfer because account cannot be killed.
* - Base Weight: 51.4 µs * - Base Weight: 51.4 µs
@@ -538,7 +538,7 @@ declare module '@polkadot/api/types/submittable' {
* * If no account exists and the call value is not less than `existential_deposit`, * * 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. * a regular account will be created and any value will be transferred.
**/ **/
call: AugmentedSubmittable<(dest: LookupSource | { Id: any } | { Index: any } | { Raw: any } | { Address32: any } | { Address20: any } | string | Uint8Array, value: Compact<BalanceOf> | AnyNumber | Uint8Array, gasLimit: Compact<Gas> | AnyNumber | Uint8Array, data: Bytes | string | Uint8Array) => SubmittableExtrinsic<ApiType>, [LookupSource, Compact<BalanceOf>, Compact<Gas>, Bytes]>; call: AugmentedSubmittable<(dest: LookupSource | { Id: any } | { Index: any } | { Raw: any } | { Address32: any } | { Address20: any } | string | Uint8Array, value: Compact<BalanceOf> | AnyNumber | Uint8Array, gasLimit: Compact<Weight> | AnyNumber | Uint8Array, data: Bytes | string | Uint8Array) => SubmittableExtrinsic<ApiType>, [LookupSource, Compact<BalanceOf>, Compact<Weight>, Bytes]>;
/** /**
* Allows block producers to claim a small reward for evicting a contract. If a block * 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. * producer fails to do so, a regular users will be allowed to claim the reward.
@@ -552,26 +552,37 @@ declare module '@polkadot/api/types/submittable' {
**/ **/
claimSurcharge: AugmentedSubmittable<(dest: AccountId | string | Uint8Array, auxSender: Option<AccountId> | null | object | string | Uint8Array) => SubmittableExtrinsic<ApiType>, [AccountId, Option<AccountId>]>; claimSurcharge: AugmentedSubmittable<(dest: AccountId | string | Uint8Array, auxSender: Option<AccountId> | null | object | string | Uint8Array) => SubmittableExtrinsic<ApiType>, [AccountId, Option<AccountId>]>;
/** /**
* Instantiates a new contract from the `code_hash` generated by `put_code`, * Instantiates a contract from a previously deployed wasm binary.
* optionally transferring some balance.
* *
* The supplied `salt` is used for contract address deriviation. See `fn contract_address`. * This function is identical to [`Self::instantiate_with_code`] but without the
* code deployment step. Instead, the `code_hash` of an on-chain deployed wasm binary
* must be supplied.
**/
instantiate: AugmentedSubmittable<(endowment: Compact<BalanceOf> | AnyNumber | Uint8Array, gasLimit: Compact<Weight> | AnyNumber | Uint8Array, codeHash: CodeHash | string | Uint8Array, data: Bytes | string | Uint8Array, salt: Bytes | string | Uint8Array) => SubmittableExtrinsic<ApiType>, [Compact<BalanceOf>, Compact<Weight>, CodeHash, Bytes, Bytes]>;
/**
* Instantiates a new contract from the supplied `code` optionally transferring
* some balance.
*
* This is the only function that can deploy new code to the chain.
*
* # Parameters
*
* * `endowment`: The balance to transfer from the `origin` to the newly created contract.
* * `gas_limit`: The gas limit enforced when executing the constructor.
* * `code`: The contract code to deploy in raw bytes.
* * `data`: The input data to pass to the contract constructor.
* * `salt`: Used for the address derivation. See [`Self::contract_address`].
* *
* Instantiation is executed as follows: * Instantiation is executed as follows:
* *
* - The supplied `code` is instrumented, deployed, and a `code_hash` is created for that code.
* - If the `code_hash` already exists on the chain the underlying `code` will be shared.
* - The destination address is computed based on the sender, code_hash and the salt. * - The destination address is computed based on the sender, code_hash and the salt.
* - The smart-contract account is created at the computed address. * - The smart-contract account is created at the computed address.
* - The `ctor_code` is executed in the context of the newly-created account. Buffer returned * - The `endowment` is transferred to the new account.
* after the execution is saved as the `code` of the account. That code will be invoked * - The `deploy` function is executed in the context of the newly-created account.
* upon any call received by this account.
* - The contract is initialized.
**/ **/
instantiate: AugmentedSubmittable<(endowment: Compact<BalanceOf> | AnyNumber | Uint8Array, gasLimit: Compact<Gas> | AnyNumber | Uint8Array, codeHash: CodeHash | string | Uint8Array, data: Bytes | string | Uint8Array, salt: Bytes | string | Uint8Array) => SubmittableExtrinsic<ApiType>, [Compact<BalanceOf>, Compact<Gas>, CodeHash, Bytes, Bytes]>; instantiateWithCode: AugmentedSubmittable<(endowment: Compact<BalanceOf> | AnyNumber | Uint8Array, gasLimit: Compact<Weight> | AnyNumber | Uint8Array, code: Bytes | string | Uint8Array, data: Bytes | string | Uint8Array, salt: Bytes | string | Uint8Array) => SubmittableExtrinsic<ApiType>, [Compact<BalanceOf>, Compact<Weight>, Bytes, Bytes, Bytes]>;
/**
* Stores the given binary Wasm code into the chain's storage and returns its `codehash`.
* You can instantiate contracts only with stored code.
**/
putCode: AugmentedSubmittable<(code: Bytes | string | Uint8Array) => SubmittableExtrinsic<ApiType>, [Bytes]>;
/** /**
* Updates the schedule for metering contracts. * Updates the schedule for metering contracts.
* *
@@ -1051,6 +1062,26 @@ declare module '@polkadot/api/types/submittable' {
**/ **/
vote: AugmentedSubmittable<(refIndex: Compact<ReferendumIndex> | AnyNumber | Uint8Array, vote: AccountVote | { Standard: any } | { Split: any } | string | Uint8Array) => SubmittableExtrinsic<ApiType>, [Compact<ReferendumIndex>, AccountVote]>; vote: AugmentedSubmittable<(refIndex: Compact<ReferendumIndex> | AnyNumber | Uint8Array, vote: AccountVote | { Standard: any } | { Split: any } | string | Uint8Array) => SubmittableExtrinsic<ApiType>, [Compact<ReferendumIndex>, AccountVote]>;
}; };
electionProviderMultiPhase: {
[key: string]: SubmittableExtrinsicFunction<ApiType>;
/**
* Submit a solution for the unsigned phase.
*
* The dispatch origin fo this call must be __none__.
*
* This submission is checked on the fly. Moreover, this unsigned solution is only
* validated when submitted to the pool from the **local** node. Effectively, this means
* that only active validators can submit this transaction when authoring a block (similar
* to an inherent).
*
* To prevent any incorrect solution (and thus wasted time/weight), this transaction will
* panic if the solution submitted by the validator is invalid in any way, effectively
* putting their authoring reward at risk.
*
* No deposit or reward is associated with this submission.
**/
submitUnsigned: AugmentedSubmittable<(solution: RawSolution | { compact?: any; score?: any; round?: any } | string | Uint8Array, witness: SolutionOrSnapshotSize | { voters?: any; targets?: any } | string | Uint8Array) => SubmittableExtrinsic<ApiType>, [RawSolution, SolutionOrSnapshotSize]>;
};
elections: { elections: {
[key: string]: SubmittableExtrinsicFunction<ApiType>; [key: string]: SubmittableExtrinsicFunction<ApiType>;
/** /**
+1 -1
View File
@@ -9,7 +9,7 @@ import type { ApiInterfaceRx, ApiTypes, DecoratedErrors, DecoratedEvents, Decora
import { assertReturn } from '@polkadot/util'; import { assertReturn } from '@polkadot/util';
import { packageInfo } from '../detectPackage'; import { packageInfo } from '../packageInfo';
import { Init } from './Init'; import { Init } from './Init';
interface PkgJson { interface PkgJson {
+9 -18
View File
@@ -2,7 +2,7 @@
// SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: Apache-2.0
import type { Text } from '@polkadot/types'; import type { Text } from '@polkadot/types';
import type { ChainProperties, Hash, RuntimeVersion, SignedBlock } from '@polkadot/types/interfaces'; import type { ChainProperties, Hash, RuntimeVersion } from '@polkadot/types/interfaces';
import type { Registry } from '@polkadot/types/types'; import type { Registry } from '@polkadot/types/types';
import type { Observable, Subscription } from '@polkadot/x-rxjs'; import type { Observable, Subscription } from '@polkadot/x-rxjs';
import type { ApiBase, ApiOptions, ApiTypes, DecorateMethod } from '../types'; import type { ApiBase, ApiOptions, ApiTypes, DecorateMethod } from '../types';
@@ -12,8 +12,7 @@ import BN from 'bn.js';
import { Metadata } from '@polkadot/metadata'; import { Metadata } from '@polkadot/metadata';
import { TypeRegistry } from '@polkadot/types/create'; import { TypeRegistry } from '@polkadot/types/create';
import { LATEST_EXTRINSIC_VERSION } from '@polkadot/types/extrinsic/Extrinsic'; import { getSpecAlias, getSpecExtensions, getSpecHasher, getSpecRpc, getSpecTypes, getUpgradeVersion } from '@polkadot/types-known';
import { getSpecAlias, getSpecRpc, getSpecTypes, getUpgradeVersion } from '@polkadot/types-known';
import { assert, BN_ZERO, logger, u8aEq, u8aToHex, u8aToU8a } from '@polkadot/util'; import { assert, BN_ZERO, logger, u8aEq, u8aToHex, u8aToU8a } from '@polkadot/util';
import { cryptoWaitReady } from '@polkadot/util-crypto'; import { cryptoWaitReady } from '@polkadot/util-crypto';
import { of } from '@polkadot/x-rxjs'; import { of } from '@polkadot/x-rxjs';
@@ -85,13 +84,17 @@ export abstract class Init<ApiType extends ApiTypes> extends Decorate<ApiType> {
registry.setChainProperties(chainProps || this.registry.getChainProperties()); registry.setChainProperties(chainProps || this.registry.getChainProperties());
registry.setKnownTypes(this._options); registry.setKnownTypes(this._options);
registry.register(getSpecTypes(registry, chain, version.specName, version.specVersion)); registry.register(getSpecTypes(registry, chain, version.specName, version.specVersion));
registry.setHasher(getSpecHasher(registry, chain, version.specName));
// for bundled types, pull through the aliases defined // for bundled types, pull through the aliases defined
if (registry.knownTypes.typesBundle) { if (registry.knownTypes.typesBundle) {
registry.knownTypes.typesAlias = getSpecAlias(registry, chain, version.specName); registry.knownTypes.typesAlias = getSpecAlias(registry, chain, version.specName);
} }
registry.setMetadata(metadata, undefined, this._options.signedExtensions); registry.setMetadata(metadata, undefined, {
...getSpecExtensions(registry, chain, version.specName),
...(this._options.signedExtensions || {})
});
return registry; return registry;
} }
@@ -282,20 +285,8 @@ export abstract class Init<ApiType extends ApiTypes> extends Decorate<ApiType> {
return [genesisHash, metadata]; return [genesisHash, metadata];
} }
private async _initFromMeta (metadata: Metadata): Promise<boolean> { private _initFromMeta (metadata: Metadata): boolean {
const metaExtrinsic = metadata.asLatest.extrinsic; this._extrinsicType = metadata.asLatest.extrinsic.version.toNumber();
// only inject if we are not a clone (global init)
if (metaExtrinsic.version.gt(BN_ZERO)) {
this._extrinsicType = metaExtrinsic.version.toNumber();
} else if (!this._options.source) {
// detect the extrinsic version in-use based on the last block
const { block: { extrinsics: [firstTx] } }: SignedBlock = await this._rpcCore.chain.getBlock().toPromise();
// If we haven't sync-ed to 1 yes, this won't have any values
this._extrinsicType = firstTx ? firstTx.type : LATEST_EXTRINSIC_VERSION;
}
this._rx.extrinsicType = this._extrinsicType; this._rx.extrinsicType = this._extrinsicType;
this._rx.genesisHash = this._genesisHash; this._rx.genesisHash = this._genesisHash;
this._rx.runtimeVersion = this._runtimeVersion as RuntimeVersion; // must be set here this._rx.runtimeVersion = this._runtimeVersion as RuntimeVersion; // must be set here
+8 -19
View File
@@ -1,25 +1,14 @@
// Copyright 2017-2021 @polkadot/api authors & contributors // Copyright 2017-2021 @polkadot/api authors & contributors
// SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: Apache-2.0
// For esm, this should be import.meta.url or to get the same behavior as __dirname, we can use import { packageInfo as deriveInfo } from '@polkadot/api-derive/packageInfo';
// import { packageInfo as metaInfo } from '@polkadot/metadata/packageInfo';
// new URL(import.meta.url).pathname) import { packageInfo as coreInfo } from '@polkadot/rpc-core/packageInfo';
// import { packageInfo as providerInfo } from '@polkadot/rpc-provider/packageInfo';
// The issue is the WP4 has "some" issues with import.meta.url. So because of bundlers, we can't have import { packageInfo as typesInfo } from '@polkadot/types/packageInfo';
// nice things... In this case it is even worse since import.meta.url won't even make it compile, so import { packageInfo as knownInfo } from '@polkadot/types-known/packageInfo';
// there is a complete dead end with usage thereof
//
// When that is fixed, a solution is to have both .js & .mjs files, with the following content -
//
// cjs: util.detectPackage(packageInfo, () => __dirname);
// esm: detectPackage(packageInfo, () => import.meta.url);
//
// With the above we additionally need a .d.ts to just export the packageInfo
import { detectPackage } from '@polkadot/util'; import { detectPackage } from '@polkadot/util';
import packageInfo from './package-info.json'; import { packageInfo } from './packageInfo';
detectPackage(packageInfo, typeof __dirname !== 'undefined' && __dirname); detectPackage(packageInfo, typeof __dirname !== 'undefined' && __dirname, [deriveInfo, metaInfo, coreInfo, providerInfo, typesInfo, knownInfo]);
export { packageInfo };
+2 -2
View File
@@ -6,7 +6,7 @@ import './detectPackage';
export { Keyring } from '@polkadot/keyring'; export { Keyring } from '@polkadot/keyring';
export { WsProvider } from '@polkadot/rpc-provider/ws'; export { WsProvider } from '@polkadot/rpc-provider/ws';
export { packageInfo } from './packageInfo';
export { ApiPromise } from './promise'; export { ApiPromise } from './promise';
export { ApiRx } from './rx';
export { SubmittableResult } from './submittable'; export { SubmittableResult } from './submittable';
export { ApiRx } from './rx';
+6
View File
@@ -0,0 +1,6 @@
// Copyright 2017-2021 @polkadot/dev authors & contributors
// SPDX-License-Identifier: Apache-2.0
// Auto-generated by @polkadot/dev, do not edit
export const packageInfo = { name: '@polkadot/api', version: '3.11.1' };
+3 -3
View File
@@ -66,14 +66,14 @@ export class SubmittableResult implements ISubmittableResult {
/** /**
* @description Filters EventRecords for the specified method & section (there could be multiple) * @description Filters EventRecords for the specified method & section (there could be multiple)
*/ */
public filterRecords (section: string, method: string): EventRecord[] { public filterRecords (section: string, method: string | string[]): EventRecord[] {
return filterAndApply(this.events, section, [method], recordIdentity); return filterAndApply(this.events, section, Array.isArray(method) ? method : [method], recordIdentity);
} }
/** /**
* @description Finds an EventRecord for the specified method & section * @description Finds an EventRecord for the specified method & section
*/ */
public findRecord (section: string, method: string): EventRecord | undefined { public findRecord (section: string, method: string | string[]): EventRecord | undefined {
return this.filterRecords(section, method)[0]; return this.filterRecords(section, method)[0];
} }
+1 -1
View File
@@ -60,7 +60,7 @@ export interface ApiOptions extends RegisteredTypes {
/** /**
* @description Any chain-specific signed extensions that are now well-known * @description Any chain-specific signed extensions that are now well-known
*/ */
signedExtensions?: Record<string, ExtDef>; signedExtensions?: ExtDef;
/** /**
* @description An external signer which will be used to sign extrinsic when account passed in is not KeyringPair * @description An external signer which will be used to sign extrinsic when account passed in is not KeyringPair
*/ */
+7 -7
View File
@@ -35,19 +35,19 @@ export type QueryableStorageEntry<ApiType extends ApiTypes, A extends AnyTuple =
// eslint-disable-next-line no-use-before-define // eslint-disable-next-line no-use-before-define
: AugmentedQuery<'promise', GenericStorageEntryFunction, A> & StorageEntryPromiseOverloads; : AugmentedQuery<'promise', GenericStorageEntryFunction, A> & StorageEntryPromiseOverloads;
export interface StorageEntryBase<ApiType extends ApiTypes, F extends AnyFunction, A extends AnyTuple> { export interface StorageEntryBase<ApiType extends ApiTypes, F extends AnyFunction, A extends AnyTuple = AnyTuple> {
at: <T extends Codec | any = ObsInnerType<ReturnType<F>>>(hash: Hash | Uint8Array | string, ...args: Parameters<F>) => PromiseOrObs<ApiType, T>; at: <T extends Codec | any = ObsInnerType<ReturnType<F>>>(hash: Hash | Uint8Array | string, ...args: Parameters<F>) => PromiseOrObs<ApiType, T>;
creator: StorageEntry; creator: StorageEntry;
entries: <T extends Codec | any = ObsInnerType<ReturnType<F>>>(arg?: Parameters<F>[0]) => PromiseOrObs<ApiType, [StorageKey<A>, T][]>; entries: <T extends Codec | any = ObsInnerType<ReturnType<F>>, K extends AnyTuple = A>(arg?: Parameters<F>[0]) => PromiseOrObs<ApiType, [StorageKey<K>, T][]>;
entriesAt: <T extends Codec | any = ObsInnerType<ReturnType<F>>>(hash: Hash | Uint8Array | string, arg?: Parameters<F>[0]) => PromiseOrObs<ApiType, [StorageKey<A>, T][]>; entriesAt: <T extends Codec | any = ObsInnerType<ReturnType<F>>, K extends AnyTuple = A>(hash: Hash | Uint8Array | string, arg?: Parameters<F>[0]) => PromiseOrObs<ApiType, [StorageKey<K>, T][]>;
entriesPaged: <T extends Codec | any = ObsInnerType<ReturnType<F>>>(opts: PaginationOptions<Parameters<F>[0]>) => PromiseOrObs<ApiType, [StorageKey<A>, T][]>; entriesPaged: <T extends Codec | any = ObsInnerType<ReturnType<F>>, K extends AnyTuple = A>(opts: PaginationOptions<Parameters<F>[0]>) => PromiseOrObs<ApiType, [StorageKey<K>, T][]>;
hash: (...args: Parameters<F>) => PromiseOrObs<ApiType, Hash>; hash: (...args: Parameters<F>) => PromiseOrObs<ApiType, Hash>;
is: (key: IStorageKey<AnyTuple>) => key is IStorageKey<A>; is: (key: IStorageKey<AnyTuple>) => key is IStorageKey<A>;
key: (...args: Parameters<F>) => string; key: (...args: Parameters<F>) => string;
keyPrefix: () => string; keyPrefix: () => string;
keys: (arg?: any) => PromiseOrObs<ApiType, StorageKey<A>[]>; keys: <K extends AnyTuple = A> (arg?: any) => PromiseOrObs<ApiType, StorageKey<K>[]>;
keysAt: (hash: Hash | Uint8Array | string, arg?: any) => PromiseOrObs<ApiType, StorageKey<A>[]>; keysAt: <K extends AnyTuple = A> (hash: Hash | Uint8Array | string, arg?: any) => PromiseOrObs<ApiType, StorageKey<K>[]>;
keysPaged: (opts: PaginationOptions<Parameters<F>[0]>) => PromiseOrObs<ApiType, StorageKey<A>[]>; keysPaged: <K extends AnyTuple = A> (opts: PaginationOptions<Parameters<F>[0]>) => PromiseOrObs<ApiType, StorageKey<K>[]>;
// @deprecated The underlying RPC this been marked unsafe and is generally not exposed // @deprecated The underlying RPC this been marked unsafe and is generally not exposed
range: <T extends Codec | any = ObsInnerType<ReturnType<F>>>([from, to]: [Hash | Uint8Array | string, Hash | Uint8Array | string | undefined] | [Hash | Uint8Array | string], ...args: Parameters<F>) => PromiseOrObs<ApiType, [Hash, T][]>; range: <T extends Codec | any = ObsInnerType<ReturnType<F>>>([from, to]: [Hash | Uint8Array | string, Hash | Uint8Array | string | undefined] | [Hash | Uint8Array | string], ...args: Parameters<F>) => PromiseOrObs<ApiType, [Hash, T][]>;
size: (...args: Parameters<F>) => PromiseOrObs<ApiType, u64>; size: (...args: Parameters<F>) => PromiseOrObs<ApiType, u64>;
+7 -7
View File
@@ -1,6 +1,6 @@
{ {
"name": "@polkadot/metadata", "name": "@polkadot/metadata",
"version": "3.7.2", "version": "3.11.1",
"description": "Helpers to extract information from runtime metadata", "description": "Helpers to extract information from runtime metadata",
"main": "index.js", "main": "index.js",
"sideEffects": [ "sideEffects": [
@@ -15,14 +15,14 @@
"bugs": "https://github.com/polkadot-js/api/issues", "bugs": "https://github.com/polkadot-js/api/issues",
"homepage": "https://github.com/polkadot-js/api/tree/master/packages/type-metadata#readme", "homepage": "https://github.com/polkadot-js/api/tree/master/packages/type-metadata#readme",
"dependencies": { "dependencies": {
"@babel/runtime": "^7.12.5", "@babel/runtime": "^7.13.8",
"@polkadot/types": "3.7.2", "@polkadot/types": "3.11.1",
"@polkadot/types-known": "3.7.2", "@polkadot/types-known": "3.11.1",
"@polkadot/util": "^5.5.1", "@polkadot/util": "^5.9.2",
"@polkadot/util-crypto": "^5.5.1", "@polkadot/util-crypto": "^5.9.2",
"bn.js": "^4.11.9" "bn.js": "^4.11.9"
}, },
"devDependencies": { "devDependencies": {
"@polkadot/keyring": "^5.5.1" "@polkadot/keyring": "^5.9.2"
} }
} }
+13 -1
View File
@@ -2,7 +2,7 @@
// SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: Apache-2.0
import type { MetadataAll, MetadataLatest, MetadataV9, MetadataV10, MetadataV11, MetadataV12 } from '@polkadot/types/interfaces/metadata'; import type { MetadataAll, MetadataLatest, MetadataV9, MetadataV10, MetadataV11, MetadataV12 } from '@polkadot/types/interfaces/metadata';
import type { Registry } from '@polkadot/types/types'; import type { AnyJson, Registry } from '@polkadot/types/types';
import { Struct } from '@polkadot/types/codec'; import { Struct } from '@polkadot/types/codec';
import { assert } from '@polkadot/util'; import { assert } from '@polkadot/util';
@@ -126,4 +126,16 @@ export class MetadataVersioned extends Struct {
public getUniqTypes (throwError: boolean): string[] { public getUniqTypes (throwError: boolean): string[] {
return getUniqTypes(this.registry, this.asLatest, throwError); return getUniqTypes(this.registry, this.asLatest, throwError);
} }
/**
* @description Converts the Object to JSON, typically used for RPC transfers
*/
public toJSON (): Record<string, AnyJson> {
// HACK(y): ensure that we apply the aliasses if we have not done so already, this is
// needed to ensure we have the overrides as intended (only applied in toLatest)
// eslint-disable-next-line no-unused-expressions
this.asLatest;
return super.toJSON();
}
} }
+1 -1
View File
@@ -30,4 +30,4 @@ export function expandMetadata (registry: Registry, metadata: Metadata): Decorat
}; };
} }
export { decorateConstants, decorateExtrinsics, decorateStorage }; export { decorateConstants, decorateErrors, decorateEvents, decorateExtrinsics, decorateStorage };
+4 -19
View File
@@ -1,25 +1,10 @@
// Copyright 2017-2021 @polkadot/metadata authors & contributors // Copyright 2017-2021 @polkadot/metadata authors & contributors
// SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: Apache-2.0
// For esm, this should be import.meta.url or to get the same behavior as __dirname, we can use import { packageInfo as typesInfo } from '@polkadot/types/packageInfo';
// import { packageInfo as knownInfo } from '@polkadot/types-known/packageInfo';
// new URL(import.meta.url).pathname)
//
// The issue is the WP4 has "some" issues with import.meta.url. So because of bundlers, we can't have
// nice things... In this case it is even worse since import.meta.url won't even make it compile, so
// there is a complete dead end with usage thereof
//
// When that is fixed, a solution is to have both .js & .mjs files, with the following content -
//
// cjs: util.detectPackage(packageInfo, () => __dirname);
// esm: detectPackage(packageInfo, () => import.meta.url);
//
// With the above we additionally need a .d.ts to just export the packageInfo
import { detectPackage } from '@polkadot/util'; import { detectPackage } from '@polkadot/util';
import packageInfo from './package-info.json'; import { packageInfo } from './packageInfo';
detectPackage(packageInfo, typeof __dirname !== 'undefined' && __dirname); detectPackage(packageInfo, typeof __dirname !== 'undefined' && __dirname, [typesInfo, knownInfo]);
export { packageInfo };
+1
View File
@@ -5,3 +5,4 @@ import './detectPackage';
export { Metadata } from './Metadata'; export { Metadata } from './Metadata';
export { decorateConstants, decorateExtrinsics, decorateStorage, expandMetadata } from './decorate'; export { decorateConstants, decorateExtrinsics, decorateStorage, expandMetadata } from './decorate';
export { packageInfo } from './packageInfo';
+6
View File
@@ -0,0 +1,6 @@
// Copyright 2017-2021 @polkadot/dev authors & contributors
// SPDX-License-Identifier: Apache-2.0
// Auto-generated by @polkadot/dev, do not edit
export const packageInfo = { name: '@polkadot/metadata', version: '3.11.1' };
+423 -95
View File
@@ -474,7 +474,7 @@
{ {
"name": "Version", "name": "Version",
"type": "RuntimeVersion", "type": "RuntimeVersion",
"value": "0x106e6f6465387375627374726174652d6e6f64650a000000050100000000000030df6acb689907609b0300000037e397fc7c91f5e40100000040fe3ad401f8959a04000000d2bc9897eed08f1502000000f78b278be53f454c02000000ed99c5acb25eedf502000000cbca25e39f14238702000000687ad44ad37f03c201000000bc9d89904f5b923f0100000068b66ba122c93fa70100000037c8bb1350a9a2a801000000ab3c0572291feb8b0100000002000000", "value": "0x106e6f6465387375627374726174652d6e6f64650a000000090100000000000034df6acb689907609b0300000037e397fc7c91f5e40100000040fe3ad401f8959a04000000d2bc9897eed08f1502000000f78b278be53f454c02000000ed99c5acb25eedf502000000cbca25e39f14238702000000687ad44ad37f03c201000000bc9d89904f5b923f0100000068b66ba122c93fa70100000037c8bb1350a9a2a80100000091d5df18b0d2cf5801000000ab3c0572291feb8b0100000002000000",
"documentation": [ "documentation": [
" Get the chain's current version." " Get the chain's current version."
] ]
@@ -671,7 +671,7 @@
"name": "GenesisSlot", "name": "GenesisSlot",
"modifier": "Default", "modifier": "Default",
"type": { "type": {
"Plain": "u64" "Plain": "Slot"
}, },
"fallback": "0x0000000000000000", "fallback": "0x0000000000000000",
"documentation": [ "documentation": [
@@ -683,7 +683,7 @@
"name": "CurrentSlot", "name": "CurrentSlot",
"modifier": "Default", "modifier": "Default",
"type": { "type": {
"Plain": "u64" "Plain": "Slot"
}, },
"fallback": "0x0000000000000000", "fallback": "0x0000000000000000",
"documentation": [ "documentation": [
@@ -1331,7 +1331,7 @@
"documentation": [ "documentation": [
" The balance of an account.", " The balance of an account.",
"", "",
" NOTE: This is only used in the case that this module is used to store balances." " NOTE: This is only used in the case that this pallet is used to store balances."
] ]
}, },
{ {
@@ -1489,7 +1489,7 @@
"", "",
" 99% of the time you want [`transfer`] instead.", " 99% of the time you want [`transfer`] instead.",
"", "",
" [`transfer`]: struct.Module.html#method.transfer", " [`transfer`]: struct.Pallet.html#method.transfer",
" # <weight>", " # <weight>",
" - Cheaper than transfer because account cannot be killed.", " - Cheaper than transfer because account cannot be killed.",
" - Base Weight: 51.4 µs", " - Base Weight: 51.4 µs",
@@ -1697,6 +1697,230 @@
"errors": [], "errors": [],
"index": 7 "index": 7
}, },
{
"name": "ElectionProviderMultiPhase",
"storage": {
"prefix": "ElectionProviderMultiPhase",
"items": [
{
"name": "Round",
"modifier": "Default",
"type": {
"Plain": "u32"
},
"fallback": "0x01000000",
"documentation": [
" Internal counter for the number of rounds.",
"",
" This is useful for de-duplication of transactions submitted to the pool, and general",
" diagnostics of the pallet.",
"",
" This is merely incremented once per every time that an upstream `elect` is called."
]
},
{
"name": "CurrentPhase",
"modifier": "Default",
"type": {
"Plain": "Phase"
},
"fallback": "0x00",
"documentation": [
" Current phase."
]
},
{
"name": "QueuedSolution",
"modifier": "Optional",
"type": {
"Plain": "ReadySolution"
},
"fallback": "0x00",
"documentation": [
" Current best solution, signed or unsigned, queued to be returned upon `elect`."
]
},
{
"name": "Snapshot",
"modifier": "Optional",
"type": {
"Plain": "RoundSnapshot"
},
"fallback": "0x00",
"documentation": [
" Snapshot data of the round.",
"",
" This is created at the beginning of the signed phase and cleared upon calling `elect`."
]
},
{
"name": "DesiredTargets",
"modifier": "Optional",
"type": {
"Plain": "u32"
},
"fallback": "0x00",
"documentation": [
" Desired number of targets to elect for this round.",
"",
" Only exists when [`Snapshot`] is present."
]
},
{
"name": "SnapshotMetadata",
"modifier": "Optional",
"type": {
"Plain": "SolutionOrSnapshotSize"
},
"fallback": "0x00",
"documentation": [
" The metadata of the [`RoundSnapshot`]",
"",
" Only exists when [`Snapshot`] is present."
]
}
]
},
"calls": [
{
"name": "submit_unsigned",
"args": [
{
"name": "solution",
"type": "RawSolution"
},
{
"name": "witness",
"type": "SolutionOrSnapshotSize"
}
],
"documentation": [
" Submit a solution for the unsigned phase.",
"",
" The dispatch origin fo this call must be __none__.",
"",
" This submission is checked on the fly. Moreover, this unsigned solution is only",
" validated when submitted to the pool from the **local** node. Effectively, this means",
" that only active validators can submit this transaction when authoring a block (similar",
" to an inherent).",
"",
" To prevent any incorrect solution (and thus wasted time/weight), this transaction will",
" panic if the solution submitted by the validator is invalid in any way, effectively",
" putting their authoring reward at risk.",
"",
" No deposit or reward is associated with this submission."
]
}
],
"events": [
{
"name": "SolutionStored",
"args": [
"ElectionCompute"
],
"documentation": [
" A solution was stored with the given compute.",
"",
" If the solution is signed, this means that it hasn't yet been processed. If the",
" solution is unsigned, this means that it has also been processed."
]
},
{
"name": "ElectionFinalized",
"args": [
"Option<ElectionCompute>"
],
"documentation": [
" The election has been finalized, with `Some` of the given computation, or else if the",
" election failed, `None`."
]
},
{
"name": "Rewarded",
"args": [
"AccountId"
],
"documentation": [
" An account has been rewarded for their signed submission being finalized."
]
},
{
"name": "Slashed",
"args": [
"AccountId"
],
"documentation": [
" An account has been slashed for submitting an invalid signed submission."
]
},
{
"name": "SignedPhaseStarted",
"args": [
"u32"
],
"documentation": [
" The signed phase of the given round has started."
]
},
{
"name": "UnsignedPhaseStarted",
"args": [
"u32"
],
"documentation": [
" The unsigned phase of the given round has started."
]
}
],
"constants": [
{
"name": "UnsignedPhase",
"type": "BlockNumber",
"value": "0x32000000",
"documentation": [
" Duration of the unsigned phase."
]
},
{
"name": "SignedPhase",
"type": "BlockNumber",
"value": "0x32000000",
"documentation": [
" Duration of the signed phase."
]
},
{
"name": "SolutionImprovementThreshold",
"type": "Perbill",
"value": "0x20a10700",
"documentation": [
" The minimum amount of improvement to the solution score that defines a solution as",
" \"better\" (in any phase)."
]
}
],
"errors": [
{
"name": "PreDispatchEarlySubmission",
"documentation": [
" Submission was too early."
]
},
{
"name": "PreDispatchWrongWinnerCount",
"documentation": [
" Wrong number of winners presented."
]
},
{
"name": "PreDispatchWeakSubmission",
"documentation": [
" Submission was too weak, score-wise."
]
}
],
"index": 8
},
{ {
"name": "Staking", "name": "Staking",
"storage": { "storage": {
@@ -2148,6 +2372,19 @@
" The earliest era for which we have a pending, unapplied slash." " The earliest era for which we have a pending, unapplied slash."
] ]
}, },
{
"name": "CurrentPlannedSession",
"modifier": "Default",
"type": {
"Plain": "SessionIndex"
},
"fallback": "0x00000000",
"documentation": [
" The last planned session scheduled by the session pallet.",
"",
" This is basically in sync with the call to [`SessionManager::new_session`]."
]
},
{ {
"name": "SnapshotValidators", "name": "SnapshotValidators",
"modifier": "Optional", "modifier": "Optional",
@@ -2157,7 +2394,9 @@
"fallback": "0x00", "fallback": "0x00",
"documentation": [ "documentation": [
" Snapshot of validators at the beginning of the current election window. This should only", " Snapshot of validators at the beginning of the current election window. This should only",
" have a value when [`EraElectionStatus`] == `ElectionStatus::Open(_)`." " have a value when [`EraElectionStatus`] == `ElectionStatus::Open(_)`.",
"",
" TWO_PHASE_NOTE: should be removed once we switch to multi-phase."
] ]
}, },
{ {
@@ -2169,7 +2408,9 @@
"fallback": "0x00", "fallback": "0x00",
"documentation": [ "documentation": [
" Snapshot of nominators at the beginning of the current election window. This should only", " Snapshot of nominators at the beginning of the current election window. This should only",
" have a value when [`EraElectionStatus`] == `ElectionStatus::Open(_)`." " have a value when [`EraElectionStatus`] == `ElectionStatus::Open(_)`.",
"",
" TWO_PHASE_NOTE: should be removed once we switch to multi-phase."
] ]
}, },
{ {
@@ -2182,7 +2423,9 @@
"documentation": [ "documentation": [
" The next validator set. At the end of an era, if this is available (potentially from the", " The next validator set. At the end of an era, if this is available (potentially from the",
" result of an offchain worker), it is immediately used. Otherwise, the on-chain election", " result of an offchain worker), it is immediately used. Otherwise, the on-chain election",
" is executed." " is executed.",
"",
" TWO_PHASE_NOTE: should be removed once we switch to multi-phase."
] ]
}, },
{ {
@@ -2193,7 +2436,9 @@
}, },
"fallback": "0x00", "fallback": "0x00",
"documentation": [ "documentation": [
" The score of the current [`QueuedElected`]." " The score of the current [`QueuedElected`].",
"",
" TWO_PHASE_NOTE: should be removed once we switch to multi-phase."
] ]
}, },
{ {
@@ -2205,7 +2450,9 @@
"fallback": "0x00", "fallback": "0x00",
"documentation": [ "documentation": [
" Flag to control the execution of the offchain election. When `Open(_)`, we accept", " Flag to control the execution of the offchain election. When `Open(_)`, we accept",
" solutions to be submitted." " solutions to be submitted.",
"",
" TWO_PHASE_NOTE: should be removed once we switch to multi-phase."
] ]
}, },
{ {
@@ -2217,7 +2464,9 @@
"fallback": "0x00", "fallback": "0x00",
"documentation": [ "documentation": [
" True if the current **planned** session is final. Note that this does not take era", " True if the current **planned** session is final. Note that this does not take era",
" forcing into account." " forcing into account.",
"",
" TWO_PHASE_NOTE: should be removed once we switch to multi-phase."
] ]
}, },
{ {
@@ -3363,7 +3612,7 @@
] ]
} }
], ],
"index": 8 "index": 9
}, },
{ {
"name": "Session", "name": "Session",
@@ -3557,7 +3806,7 @@
] ]
} }
], ],
"index": 9 "index": 10
}, },
{ {
"name": "Democracy", "name": "Democracy",
@@ -4806,7 +5055,7 @@
] ]
} }
], ],
"index": 10 "index": 11
}, },
{ {
"name": "Council", "name": "Council",
@@ -5265,7 +5514,7 @@
] ]
} }
], ],
"index": 11 "index": 12
}, },
{ {
"name": "TechnicalCommittee", "name": "TechnicalCommittee",
@@ -5724,7 +5973,7 @@
] ]
} }
], ],
"index": 12 "index": 13
}, },
{ {
"name": "Elections", "name": "Elections",
@@ -6183,7 +6432,7 @@
] ]
} }
], ],
"index": 13 "index": 14
}, },
{ {
"name": "TechnicalMembership", "name": "TechnicalMembership",
@@ -6366,7 +6615,7 @@
], ],
"constants": [], "constants": [],
"errors": [], "errors": [],
"index": 14 "index": 15
}, },
{ {
"name": "Grandpa", "name": "Grandpa",
@@ -6589,7 +6838,7 @@
] ]
} }
], ],
"index": 15 "index": 16
}, },
{ {
"name": "Treasury", "name": "Treasury",
@@ -6829,7 +7078,7 @@
] ]
} }
], ],
"index": 16 "index": 17
}, },
{ {
"name": "Contracts", "name": "Contracts",
@@ -6842,7 +7091,7 @@
"type": { "type": {
"Plain": "Schedule" "Plain": "Schedule"
}, },
"fallback": "0x000000000004000000000200000001000080000000100000000010000000010000200000000000080019060000016302005498030053100000941c0000a40d0000f11800005e2a00007000000044790100dcf102007907000080060000690700001a06000013190000f92800007f0700007d9ea70811080000a3070000770a00003308000023080000a5070000a3070000050a00003c0a000077090000b50900008f090000240a00007f09000041090000f9090000ec090000120a0000b70900003f0900003b200000cc1c000017200000471d0000e3090000c409000087090000080a00002e0a0000310a00003e0a0000380a00009c33260000000000a8fa2500000000005620250000000000848b4f00000000000e4a250000000000003f2500000000001066250000000000c0905400000000008c4e2500000000006c4b250000000000b49d490000000000466b12000000000090786500000000000f01000000000000b01b4300000000000003000000000000989e591f00000000c07d7c220000000040eca60900000000a4b55a0000000000701683000000000022b8c80700000000aa0900000000000076e85f0000000000bab5971100000000cf02000000000000f81bbb0800000000dedb070200000000dc050000000000007271d10900000000f49adb08000000007e070e08000000004a02000000000000260300000000000008f83e1b0000000051020000000000003103000000000000d70a000000000000d49522000000000068100000000000007c09250000000000240d000000000000b6e22000000000001f0600000000000006a22000000000001c06000000000000", "fallback": "0x0000000000040000000002000000010000800000001000000000100000000100002000000078060000a5600200a1740300271600000d1c0000e20c00006e160000ff280000a00000008b780100e4f80200b70600002c06000027070000a705000074170000ca2700002807000002ea8f08ef070000fd0700003c0a0000630800007f070000c7070000fe0700008909000022090000ea080000c30900002709000059070000d508000082080000b60900007a090000c90800009b080000bb080000a51f0000b51c00009a1f0000c21c00008c0800006b080000ea0800004009000092090000fc080000ae090000c2090000ae37290000000000e636290000000000be5a280000000000d479570000000000bc25280000000000a285280000000000008c28000000000052385c00000000003a07280000000000942a280000000000541d4d00000000002603130000000000b08a6f00000000000b01000000000000a053480000000000fd020000000000009862332700000000a32000000000000000e3bd3100000000902200000000000056120000000000006872ad0900000000de326200000000007cfe8e00000000008211ce07000000009309000000000000ac096d0000000000e43f161100000000da020000000000005e74cf0800000000e07b0b0200000000f005000000000000deb1c40a00000000f24a370900000000ff0e000000000000228bf9080000000049020000000000002a030000000000004c971c2300000000892100000000000067020000000000005703000000000000e60b000000000000aac22400000000006210000000000000f434270000000000200d00000000000094672200000000001806000000000000f86c2200000000001806000000000000",
"documentation": [ "documentation": [
" Current cost schedule for contracts." " Current cost schedule for contracts."
] ]
@@ -6939,19 +7188,6 @@
" The schedule must have a greater version than the stored schedule." " The schedule must have a greater version than the stored schedule."
] ]
}, },
{
"name": "put_code",
"args": [
{
"name": "code",
"type": "Bytes"
}
],
"documentation": [
" Stores the given binary Wasm code into the chain's storage and returns its `codehash`.",
" You can instantiate contracts only with stored code."
]
},
{ {
"name": "call", "name": "call",
"args": [ "args": [
@@ -6965,7 +7201,7 @@
}, },
{ {
"name": "gas_limit", "name": "gas_limit",
"type": "Compact<Gas>" "type": "Compact<Weight>"
}, },
{ {
"name": "data", "name": "data",
@@ -6982,6 +7218,54 @@
" a regular account will be created and any value will be transferred." " a regular account will be created and any value will be transferred."
] ]
}, },
{
"name": "instantiate_with_code",
"args": [
{
"name": "endowment",
"type": "Compact<BalanceOf>"
},
{
"name": "gas_limit",
"type": "Compact<Weight>"
},
{
"name": "code",
"type": "Bytes"
},
{
"name": "data",
"type": "Bytes"
},
{
"name": "salt",
"type": "Bytes"
}
],
"documentation": [
" Instantiates a new contract from the supplied `code` optionally transferring",
" some balance.",
"",
" This is the only function that can deploy new code to the chain.",
"",
" # Parameters",
"",
" * `endowment`: The balance to transfer from the `origin` to the newly created contract.",
" * `gas_limit`: The gas limit enforced when executing the constructor.",
" * `code`: The contract code to deploy in raw bytes.",
" * `data`: The input data to pass to the contract constructor.",
" * `salt`: Used for the address derivation. See [`Self::contract_address`].",
"",
" Instantiation is executed as follows:",
"",
" - The supplied `code` is instrumented, deployed, and a `code_hash` is created for that code.",
" - If the `code_hash` already exists on the chain the underlying `code` will be shared.",
" - The destination address is computed based on the sender, code_hash and the salt.",
" - The smart-contract account is created at the computed address.",
" - The `endowment` is transferred to the new account.",
" - The `deploy` function is executed in the context of the newly-created account."
]
},
{ {
"name": "instantiate", "name": "instantiate",
"args": [ "args": [
@@ -6991,7 +7275,7 @@
}, },
{ {
"name": "gas_limit", "name": "gas_limit",
"type": "Compact<Gas>" "type": "Compact<Weight>"
}, },
{ {
"name": "code_hash", "name": "code_hash",
@@ -7007,19 +7291,11 @@
} }
], ],
"documentation": [ "documentation": [
" Instantiates a new contract from the `code_hash` generated by `put_code`,", " Instantiates a contract from a previously deployed wasm binary.",
" optionally transferring some balance.",
"", "",
" The supplied `salt` is used for contract address deriviation. See `fn contract_address`.", " This function is identical to [`Self::instantiate_with_code`] but without the",
"", " code deployment step. Instead, the `code_hash` of an on-chain deployed wasm binary",
" Instantiation is executed as follows:", " must be supplied."
"",
" - The destination address is computed based on the sender, code_hash and the salt.",
" - The smart-contract account is created at the computed address.",
" - The `ctor_code` is executed in the context of the newly-created account. Buffer returned",
" after the execution is saved as the `code` of the account. That code will be invoked",
" upon any call received by this account.",
" - The contract is initialized."
] ]
}, },
{ {
@@ -7055,23 +7331,37 @@
"AccountId" "AccountId"
], ],
"documentation": [ "documentation": [
" Contract deployed by address at the specified address. \\[owner, contract\\]" " Contract deployed by address at the specified address. \\[deployer, contract\\]"
] ]
}, },
{ {
"name": "Evicted", "name": "Evicted",
"args": [ "args": [
"AccountId", "AccountId"
"bool"
], ],
"documentation": [ "documentation": [
" Contract has been evicted and is now in tombstone state.", " Contract has been evicted and is now in tombstone state. \\[contract\\]"
" \\[contract, tombstone\\]", ]
},
{
"name": "Terminated",
"args": [
"AccountId",
"AccountId"
],
"documentation": [
" Contract has been terminated without leaving a tombstone.",
" \\[contract, beneficiary\\]",
"", "",
" # Params", " # Params",
"", "",
" - `contract`: `AccountId`: The account ID of the evicted contract.", " - `contract`: The contract that was terminated.",
" - `tombstone`: `bool`: True if the evicted contract left behind a tombstone." " - `beneficiary`: The account that received the contracts remaining balance.",
"",
" # Note",
"",
" The only way for a contract to be removed without a tombstone and emitting",
" this event is by calling `seal_terminate`."
] ]
}, },
{ {
@@ -7083,15 +7373,15 @@
"Balance" "Balance"
], ],
"documentation": [ "documentation": [
" Restoration for a contract has been successful.", " Restoration of a contract has been successful.",
" \\[donor, dest, code_hash, rent_allowance\\]", " \\[restorer, dest, code_hash, rent_allowance\\]",
"", "",
" # Params", " # Params",
"", "",
" - `donor`: `AccountId`: Account ID of the restoring contract", " - `restorer`: Account ID of the restoring contract.",
" - `dest`: `AccountId`: Account ID of the restored contract", " - `dest`: Account ID of the restored contract.",
" - `code_hash`: `Hash`: Code hash of the restored contract", " - `code_hash`: Code hash of the restored contract.",
" - `rent_allowance: `Balance`: Rent allowance of the restored contract" " - `rent_allowance`: Rent allowance of the restored contract."
] ]
}, },
{ {
@@ -7100,8 +7390,7 @@
"Hash" "Hash"
], ],
"documentation": [ "documentation": [
" Code with the specified hash has been stored.", " Code with the specified hash has been stored. \\[code_hash\\]"
" \\[code_hash\\]"
] ]
}, },
{ {
@@ -7110,18 +7399,41 @@
"u32" "u32"
], ],
"documentation": [ "documentation": [
" Triggered when the current \\[schedule\\] is updated." " Triggered when the current schedule is updated.",
" \\[version\\]",
"",
" # Params",
"",
" - `version`: The version of the newly set schedule."
] ]
}, },
{ {
"name": "ContractExecution", "name": "ContractEmitted",
"args": [ "args": [
"AccountId", "AccountId",
"Bytes" "Bytes"
], ],
"documentation": [ "documentation": [
" An event deposited upon execution of a contract from the account.", " A custom event emitted by the contract.",
" \\[account, data\\]" " \\[contract, data\\]",
"",
" # Params",
"",
" - `contract`: The contract that emitted the event.",
" - `data`: Data supplied by the contract. Metadata generated during contract",
" compilation is needed to decode it."
]
},
{
"name": "CodeRemoved",
"args": [
"Hash"
],
"documentation": [
" A code with the specified hash was removed.",
" \\[code_hash\\]",
"",
" This happens when the last contract that uses this code hash was removed or evicted."
] ]
} }
], ],
@@ -7209,8 +7521,7 @@
"type": "u32", "type": "u32",
"value": "0x20000000", "value": "0x20000000",
"documentation": [ "documentation": [
" The maximum nesting level of a call/instantiate stack. A reasonable default", " The maximum nesting level of a call/instantiate stack."
" value is 100."
] ]
}, },
{ {
@@ -7218,13 +7529,13 @@
"type": "u32", "type": "u32",
"value": "0x00400000", "value": "0x00400000",
"documentation": [ "documentation": [
" The maximum size of a storage value in bytes. A reasonable default is 16 KiB." " The maximum size of a storage value and event payload in bytes."
] ]
}, },
{ {
"name": "DeletionQueueDepth", "name": "DeletionQueueDepth",
"type": "u32", "type": "u32",
"value": "0x11010000", "value": "0x1b010000",
"documentation": [ "documentation": [
" The maximum number of tries that can be queued for deletion." " The maximum number of tries that can be queued for deletion."
] ]
@@ -7236,6 +7547,16 @@
"documentation": [ "documentation": [
" The maximum amount of weight that can be consumed per block for lazy trie removal." " The maximum amount of weight that can be consumed per block for lazy trie removal."
] ]
},
{
"name": "MaxCodeSize",
"type": "u32",
"value": "0x00000200",
"documentation": [
" The maximum length of a contract code in bytes. This limit applies to the instrumented",
" version of the code. Therefore `instantiate_with_code` can fail even when supplying",
" a wasm binary below this maximum size."
]
} }
], ],
"errors": [ "errors": [
@@ -7328,7 +7649,8 @@
{ {
"name": "CodeTooLarge", "name": "CodeTooLarge",
"documentation": [ "documentation": [
" The code supplied to `put_code` exceeds the limit specified in the current schedule." " The code supplied to `instantiate_with_code` exceeds the limit specified in the",
" current schedule."
] ]
}, },
{ {
@@ -7406,7 +7728,7 @@
"documentation": [ "documentation": [
" Removal of a contract failed because the deletion queue is full.", " Removal of a contract failed because the deletion queue is full.",
"", "",
" This can happen when either calling [`Module::claim_surcharge`] or `seal_terminate`.", " This can happen when either calling [`Pallet::claim_surcharge`] or `seal_terminate`.",
" The queue is filled by deleting contracts and emptied by a fixed amount each block.", " The queue is filled by deleting contracts and emptied by a fixed amount each block.",
" Trying again during another block is the only way to resolve this issue." " Trying again during another block is the only way to resolve this issue."
] ]
@@ -7416,7 +7738,7 @@
"documentation": [ "documentation": [
" A contract could not be evicted because it has enough balance to pay rent.", " A contract could not be evicted because it has enough balance to pay rent.",
"", "",
" This can be returned from [`Module::claim_surcharge`] because the target", " This can be returned from [`Pallet::claim_surcharge`] because the target",
" contract has enough balance to pay for its rent." " contract has enough balance to pay for its rent."
] ]
}, },
@@ -7428,9 +7750,15 @@
" This can either happen when the accumulated storage in bytes is too large or", " This can either happen when the accumulated storage in bytes is too large or",
" when number of storage items is too large." " when number of storage items is too large."
] ]
},
{
"name": "DuplicateContract",
"documentation": [
" A contract with the same AccountId already exists."
]
} }
], ],
"index": 17 "index": 18
}, },
{ {
"name": "Sudo", "name": "Sudo",
@@ -7582,7 +7910,7 @@
] ]
} }
], ],
"index": 18 "index": 19
}, },
{ {
"name": "ImOnline", "name": "ImOnline",
@@ -7648,7 +7976,7 @@
}, },
"fallback": "0x00000000", "fallback": "0x00000000",
"documentation": [ "documentation": [
" For each session index, we keep a mapping of `T::ValidatorId` to the", " For each session index, we keep a mapping of `ValidatorId<T>` to the",
" number of blocks authored by the given authority." " number of blocks authored by the given authority."
] ]
} }
@@ -7722,7 +8050,7 @@
] ]
} }
], ],
"index": 19 "index": 20
}, },
{ {
"name": "AuthorityDiscovery", "name": "AuthorityDiscovery",
@@ -7731,7 +8059,7 @@
"events": null, "events": null,
"constants": [], "constants": [],
"errors": [], "errors": [],
"index": 20 "index": 21
}, },
{ {
"name": "Offences", "name": "Offences",
@@ -7825,7 +8153,7 @@
], ],
"constants": [], "constants": [],
"errors": [], "errors": [],
"index": 21 "index": 22
}, },
{ {
"name": "Historical", "name": "Historical",
@@ -7834,7 +8162,7 @@
"events": null, "events": null,
"constants": [], "constants": [],
"errors": [], "errors": [],
"index": 22 "index": 23
}, },
{ {
"name": "RandomnessCollectiveFlip", "name": "RandomnessCollectiveFlip",
@@ -7860,7 +8188,7 @@
"events": null, "events": null,
"constants": [], "constants": [],
"errors": [], "errors": [],
"index": 23 "index": 24
}, },
{ {
"name": "Identity", "name": "Identity",
@@ -8600,7 +8928,7 @@
] ]
} }
], ],
"index": 24 "index": 25
}, },
{ {
"name": "Society", "name": "Society",
@@ -9582,7 +9910,7 @@
] ]
} }
], ],
"index": 25 "index": 26
}, },
{ {
"name": "Recovery", "name": "Recovery",
@@ -10136,7 +10464,7 @@
] ]
} }
], ],
"index": 26 "index": 27
}, },
{ {
"name": "Vesting", "name": "Vesting",
@@ -10328,7 +10656,7 @@
] ]
} }
], ],
"index": 27 "index": 28
}, },
{ {
"name": "Scheduler", "name": "Scheduler",
@@ -10620,7 +10948,7 @@
] ]
} }
], ],
"index": 28 "index": 29
}, },
{ {
"name": "Proxy", "name": "Proxy",
@@ -11138,7 +11466,7 @@
] ]
} }
], ],
"index": 29 "index": 30
}, },
{ {
"name": "Multisig", "name": "Multisig",
@@ -11552,7 +11880,7 @@
] ]
}, },
{ {
"name": "WeightTooLow", "name": "MaxWeightTooLow",
"documentation": [ "documentation": [
" The maximum weight information provided was too low." " The maximum weight information provided was too low."
] ]
@@ -11564,7 +11892,7 @@
] ]
} }
], ],
"index": 30 "index": 31
}, },
{ {
"name": "Bounties", "name": "Bounties",
@@ -12024,7 +12352,7 @@
] ]
} }
], ],
"index": 31 "index": 32
}, },
{ {
"name": "Tips", "name": "Tips",
@@ -12397,7 +12725,7 @@
] ]
} }
], ],
"index": 32 "index": 33
}, },
{ {
"name": "Assets", "name": "Assets",
@@ -13210,7 +13538,7 @@
] ]
} }
], ],
"index": 33 "index": 34
}, },
{ {
"name": "Mmr", "name": "Mmr",
@@ -13264,7 +13592,7 @@
"events": null, "events": null,
"constants": [], "constants": [],
"errors": [], "errors": [],
"index": 34 "index": 35
}, },
{ {
"name": "Lottery", "name": "Lottery",
@@ -13486,7 +13814,7 @@
} }
], ],
"errors": [], "errors": [],
"index": 35 "index": 36
} }
], ],
"extrinsic": { "extrinsic": {
File diff suppressed because one or more lines are too long
+12 -9
View File
@@ -1,9 +1,12 @@
{ {
"name": "@polkadot/rpc-core", "name": "@polkadot/rpc-core",
"version": "3.7.2", "version": "3.11.1",
"description": "A JavaScript wrapper for the Polkadot JsonRPC interface", "description": "A JavaScript wrapper for the Polkadot JsonRPC interface",
"main": "index.js", "main": "index.js",
"sideEffects": false, "sideEffects": [
"./detectPackage.js",
"./detectPackage.mjs"
],
"author": "Jaco Greeff <jacogr@gmail.com>", "author": "Jaco Greeff <jacogr@gmail.com>",
"maintainers": [], "maintainers": [],
"contributors": [], "contributors": [],
@@ -12,14 +15,14 @@
"bugs": "https://github.com/polkadot-js/api/issues", "bugs": "https://github.com/polkadot-js/api/issues",
"homepage": "https://github.com/polkadot-js/api/tree/master/packages/rpc-core#readme", "homepage": "https://github.com/polkadot-js/api/tree/master/packages/rpc-core#readme",
"dependencies": { "dependencies": {
"@babel/runtime": "^7.12.5", "@babel/runtime": "^7.13.8",
"@polkadot/metadata": "3.7.2", "@polkadot/metadata": "3.11.1",
"@polkadot/rpc-provider": "3.7.2", "@polkadot/rpc-provider": "3.11.1",
"@polkadot/types": "3.7.2", "@polkadot/types": "3.11.1",
"@polkadot/util": "^5.5.1", "@polkadot/util": "^5.9.2",
"@polkadot/x-rxjs": "^5.5.1" "@polkadot/x-rxjs": "^5.9.2"
}, },
"devDependencies": { "devDependencies": {
"@polkadot/keyring": "^5.5.1" "@polkadot/keyring": "^5.9.2"
} }
} }
+11
View File
@@ -0,0 +1,11 @@
// Copyright 2017-2021 @polkadot/rpc-core authors & contributors
// SPDX-License-Identifier: Apache-2.0
import { packageInfo as metaInfo } from '@polkadot/metadata/packageInfo';
import { packageInfo as providerInfo } from '@polkadot/rpc-provider/packageInfo';
import { packageInfo as typesInfo } from '@polkadot/types/packageInfo';
import { detectPackage } from '@polkadot/util';
import { packageInfo } from './packageInfo';
detectPackage(packageInfo, typeof __dirname !== 'undefined' && __dirname, [metaInfo, providerInfo, typesInfo]);
+4
View File
@@ -1,6 +1,8 @@
// Copyright 2017-2021 @polkadot/rpc-core authors & contributors // Copyright 2017-2021 @polkadot/rpc-core authors & contributors
// SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: Apache-2.0
import './detectPackage';
import type { ProviderInterface, ProviderInterfaceCallback } from '@polkadot/rpc-provider/types'; import type { ProviderInterface, ProviderInterfaceCallback } from '@polkadot/rpc-provider/types';
import type { StorageKey, Vec } from '@polkadot/types'; import type { StorageKey, Vec } from '@polkadot/types';
import type { Hash } from '@polkadot/types/interfaces'; import type { Hash } from '@polkadot/types/interfaces';
@@ -18,6 +20,8 @@ import { publishReplay, refCount } from '@polkadot/x-rxjs/operators';
import { drr, refCountDelay } from './util'; import { drr, refCountDelay } from './util';
export { packageInfo } from './packageInfo';
interface StorageChangeSetJSON { interface StorageChangeSetJSON {
block: string; block: string;
changes: [string, string | null][]; changes: [string, string | null][];
+6
View File
@@ -0,0 +1,6 @@
// Copyright 2017-2021 @polkadot/dev authors & contributors
// SPDX-License-Identifier: Apache-2.0
// Auto-generated by @polkadot/dev, do not edit
export const packageInfo = { name: '@polkadot/rpc-core', version: '3.11.1' };
+15 -12
View File
@@ -1,9 +1,12 @@
{ {
"name": "@polkadot/rpc-provider", "name": "@polkadot/rpc-provider",
"version": "3.7.2", "version": "3.11.1",
"description": "Transport providers for the API", "description": "Transport providers for the API",
"main": "index.js", "main": "index.js",
"sideEffects": false, "sideEffects": [
"./detectPackage.js",
"./detectPackage.mjs"
],
"author": "Jaco Greeff <jacogr@gmail.com>", "author": "Jaco Greeff <jacogr@gmail.com>",
"maintainers": [], "maintainers": [],
"contributors": [], "contributors": [],
@@ -12,20 +15,20 @@
"bugs": "https://github.com/polkadot-js/api/issues", "bugs": "https://github.com/polkadot-js/api/issues",
"homepage": "https://github.com/polkadot-js/api/tree/master/packages/rpc-provider#readme", "homepage": "https://github.com/polkadot-js/api/tree/master/packages/rpc-provider#readme",
"dependencies": { "dependencies": {
"@babel/runtime": "^7.12.5", "@babel/runtime": "^7.13.8",
"@polkadot/types": "3.7.2", "@polkadot/types": "3.11.1",
"@polkadot/util": "^5.5.1", "@polkadot/util": "^5.9.2",
"@polkadot/util-crypto": "^5.5.1", "@polkadot/util-crypto": "^5.9.2",
"@polkadot/x-fetch": "^5.5.1", "@polkadot/x-fetch": "^5.9.2",
"@polkadot/x-global": "^5.5.1", "@polkadot/x-global": "^5.9.2",
"@polkadot/x-ws": "^5.5.1", "@polkadot/x-ws": "^5.9.2",
"bn.js": "^4.11.9", "bn.js": "^4.11.9",
"eventemitter3": "^4.0.7" "eventemitter3": "^4.0.7"
}, },
"devDependencies": { "devDependencies": {
"@polkadot/keyring": "^5.5.1", "@polkadot/keyring": "^5.9.2",
"@polkadot/metadata": "3.7.2", "@polkadot/metadata": "3.11.1",
"mock-socket": "^9.0.3", "mock-socket": "^9.0.3",
"nock": "^13.0.7" "nock": "^13.0.9"
} }
} }
@@ -0,0 +1,9 @@
// Copyright 2017-2021 @polkadot/rpc-provider authors & contributors
// SPDX-License-Identifier: Apache-2.0
import { packageInfo as typesInfo } from '@polkadot/types/packageInfo';
import { detectPackage } from '@polkadot/util';
import { packageInfo } from './packageInfo';
detectPackage(packageInfo, typeof __dirname !== 'undefined' && __dirname, [typesInfo]);
+3
View File
@@ -1,5 +1,8 @@
// Copyright 2017-2021 @polkadot/rpc-provider authors & contributors // Copyright 2017-2021 @polkadot/rpc-provider authors & contributors
// SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: Apache-2.0
import './detectPackage';
export { HttpProvider } from './http'; export { HttpProvider } from './http';
export { packageInfo } from './packageInfo';
export { WsProvider } from './ws'; export { WsProvider } from './ws';
+6
View File
@@ -0,0 +1,6 @@
// Copyright 2017-2021 @polkadot/dev authors & contributors
// SPDX-License-Identifier: Apache-2.0
// Auto-generated by @polkadot/dev, do not edit
export const packageInfo = { name: '@polkadot/rpc-provider', version: '3.11.1' };
+30 -11
View File
@@ -42,6 +42,16 @@ const RETRY_DELAY = 1000;
const l = logger('api-ws'); const l = logger('api-ws');
function eraseRecord<T> (record: Record<string, T>, cb?: (item: T) => void): void {
Object.keys(record).forEach((key): void => {
if (cb) {
cb(record[key]);
}
delete record[key];
});
}
/** /**
* # @polkadot/rpc-provider/ws * # @polkadot/rpc-provider/ws
* *
@@ -189,6 +199,7 @@ export class WsProvider implements ProviderInterface {
* @description Connect, never throwing an error, but rather forcing a retry * @description Connect, never throwing an error, but rather forcing a retry
*/ */
public async connectWithRetry (): Promise<void> { public async connectWithRetry (): Promise<void> {
if (this.#autoConnectMs > 0) {
try { try {
await this.connect(); await this.connect();
} catch (error) { } catch (error) {
@@ -196,7 +207,8 @@ export class WsProvider implements ProviderInterface {
this.connectWithRetry().catch((): void => { this.connectWithRetry().catch((): void => {
// does not throw // does not throw
}); });
}, this.#autoConnectMs || RETRY_DELAY); }, this.#autoConnectMs);
}
} }
} }
@@ -243,8 +255,8 @@ export class WsProvider implements ProviderInterface {
* @param params Encoded parameters as applicable for the method * @param params Encoded parameters as applicable for the method
* @param subscription Subscription details (internally used) * @param subscription Subscription details (internally used)
*/ */
public send (method: string, params: any[], subscription?: SubscriptionHandler): Promise<any> { public send <T = any> (method: string, params: any[], subscription?: SubscriptionHandler): Promise<T> {
return new Promise((resolve, reject): void => { return new Promise<T>((resolve, reject): void => {
try { try {
assert(this.isConnected && !isNull(this.#websocket), 'WebSocket is not connected'); assert(this.isConnected && !isNull(this.#websocket), 'WebSocket is not connected');
@@ -296,10 +308,8 @@ export class WsProvider implements ProviderInterface {
* }) * })
* ``` * ```
*/ */
public async subscribe (type: string, method: string, params: any[], callback: ProviderInterfaceCallback): Promise<number | string> { public subscribe (type: string, method: string, params: any[], callback: ProviderInterfaceCallback): Promise<number | string> {
const id = await this.send(method, params, { callback, type }) as Promise<number | string>; return this.send<number | string>(method, params, { callback, type });
return id;
} }
/** /**
@@ -320,9 +330,13 @@ export class WsProvider implements ProviderInterface {
delete this.#subscriptions[subscription]; delete this.#subscriptions[subscription];
const result = await this.send(method, [id]) as Promise<boolean>; try {
return this.isConnected && !isNull(this.#websocket)
return result; ? this.send<boolean>(method, [id])
: true;
} catch (error) {
return false;
}
} }
#emit = (type: ProviderInterfaceEmitted, ...args: any[]): void => { #emit = (type: ProviderInterfaceEmitted, ...args: any[]): void => {
@@ -330,12 +344,17 @@ export class WsProvider implements ProviderInterface {
} }
#onSocketClose = (event: CloseEvent): void => { #onSocketClose = (event: CloseEvent): void => {
const error = new Error(`disconnected from ${this.#endpoints[this.#endpointIndex]}: ${event.code}:: ${event.reason || getWSErrorString(event.code)}`);
if (this.#autoConnectMs > 0) { if (this.#autoConnectMs > 0) {
l.error(`disconnected from ${this.#endpoints[this.#endpointIndex]}: ${event.code}:: ${event.reason || getWSErrorString(event.code)}`); l.error(error.message);
} }
this.#isConnected = false; this.#isConnected = false;
this.#emit('disconnected'); this.#emit('disconnected');
// reject all hanging requests
eraseRecord(this.#handlers, (handler) => handler.callback(error, undefined));
eraseRecord(this.#waitingForId);
if (this.#autoConnectMs > 0) { if (this.#autoConnectMs > 0) {
setTimeout((): void => { setTimeout((): void => {
+2 -7
View File
@@ -5,9 +5,9 @@
import nock from 'nock'; import nock from 'nock';
const TEST_HTTP_URL = 'http://localhost:9944'; export const TEST_HTTP_URL = 'http://localhost:9944';
function mockHttp (requests: any[]): any { export function mockHttp (requests: any[]): any {
nock.cleanAll(); nock.cleanAll();
return requests.reduce((scope, request: any): nock.Scope => { return requests.reduce((scope, request: any): nock.Scope => {
@@ -21,8 +21,3 @@ function mockHttp (requests: any[]): any {
}); });
}, nock(TEST_HTTP_URL)); }, nock(TEST_HTTP_URL));
} }
export {
TEST_HTTP_URL,
mockHttp
};
+3 -8
View File
@@ -3,8 +3,6 @@
import { Server, WebSocket } from 'mock-socket'; import { Server, WebSocket } from 'mock-socket';
const TEST_WS_URL = 'ws://localhost:9955';
interface Scope { interface Scope {
body: { [index: string]: Record<string, any> }; body: { [index: string]: Record<string, any> };
requests: number; requests: number;
@@ -29,6 +27,8 @@ interface ReplyDef {
global.WebSocket = WebSocket; global.WebSocket = WebSocket;
export const TEST_WS_URL = 'ws://localhost:9955';
// should be JSONRPC def return // should be JSONRPC def return
function createError ({ error: { code, message }, id }: ErrorDef): any { function createError ({ error: { code, message }, id }: ErrorDef): any {
return { return {
@@ -51,7 +51,7 @@ function createReply ({ id, reply: { result } }: ReplyDef): any {
} }
// scope definition returned // scope definition returned
function mockWs (requests: ({ method: string } & ErrorDef)[], wsUrl: string = TEST_WS_URL): Scope { export function mockWs (requests: ({ method: string } & ErrorDef)[], wsUrl: string = TEST_WS_URL): Scope {
const server = new Server(wsUrl); const server = new Server(wsUrl);
let requestCount = 0; let requestCount = 0;
@@ -85,8 +85,3 @@ function mockWs (requests: ({ method: string } & ErrorDef)[], wsUrl: string = TE
return scope; return scope;
} }
export {
TEST_WS_URL,
mockWs
};
+15 -12
View File
@@ -1,9 +1,12 @@
{ {
"name": "@polkadot/typegen", "name": "@polkadot/typegen",
"version": "3.7.2", "version": "3.11.1",
"description": "Type generation scripts", "description": "Type generation scripts",
"main": "index.js", "main": "index.js",
"sideEffects": false, "sideEffects": [
"./detectPackage.js",
"./detectPackage.mjs"
],
"bin": { "bin": {
"polkadot-types-chain-info": "./scripts/polkadot-types-chain-info.js", "polkadot-types-chain-info": "./scripts/polkadot-types-chain-info.js",
"polkadot-types-from-chain": "./scripts/polkadot-types-from-chain.js", "polkadot-types-from-chain": "./scripts/polkadot-types-from-chain.js",
@@ -19,20 +22,20 @@
"bugs": "https://github.com/polkadot-js/api/issues", "bugs": "https://github.com/polkadot-js/api/issues",
"homepage": "https://github.com/polkadot-js/api/tree/master/packages/typegen#readme", "homepage": "https://github.com/polkadot-js/api/tree/master/packages/typegen#readme",
"dependencies": { "dependencies": {
"@babel/core": "^7.12.10", "@babel/core": "^7.13.8",
"@babel/register": "^7.12.10", "@babel/register": "^7.13.8",
"@babel/runtime": "^7.12.5", "@babel/runtime": "^7.13.8",
"@polkadot/api": "3.7.2", "@polkadot/api": "3.11.1",
"@polkadot/metadata": "3.7.2", "@polkadot/metadata": "3.11.1",
"@polkadot/rpc-provider": "3.7.2", "@polkadot/rpc-provider": "3.11.1",
"@polkadot/types": "3.7.2", "@polkadot/types": "3.11.1",
"@polkadot/util": "^5.5.1", "@polkadot/util": "^5.9.2",
"handlebars": "^4.7.6", "handlebars": "^4.7.7",
"websocket": "^1.0.33", "websocket": "^1.0.33",
"yargs": "^16.2.0" "yargs": "^16.2.0"
}, },
"devDependencies": { "devDependencies": {
"@types/websocket": "^1.0.1", "@types/websocket": "^1.0.1",
"@types/yargs": "^15.0.13" "@types/yargs": "^16.0.0"
} }
} }
+12
View File
@@ -0,0 +1,12 @@
// Copyright 2017-2021 @polkadot/typegen authors & contributors
// SPDX-License-Identifier: Apache-2.0
import { packageInfo as apiInfo } from '@polkadot/api/packageInfo';
import { packageInfo as metaInfo } from '@polkadot/metadata/packageInfo';
import { packageInfo as providerInfo } from '@polkadot/rpc-provider/packageInfo';
import { packageInfo as typesInfo } from '@polkadot/types/packageInfo';
import { detectPackage } from '@polkadot/util';
import { packageInfo } from './packageInfo';
detectPackage(packageInfo, typeof __dirname !== 'undefined' && __dirname, [apiInfo, metaInfo, providerInfo, typesInfo]);
+5 -3
View File
@@ -87,12 +87,12 @@ function tsInt (definitions: Record<string, ModuleTypes>, def: TypeDef, imports:
} }
/** @internal */ /** @internal */
function tsResultGetter (definitions: Record<string, ModuleTypes>, resultName = '', getter: 'Ok' | 'Error', def: TypeDef, imports: TypeImports): string { function tsResultGetter (definitions: Record<string, ModuleTypes>, resultName = '', getter: 'Ok' | 'Err' | 'Error', def: TypeDef, imports: TypeImports): string {
const { info, type } = def; const { info, type } = def;
const asGetter = type === 'Null' const asGetter = type === 'Null'
? '' ? ''
: createGetter(definitions, `as${getter}`, info === TypeDefInfo.Tuple ? formatType(definitions, def, imports) : type, imports); : (getter === 'Error' ? ' /** @deprecated Use asErr */\n' : '') + createGetter(definitions, `as${getter}`, info === TypeDefInfo.Tuple ? formatType(definitions, def, imports) : type, imports);
const isGetter = createGetter(definitions, `is${getter}`, 'boolean', imports); const isGetter = (getter === 'Error' ? ' /** @deprecated Use isErr */\n' : '') + createGetter(definitions, `is${getter}`, 'boolean', imports);
switch (info) { switch (info) {
case TypeDefInfo.Plain: case TypeDefInfo.Plain:
@@ -110,6 +110,8 @@ function tsResultGetter (definitions: Record<string, ModuleTypes>, resultName =
function tsResult (definitions: Record<string, ModuleTypes>, def: TypeDef, imports: TypeImports): string { function tsResult (definitions: Record<string, ModuleTypes>, def: TypeDef, imports: TypeImports): string {
const [okDef, errorDef] = (def.sub as TypeDef[]); const [okDef, errorDef] = (def.sub as TypeDef[]);
const inner = [ const inner = [
tsResultGetter(definitions, def.name, 'Err', errorDef, imports),
// @deprecated, use Err
tsResultGetter(definitions, def.name, 'Error', errorDef, imports), tsResultGetter(definitions, def.name, 'Error', errorDef, imports),
tsResultGetter(definitions, def.name, 'Ok', okDef, imports) tsResultGetter(definitions, def.name, 'Ok', okDef, imports)
].join(''); ].join('');
+3
View File
@@ -1,4 +1,7 @@
// Copyright 2017-2021 @polkadot/typegen authors & contributors // Copyright 2017-2021 @polkadot/typegen authors & contributors
// SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: Apache-2.0
import './detectPackage';
export { packageInfo } from './packageInfo';
export { formatType } from './util/formatting'; export { formatType } from './util/formatting';
+6
View File
@@ -0,0 +1,6 @@
// Copyright 2017-2021 @polkadot/dev authors & contributors
// SPDX-License-Identifier: Apache-2.0
// Auto-generated by @polkadot/dev, do not edit
export const packageInfo = { name: '@polkadot/typegen', version: '3.11.1' };
+2 -2
View File
@@ -70,8 +70,8 @@ export function setImports (allDefs: Record<string, ModuleTypes>, imports: TypeI
setImports(allDefs, imports, [typeDef.sub.type]); setImports(allDefs, imports, [typeDef.sub.type]);
} }
} else if (type.includes('[') && type.includes('|')) { } else if (type.includes('[') && type.includes('|')) {
// We split the types // We split the types (we already dod the check above, so safe-path should not be caught)
const splitTypes = /\[\s?(.+?)\s?\]/.exec(type)![1].split(/\s?\|\s?/); const splitTypes = (/\[\s?(.+?)\s?\]/.exec(type) || ['', ''])[1].split(/\s?\|\s?/);
setImports(allDefs, imports, splitTypes); setImports(allDefs, imports, splitTypes);
} else { } else {
+9 -5
View File
@@ -1,9 +1,12 @@
{ {
"name": "@polkadot/types-known", "name": "@polkadot/types-known",
"version": "3.7.2", "version": "3.11.1",
"description": "A JavaScript wrapper for the Polkadot JsonRPC interface", "description": "A JavaScript wrapper for the Polkadot JsonRPC interface",
"main": "index.js", "main": "index.js",
"sideEffects": false, "sideEffects": [
"./detectPackage.js",
"./detectPackage.mjs"
],
"author": "Jaco Greeff <jacogr@gmail.com>", "author": "Jaco Greeff <jacogr@gmail.com>",
"maintainers": [], "maintainers": [],
"contributors": [], "contributors": [],
@@ -12,9 +15,10 @@
"bugs": "https://github.com/polkadot-js/api/issues", "bugs": "https://github.com/polkadot-js/api/issues",
"homepage": "https://github.com/polkadot-js/api/tree/master/packages/types-known#readme", "homepage": "https://github.com/polkadot-js/api/tree/master/packages/types-known#readme",
"dependencies": { "dependencies": {
"@babel/runtime": "^7.12.5", "@babel/runtime": "^7.13.8",
"@polkadot/types": "3.7.2", "@polkadot/networks": "^5.9.2",
"@polkadot/util": "^5.5.1", "@polkadot/types": "3.11.1",
"@polkadot/util": "^5.9.2",
"bn.js": "^4.11.9" "bn.js": "^4.11.9"
}, },
"devDependencies": { "devDependencies": {
@@ -0,0 +1,9 @@
// Copyright 2017-2021 @polkadot/types-known authors & contributors
// SPDX-License-Identifier: Apache-2.0
import { packageInfo as typesInfo } from '@polkadot/types/packageInfo';
import { detectPackage } from '@polkadot/util';
import { packageInfo } from './packageInfo';
detectPackage(packageInfo, typeof __dirname !== 'undefined' && __dirname, [typesInfo]);
+26 -1
View File
@@ -1,10 +1,13 @@
// Copyright 2017-2021 @polkadot/types-known authors & contributors // Copyright 2017-2021 @polkadot/types-known authors & contributors
// SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: Apache-2.0
import './detectPackage';
import type BN from 'bn.js'; import type BN from 'bn.js';
import type { Text } from '@polkadot/types'; import type { Text } from '@polkadot/types';
import type { ExtDef } from '@polkadot/types/extrinsic/signedExtensions/types';
import type { Hash } from '@polkadot/types/interfaces'; import type { Hash } from '@polkadot/types/interfaces';
import type { ChainUpgradeVersion, DefinitionRpc, DefinitionRpcSub, OverrideModuleType, OverrideVersionedType, Registry, RegistryTypes } from '@polkadot/types/types'; import type { ChainUpgradeVersion, CodecHasher, DefinitionRpc, DefinitionRpcSub, OverrideModuleType, OverrideVersionedType, Registry, RegistryTypes } from '@polkadot/types/types';
import { bnToBn, isUndefined } from '@polkadot/util'; import { bnToBn, isUndefined } from '@polkadot/util';
@@ -13,6 +16,8 @@ import typesModules from './modules';
import typesSpec from './spec'; import typesSpec from './spec';
import upgrades from './upgrades'; import upgrades from './upgrades';
export { packageInfo } from './packageInfo';
// flatten a VersionedType[] into a Record<string, string> // flatten a VersionedType[] into a Record<string, string>
/** @internal */ /** @internal */
function filterVersions (versions: OverrideVersionedType[] = [], specVersion: number): RegistryTypes { function filterVersions (versions: OverrideVersionedType[] = [], specVersion: number): RegistryTypes {
@@ -37,6 +42,19 @@ export function getModuleTypes ({ knownTypes }: Registry, section: string): Over
}; };
} }
/**
* @description Based on the chain and runtimeVersion, get the applicable signed extensions (ready for registration)
*/
export function getSpecExtensions ({ knownTypes }: Registry, chainName: Text | string, specName: Text | string): ExtDef {
const _chainName = chainName.toString();
const _specName = specName.toString();
return {
...(knownTypes.typesBundle?.spec?.[_specName]?.signedExtensions || {}),
...(knownTypes.typesBundle?.chain?.[_chainName]?.signedExtensions || {})
};
}
/** /**
* @description Based on the chain and runtimeVersion, get the applicable types (ready for registration) * @description Based on the chain and runtimeVersion, get the applicable types (ready for registration)
*/ */
@@ -60,6 +78,13 @@ export function getSpecTypes ({ knownTypes }: Registry, chainName: Text | string
}; };
} }
export function getSpecHasher ({ knownTypes }: Registry, chainName: Text | string, specName: Text | string): CodecHasher | null {
const _chainName = chainName.toString();
const _specName = specName.toString();
return knownTypes.hasher || knownTypes.typesBundle?.chain?.[_chainName]?.hasher || knownTypes.typesBundle?.spec?.[_specName]?.hasher || null;
}
/** /**
* @description Based on the chain and runtimeVersion, get the applicable rpc definitions (ready for registration) * @description Based on the chain and runtimeVersion, get the applicable rpc definitions (ready for registration)
*/ */
+6
View File
@@ -0,0 +1,6 @@
// Copyright 2017-2021 @polkadot/dev authors & contributors
// SPDX-License-Identifier: Apache-2.0
// Auto-generated by @polkadot/dev, do not edit
export const packageInfo = { name: '@polkadot/types-known', version: '3.11.1' };
+1 -1
View File
@@ -11,7 +11,7 @@ const sharedTypes = {
Keys: 'SessionKeys6', Keys: 'SessionKeys6',
LookupSource: 'MultiAddress', LookupSource: 'MultiAddress',
ProxyType: { ProxyType: {
_enum: ['Any', 'NonTransfer', 'Governance', 'Staking', 'IdentityJudgement'] _enum: ['Any', 'NonTransfer', 'Governance', 'Staking', 'IdentityJudgement', 'CancelProxy']
}, },
ValidatorPrefs: 'ValidatorPrefsWithBlocked' ValidatorPrefs: 'ValidatorPrefsWithBlocked'
}; };
+9 -2
View File
@@ -11,8 +11,15 @@ const sharedTypes = {
Keys: 'SessionKeys6', Keys: 'SessionKeys6',
LookupSource: 'MultiAddress', LookupSource: 'MultiAddress',
ProxyType: { ProxyType: {
// was: SudoBalances _enum: {
_enum: ['Any', 'NonTransfer', 'Governance', 'Staking', 'Unused', 'IdentityJudgement'] Any: 0,
NonTransfer: 1,
Governance: 2,
Staking: 3,
// SudoBalances: 4,
IdentityJudgement: 5,
CancelProxy: 6
}
}, },
ValidatorPrefs: 'ValidatorPrefsWithBlocked' ValidatorPrefs: 'ValidatorPrefsWithBlocked'
}; };
+2 -26
View File
@@ -18,39 +18,15 @@ const sharedTypes = {
const versioned: OverrideVersionedType[] = [ const versioned: OverrideVersionedType[] = [
{ {
minmax: [0, 9], minmax: [0, 200],
types: { types: {
...sharedTypes, ...sharedTypes,
AccountInfo: 'AccountInfoWithRefCount',
Address: 'AccountId',
CompactAssignments: 'CompactAssignmentsTo257',
LookupSource: 'AccountId',
RefCount: 'RefCountTo259',
RewardDestination: 'RewardDestinationTo257',
Keys: 'SessionKeys5'
}
},
{
minmax: [10, 12],
types: {
...sharedTypes,
AccountInfo: 'AccountInfoWithRefCount',
Address: 'AccountId',
Keys: 'SessionKeys5',
LookupSource: 'AccountId'
}
},
{
minmax: [13, 201],
types: {
...sharedTypes,
AccountInfo: 'AccountInfoWithRefCount',
Address: 'AccountId', Address: 'AccountId',
LookupSource: 'AccountId' LookupSource: 'AccountId'
} }
}, },
{ {
minmax: [202, undefined], minmax: [201, undefined],
types: { types: {
...sharedTypes ...sharedTypes
} }
+2 -2
View File
@@ -11,8 +11,8 @@ const sharedTypes = {
Keys: 'SessionKeys6', Keys: 'SessionKeys6',
LookupSource: 'MultiAddress', LookupSource: 'MultiAddress',
ProxyType: { ProxyType: {
// was: SudoBalances _enum: ['Any', 'NonTransfer', 'Staking', 'SudoBalances', 'IdentityJudgement', 'CancelProxy'
_enum: ['Any', 'NonTransfer', 'Staking', 'Unused', 'IdentityJudgement'] ]
}, },
ValidatorPrefs: 'ValidatorPrefsWithBlocked' ValidatorPrefs: 'ValidatorPrefsWithBlocked'
}; };
@@ -1,10 +1,62 @@
// Copyright 2017-2021 @polkadot/types-known authors & contributors // Copyright 2017-2021 @polkadot/types-known authors & contributors
// SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: Apache-2.0
import { assert, u8aEq } from '@polkadot/util';
import all from '.'; import all from '.';
interface TestDef {
genesisHash: string;
network: string;
versions: [number, [number, number]][];
}
const TESTS: TestDef[] = [
{
genesisHash: '0xb0a8d493285c2df73290dfb7e61f870f17b41801197a149ca93654499ea3dafe',
network: 'kusama',
versions: [
[0, [0, 1020]],
[17, [901442, 1045]]
]
},
{
genesisHash: '0x91b171bb158e2d3848fa23a9f1c25182fb8e20313b2c1eb49219da7a70ce90c3',
network: 'polkadot',
versions: [
[0, [0, 0]],
[19, [2436698, 26]]
]
},
{
genesisHash: '0xe143f23803ac50e8f6f8e62695d1ce9e4e1d68aa36c1cd2cfd15340213f3423e',
network: 'westend',
versions: [
[0, [214356, 4]],
[23, [4207800, 48]]
]
}
];
describe('upgrades', (): void => { describe('upgrades', (): void => {
it('is valid', (): void => { TESTS.forEach(({ genesisHash, network, versions }): void => {
expect(all).toBeDefined(); describe(network, (): void => {
const chain = all.find((n) => n.network === network);
assert(chain, `Unable to find the entry for ${network}`);
it('has a valid genesisHash', (): void => {
expect(u8aEq(chain.genesisHash, genesisHash)).toBe(true);
});
versions.forEach(([index, [blockNumber, specVersion]]): void => {
it(`has a valid entry at index ${index}`, (): void => {
const version = chain.versions[index];
expect(version.blockNumber.eqn(blockNumber)).toBe(true);
expect(version.specVersion.eqn(specVersion)).toBe(true);
});
});
});
}); });
}); });
+16 -8
View File
@@ -6,14 +6,22 @@ import type { ChainUpgradesRaw } from './types';
import BN from 'bn.js'; import BN from 'bn.js';
import networks from '@polkadot/networks';
import { assert, hexToU8a } from '@polkadot/util'; import { assert, hexToU8a } from '@polkadot/util';
import kusama from './kusama'; import kusama from './kusama';
import polkadot from './polkadot'; import polkadot from './polkadot';
import westend from './westend'; import westend from './westend';
// testnets are not available in the networks map
const NET_EXTRA: Record<string, { genesisHash: string[] }> = {
westend: {
genesisHash: ['0xe143f23803ac50e8f6f8e62695d1ce9e4e1d68aa36c1cd2cfd15340213f3423e']
}
};
/** @internal */ /** @internal */
function checkOrder (network: string, versions: [number, number][]): [number, number][] { function checkOrder (network: string, versions: ChainUpgradesRaw): [number, number][] {
const ooo = versions.filter((curr, index): boolean => { const ooo = versions.filter((curr, index): boolean => {
const prev = versions[index - 1]; const prev = versions[index - 1];
@@ -28,9 +36,13 @@ function checkOrder (network: string, versions: [number, number][]): [number, nu
} }
/** @internal */ /** @internal */
function rawToFinal (network: string, { genesisHash, versions }: ChainUpgradesRaw): ChainUpgrades { function mapRaw ([network, versions]: [string, ChainUpgradesRaw]): ChainUpgrades {
const chain = networks.find((n) => n.network === network) || NET_EXTRA[network];
assert(chain, `Unable to find info for chain ${network}`);
return { return {
genesisHash: hexToU8a(genesisHash), genesisHash: hexToU8a(chain.genesisHash[0]),
network, network,
versions: checkOrder(network, versions).map(([blockNumber, specVersion]) => ({ versions: checkOrder(network, versions).map(([blockNumber, specVersion]) => ({
blockNumber: new BN(blockNumber), blockNumber: new BN(blockNumber),
@@ -40,10 +52,6 @@ function rawToFinal (network: string, { genesisHash, versions }: ChainUpgradesRa
} }
// Type overrides for specific spec types & versions as given in runtimeVersion // Type overrides for specific spec types & versions as given in runtimeVersion
const upgrades: ChainUpgrades[] = [ const upgrades = Object.entries({ kusama, polkadot, westend }).map(mapRaw);
rawToFinal('kusama', kusama),
rawToFinal('polkadot', polkadot),
rawToFinal('westend', westend)
];
export default upgrades; export default upgrades;
+4 -6
View File
@@ -3,9 +3,7 @@
import type { ChainUpgradesRaw } from './types'; import type { ChainUpgradesRaw } from './types';
const upgrades: ChainUpgradesRaw = { const upgrades: ChainUpgradesRaw = [
genesisHash: '0xb0a8d493285c2df73290dfb7e61f870f17b41801197a149ca93654499ea3dafe',
versions: [
[0, 1020], [26669, 1021], [38245, 1022], [54248, 1023], [59659, 1024], [0, 1020], [26669, 1021], [38245, 1022], [54248, 1023], [59659, 1024],
[67651, 1025], [82191, 1027], [83238, 1028], [101503, 1029], [203466, 1030], [67651, 1025], [82191, 1027], [83238, 1028], [101503, 1029], [203466, 1030],
[295787, 1031], [461692, 1032], [504329, 1033], [569327, 1038], [587687, 1039], [295787, 1031], [461692, 1032], [504329, 1033], [569327, 1038], [587687, 1039],
@@ -13,8 +11,8 @@ const upgrades: ChainUpgradesRaw = {
[1472960, 1052], [1475648, 1053], [1491596, 1054], [1574408, 1055], [2064961, 1058], [1472960, 1052], [1475648, 1053], [1491596, 1054], [1574408, 1055], [2064961, 1058],
[2201991, 1062], [2671528, 2005], [2704202, 2007], [2728002, 2008], [2832534, 2011], [2201991, 1062], [2671528, 2005], [2704202, 2007], [2728002, 2008], [2832534, 2011],
[2962294, 2012], [3240000, 2013], [3274408, 2015], [3323565, 2019], [3534175, 2022], [2962294, 2012], [3240000, 2013], [3274408, 2015], [3323565, 2019], [3534175, 2022],
[3860281, 2023], [4143129, 2024], [4401242, 2025], [4841367, 2026], [5961600, 2027] [3860281, 2023], [4143129, 2024], [4401242, 2025], [4841367, 2026], [5961600, 2027],
] [6137912, 2028]
}; ];
export default upgrades; export default upgrades;
@@ -3,14 +3,12 @@
import type { ChainUpgradesRaw } from './types'; import type { ChainUpgradesRaw } from './types';
const upgrades: ChainUpgradesRaw = { const upgrades: ChainUpgradesRaw = [
genesisHash: '0x91b171bb158e2d3848fa23a9f1c25182fb8e20313b2c1eb49219da7a70ce90c3',
versions: [
[0, 0], [29231, 1], [188836, 5], [199405, 6], [214264, 7], [0, 0], [29231, 1], [188836, 5], [199405, 6], [214264, 7],
[244358, 8], [303079, 9], [314201, 10], [342400, 11], [443963, 12], [244358, 8], [303079, 9], [314201, 10], [342400, 11], [443963, 12],
[528470, 13], [687751, 14], [746085, 15], [787923, 16], [799302, 17], [528470, 13], [687751, 14], [746085, 15], [787923, 16], [799302, 17],
[1205128, 18], [1603423, 23], [1733218, 24], [2005673, 25] [1205128, 18], [1603423, 23], [1733218, 24], [2005673, 25], [2436698, 26],
] [3613564, 27], [3899547, 28]
}; ];
export default upgrades; export default upgrades;
+1 -4
View File
@@ -1,7 +1,4 @@
// Copyright 2017-2021 @polkadot/types-known authors & contributors // Copyright 2017-2021 @polkadot/types-known authors & contributors
// SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: Apache-2.0
export interface ChainUpgradesRaw { export type ChainUpgradesRaw = [number, number][];
genesisHash: string;
versions: [number, number][];
}
+2 -5
View File
@@ -3,15 +3,12 @@
import type { ChainUpgradesRaw } from './types'; import type { ChainUpgradesRaw } from './types';
const upgrades: ChainUpgradesRaw = { const upgrades: ChainUpgradesRaw = [
genesisHash: '0xe143f23803ac50e8f6f8e62695d1ce9e4e1d68aa36c1cd2cfd15340213f3423e',
versions: [
[214356, 4], [392764, 7], [409740, 8], [809976, 20], [877581, 24], [214356, 4], [392764, 7], [409740, 8], [809976, 20], [877581, 24],
[879238, 25], [889472, 26], [902937, 27], [932751, 28], [991142, 29], [879238, 25], [889472, 26], [902937, 27], [932751, 28], [991142, 29],
[1030162, 31], [1119657, 32], [1199282, 33], [1342534, 34], [1392263, 35], [1030162, 31], [1119657, 32], [1199282, 33], [1342534, 34], [1392263, 35],
[1431703, 36], [1433369, 37], [1490972, 41], [2087397, 43], [2316688, 44], [1431703, 36], [1433369, 37], [1490972, 41], [2087397, 43], [2316688, 44],
[2549864, 45], [3925782, 46], [3925843, 47], [4207800, 48] [2549864, 45], [3925782, 46], [3925843, 47], [4207800, 48]
] ];
};
export default upgrades; export default upgrades;
+7 -7
View File
@@ -1,6 +1,6 @@
{ {
"name": "@polkadot/types", "name": "@polkadot/types",
"version": "3.7.2", "version": "3.11.1",
"description": "Implementation of the Parity codec", "description": "Implementation of the Parity codec",
"main": "index.js", "main": "index.js",
"sideEffects": [ "sideEffects": [
@@ -15,15 +15,15 @@
"bugs": "https://github.com/polkadot-js/api/issues", "bugs": "https://github.com/polkadot-js/api/issues",
"homepage": "https://github.com/polkadot-js/api/tree/master/packages/types#readme", "homepage": "https://github.com/polkadot-js/api/tree/master/packages/types#readme",
"dependencies": { "dependencies": {
"@babel/runtime": "^7.12.5", "@babel/runtime": "^7.13.8",
"@polkadot/metadata": "3.7.2", "@polkadot/metadata": "3.11.1",
"@polkadot/util": "^5.5.1", "@polkadot/util": "^5.9.2",
"@polkadot/util-crypto": "^5.5.1", "@polkadot/util-crypto": "^5.9.2",
"@polkadot/x-rxjs": "^5.5.1", "@polkadot/x-rxjs": "^5.9.2",
"@types/bn.js": "^4.11.6", "@types/bn.js": "^4.11.6",
"bn.js": "^4.11.9" "bn.js": "^4.11.9"
}, },
"devDependencies": { "devDependencies": {
"@polkadot/keyring": "^5.5.1" "@polkadot/keyring": "^5.9.2"
} }
} }
+79 -9
View File
@@ -14,16 +14,17 @@ import type { PrefixedStorageKey } from '@polkadot/types/interfaces/childstate';
import type { EthereumAddress, StatementKind } from '@polkadot/types/interfaces/claims'; import type { EthereumAddress, StatementKind } from '@polkadot/types/interfaces/claims';
import type { CollectiveOrigin, MemberCount, ProposalIndex, Votes, VotesTo230 } from '@polkadot/types/interfaces/collective'; import type { CollectiveOrigin, MemberCount, ProposalIndex, Votes, VotesTo230 } from '@polkadot/types/interfaces/collective';
import type { AuthorityId, RawVRFOutput } from '@polkadot/types/interfaces/consensus'; import type { AuthorityId, RawVRFOutput } from '@polkadot/types/interfaces/consensus';
import type { AliveContractInfo, CodeHash, ContractCallRequest, ContractExecResult, ContractExecResultErr, ContractExecResultErrModule, ContractExecResultOk, ContractExecResultResult, ContractExecResultSuccessTo255, ContractExecResultSuccessTo260, ContractExecResultTo255, ContractExecResultTo260, ContractInfo, ContractStorageKey, DeletedContract, Gas, HostFnWeights, InstructionWeights, Limits, PrefabWasmModule, PrefabWasmModuleReserved, Schedule, ScheduleTo212, ScheduleTo258, SeedOf, TombstoneContractInfo, TrieId } from '@polkadot/types/interfaces/contracts'; import type { AliveContractInfo, CodeHash, ContractCallRequest, ContractExecResult, ContractExecResultErr, ContractExecResultErrModule, ContractExecResultOk, ContractExecResultResult, ContractExecResultSuccessTo255, ContractExecResultSuccessTo260, ContractExecResultTo255, ContractExecResultTo260, ContractInfo, ContractStorageKey, DeletedContract, Gas, HostFnWeights, HostFnWeightsTo264, InstructionWeights, Limits, LimitsTo264, PrefabWasmModule, PrefabWasmModuleReserved, Schedule, ScheduleTo212, ScheduleTo258, ScheduleTo264, SeedOf, TombstoneContractInfo, TrieId } from '@polkadot/types/interfaces/contracts';
import type { ContractConstructorSpec, ContractContractSpec, ContractCryptoHasher, ContractDiscriminant, ContractDisplayName, ContractEventParamSpec, ContractEventSpec, ContractLayoutArray, ContractLayoutCell, ContractLayoutEnum, ContractLayoutHash, ContractLayoutHashingStrategy, ContractLayoutKey, ContractLayoutStruct, ContractLayoutStructField, ContractMessageParamSpec, ContractMessageSpec, ContractProject, ContractProjectContract, ContractProjectSource, ContractSelector, ContractStorageLayout, ContractTypeSpec } from '@polkadot/types/interfaces/contractsAbi'; import type { ContractConstructorSpec, ContractContractSpec, ContractCryptoHasher, ContractDiscriminant, ContractDisplayName, ContractEventParamSpec, ContractEventSpec, ContractLayoutArray, ContractLayoutCell, ContractLayoutEnum, ContractLayoutHash, ContractLayoutHashingStrategy, ContractLayoutKey, ContractLayoutStruct, ContractLayoutStructField, ContractMessageParamSpec, ContractMessageSpec, ContractProject, ContractProjectContract, ContractProjectSource, ContractSelector, ContractStorageLayout, ContractTypeSpec } from '@polkadot/types/interfaces/contractsAbi';
import type { DeployData, FundIndex, FundInfo, LastContribution } from '@polkadot/types/interfaces/crowdloan'; import type { DeployData, FundIndex, FundInfo, LastContribution } from '@polkadot/types/interfaces/crowdloan';
import type { AccountVote, AccountVoteSplit, AccountVoteStandard, Conviction, Delegations, PreimageStatus, PreimageStatusAvailable, PriorLock, PropIndex, Proposal, ProxyState, ReferendumIndex, ReferendumInfo, ReferendumInfoFinished, ReferendumInfoTo239, ReferendumStatus, Tally, Voting, VotingDelegating, VotingDirect, VotingDirectVote } from '@polkadot/types/interfaces/democracy'; import type { AccountVote, AccountVoteSplit, AccountVoteStandard, Conviction, Delegations, PreimageStatus, PreimageStatusAvailable, PriorLock, PropIndex, Proposal, ProxyState, ReferendumIndex, ReferendumInfo, ReferendumInfoFinished, ReferendumInfoTo239, ReferendumStatus, Tally, Voting, VotingDelegating, VotingDirect, VotingDirectVote } from '@polkadot/types/interfaces/democracy';
import type { ApprovalFlag, DefunctVoter, Renouncing, SetIndex, Vote, VoteIndex, VoteThreshold, VoterInfo } from '@polkadot/types/interfaces/elections'; import type { ApprovalFlag, DefunctVoter, Renouncing, SetIndex, Vote, VoteIndex, VoteThreshold, VoterInfo } from '@polkadot/types/interfaces/elections';
import type { CreatedBlock, ImportedAux } from '@polkadot/types/interfaces/engine'; import type { CreatedBlock, ImportedAux } from '@polkadot/types/interfaces/engine';
import type { EthAccount, EthBlock, EthBloom, EthCallRequest, EthFilter, EthFilterAddress, EthFilterTopic, EthFilterTopicEntry, EthFilterTopicInner, EthHeader, EthLog, EthReceipt, EthRichBlock, EthRichHeader, EthStorageProof, EthSubKind, EthSubParams, EthSubResult, EthSyncInfo, EthSyncStatus, EthTransaction, EthTransactionAction, EthTransactionCondition, EthTransactionRequest, EthTransactionStatus, EthWork, EthereumAccountId, EthereumLookupSource, EthereumSignature } from '@polkadot/types/interfaces/eth'; import type { EthAccount, EthBlock, EthBloom, EthCallRequest, EthFilter, EthFilterAddress, EthFilterChanges, EthFilterTopic, EthFilterTopicEntry, EthFilterTopicInner, EthHeader, EthLog, EthReceipt, EthRichBlock, EthRichHeader, EthStorageProof, EthSubKind, EthSubParams, EthSubResult, EthSyncInfo, EthSyncStatus, EthTransaction, EthTransactionAction, EthTransactionCondition, EthTransactionRequest, EthTransactionStatus, EthWork, EthereumAccountId, EthereumLookupSource, EthereumSignature } from '@polkadot/types/interfaces/eth';
import type { EvmAccount, EvmLog, EvmVicinity, ExitError, ExitFatal, ExitReason, ExitRevert, ExitSucceed } from '@polkadot/types/interfaces/evm'; import type { EvmAccount, EvmLog, EvmVicinity, ExitError, ExitFatal, ExitReason, ExitRevert, ExitSucceed } from '@polkadot/types/interfaces/evm';
import type { AnySignature, EcdsaSignature, Ed25519Signature, Extrinsic, ExtrinsicEra, ExtrinsicPayload, ExtrinsicPayloadUnknown, ExtrinsicPayloadV4, ExtrinsicSignature, ExtrinsicSignatureV4, ExtrinsicUnknown, ExtrinsicV4, ImmortalEra, MortalEra, MultiSignature, Signature, SignerPayload, Sr25519Signature } from '@polkadot/types/interfaces/extrinsics'; import type { AnySignature, EcdsaSignature, Ed25519Signature, Extrinsic, ExtrinsicEra, ExtrinsicPayload, ExtrinsicPayloadUnknown, ExtrinsicPayloadV4, ExtrinsicSignature, ExtrinsicSignatureV4, ExtrinsicUnknown, ExtrinsicV4, ImmortalEra, MortalEra, MultiSignature, Signature, SignerPayload, Sr25519Signature } from '@polkadot/types/interfaces/extrinsics';
import type { AssetOptions, Owner, PermissionLatest, PermissionVersions, PermissionsV1 } from '@polkadot/types/interfaces/genericAsset'; import type { AssetOptions, Owner, PermissionLatest, PermissionVersions, PermissionsV1 } from '@polkadot/types/interfaces/genericAsset';
import type { ActiveGilt, ActiveGiltsTotal, ActiveIndex, GiltBid } from '@polkadot/types/interfaces/gilt';
import type { AuthorityIndex, AuthorityList, AuthorityWeight, EncodedFinalityProofs, GrandpaEquivocation, GrandpaEquivocationProof, GrandpaEquivocationValue, GrandpaPrevote, JustificationNotification, KeyOwnerProof, NextAuthority, PendingPause, PendingResume, Precommits, Prevotes, ReportedRoundStates, RoundState, SetId, StoredPendingChange, StoredState } from '@polkadot/types/interfaces/grandpa'; import type { AuthorityIndex, AuthorityList, AuthorityWeight, EncodedFinalityProofs, GrandpaEquivocation, GrandpaEquivocationProof, GrandpaEquivocationValue, GrandpaPrevote, JustificationNotification, KeyOwnerProof, NextAuthority, PendingPause, PendingResume, Precommits, Prevotes, ReportedRoundStates, RoundState, SetId, StoredPendingChange, StoredState } from '@polkadot/types/interfaces/grandpa';
import type { IdentityFields, IdentityInfo, IdentityInfoAdditional, IdentityJudgement, RegistrarIndex, RegistrarInfo, Registration, RegistrationJudgement } from '@polkadot/types/interfaces/identity'; import type { IdentityFields, IdentityInfo, IdentityInfoAdditional, IdentityJudgement, RegistrarIndex, RegistrarInfo, Registration, RegistrationJudgement } from '@polkadot/types/interfaces/identity';
import type { AuthIndex, AuthoritySignature, Heartbeat, HeartbeatTo244, OpaqueMultiaddr, OpaqueNetworkState, OpaquePeerId } from '@polkadot/types/interfaces/imOnline'; import type { AuthIndex, AuthoritySignature, Heartbeat, HeartbeatTo244, OpaqueMultiaddr, OpaqueNetworkState, OpaquePeerId } from '@polkadot/types/interfaces/imOnline';
@@ -31,22 +32,22 @@ import type { CallIndex, LotteryConfig } from '@polkadot/types/interfaces/lotter
import type { DoubleMapTypeLatest, DoubleMapTypeV10, DoubleMapTypeV11, DoubleMapTypeV12, DoubleMapTypeV9, ErrorMetadataLatest, ErrorMetadataV10, ErrorMetadataV11, ErrorMetadataV12, ErrorMetadataV9, EventMetadataLatest, EventMetadataV10, EventMetadataV11, EventMetadataV12, EventMetadataV9, ExtrinsicMetadataLatest, ExtrinsicMetadataV11, ExtrinsicMetadataV12, FunctionArgumentMetadataLatest, FunctionArgumentMetadataV10, FunctionArgumentMetadataV11, FunctionArgumentMetadataV12, FunctionArgumentMetadataV9, FunctionMetadataLatest, FunctionMetadataV10, FunctionMetadataV11, FunctionMetadataV12, FunctionMetadataV9, MapTypeLatest, MapTypeV10, MapTypeV11, MapTypeV12, MapTypeV9, MetadataAll, MetadataLatest, MetadataV10, MetadataV11, MetadataV12, MetadataV9, ModuleConstantMetadataLatest, ModuleConstantMetadataV10, ModuleConstantMetadataV11, ModuleConstantMetadataV12, ModuleConstantMetadataV9, ModuleMetadataLatest, ModuleMetadataV10, ModuleMetadataV11, ModuleMetadataV12, ModuleMetadataV9, StorageEntryMetadataLatest, StorageEntryMetadataV10, StorageEntryMetadataV11, StorageEntryMetadataV12, StorageEntryMetadataV9, StorageEntryModifierLatest, StorageEntryModifierV10, StorageEntryModifierV11, StorageEntryModifierV12, StorageEntryModifierV9, StorageEntryTypeLatest, StorageEntryTypeV10, StorageEntryTypeV11, StorageEntryTypeV12, StorageEntryTypeV9, StorageHasher, StorageHasherV10, StorageHasherV11, StorageHasherV12, StorageHasherV9, StorageMetadataLatest, StorageMetadataV10, StorageMetadataV11, StorageMetadataV12, StorageMetadataV9 } from '@polkadot/types/interfaces/metadata'; import type { DoubleMapTypeLatest, DoubleMapTypeV10, DoubleMapTypeV11, DoubleMapTypeV12, DoubleMapTypeV9, ErrorMetadataLatest, ErrorMetadataV10, ErrorMetadataV11, ErrorMetadataV12, ErrorMetadataV9, EventMetadataLatest, EventMetadataV10, EventMetadataV11, EventMetadataV12, EventMetadataV9, ExtrinsicMetadataLatest, ExtrinsicMetadataV11, ExtrinsicMetadataV12, FunctionArgumentMetadataLatest, FunctionArgumentMetadataV10, FunctionArgumentMetadataV11, FunctionArgumentMetadataV12, FunctionArgumentMetadataV9, FunctionMetadataLatest, FunctionMetadataV10, FunctionMetadataV11, FunctionMetadataV12, FunctionMetadataV9, MapTypeLatest, MapTypeV10, MapTypeV11, MapTypeV12, MapTypeV9, MetadataAll, MetadataLatest, MetadataV10, MetadataV11, MetadataV12, MetadataV9, ModuleConstantMetadataLatest, ModuleConstantMetadataV10, ModuleConstantMetadataV11, ModuleConstantMetadataV12, ModuleConstantMetadataV9, ModuleMetadataLatest, ModuleMetadataV10, ModuleMetadataV11, ModuleMetadataV12, ModuleMetadataV9, StorageEntryMetadataLatest, StorageEntryMetadataV10, StorageEntryMetadataV11, StorageEntryMetadataV12, StorageEntryMetadataV9, StorageEntryModifierLatest, StorageEntryModifierV10, StorageEntryModifierV11, StorageEntryModifierV12, StorageEntryModifierV9, StorageEntryTypeLatest, StorageEntryTypeV10, StorageEntryTypeV11, StorageEntryTypeV12, StorageEntryTypeV9, StorageHasher, StorageHasherV10, StorageHasherV11, StorageHasherV12, StorageHasherV9, StorageMetadataLatest, StorageMetadataV10, StorageMetadataV11, StorageMetadataV12, StorageMetadataV9 } from '@polkadot/types/interfaces/metadata';
import type { StorageKind } from '@polkadot/types/interfaces/offchain'; import type { StorageKind } from '@polkadot/types/interfaces/offchain';
import type { DeferredOffenceOf, Kind, OffenceDetails, Offender, OpaqueTimeSlot, ReportIdOf, Reporter } from '@polkadot/types/interfaces/offences'; import type { DeferredOffenceOf, Kind, OffenceDetails, Offender, OpaqueTimeSlot, ReportIdOf, Reporter } from '@polkadot/types/interfaces/offences';
import type { AbridgedCandidateReceipt, AbridgedHostConfiguration, AbridgedHrmpChannel, AbstractFungible, AbstractNonFungible, AccountId32Junction, AccountIndex64Junction, AccountKey20Junction, AssetInstance, AssignmentId, AssignmentKind, AttestedCandidate, AuctionIndex, AuthorityDiscoveryId, AvailabilityBitfield, AvailabilityBitfieldRecord, BackedCandidate, Balances, Bidder, BufferedSessionChange, CandidateCommitments, CandidateDescriptor, CandidateHash, CandidatePendingAvailability, CandidateReceipt, CollatorId, CollatorSignature, CommittedCandidateReceipt, ConcreteFungible, ConcreteNonFungible, CoreAssignment, CoreIndex, CoreOccupied, DepositAsset, DepositReserveAsset, DoubleVoteReport, DownwardMessage, ExchangeAsset, GlobalValidationSchedule, GroupIndex, HeadData, HostConfiguration, HrmpChannel, HrmpChannelId, HrmpOpenChannelRequest, InboundDownwardMessage, InboundHrmpMessage, InboundHrmpMessages, IncomingParachain, IncomingParachainDeploy, IncomingParachainFixed, InitiateReserveWithdraw, InitiateTeleport, Junction, LeasePeriod, LeasePeriodOf, LocalValidationData, MessageIngestionType, MessagingStateSnapshot, MessagingStateSnapshotEgressEntry, MultiAsset, MultiLocation, NetworkId, NewBidder, NewBidderOption, Order, OriginKind, OutboundHrmpMessage, ParaGenesisArgs, ParaId, ParaInfo, ParaPastCodeMeta, ParaScheduling, ParaValidatorIndex, ParachainDispatchOrigin, ParachainProposal, ParathreadClaim, ParathreadClaimQueue, ParathreadEntry, PersistedValidationData, QueryHolding, QueuedParathread, RegisteredParachainInfo, RelayChainBlockNumber, RelayTo, RelayedFrom, Remark, ReserveAssetDeposit, Retriable, Scheduling, SessionInfo, SessionInfoValidatorGroup, SignedAvailabilityBitfield, SignedAvailabilityBitfields, SigningContext, SlotRange, Statement, SubId, SystemInherentData, TeleportAsset, Transact, TransientValidationData, UpwardMessage, ValidationCode, ValidationData, ValidationDataType, ValidationFunctionParams, ValidatorSignature, ValidityAttestation, VecInboundHrmpMessage, VersionedMultiAsset, VersionedMultiLocation, VersionedXcm, WinnersData, WinnersDataTuple, WinningData, WinningDataEntry, WithdrawAsset, Xcm, XcmError, XcmResult } from '@polkadot/types/interfaces/parachains'; import type { AbridgedCandidateReceipt, AbridgedHostConfiguration, AbridgedHrmpChannel, AbstractFungible, AbstractNonFungible, AccountId32Junction, AccountIndex64Junction, AccountKey20Junction, AssetInstance, AssignmentId, AssignmentKind, AttestedCandidate, AuctionIndex, AuthorityDiscoveryId, AvailabilityBitfield, AvailabilityBitfieldRecord, BackedCandidate, Balances, Bidder, BufferedSessionChange, CandidateCommitments, CandidateDescriptor, CandidateHash, CandidatePendingAvailability, CandidateReceipt, CollatorId, CollatorSignature, CommittedCandidateReceipt, ConcreteFungible, ConcreteNonFungible, CoreAssignment, CoreIndex, CoreOccupied, DepositAsset, DepositReserveAsset, DoubleVoteReport, DownwardMessage, ExchangeAsset, GlobalValidationSchedule, GroupIndex, HeadData, HostConfiguration, HrmpChannel, HrmpChannelId, HrmpOpenChannelRequest, InboundDownwardMessage, InboundHrmpMessage, InboundHrmpMessages, IncomingParachain, IncomingParachainDeploy, IncomingParachainFixed, InitiateReserveWithdraw, InitiateTeleport, Junction, LeasePeriod, LeasePeriodOf, LocalValidationData, MessageIngestionType, MessageQueueChain, MessagingStateSnapshot, MessagingStateSnapshotEgressEntry, MultiAsset, MultiLocation, NetworkId, NewBidder, NewBidderOption, Order, OriginKind, OutboundHrmpMessage, ParaGenesisArgs, ParaId, ParaInfo, ParaLifecycle, ParaPastCodeMeta, ParaScheduling, ParaValidatorIndex, ParachainDispatchOrigin, ParachainInherentData, ParachainProposal, ParathreadClaim, ParathreadClaimQueue, ParathreadEntry, PersistedValidationData, QueryHolding, QueuedParathread, RegisteredParachainInfo, RelayChainBlockNumber, RelayChainHash, RelayTo, RelayedFrom, Remark, ReserveAssetDeposit, Retriable, Scheduling, SessionInfo, SessionInfoValidatorGroup, SignedAvailabilityBitfield, SignedAvailabilityBitfields, SigningContext, SlotRange, Statement, SubId, SystemInherentData, TeleportAsset, Transact, TransientValidationData, UpwardMessage, ValidationCode, ValidationData, ValidationDataType, ValidationFunctionParams, ValidatorSignature, ValidityAttestation, VecInboundHrmpMessage, VersionedMultiAsset, VersionedMultiLocation, VersionedXcm, WinnersData, WinnersDataTuple, WinningData, WinningDataEntry, WithdrawAsset, Xcm, XcmError, XcmResult } from '@polkadot/types/interfaces/parachains';
import type { FeeDetails, InclusionFee, RuntimeDispatchInfo } from '@polkadot/types/interfaces/payment'; import type { FeeDetails, InclusionFee, RuntimeDispatchInfo } from '@polkadot/types/interfaces/payment';
import type { Approvals } from '@polkadot/types/interfaces/poll'; import type { Approvals } from '@polkadot/types/interfaces/poll';
import type { ProxyAnnouncement, ProxyDefinition, ProxyType } from '@polkadot/types/interfaces/proxy'; import type { ProxyAnnouncement, ProxyDefinition, ProxyType } from '@polkadot/types/interfaces/proxy';
import type { AccountStatus, AccountValidity } from '@polkadot/types/interfaces/purchase'; import type { AccountStatus, AccountValidity } from '@polkadot/types/interfaces/purchase';
import type { ActiveRecovery, RecoveryConfig } from '@polkadot/types/interfaces/recovery'; import type { ActiveRecovery, RecoveryConfig } from '@polkadot/types/interfaces/recovery';
import type { RpcMethods } from '@polkadot/types/interfaces/rpc'; import type { RpcMethods } from '@polkadot/types/interfaces/rpc';
import type { AccountId, AccountIdOf, AccountIndex, Address, AssetId, Balance, BalanceOf, Block, BlockNumber, Call, CallHash, CallHashOf, ChangesTrieConfiguration, Consensus, ConsensusEngineId, Digest, DigestItem, ExtrinsicsWeight, Fixed128, Fixed64, FixedI128, FixedI64, FixedU128, FixedU64, H1024, H128, H160, H2048, H256, H512, H64, Hash, Header, I32F32, Index, IndicesLookupSource, Justification, KeyTypeId, KeyValue, LockIdentifier, LookupSource, LookupTarget, ModuleId, Moment, MultiAddress, OpaqueCall, Origin, OriginCaller, PalletVersion, PalletsOrigin, Pays, PerU16, Perbill, Percent, Permill, Perquintill, Phantom, PhantomData, PreRuntime, Releases, RuntimeDbWeight, Seal, SealV0, SignedBlock, Slot, StorageData, StorageProof, TransactionPriority, U32F32, ValidatorId, ValidatorIdOf, Weight, WeightMultiplier } from '@polkadot/types/interfaces/runtime'; import type { AccountId, AccountIdOf, AccountIndex, Address, AssetId, Balance, BalanceOf, Block, BlockNumber, Call, CallHash, CallHashOf, ChangesTrieConfiguration, CodecHash, Consensus, ConsensusEngineId, Digest, DigestItem, ExtrinsicsWeight, Fixed128, Fixed64, FixedI128, FixedI64, FixedU128, FixedU64, H1024, H128, H160, H2048, H256, H512, H64, Hash, Header, I32F32, Index, IndicesLookupSource, Justification, KeyTypeId, KeyValue, LockIdentifier, LookupSource, LookupTarget, ModuleId, Moment, MultiAddress, OpaqueCall, Origin, OriginCaller, PalletVersion, PalletsOrigin, Pays, PerU16, Perbill, Percent, Permill, Perquintill, Phantom, PhantomData, PreRuntime, Releases, RuntimeDbWeight, Seal, SealV0, SignedBlock, Slot, StorageData, StorageProof, TransactionPriority, U32F32, ValidatorId, ValidatorIdOf, Weight, WeightMultiplier } from '@polkadot/types/interfaces/runtime';
import type { SiField, SiLookupTypeId, SiPath, SiType, SiTypeDef, SiTypeDefArray, SiTypeDefComposite, SiTypeDefPrimitive, SiTypeDefSequence, SiTypeDefTuple, SiTypeDefVariant, SiVariant } from '@polkadot/types/interfaces/scaleInfo'; import type { SiField, SiLookupTypeId, SiPath, SiType, SiTypeDef, SiTypeDefArray, SiTypeDefComposite, SiTypeDefPrimitive, SiTypeDefSequence, SiTypeDefTuple, SiTypeDefVariant, SiVariant } from '@polkadot/types/interfaces/scaleInfo';
import type { Period, Priority, SchedulePeriod, SchedulePriority, Scheduled, ScheduledTo254, TaskAddress } from '@polkadot/types/interfaces/scheduler'; import type { Period, Priority, SchedulePeriod, SchedulePriority, Scheduled, ScheduledTo254, TaskAddress } from '@polkadot/types/interfaces/scheduler';
import type { FullIdentification, IdentificationTuple, Keys, MembershipProof, SessionIndex, SessionKeys1, SessionKeys2, SessionKeys3, SessionKeys4, SessionKeys5, SessionKeys6, SessionKeys7, SessionKeys8, SessionKeys9, ValidatorCount } from '@polkadot/types/interfaces/session'; import type { FullIdentification, IdentificationTuple, Keys, MembershipProof, SessionIndex, SessionKeys1, SessionKeys2, SessionKeys3, SessionKeys4, SessionKeys5, SessionKeys6, SessionKeys7, SessionKeys8, SessionKeys9, ValidatorCount } from '@polkadot/types/interfaces/session';
import type { Bid, BidKind, SocietyJudgement, SocietyVote, StrikeCount, VouchingStatus } from '@polkadot/types/interfaces/society'; import type { Bid, BidKind, SocietyJudgement, SocietyVote, StrikeCount, VouchingStatus } from '@polkadot/types/interfaces/society';
import type { ActiveEraInfo, CompactAssignments, CompactAssignmentsTo257, CompactScore, CompactScoreCompact, ElectionCompute, ElectionResult, ElectionScore, ElectionSize, ElectionStatus, EraIndex, EraPoints, EraRewardPoints, EraRewards, Exposure, Forcing, IndividualExposure, KeyType, MomentOf, Nominations, NominatorIndex, NominatorIndexCompact, OffchainAccuracy, OffchainAccuracyCompact, PhragmenScore, Points, RewardDestination, RewardDestinationTo257, RewardPoint, SeatHolder, SlashJournalEntry, SlashingSpans, SlashingSpansTo204, SpanIndex, SpanRecord, StakingLedger, StakingLedgerTo223, StakingLedgerTo240, UnappliedSlash, UnappliedSlashOther, UnlockChunk, ValidatorIndex, ValidatorIndexCompact, ValidatorPrefs, ValidatorPrefsTo145, ValidatorPrefsTo196, ValidatorPrefsWithBlocked, ValidatorPrefsWithCommission, Voter } from '@polkadot/types/interfaces/staking'; import type { ActiveEraInfo, CompactAssignments, CompactAssignmentsTo257, CompactScore, CompactScoreCompact, ElectionCompute, ElectionResult, ElectionScore, ElectionSize, ElectionStatus, EraIndex, EraPoints, EraRewardPoints, EraRewards, Exposure, ExtendedBalance, Forcing, IndividualExposure, KeyType, MomentOf, Nominations, NominatorIndex, NominatorIndexCompact, OffchainAccuracy, OffchainAccuracyCompact, PhragmenScore, Points, RawSolution, ReadySolution, RewardDestination, RewardDestinationTo257, RewardPoint, RoundSnapshot, SeatHolder, SlashJournalEntry, SlashingSpans, SlashingSpansTo204, SolutionOrSnapshotSize, SolutionSupport, SolutionSupports, SpanIndex, SpanRecord, StakingLedger, StakingLedgerTo223, StakingLedgerTo240, UnappliedSlash, UnappliedSlashOther, UnlockChunk, ValidatorIndex, ValidatorIndexCompact, ValidatorPrefs, ValidatorPrefsTo145, ValidatorPrefsTo196, ValidatorPrefsWithBlocked, ValidatorPrefsWithCommission, VoteWeight, Voter } from '@polkadot/types/interfaces/staking';
import type { ApiId, KeyValueOption, ReadProof, RuntimeVersion, RuntimeVersionApi, StorageChangeSet } from '@polkadot/types/interfaces/state'; import type { ApiId, KeyValueOption, ReadProof, RuntimeVersion, RuntimeVersionApi, StorageChangeSet } from '@polkadot/types/interfaces/state';
import type { WeightToFeeCoefficient } from '@polkadot/types/interfaces/support'; import type { WeightToFeeCoefficient } from '@polkadot/types/interfaces/support';
import type { AccountInfo, AccountInfoWithProviders, AccountInfoWithRefCount, ApplyExtrinsicResult, BlockLength, BlockWeights, ChainProperties, ChainType, ConsumedWeight, DigestOf, DispatchClass, DispatchError, DispatchErrorModule, DispatchErrorTo198, DispatchInfo, DispatchInfoTo190, DispatchInfoTo244, DispatchOutcome, DispatchResult, DispatchResultOf, DispatchResultTo198, Event, EventId, EventIndex, EventRecord, Health, InvalidTransaction, Key, LastRuntimeUpgradeInfo, NetworkState, NetworkStatePeerset, NetworkStatePeersetInfo, NodeRole, NotConnectedPeer, Peer, PeerEndpoint, PeerEndpointAddr, PeerInfo, PeerPing, PerDispatchClass, PerDispatchClassU32, Phase, RawOrigin, RefCount, RefCountTo259, SyncState, SystemOrigin, TransactionValidityError, UnknownTransaction, WeightPerClass } from '@polkadot/types/interfaces/system'; import type { AccountInfo, AccountInfoWithProviders, AccountInfoWithRefCount, ApplyExtrinsicResult, BlockLength, BlockWeights, ChainProperties, ChainType, ConsumedWeight, DigestOf, DispatchClass, DispatchError, DispatchErrorModule, DispatchErrorTo198, DispatchInfo, DispatchInfoTo190, DispatchInfoTo244, DispatchOutcome, DispatchResult, DispatchResultOf, DispatchResultTo198, Event, EventId, EventIndex, EventRecord, Health, InvalidTransaction, Key, LastRuntimeUpgradeInfo, NetworkState, NetworkStatePeerset, NetworkStatePeersetInfo, NodeRole, NotConnectedPeer, Peer, PeerEndpoint, PeerEndpointAddr, PeerInfo, PeerPing, PerDispatchClassU32, PerDispatchClassWeight, PerDispatchClassWeightsPerClass, Phase, RawOrigin, RefCount, RefCountTo259, SyncState, SystemOrigin, TransactionValidityError, UnknownTransaction, WeightPerClass } from '@polkadot/types/interfaces/system';
import type { Bounty, BountyIndex, BountyStatus, BountyStatusActive, BountyStatusCuratorProposed, BountyStatusPendingPayout, OpenTip, OpenTipFinderTo225, OpenTipTip, OpenTipTo225, TreasuryProposal } from '@polkadot/types/interfaces/treasury'; import type { Bounty, BountyIndex, BountyStatus, BountyStatusActive, BountyStatusCuratorProposed, BountyStatusPendingPayout, OpenTip, OpenTipFinderTo225, OpenTipTip, OpenTipTo225, TreasuryProposal } from '@polkadot/types/interfaces/treasury';
import type { Multiplier } from '@polkadot/types/interfaces/txpayment'; import type { Multiplier } from '@polkadot/types/interfaces/txpayment';
import type { Multisig, Timepoint } from '@polkadot/types/interfaces/utility'; import type { Multisig, Timepoint } from '@polkadot/types/interfaces/utility';
@@ -55,6 +56,7 @@ import type { VestingInfo } from '@polkadot/types/interfaces/vesting';
declare module '@polkadot/types/types/registry' { declare module '@polkadot/types/types/registry' {
export interface InterfaceTypes { export interface InterfaceTypes {
'Compact<AccountIndex>': Compact<AccountIndex>; 'Compact<AccountIndex>': Compact<AccountIndex>;
'Compact<ActiveIndex>': Compact<ActiveIndex>;
'Compact<ApprovalFlag>': Compact<ApprovalFlag>; 'Compact<ApprovalFlag>': Compact<ApprovalFlag>;
'Compact<AssetId>': Compact<AssetId>; 'Compact<AssetId>': Compact<AssetId>;
'Compact<AuctionIndex>': Compact<AuctionIndex>; 'Compact<AuctionIndex>': Compact<AuctionIndex>;
@@ -73,6 +75,7 @@ declare module '@polkadot/types/types/registry' {
'Compact<CoreIndex>': Compact<CoreIndex>; 'Compact<CoreIndex>': Compact<CoreIndex>;
'Compact<EraIndex>': Compact<EraIndex>; 'Compact<EraIndex>': Compact<EraIndex>;
'Compact<EventIndex>': Compact<EventIndex>; 'Compact<EventIndex>': Compact<EventIndex>;
'Compact<ExtendedBalance>': Compact<ExtendedBalance>;
'Compact<FixedU128>': Compact<FixedU128>; 'Compact<FixedU128>': Compact<FixedU128>;
'Compact<FixedU64>': Compact<FixedU64>; 'Compact<FixedU64>': Compact<FixedU64>;
'Compact<FundIndex>': Compact<FundIndex>; 'Compact<FundIndex>': Compact<FundIndex>;
@@ -135,6 +138,7 @@ declare module '@polkadot/types/types/registry' {
'Compact<ValidatorCount>': Compact<ValidatorCount>; 'Compact<ValidatorCount>': Compact<ValidatorCount>;
'Compact<ValidatorIndex>': Compact<ValidatorIndex>; 'Compact<ValidatorIndex>': Compact<ValidatorIndex>;
'Compact<VoteIndex>': Compact<VoteIndex>; 'Compact<VoteIndex>': Compact<VoteIndex>;
'Compact<VoteWeight>': Compact<VoteWeight>;
'Compact<Weight>': Compact<Weight>; 'Compact<Weight>': Compact<Weight>;
'Option<AbridgedCandidateReceipt>': Option<AbridgedCandidateReceipt>; 'Option<AbridgedCandidateReceipt>': Option<AbridgedCandidateReceipt>;
'Option<AbridgedHostConfiguration>': Option<AbridgedHostConfiguration>; 'Option<AbridgedHostConfiguration>': Option<AbridgedHostConfiguration>;
@@ -157,6 +161,9 @@ declare module '@polkadot/types/types/registry' {
'Option<AccountVoteSplit>': Option<AccountVoteSplit>; 'Option<AccountVoteSplit>': Option<AccountVoteSplit>;
'Option<AccountVoteStandard>': Option<AccountVoteStandard>; 'Option<AccountVoteStandard>': Option<AccountVoteStandard>;
'Option<ActiveEraInfo>': Option<ActiveEraInfo>; 'Option<ActiveEraInfo>': Option<ActiveEraInfo>;
'Option<ActiveGilt>': Option<ActiveGilt>;
'Option<ActiveGiltsTotal>': Option<ActiveGiltsTotal>;
'Option<ActiveIndex>': Option<ActiveIndex>;
'Option<ActiveRecovery>': Option<ActiveRecovery>; 'Option<ActiveRecovery>': Option<ActiveRecovery>;
'Option<Address>': Option<Address>; 'Option<Address>': Option<Address>;
'Option<AliveContractInfo>': Option<AliveContractInfo>; 'Option<AliveContractInfo>': Option<AliveContractInfo>;
@@ -228,6 +235,7 @@ declare module '@polkadot/types/types/registry' {
'Option<ChainProperties>': Option<ChainProperties>; 'Option<ChainProperties>': Option<ChainProperties>;
'Option<ChainType>': Option<ChainType>; 'Option<ChainType>': Option<ChainType>;
'Option<ChangesTrieConfiguration>': Option<ChangesTrieConfiguration>; 'Option<ChangesTrieConfiguration>': Option<ChangesTrieConfiguration>;
'Option<CodecHash>': Option<CodecHash>;
'Option<CodeHash>': Option<CodeHash>; 'Option<CodeHash>': Option<CodeHash>;
'Option<CollatorId>': Option<CollatorId>; 'Option<CollatorId>': Option<CollatorId>;
'Option<CollatorSignature>': Option<CollatorSignature>; 'Option<CollatorSignature>': Option<CollatorSignature>;
@@ -340,6 +348,7 @@ declare module '@polkadot/types/types/registry' {
'Option<EthereumSignature>': Option<EthereumSignature>; 'Option<EthereumSignature>': Option<EthereumSignature>;
'Option<EthFilter>': Option<EthFilter>; 'Option<EthFilter>': Option<EthFilter>;
'Option<EthFilterAddress>': Option<EthFilterAddress>; 'Option<EthFilterAddress>': Option<EthFilterAddress>;
'Option<EthFilterChanges>': Option<EthFilterChanges>;
'Option<EthFilterTopic>': Option<EthFilterTopic>; 'Option<EthFilterTopic>': Option<EthFilterTopic>;
'Option<EthFilterTopicEntry>': Option<EthFilterTopicEntry>; 'Option<EthFilterTopicEntry>': Option<EthFilterTopicEntry>;
'Option<EthFilterTopicInner>': Option<EthFilterTopicInner>; 'Option<EthFilterTopicInner>': Option<EthFilterTopicInner>;
@@ -379,6 +388,7 @@ declare module '@polkadot/types/types/registry' {
'Option<ExitRevert>': Option<ExitRevert>; 'Option<ExitRevert>': Option<ExitRevert>;
'Option<ExitSucceed>': Option<ExitSucceed>; 'Option<ExitSucceed>': Option<ExitSucceed>;
'Option<Exposure>': Option<Exposure>; 'Option<Exposure>': Option<Exposure>;
'Option<ExtendedBalance>': Option<ExtendedBalance>;
'Option<Extrinsic>': Option<Extrinsic>; 'Option<Extrinsic>': Option<Extrinsic>;
'Option<ExtrinsicEra>': Option<ExtrinsicEra>; 'Option<ExtrinsicEra>': Option<ExtrinsicEra>;
'Option<ExtrinsicMetadataLatest>': Option<ExtrinsicMetadataLatest>; 'Option<ExtrinsicMetadataLatest>': Option<ExtrinsicMetadataLatest>;
@@ -416,6 +426,7 @@ declare module '@polkadot/types/types/registry' {
'Option<FundIndex>': Option<FundIndex>; 'Option<FundIndex>': Option<FundIndex>;
'Option<FundInfo>': Option<FundInfo>; 'Option<FundInfo>': Option<FundInfo>;
'Option<Gas>': Option<Gas>; 'Option<Gas>': Option<Gas>;
'Option<GiltBid>': Option<GiltBid>;
'Option<GlobalValidationSchedule>': Option<GlobalValidationSchedule>; 'Option<GlobalValidationSchedule>': Option<GlobalValidationSchedule>;
'Option<GrandpaEquivocation>': Option<GrandpaEquivocation>; 'Option<GrandpaEquivocation>': Option<GrandpaEquivocation>;
'Option<GrandpaEquivocationProof>': Option<GrandpaEquivocationProof>; 'Option<GrandpaEquivocationProof>': Option<GrandpaEquivocationProof>;
@@ -437,6 +448,7 @@ declare module '@polkadot/types/types/registry' {
'Option<HeartbeatTo244>': Option<HeartbeatTo244>; 'Option<HeartbeatTo244>': Option<HeartbeatTo244>;
'Option<HostConfiguration>': Option<HostConfiguration>; 'Option<HostConfiguration>': Option<HostConfiguration>;
'Option<HostFnWeights>': Option<HostFnWeights>; 'Option<HostFnWeights>': Option<HostFnWeights>;
'Option<HostFnWeightsTo264>': Option<HostFnWeightsTo264>;
'Option<HrmpChannel>': Option<HrmpChannel>; 'Option<HrmpChannel>': Option<HrmpChannel>;
'Option<HrmpChannelId>': Option<HrmpChannelId>; 'Option<HrmpChannelId>': Option<HrmpChannelId>;
'Option<HrmpOpenChannelRequest>': Option<HrmpOpenChannelRequest>; 'Option<HrmpOpenChannelRequest>': Option<HrmpOpenChannelRequest>;
@@ -492,6 +504,7 @@ declare module '@polkadot/types/types/registry' {
'Option<LeasePeriod>': Option<LeasePeriod>; 'Option<LeasePeriod>': Option<LeasePeriod>;
'Option<LeasePeriodOf>': Option<LeasePeriodOf>; 'Option<LeasePeriodOf>': Option<LeasePeriodOf>;
'Option<Limits>': Option<Limits>; 'Option<Limits>': Option<Limits>;
'Option<LimitsTo264>': Option<LimitsTo264>;
'Option<LocalValidationData>': Option<LocalValidationData>; 'Option<LocalValidationData>': Option<LocalValidationData>;
'Option<LockIdentifier>': Option<LockIdentifier>; 'Option<LockIdentifier>': Option<LockIdentifier>;
'Option<LookupSource>': Option<LookupSource>; 'Option<LookupSource>': Option<LookupSource>;
@@ -507,6 +520,7 @@ declare module '@polkadot/types/types/registry' {
'Option<MemberCount>': Option<MemberCount>; 'Option<MemberCount>': Option<MemberCount>;
'Option<MembershipProof>': Option<MembershipProof>; 'Option<MembershipProof>': Option<MembershipProof>;
'Option<MessageIngestionType>': Option<MessageIngestionType>; 'Option<MessageIngestionType>': Option<MessageIngestionType>;
'Option<MessageQueueChain>': Option<MessageQueueChain>;
'Option<MessagingStateSnapshot>': Option<MessagingStateSnapshot>; 'Option<MessagingStateSnapshot>': Option<MessagingStateSnapshot>;
'Option<MessagingStateSnapshotEgressEntry>': Option<MessagingStateSnapshotEgressEntry>; 'Option<MessagingStateSnapshotEgressEntry>': Option<MessagingStateSnapshotEgressEntry>;
'Option<MetadataAll>': Option<MetadataAll>; 'Option<MetadataAll>': Option<MetadataAll>;
@@ -573,10 +587,12 @@ declare module '@polkadot/types/types/registry' {
'Option<PalletsOrigin>': Option<PalletsOrigin>; 'Option<PalletsOrigin>': Option<PalletsOrigin>;
'Option<PalletVersion>': Option<PalletVersion>; 'Option<PalletVersion>': Option<PalletVersion>;
'Option<ParachainDispatchOrigin>': Option<ParachainDispatchOrigin>; 'Option<ParachainDispatchOrigin>': Option<ParachainDispatchOrigin>;
'Option<ParachainInherentData>': Option<ParachainInherentData>;
'Option<ParachainProposal>': Option<ParachainProposal>; 'Option<ParachainProposal>': Option<ParachainProposal>;
'Option<ParaGenesisArgs>': Option<ParaGenesisArgs>; 'Option<ParaGenesisArgs>': Option<ParaGenesisArgs>;
'Option<ParaId>': Option<ParaId>; 'Option<ParaId>': Option<ParaId>;
'Option<ParaInfo>': Option<ParaInfo>; 'Option<ParaInfo>': Option<ParaInfo>;
'Option<ParaLifecycle>': Option<ParaLifecycle>;
'Option<ParaPastCodeMeta>': Option<ParaPastCodeMeta>; 'Option<ParaPastCodeMeta>': Option<ParaPastCodeMeta>;
'Option<ParaScheduling>': Option<ParaScheduling>; 'Option<ParaScheduling>': Option<ParaScheduling>;
'Option<ParathreadClaim>': Option<ParathreadClaim>; 'Option<ParathreadClaim>': Option<ParathreadClaim>;
@@ -593,8 +609,9 @@ declare module '@polkadot/types/types/registry' {
'Option<PendingResume>': Option<PendingResume>; 'Option<PendingResume>': Option<PendingResume>;
'Option<Perbill>': Option<Perbill>; 'Option<Perbill>': Option<Perbill>;
'Option<Percent>': Option<Percent>; 'Option<Percent>': Option<Percent>;
'Option<PerDispatchClass>': Option<PerDispatchClass>;
'Option<PerDispatchClassU32>': Option<PerDispatchClassU32>; 'Option<PerDispatchClassU32>': Option<PerDispatchClassU32>;
'Option<PerDispatchClassWeight>': Option<PerDispatchClassWeight>;
'Option<PerDispatchClassWeightsPerClass>': Option<PerDispatchClassWeightsPerClass>;
'Option<Period>': Option<Period>; 'Option<Period>': Option<Period>;
'Option<Permill>': Option<Permill>; 'Option<Permill>': Option<Permill>;
'Option<PermissionLatest>': Option<PermissionLatest>; 'Option<PermissionLatest>': Option<PermissionLatest>;
@@ -639,8 +656,10 @@ declare module '@polkadot/types/types/registry' {
'Option<RawBabePreDigestSecondaryVRF>': Option<RawBabePreDigestSecondaryVRF>; 'Option<RawBabePreDigestSecondaryVRF>': Option<RawBabePreDigestSecondaryVRF>;
'Option<RawBabePreDigestTo159>': Option<RawBabePreDigestTo159>; 'Option<RawBabePreDigestTo159>': Option<RawBabePreDigestTo159>;
'Option<RawOrigin>': Option<RawOrigin>; 'Option<RawOrigin>': Option<RawOrigin>;
'Option<RawSolution>': Option<RawSolution>;
'Option<RawVRFOutput>': Option<RawVRFOutput>; 'Option<RawVRFOutput>': Option<RawVRFOutput>;
'Option<ReadProof>': Option<ReadProof>; 'Option<ReadProof>': Option<ReadProof>;
'Option<ReadySolution>': Option<ReadySolution>;
'Option<Reasons>': Option<Reasons>; 'Option<Reasons>': Option<Reasons>;
'Option<RecoveryConfig>': Option<RecoveryConfig>; 'Option<RecoveryConfig>': Option<RecoveryConfig>;
'Option<RefCount>': Option<RefCount>; 'Option<RefCount>': Option<RefCount>;
@@ -656,6 +675,7 @@ declare module '@polkadot/types/types/registry' {
'Option<Registration>': Option<Registration>; 'Option<Registration>': Option<Registration>;
'Option<RegistrationJudgement>': Option<RegistrationJudgement>; 'Option<RegistrationJudgement>': Option<RegistrationJudgement>;
'Option<RelayChainBlockNumber>': Option<RelayChainBlockNumber>; 'Option<RelayChainBlockNumber>': Option<RelayChainBlockNumber>;
'Option<RelayChainHash>': Option<RelayChainHash>;
'Option<RelayedFrom>': Option<RelayedFrom>; 'Option<RelayedFrom>': Option<RelayedFrom>;
'Option<RelayTo>': Option<RelayTo>; 'Option<RelayTo>': Option<RelayTo>;
'Option<Releases>': Option<Releases>; 'Option<Releases>': Option<Releases>;
@@ -669,6 +689,7 @@ declare module '@polkadot/types/types/registry' {
'Option<RewardDestination>': Option<RewardDestination>; 'Option<RewardDestination>': Option<RewardDestination>;
'Option<RewardDestinationTo257>': Option<RewardDestinationTo257>; 'Option<RewardDestinationTo257>': Option<RewardDestinationTo257>;
'Option<RewardPoint>': Option<RewardPoint>; 'Option<RewardPoint>': Option<RewardPoint>;
'Option<RoundSnapshot>': Option<RoundSnapshot>;
'Option<RoundState>': Option<RoundState>; 'Option<RoundState>': Option<RoundState>;
'Option<RpcMethods>': Option<RpcMethods>; 'Option<RpcMethods>': Option<RpcMethods>;
'Option<RuntimeDbWeight>': Option<RuntimeDbWeight>; 'Option<RuntimeDbWeight>': Option<RuntimeDbWeight>;
@@ -682,6 +703,7 @@ declare module '@polkadot/types/types/registry' {
'Option<SchedulePriority>': Option<SchedulePriority>; 'Option<SchedulePriority>': Option<SchedulePriority>;
'Option<ScheduleTo212>': Option<ScheduleTo212>; 'Option<ScheduleTo212>': Option<ScheduleTo212>;
'Option<ScheduleTo258>': Option<ScheduleTo258>; 'Option<ScheduleTo258>': Option<ScheduleTo258>;
'Option<ScheduleTo264>': Option<ScheduleTo264>;
'Option<Scheduling>': Option<Scheduling>; 'Option<Scheduling>': Option<Scheduling>;
'Option<Seal>': Option<Seal>; 'Option<Seal>': Option<Seal>;
'Option<SealV0>': Option<SealV0>; 'Option<SealV0>': Option<SealV0>;
@@ -727,6 +749,9 @@ declare module '@polkadot/types/types/registry' {
'Option<SlotRange>': Option<SlotRange>; 'Option<SlotRange>': Option<SlotRange>;
'Option<SocietyJudgement>': Option<SocietyJudgement>; 'Option<SocietyJudgement>': Option<SocietyJudgement>;
'Option<SocietyVote>': Option<SocietyVote>; 'Option<SocietyVote>': Option<SocietyVote>;
'Option<SolutionOrSnapshotSize>': Option<SolutionOrSnapshotSize>;
'Option<SolutionSupport>': Option<SolutionSupport>;
'Option<SolutionSupports>': Option<SolutionSupports>;
'Option<SpanIndex>': Option<SpanIndex>; 'Option<SpanIndex>': Option<SpanIndex>;
'Option<SpanRecord>': Option<SpanRecord>; 'Option<SpanRecord>': Option<SpanRecord>;
'Option<Sr25519Signature>': Option<Sr25519Signature>; 'Option<Sr25519Signature>': Option<Sr25519Signature>;
@@ -837,6 +862,7 @@ declare module '@polkadot/types/types/registry' {
'Option<Votes>': Option<Votes>; 'Option<Votes>': Option<Votes>;
'Option<VotesTo230>': Option<VotesTo230>; 'Option<VotesTo230>': Option<VotesTo230>;
'Option<VoteThreshold>': Option<VoteThreshold>; 'Option<VoteThreshold>': Option<VoteThreshold>;
'Option<VoteWeight>': Option<VoteWeight>;
'Option<Voting>': Option<Voting>; 'Option<Voting>': Option<Voting>;
'Option<VotingDelegating>': Option<VotingDelegating>; 'Option<VotingDelegating>': Option<VotingDelegating>;
'Option<VotingDirect>': Option<VotingDirect>; 'Option<VotingDirect>': Option<VotingDirect>;
@@ -879,6 +905,9 @@ declare module '@polkadot/types/types/registry' {
'Vec<AccountVoteSplit>': Vec<AccountVoteSplit>; 'Vec<AccountVoteSplit>': Vec<AccountVoteSplit>;
'Vec<AccountVoteStandard>': Vec<AccountVoteStandard>; 'Vec<AccountVoteStandard>': Vec<AccountVoteStandard>;
'Vec<ActiveEraInfo>': Vec<ActiveEraInfo>; 'Vec<ActiveEraInfo>': Vec<ActiveEraInfo>;
'Vec<ActiveGilt>': Vec<ActiveGilt>;
'Vec<ActiveGiltsTotal>': Vec<ActiveGiltsTotal>;
'Vec<ActiveIndex>': Vec<ActiveIndex>;
'Vec<ActiveRecovery>': Vec<ActiveRecovery>; 'Vec<ActiveRecovery>': Vec<ActiveRecovery>;
'Vec<Address>': Vec<Address>; 'Vec<Address>': Vec<Address>;
'Vec<AliveContractInfo>': Vec<AliveContractInfo>; 'Vec<AliveContractInfo>': Vec<AliveContractInfo>;
@@ -950,6 +979,7 @@ declare module '@polkadot/types/types/registry' {
'Vec<ChainProperties>': Vec<ChainProperties>; 'Vec<ChainProperties>': Vec<ChainProperties>;
'Vec<ChainType>': Vec<ChainType>; 'Vec<ChainType>': Vec<ChainType>;
'Vec<ChangesTrieConfiguration>': Vec<ChangesTrieConfiguration>; 'Vec<ChangesTrieConfiguration>': Vec<ChangesTrieConfiguration>;
'Vec<CodecHash>': Vec<CodecHash>;
'Vec<CodeHash>': Vec<CodeHash>; 'Vec<CodeHash>': Vec<CodeHash>;
'Vec<CollatorId>': Vec<CollatorId>; 'Vec<CollatorId>': Vec<CollatorId>;
'Vec<CollatorSignature>': Vec<CollatorSignature>; 'Vec<CollatorSignature>': Vec<CollatorSignature>;
@@ -1062,6 +1092,7 @@ declare module '@polkadot/types/types/registry' {
'Vec<EthereumSignature>': Vec<EthereumSignature>; 'Vec<EthereumSignature>': Vec<EthereumSignature>;
'Vec<EthFilter>': Vec<EthFilter>; 'Vec<EthFilter>': Vec<EthFilter>;
'Vec<EthFilterAddress>': Vec<EthFilterAddress>; 'Vec<EthFilterAddress>': Vec<EthFilterAddress>;
'Vec<EthFilterChanges>': Vec<EthFilterChanges>;
'Vec<EthFilterTopic>': Vec<EthFilterTopic>; 'Vec<EthFilterTopic>': Vec<EthFilterTopic>;
'Vec<EthFilterTopicEntry>': Vec<EthFilterTopicEntry>; 'Vec<EthFilterTopicEntry>': Vec<EthFilterTopicEntry>;
'Vec<EthFilterTopicInner>': Vec<EthFilterTopicInner>; 'Vec<EthFilterTopicInner>': Vec<EthFilterTopicInner>;
@@ -1101,6 +1132,7 @@ declare module '@polkadot/types/types/registry' {
'Vec<ExitRevert>': Vec<ExitRevert>; 'Vec<ExitRevert>': Vec<ExitRevert>;
'Vec<ExitSucceed>': Vec<ExitSucceed>; 'Vec<ExitSucceed>': Vec<ExitSucceed>;
'Vec<Exposure>': Vec<Exposure>; 'Vec<Exposure>': Vec<Exposure>;
'Vec<ExtendedBalance>': Vec<ExtendedBalance>;
'Vec<Extrinsic>': Vec<Extrinsic>; 'Vec<Extrinsic>': Vec<Extrinsic>;
'Vec<ExtrinsicEra>': Vec<ExtrinsicEra>; 'Vec<ExtrinsicEra>': Vec<ExtrinsicEra>;
'Vec<ExtrinsicMetadataLatest>': Vec<ExtrinsicMetadataLatest>; 'Vec<ExtrinsicMetadataLatest>': Vec<ExtrinsicMetadataLatest>;
@@ -1138,6 +1170,7 @@ declare module '@polkadot/types/types/registry' {
'Vec<FundIndex>': Vec<FundIndex>; 'Vec<FundIndex>': Vec<FundIndex>;
'Vec<FundInfo>': Vec<FundInfo>; 'Vec<FundInfo>': Vec<FundInfo>;
'Vec<Gas>': Vec<Gas>; 'Vec<Gas>': Vec<Gas>;
'Vec<GiltBid>': Vec<GiltBid>;
'Vec<GlobalValidationSchedule>': Vec<GlobalValidationSchedule>; 'Vec<GlobalValidationSchedule>': Vec<GlobalValidationSchedule>;
'Vec<GrandpaEquivocation>': Vec<GrandpaEquivocation>; 'Vec<GrandpaEquivocation>': Vec<GrandpaEquivocation>;
'Vec<GrandpaEquivocationProof>': Vec<GrandpaEquivocationProof>; 'Vec<GrandpaEquivocationProof>': Vec<GrandpaEquivocationProof>;
@@ -1159,6 +1192,7 @@ declare module '@polkadot/types/types/registry' {
'Vec<HeartbeatTo244>': Vec<HeartbeatTo244>; 'Vec<HeartbeatTo244>': Vec<HeartbeatTo244>;
'Vec<HostConfiguration>': Vec<HostConfiguration>; 'Vec<HostConfiguration>': Vec<HostConfiguration>;
'Vec<HostFnWeights>': Vec<HostFnWeights>; 'Vec<HostFnWeights>': Vec<HostFnWeights>;
'Vec<HostFnWeightsTo264>': Vec<HostFnWeightsTo264>;
'Vec<HrmpChannel>': Vec<HrmpChannel>; 'Vec<HrmpChannel>': Vec<HrmpChannel>;
'Vec<HrmpChannelId>': Vec<HrmpChannelId>; 'Vec<HrmpChannelId>': Vec<HrmpChannelId>;
'Vec<HrmpOpenChannelRequest>': Vec<HrmpOpenChannelRequest>; 'Vec<HrmpOpenChannelRequest>': Vec<HrmpOpenChannelRequest>;
@@ -1214,6 +1248,7 @@ declare module '@polkadot/types/types/registry' {
'Vec<LeasePeriod>': Vec<LeasePeriod>; 'Vec<LeasePeriod>': Vec<LeasePeriod>;
'Vec<LeasePeriodOf>': Vec<LeasePeriodOf>; 'Vec<LeasePeriodOf>': Vec<LeasePeriodOf>;
'Vec<Limits>': Vec<Limits>; 'Vec<Limits>': Vec<Limits>;
'Vec<LimitsTo264>': Vec<LimitsTo264>;
'Vec<LocalValidationData>': Vec<LocalValidationData>; 'Vec<LocalValidationData>': Vec<LocalValidationData>;
'Vec<LockIdentifier>': Vec<LockIdentifier>; 'Vec<LockIdentifier>': Vec<LockIdentifier>;
'Vec<LookupSource>': Vec<LookupSource>; 'Vec<LookupSource>': Vec<LookupSource>;
@@ -1229,6 +1264,7 @@ declare module '@polkadot/types/types/registry' {
'Vec<MemberCount>': Vec<MemberCount>; 'Vec<MemberCount>': Vec<MemberCount>;
'Vec<MembershipProof>': Vec<MembershipProof>; 'Vec<MembershipProof>': Vec<MembershipProof>;
'Vec<MessageIngestionType>': Vec<MessageIngestionType>; 'Vec<MessageIngestionType>': Vec<MessageIngestionType>;
'Vec<MessageQueueChain>': Vec<MessageQueueChain>;
'Vec<MessagingStateSnapshot>': Vec<MessagingStateSnapshot>; 'Vec<MessagingStateSnapshot>': Vec<MessagingStateSnapshot>;
'Vec<MessagingStateSnapshotEgressEntry>': Vec<MessagingStateSnapshotEgressEntry>; 'Vec<MessagingStateSnapshotEgressEntry>': Vec<MessagingStateSnapshotEgressEntry>;
'Vec<MetadataAll>': Vec<MetadataAll>; 'Vec<MetadataAll>': Vec<MetadataAll>;
@@ -1295,10 +1331,12 @@ declare module '@polkadot/types/types/registry' {
'Vec<PalletsOrigin>': Vec<PalletsOrigin>; 'Vec<PalletsOrigin>': Vec<PalletsOrigin>;
'Vec<PalletVersion>': Vec<PalletVersion>; 'Vec<PalletVersion>': Vec<PalletVersion>;
'Vec<ParachainDispatchOrigin>': Vec<ParachainDispatchOrigin>; 'Vec<ParachainDispatchOrigin>': Vec<ParachainDispatchOrigin>;
'Vec<ParachainInherentData>': Vec<ParachainInherentData>;
'Vec<ParachainProposal>': Vec<ParachainProposal>; 'Vec<ParachainProposal>': Vec<ParachainProposal>;
'Vec<ParaGenesisArgs>': Vec<ParaGenesisArgs>; 'Vec<ParaGenesisArgs>': Vec<ParaGenesisArgs>;
'Vec<ParaId>': Vec<ParaId>; 'Vec<ParaId>': Vec<ParaId>;
'Vec<ParaInfo>': Vec<ParaInfo>; 'Vec<ParaInfo>': Vec<ParaInfo>;
'Vec<ParaLifecycle>': Vec<ParaLifecycle>;
'Vec<ParaPastCodeMeta>': Vec<ParaPastCodeMeta>; 'Vec<ParaPastCodeMeta>': Vec<ParaPastCodeMeta>;
'Vec<ParaScheduling>': Vec<ParaScheduling>; 'Vec<ParaScheduling>': Vec<ParaScheduling>;
'Vec<ParathreadClaim>': Vec<ParathreadClaim>; 'Vec<ParathreadClaim>': Vec<ParathreadClaim>;
@@ -1315,8 +1353,9 @@ declare module '@polkadot/types/types/registry' {
'Vec<PendingResume>': Vec<PendingResume>; 'Vec<PendingResume>': Vec<PendingResume>;
'Vec<Perbill>': Vec<Perbill>; 'Vec<Perbill>': Vec<Perbill>;
'Vec<Percent>': Vec<Percent>; 'Vec<Percent>': Vec<Percent>;
'Vec<PerDispatchClass>': Vec<PerDispatchClass>;
'Vec<PerDispatchClassU32>': Vec<PerDispatchClassU32>; 'Vec<PerDispatchClassU32>': Vec<PerDispatchClassU32>;
'Vec<PerDispatchClassWeight>': Vec<PerDispatchClassWeight>;
'Vec<PerDispatchClassWeightsPerClass>': Vec<PerDispatchClassWeightsPerClass>;
'Vec<Period>': Vec<Period>; 'Vec<Period>': Vec<Period>;
'Vec<Permill>': Vec<Permill>; 'Vec<Permill>': Vec<Permill>;
'Vec<PermissionLatest>': Vec<PermissionLatest>; 'Vec<PermissionLatest>': Vec<PermissionLatest>;
@@ -1361,8 +1400,10 @@ declare module '@polkadot/types/types/registry' {
'Vec<RawBabePreDigestSecondaryVRF>': Vec<RawBabePreDigestSecondaryVRF>; 'Vec<RawBabePreDigestSecondaryVRF>': Vec<RawBabePreDigestSecondaryVRF>;
'Vec<RawBabePreDigestTo159>': Vec<RawBabePreDigestTo159>; 'Vec<RawBabePreDigestTo159>': Vec<RawBabePreDigestTo159>;
'Vec<RawOrigin>': Vec<RawOrigin>; 'Vec<RawOrigin>': Vec<RawOrigin>;
'Vec<RawSolution>': Vec<RawSolution>;
'Vec<RawVRFOutput>': Vec<RawVRFOutput>; 'Vec<RawVRFOutput>': Vec<RawVRFOutput>;
'Vec<ReadProof>': Vec<ReadProof>; 'Vec<ReadProof>': Vec<ReadProof>;
'Vec<ReadySolution>': Vec<ReadySolution>;
'Vec<Reasons>': Vec<Reasons>; 'Vec<Reasons>': Vec<Reasons>;
'Vec<RecoveryConfig>': Vec<RecoveryConfig>; 'Vec<RecoveryConfig>': Vec<RecoveryConfig>;
'Vec<RefCount>': Vec<RefCount>; 'Vec<RefCount>': Vec<RefCount>;
@@ -1378,6 +1419,7 @@ declare module '@polkadot/types/types/registry' {
'Vec<Registration>': Vec<Registration>; 'Vec<Registration>': Vec<Registration>;
'Vec<RegistrationJudgement>': Vec<RegistrationJudgement>; 'Vec<RegistrationJudgement>': Vec<RegistrationJudgement>;
'Vec<RelayChainBlockNumber>': Vec<RelayChainBlockNumber>; 'Vec<RelayChainBlockNumber>': Vec<RelayChainBlockNumber>;
'Vec<RelayChainHash>': Vec<RelayChainHash>;
'Vec<RelayedFrom>': Vec<RelayedFrom>; 'Vec<RelayedFrom>': Vec<RelayedFrom>;
'Vec<RelayTo>': Vec<RelayTo>; 'Vec<RelayTo>': Vec<RelayTo>;
'Vec<Releases>': Vec<Releases>; 'Vec<Releases>': Vec<Releases>;
@@ -1391,6 +1433,7 @@ declare module '@polkadot/types/types/registry' {
'Vec<RewardDestination>': Vec<RewardDestination>; 'Vec<RewardDestination>': Vec<RewardDestination>;
'Vec<RewardDestinationTo257>': Vec<RewardDestinationTo257>; 'Vec<RewardDestinationTo257>': Vec<RewardDestinationTo257>;
'Vec<RewardPoint>': Vec<RewardPoint>; 'Vec<RewardPoint>': Vec<RewardPoint>;
'Vec<RoundSnapshot>': Vec<RoundSnapshot>;
'Vec<RoundState>': Vec<RoundState>; 'Vec<RoundState>': Vec<RoundState>;
'Vec<RpcMethods>': Vec<RpcMethods>; 'Vec<RpcMethods>': Vec<RpcMethods>;
'Vec<RuntimeDbWeight>': Vec<RuntimeDbWeight>; 'Vec<RuntimeDbWeight>': Vec<RuntimeDbWeight>;
@@ -1404,6 +1447,7 @@ declare module '@polkadot/types/types/registry' {
'Vec<SchedulePriority>': Vec<SchedulePriority>; 'Vec<SchedulePriority>': Vec<SchedulePriority>;
'Vec<ScheduleTo212>': Vec<ScheduleTo212>; 'Vec<ScheduleTo212>': Vec<ScheduleTo212>;
'Vec<ScheduleTo258>': Vec<ScheduleTo258>; 'Vec<ScheduleTo258>': Vec<ScheduleTo258>;
'Vec<ScheduleTo264>': Vec<ScheduleTo264>;
'Vec<Scheduling>': Vec<Scheduling>; 'Vec<Scheduling>': Vec<Scheduling>;
'Vec<Seal>': Vec<Seal>; 'Vec<Seal>': Vec<Seal>;
'Vec<SealV0>': Vec<SealV0>; 'Vec<SealV0>': Vec<SealV0>;
@@ -1449,6 +1493,9 @@ declare module '@polkadot/types/types/registry' {
'Vec<SlotRange>': Vec<SlotRange>; 'Vec<SlotRange>': Vec<SlotRange>;
'Vec<SocietyJudgement>': Vec<SocietyJudgement>; 'Vec<SocietyJudgement>': Vec<SocietyJudgement>;
'Vec<SocietyVote>': Vec<SocietyVote>; 'Vec<SocietyVote>': Vec<SocietyVote>;
'Vec<SolutionOrSnapshotSize>': Vec<SolutionOrSnapshotSize>;
'Vec<SolutionSupport>': Vec<SolutionSupport>;
'Vec<SolutionSupports>': Vec<SolutionSupports>;
'Vec<SpanIndex>': Vec<SpanIndex>; 'Vec<SpanIndex>': Vec<SpanIndex>;
'Vec<SpanRecord>': Vec<SpanRecord>; 'Vec<SpanRecord>': Vec<SpanRecord>;
'Vec<Sr25519Signature>': Vec<Sr25519Signature>; 'Vec<Sr25519Signature>': Vec<Sr25519Signature>;
@@ -1559,6 +1606,7 @@ declare module '@polkadot/types/types/registry' {
'Vec<Votes>': Vec<Votes>; 'Vec<Votes>': Vec<Votes>;
'Vec<VotesTo230>': Vec<VotesTo230>; 'Vec<VotesTo230>': Vec<VotesTo230>;
'Vec<VoteThreshold>': Vec<VoteThreshold>; 'Vec<VoteThreshold>': Vec<VoteThreshold>;
'Vec<VoteWeight>': Vec<VoteWeight>;
'Vec<Voting>': Vec<Voting>; 'Vec<Voting>': Vec<Voting>;
'Vec<VotingDelegating>': Vec<VotingDelegating>; 'Vec<VotingDelegating>': Vec<VotingDelegating>;
'Vec<VotingDirect>': Vec<VotingDirect>; 'Vec<VotingDirect>': Vec<VotingDirect>;
@@ -1601,6 +1649,9 @@ declare module '@polkadot/types/types/registry' {
AccountVoteSplit: AccountVoteSplit; AccountVoteSplit: AccountVoteSplit;
AccountVoteStandard: AccountVoteStandard; AccountVoteStandard: AccountVoteStandard;
ActiveEraInfo: ActiveEraInfo; ActiveEraInfo: ActiveEraInfo;
ActiveGilt: ActiveGilt;
ActiveGiltsTotal: ActiveGiltsTotal;
ActiveIndex: ActiveIndex;
ActiveRecovery: ActiveRecovery; ActiveRecovery: ActiveRecovery;
Address: Address; Address: Address;
AliveContractInfo: AliveContractInfo; AliveContractInfo: AliveContractInfo;
@@ -1672,6 +1723,7 @@ declare module '@polkadot/types/types/registry' {
ChainProperties: ChainProperties; ChainProperties: ChainProperties;
ChainType: ChainType; ChainType: ChainType;
ChangesTrieConfiguration: ChangesTrieConfiguration; ChangesTrieConfiguration: ChangesTrieConfiguration;
CodecHash: CodecHash;
CodeHash: CodeHash; CodeHash: CodeHash;
CollatorId: CollatorId; CollatorId: CollatorId;
CollatorSignature: CollatorSignature; CollatorSignature: CollatorSignature;
@@ -1784,6 +1836,7 @@ declare module '@polkadot/types/types/registry' {
EthereumSignature: EthereumSignature; EthereumSignature: EthereumSignature;
EthFilter: EthFilter; EthFilter: EthFilter;
EthFilterAddress: EthFilterAddress; EthFilterAddress: EthFilterAddress;
EthFilterChanges: EthFilterChanges;
EthFilterTopic: EthFilterTopic; EthFilterTopic: EthFilterTopic;
EthFilterTopicEntry: EthFilterTopicEntry; EthFilterTopicEntry: EthFilterTopicEntry;
EthFilterTopicInner: EthFilterTopicInner; EthFilterTopicInner: EthFilterTopicInner;
@@ -1823,6 +1876,7 @@ declare module '@polkadot/types/types/registry' {
ExitRevert: ExitRevert; ExitRevert: ExitRevert;
ExitSucceed: ExitSucceed; ExitSucceed: ExitSucceed;
Exposure: Exposure; Exposure: Exposure;
ExtendedBalance: ExtendedBalance;
Extrinsic: Extrinsic; Extrinsic: Extrinsic;
ExtrinsicEra: ExtrinsicEra; ExtrinsicEra: ExtrinsicEra;
ExtrinsicMetadataLatest: ExtrinsicMetadataLatest; ExtrinsicMetadataLatest: ExtrinsicMetadataLatest;
@@ -1860,6 +1914,7 @@ declare module '@polkadot/types/types/registry' {
FundIndex: FundIndex; FundIndex: FundIndex;
FundInfo: FundInfo; FundInfo: FundInfo;
Gas: Gas; Gas: Gas;
GiltBid: GiltBid;
GlobalValidationSchedule: GlobalValidationSchedule; GlobalValidationSchedule: GlobalValidationSchedule;
GrandpaEquivocation: GrandpaEquivocation; GrandpaEquivocation: GrandpaEquivocation;
GrandpaEquivocationProof: GrandpaEquivocationProof; GrandpaEquivocationProof: GrandpaEquivocationProof;
@@ -1881,6 +1936,7 @@ declare module '@polkadot/types/types/registry' {
HeartbeatTo244: HeartbeatTo244; HeartbeatTo244: HeartbeatTo244;
HostConfiguration: HostConfiguration; HostConfiguration: HostConfiguration;
HostFnWeights: HostFnWeights; HostFnWeights: HostFnWeights;
HostFnWeightsTo264: HostFnWeightsTo264;
HrmpChannel: HrmpChannel; HrmpChannel: HrmpChannel;
HrmpChannelId: HrmpChannelId; HrmpChannelId: HrmpChannelId;
HrmpOpenChannelRequest: HrmpOpenChannelRequest; HrmpOpenChannelRequest: HrmpOpenChannelRequest;
@@ -1936,6 +1992,7 @@ declare module '@polkadot/types/types/registry' {
LeasePeriod: LeasePeriod; LeasePeriod: LeasePeriod;
LeasePeriodOf: LeasePeriodOf; LeasePeriodOf: LeasePeriodOf;
Limits: Limits; Limits: Limits;
LimitsTo264: LimitsTo264;
LocalValidationData: LocalValidationData; LocalValidationData: LocalValidationData;
LockIdentifier: LockIdentifier; LockIdentifier: LockIdentifier;
LookupSource: LookupSource; LookupSource: LookupSource;
@@ -1951,6 +2008,7 @@ declare module '@polkadot/types/types/registry' {
MemberCount: MemberCount; MemberCount: MemberCount;
MembershipProof: MembershipProof; MembershipProof: MembershipProof;
MessageIngestionType: MessageIngestionType; MessageIngestionType: MessageIngestionType;
MessageQueueChain: MessageQueueChain;
MessagingStateSnapshot: MessagingStateSnapshot; MessagingStateSnapshot: MessagingStateSnapshot;
MessagingStateSnapshotEgressEntry: MessagingStateSnapshotEgressEntry; MessagingStateSnapshotEgressEntry: MessagingStateSnapshotEgressEntry;
MetadataAll: MetadataAll; MetadataAll: MetadataAll;
@@ -2017,10 +2075,12 @@ declare module '@polkadot/types/types/registry' {
PalletsOrigin: PalletsOrigin; PalletsOrigin: PalletsOrigin;
PalletVersion: PalletVersion; PalletVersion: PalletVersion;
ParachainDispatchOrigin: ParachainDispatchOrigin; ParachainDispatchOrigin: ParachainDispatchOrigin;
ParachainInherentData: ParachainInherentData;
ParachainProposal: ParachainProposal; ParachainProposal: ParachainProposal;
ParaGenesisArgs: ParaGenesisArgs; ParaGenesisArgs: ParaGenesisArgs;
ParaId: ParaId; ParaId: ParaId;
ParaInfo: ParaInfo; ParaInfo: ParaInfo;
ParaLifecycle: ParaLifecycle;
ParaPastCodeMeta: ParaPastCodeMeta; ParaPastCodeMeta: ParaPastCodeMeta;
ParaScheduling: ParaScheduling; ParaScheduling: ParaScheduling;
ParathreadClaim: ParathreadClaim; ParathreadClaim: ParathreadClaim;
@@ -2037,8 +2097,9 @@ declare module '@polkadot/types/types/registry' {
PendingResume: PendingResume; PendingResume: PendingResume;
Perbill: Perbill; Perbill: Perbill;
Percent: Percent; Percent: Percent;
PerDispatchClass: PerDispatchClass;
PerDispatchClassU32: PerDispatchClassU32; PerDispatchClassU32: PerDispatchClassU32;
PerDispatchClassWeight: PerDispatchClassWeight;
PerDispatchClassWeightsPerClass: PerDispatchClassWeightsPerClass;
Period: Period; Period: Period;
Permill: Permill; Permill: Permill;
PermissionLatest: PermissionLatest; PermissionLatest: PermissionLatest;
@@ -2083,8 +2144,10 @@ declare module '@polkadot/types/types/registry' {
RawBabePreDigestSecondaryVRF: RawBabePreDigestSecondaryVRF; RawBabePreDigestSecondaryVRF: RawBabePreDigestSecondaryVRF;
RawBabePreDigestTo159: RawBabePreDigestTo159; RawBabePreDigestTo159: RawBabePreDigestTo159;
RawOrigin: RawOrigin; RawOrigin: RawOrigin;
RawSolution: RawSolution;
RawVRFOutput: RawVRFOutput; RawVRFOutput: RawVRFOutput;
ReadProof: ReadProof; ReadProof: ReadProof;
ReadySolution: ReadySolution;
Reasons: Reasons; Reasons: Reasons;
RecoveryConfig: RecoveryConfig; RecoveryConfig: RecoveryConfig;
RefCount: RefCount; RefCount: RefCount;
@@ -2100,6 +2163,7 @@ declare module '@polkadot/types/types/registry' {
Registration: Registration; Registration: Registration;
RegistrationJudgement: RegistrationJudgement; RegistrationJudgement: RegistrationJudgement;
RelayChainBlockNumber: RelayChainBlockNumber; RelayChainBlockNumber: RelayChainBlockNumber;
RelayChainHash: RelayChainHash;
RelayedFrom: RelayedFrom; RelayedFrom: RelayedFrom;
RelayTo: RelayTo; RelayTo: RelayTo;
Releases: Releases; Releases: Releases;
@@ -2113,6 +2177,7 @@ declare module '@polkadot/types/types/registry' {
RewardDestination: RewardDestination; RewardDestination: RewardDestination;
RewardDestinationTo257: RewardDestinationTo257; RewardDestinationTo257: RewardDestinationTo257;
RewardPoint: RewardPoint; RewardPoint: RewardPoint;
RoundSnapshot: RoundSnapshot;
RoundState: RoundState; RoundState: RoundState;
RpcMethods: RpcMethods; RpcMethods: RpcMethods;
RuntimeDbWeight: RuntimeDbWeight; RuntimeDbWeight: RuntimeDbWeight;
@@ -2126,6 +2191,7 @@ declare module '@polkadot/types/types/registry' {
SchedulePriority: SchedulePriority; SchedulePriority: SchedulePriority;
ScheduleTo212: ScheduleTo212; ScheduleTo212: ScheduleTo212;
ScheduleTo258: ScheduleTo258; ScheduleTo258: ScheduleTo258;
ScheduleTo264: ScheduleTo264;
Scheduling: Scheduling; Scheduling: Scheduling;
Seal: Seal; Seal: Seal;
SealV0: SealV0; SealV0: SealV0;
@@ -2171,6 +2237,9 @@ declare module '@polkadot/types/types/registry' {
SlotRange: SlotRange; SlotRange: SlotRange;
SocietyJudgement: SocietyJudgement; SocietyJudgement: SocietyJudgement;
SocietyVote: SocietyVote; SocietyVote: SocietyVote;
SolutionOrSnapshotSize: SolutionOrSnapshotSize;
SolutionSupport: SolutionSupport;
SolutionSupports: SolutionSupports;
SpanIndex: SpanIndex; SpanIndex: SpanIndex;
SpanRecord: SpanRecord; SpanRecord: SpanRecord;
Sr25519Signature: Sr25519Signature; Sr25519Signature: Sr25519Signature;
@@ -2281,6 +2350,7 @@ declare module '@polkadot/types/types/registry' {
Votes: Votes; Votes: Votes;
VotesTo230: VotesTo230; VotesTo230: VotesTo230;
VoteThreshold: VoteThreshold; VoteThreshold: VoteThreshold;
VoteWeight: VoteWeight;
Voting: Voting; Voting: Voting;
VotingDelegating: VotingDelegating; VotingDelegating: VotingDelegating;
VotingDirect: VotingDirect; VotingDirect: VotingDirect;
+2 -2
View File
@@ -1,7 +1,7 @@
// Copyright 2017-2021 @polkadot/types authors & contributors // Copyright 2017-2021 @polkadot/types authors & contributors
// SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: Apache-2.0
import type { H256 } from '../interfaces/runtime'; import type { CodecHash } from '../interfaces/runtime';
import type { AnyJson, Codec, Registry } from '../types'; import type { AnyJson, Codec, Registry } from '../types';
import { compactToU8a, u8aConcat, u8aToHex } from '@polkadot/util'; import { compactToU8a, u8aConcat, u8aToHex } from '@polkadot/util';
@@ -36,7 +36,7 @@ export abstract class AbstractArray<T extends Codec> extends Array<T> implements
/** /**
* @description returns a hash of the contents * @description returns a hash of the contents
*/ */
public get hash (): H256 { public get hash (): CodecHash {
return this.registry.hash(this.toU8a()); return this.registry.hash(this.toU8a());
} }
+7 -7
View File
@@ -1,13 +1,13 @@
// Copyright 2017-2021 @polkadot/types authors & contributors // Copyright 2017-2021 @polkadot/types authors & contributors
// SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: Apache-2.0
import type { H256 } from '../interfaces/runtime'; import type { CodecHash } from '../interfaces/runtime';
import type { AnyNumber, Codec, Registry } from '../types'; import type { AnyNumber, Codec, Registry } from '../types';
import type { UIntBitLength } from './types'; import type { UIntBitLength } from './types';
import BN from 'bn.js'; import BN from 'bn.js';
import { assert, BN_ZERO, bnToBn, bnToHex, bnToU8a, formatBalance, formatNumber, hexToBn, isHex, isString, isU8a, u8aToBn } from '@polkadot/util'; import { assert, BN_BILLION, BN_HUNDRED, BN_MILLION, BN_QUINTILL, BN_ZERO, bnToBn, bnToHex, bnToU8a, formatBalance, formatNumber, hexToBn, isHex, isString, isU8a, u8aToBn } from '@polkadot/util';
export const DEFAULT_UINT_BITS = 64; export const DEFAULT_UINT_BITS = 64;
@@ -17,10 +17,10 @@ const MAX_NUMBER_BITS = 52;
const MUL_P = new BN(1_00_00); const MUL_P = new BN(1_00_00);
const FORMATTERS: [string, BN][] = [ const FORMATTERS: [string, BN][] = [
['Perquintill', new BN(1_000_000_000_000)], ['Perquintill', BN_QUINTILL],
['Perbill', new BN(1_000_000_000)], ['Perbill', BN_BILLION],
['Permill', new BN(1_000_000)], ['Permill', BN_MILLION],
['Percent', new BN(100)] ['Percent', BN_HUNDRED]
]; ];
function toPercentage (value: BN, divisor: BN): string { function toPercentage (value: BN, divisor: BN): string {
@@ -95,7 +95,7 @@ export abstract class AbstractInt extends BN implements Codec {
/** /**
* @description returns a hash of the contents * @description returns a hash of the contents
*/ */
public get hash (): H256 { public get hash (): CodecHash {
return this.registry.hash(this.toU8a()); return this.registry.hash(this.toU8a());
} }
+2 -2
View File
@@ -1,7 +1,7 @@
// Copyright 2017-2021 @polkadot/types authors & contributors // Copyright 2017-2021 @polkadot/types authors & contributors
// SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: Apache-2.0
import type { H256 } from '../interfaces/runtime'; import type { CodecHash } from '../interfaces/runtime';
import type { AnyJson, Codec, Constructor, InterfaceTypes, Registry } from '../types'; import type { AnyJson, Codec, Constructor, InterfaceTypes, Registry } from '../types';
import { compactFromU8a, compactToU8a, isHex, isU8a, logger, u8aConcat, u8aToHex, u8aToU8a } from '@polkadot/util'; import { compactFromU8a, compactToU8a, isHex, isU8a, logger, u8aConcat, u8aToHex, u8aToU8a } from '@polkadot/util';
@@ -112,7 +112,7 @@ export class BTreeSet<V extends Codec = Codec> extends Set<V> implements Codec {
/** /**
* @description Returns a hash of the value * @description Returns a hash of the value
*/ */
public get hash (): H256 { public get hash (): CodecHash {
return this.registry.hash(this.toU8a()); return this.registry.hash(this.toU8a());
} }
+2 -2
View File
@@ -1,7 +1,7 @@
// Copyright 2017-2021 @polkadot/types authors & contributors // Copyright 2017-2021 @polkadot/types authors & contributors
// SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: Apache-2.0
import type { H256 } from '../interfaces/runtime'; import type { CodecHash } from '../interfaces/runtime';
import type { AnyJson, BareOpts, Codec, Registry } from '../types'; import type { AnyJson, BareOpts, Codec, Registry } from '../types';
/** /**
@@ -28,7 +28,7 @@ export abstract class Base<T extends Codec> implements Codec {
/** /**
* @description returns a hash of the contents * @description returns a hash of the contents
*/ */
public get hash (): H256 { public get hash (): CodecHash {
return this.registry.hash(this.toU8a()); return this.registry.hash(this.toU8a());
} }
+2 -2
View File
@@ -1,7 +1,7 @@
// Copyright 2017-2021 @polkadot/types authors & contributors // Copyright 2017-2021 @polkadot/types authors & contributors
// SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: Apache-2.0
import type { H256 } from '../interfaces'; import type { CodecHash } from '../interfaces';
import type { AnyJson, AnyNumber, Constructor, ICompact, InterfaceTypes, Registry } from '../types'; import type { AnyJson, AnyNumber, Constructor, ICompact, InterfaceTypes, Registry } from '../types';
import type { CompactEncodable, UIntBitLength } from './types'; import type { CompactEncodable, UIntBitLength } from './types';
@@ -63,7 +63,7 @@ export class Compact<T extends CompactEncodable> implements ICompact<T> {
/** /**
* @description returns a hash of the contents * @description returns a hash of the contents
*/ */
public get hash (): H256 { public get hash (): CodecHash {
return this.registry.hash(this.toU8a()); return this.registry.hash(this.toU8a());
} }
+2 -2
View File
@@ -1,7 +1,7 @@
// Copyright 2017-2021 @polkadot/types authors & contributors // Copyright 2017-2021 @polkadot/types authors & contributors
// SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: Apache-2.0
import type { H256 } from '../interfaces/runtime'; import type { CodecHash } from '../interfaces/runtime';
import type { AnyNumber, Codec, Registry } from '../types'; import type { AnyNumber, Codec, Registry } from '../types';
import type { UIntBitLength } from './types'; import type { UIntBitLength } from './types';
@@ -55,7 +55,7 @@ export class CodecDate extends Date implements Codec {
/** /**
* @description returns a hash of the contents * @description returns a hash of the contents
*/ */
public get hash (): H256 { public get hash (): CodecHash {
return this.registry.hash(this.toU8a()); return this.registry.hash(this.toU8a());
} }
+40
View File
@@ -359,6 +359,46 @@ describe('Enum', (): void => {
}); });
}); });
describe('indexed enum', (): void => {
const Test = Enum.with({
A: 5,
B: 42,
C: 69,
D: 255
});
it('handles an indexed C-like enum', (): void => {
expect(new Test(registry, 'A').toNumber()).toEqual(5);
expect(new Test(registry, 'B').toNumber()).toEqual(42);
expect(new Test(registry, 'C').toNumber()).toEqual(69);
expect(new Test(registry, 69).toNumber()).toEqual(69);
expect(new Test(registry, 'D').toNumber()).toEqual(255);
});
it('creates proper raw structure', (): void => {
expect(new Test(registry).toRawType()).toEqual(JSON.stringify({
_enum: {
A: 5,
B: 42,
C: 69,
D: 255
}
}));
});
it('has the indexes for the enum', (): void => {
expect(new Test(registry).defIndexes).toEqual([5, 42, 69, 255]);
});
it('has the correct outputs', (): void => {
const test = new Test(registry, 5);
expect(test.toU8a()).toEqual(new Uint8Array([5]));
expect(test.toHex()).toEqual('0x05');
expect(test.toJSON()).toEqual('A');
});
});
describe('toHex', (): void => { describe('toHex', (): void => {
it('has a proper hex representation & length', (): void => { it('has a proper hex representation & length', (): void => {
const Test = Enum.with({ const Test = Enum.with({
+102 -37
View File
@@ -1,7 +1,7 @@
// Copyright 2017-2021 @polkadot/types authors & contributors // Copyright 2017-2021 @polkadot/types authors & contributors
// SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: Apache-2.0
import type { H256 } from '../interfaces'; import type { CodecHash } from '../interfaces';
import type { AnyJson, Codec, Constructor, InterfaceTypes, Registry } from '../types'; import type { AnyJson, Codec, Constructor, InterfaceTypes, Registry } from '../types';
import { assert, hexToU8a, isHex, isNumber, isObject, isString, isU8a, isUndefined, stringCamelCase, stringUpperFirst, u8aConcat, u8aToHex } from '@polkadot/util'; import { assert, hexToU8a, isHex, isNumber, isObject, isString, isU8a, isUndefined, stringCamelCase, stringUpperFirst, u8aConcat, u8aToHex } from '@polkadot/util';
@@ -15,56 +15,100 @@ export interface EnumConstructor<T = Codec> {
new(registry: Registry, value?: any, index?: number): T; new(registry: Registry, value?: any, index?: number): T;
} }
type TypesDef = Record<string, Constructor>; interface EntryDef {
Type: Constructor;
index: number;
}
type TypesDef = Record<string, EntryDef>;
interface Decoded { interface Decoded {
index: number; index: number;
value: Codec; value: Codec;
} }
function extractDef (registry: Registry, _def: Record<string, keyof InterfaceTypes | Constructor> | string[]): { def: TypesDef; isBasic: boolean } { function isRustEnum (def: Record<string, keyof InterfaceTypes | Constructor> | Record<string, number>): def is Record<string, keyof InterfaceTypes | Constructor> {
if (!Array.isArray(_def)) { const defValues = Object.values(def);
const def = mapToTypeMap(registry, _def);
const isBasic = !Object.values(def).some((type): boolean => type !== Null);
if (defValues.some((v) => isNumber(v))) {
assert(defValues.every((v) => isNumber(v) && v >= 0 && v <= 255), 'Invalid number-indexed enum definition');
return false;
}
return true;
}
function extractDef (registry: Registry, _def: Record<string, keyof InterfaceTypes | Constructor> | Record<string, number> | string[]): { def: TypesDef; isBasic: boolean; isIndexed: boolean } {
if (Array.isArray(_def)) {
return { return {
def, def: _def.reduce((def: TypesDef, key, index): TypesDef => {
isBasic def[key] = { Type: Null, index };
return def;
}, {}),
isBasic: true,
isIndexed: false
}; };
} }
return { let isBasic: boolean;
def: _def.reduce((def, key): TypesDef => { let isIndexed: boolean;
def[key] = Null; let def: TypesDef;
if (isRustEnum(_def)) {
def = Object
.entries(mapToTypeMap(registry, _def))
.reduce((def: TypesDef, [key, Type], index): TypesDef => {
def[key] = { Type, index };
return def; return def;
}, {} as TypesDef), }, {});
isBasic: true isBasic = !Object.values(def).some(({ Type }) => Type !== Null);
isIndexed = false;
} else {
def = Object
.entries(_def)
.reduce((def: TypesDef, [key, index]): TypesDef => {
def[key] = { Type: Null, index };
return def;
}, {});
isBasic = true;
isIndexed = true;
}
return {
def,
isBasic,
isIndexed
}; };
} }
function createFromValue (registry: Registry, def: TypesDef, index = 0, value?: any): Decoded { function createFromValue (registry: Registry, def: TypesDef, index = 0, value?: any): Decoded {
const Clazz = Object.values(def)[index]; const entry = Object.values(def).find((e) => e.index === index);
assert(!isUndefined(Clazz), `Unable to create Enum via index ${index}, in ${Object.keys(def).join(', ')}`); assert(!isUndefined(entry), `Unable to create Enum via index ${index}, in ${Object.keys(def).join(', ')}`);
return { return {
index, index,
value: value instanceof Clazz ? value : new Clazz(registry, value) value: value instanceof entry.Type
? value
: new entry.Type(registry, value)
}; };
} }
function decodeFromJSON (registry: Registry, def: TypesDef, key: string, value?: any): Decoded { function decodeFromJSON (registry: Registry, def: TypesDef, key: string, value?: any): Decoded {
// JSON comes in the form of { "<type (lowercased)>": "<value for type>" }, here we // JSON comes in the form of { "<type (lowercased)>": "<value for type>" }, here we
// additionally force to lower to ensure forward compat // additionally force to lower to ensure forward compat
const keys = Object.keys(def).map((k): string => k.toLowerCase()); const keys = Object.keys(def).map((k) => k.toLowerCase());
const keyLower = key.toLowerCase(); const keyLower = key.toLowerCase();
const index = keys.indexOf(keyLower); const index = keys.indexOf(keyLower);
assert(index !== -1, `Cannot map Enum JSON, unable to find '${key}' in ${keys.join(', ')}`); assert(index !== -1, `Cannot map Enum JSON, unable to find '${key}' in ${keys.join(', ')}`);
try { try {
return createFromValue(registry, def, index, value); return createFromValue(registry, def, Object.values(def)[index].index, value);
} catch (error) { } catch (error) {
throw new Error(`Enum(${key}):: ${(error as Error).message}`); throw new Error(`Enum(${key}):: ${(error as Error).message}`);
} }
@@ -79,7 +123,10 @@ function decodeFromString (registry: Registry, def: TypesDef, value: string): De
function decodeFromValue (registry: Registry, def: TypesDef, value?: any): Decoded { function decodeFromValue (registry: Registry, def: TypesDef, value?: any): Decoded {
if (isU8a(value)) { if (isU8a(value)) {
// nested, we don't want to match isObject below
if (value.length) {
return createFromValue(registry, def, value[0], value.subarray(1)); return createFromValue(registry, def, value[0], value.subarray(1));
}
} else if (isNumber(value)) { } else if (isNumber(value)) {
return createFromValue(registry, def, value); return createFromValue(registry, def, value);
} else if (isString(value)) { } else if (isString(value)) {
@@ -91,7 +138,7 @@ function decodeFromValue (registry: Registry, def: TypesDef, value?: any): Decod
} }
// Worst-case scenario, return the first with default // Worst-case scenario, return the first with default
return createFromValue(registry, def, 0); return createFromValue(registry, def, Object.values(def)[0].index);
} }
function decodeEnum (registry: Registry, def: TypesDef, value?: any, index?: number): Decoded { function decodeEnum (registry: Registry, def: TypesDef, value?: any, index?: number): Decoded {
@@ -104,7 +151,6 @@ function decodeEnum (registry: Registry, def: TypesDef, value?: any, index?: num
return createFromValue(registry, def, value.index, value.value); return createFromValue(registry, def, value.index, value.value);
} }
// Or else, we just look at `value`
return decodeFromValue(registry, def, value); return decodeFromValue(registry, def, value);
} }
@@ -122,27 +168,30 @@ export class Enum implements Codec {
readonly #def: TypesDef; readonly #def: TypesDef;
readonly #index: number; readonly #entryIndex: number;
readonly #indexes: number[]; readonly #indexes: number[];
readonly #isBasic: boolean; readonly #isBasic: boolean;
readonly #isIndexed: boolean;
readonly #raw: Codec; readonly #raw: Codec;
constructor (registry: Registry, def: Record<string, keyof InterfaceTypes | Constructor> | string[], value?: unknown, index?: number) { constructor (registry: Registry, def: Record<string, keyof InterfaceTypes | Constructor> | Record<string, number> | string[], value?: unknown, index?: number) {
const defInfo = extractDef(registry, def); const defInfo = extractDef(registry, def);
const decoded = decodeEnum(registry, defInfo.def, value, index); const decoded = decodeEnum(registry, defInfo.def, value, index);
this.registry = registry; this.registry = registry;
this.#def = defInfo.def; this.#def = defInfo.def;
this.#isBasic = defInfo.isBasic; this.#isBasic = defInfo.isBasic;
this.#indexes = Object.keys(defInfo.def).map((_, index): number => index); this.#isIndexed = defInfo.isIndexed;
this.#index = this.#indexes.indexOf(decoded.index) || 0; this.#indexes = Object.values(defInfo.def).map(({ index }) => index);
this.#entryIndex = this.#indexes.indexOf(decoded.index) || 0;
this.#raw = decoded.value; this.#raw = decoded.value;
} }
public static with (Types: Record<string, keyof InterfaceTypes | Constructor> | string[]): EnumConstructor<Enum> { public static with (Types: Record<string, keyof InterfaceTypes | Constructor> | Record<string, number> | string[]): EnumConstructor<Enum> {
return class extends Enum { return class extends Enum {
constructor (registry: Registry, value?: unknown, index?: number) { constructor (registry: Registry, value?: unknown, index?: number) {
super(registry, Types, value, index); super(registry, Types, value, index);
@@ -182,15 +231,15 @@ export class Enum implements Codec {
/** /**
* @description returns a hash of the contents * @description returns a hash of the contents
*/ */
public get hash (): H256 { public get hash (): CodecHash {
return this.registry.hash(this.toU8a()); return this.registry.hash(this.toU8a());
} }
/** /**
* @description The index of the metadata value * @description The index of the enum value
*/ */
public get index (): number { public get index (): number {
return this.#index; return this.#indexes[this.#entryIndex];
} }
/** /**
@@ -224,8 +273,8 @@ export class Enum implements Codec {
/** /**
* @description The available keys for this enum * @description The available keys for this enum
*/ */
public get defEntries (): string[] { public get defIndexes (): number[] {
return Object.keys(this.#def); return this.#indexes;
} }
/** /**
@@ -239,7 +288,7 @@ export class Enum implements Codec {
* @description The name of the type this enum value represents * @description The name of the type this enum value represents
*/ */
public get type (): string { public get type (): string {
return this.defKeys[this.#index]; return this.defKeys[this.#entryIndex];
} }
/** /**
@@ -301,16 +350,32 @@ export class Enum implements Codec {
* @description Returns the number representation for the value * @description Returns the number representation for the value
*/ */
public toNumber (): number { public toNumber (): number {
return this.#index; return this.index;
} }
/** /**
* @description Returns a raw struct representation of the enum types * @description Returns a raw struct representation of the enum types
*/ */
protected _toRawStruct (): string[] | Record<string, string> { protected _toRawStruct (): string[] | Record<string, string | number> {
return this.#isBasic if (this.#isBasic) {
? this.defKeys return this.#isIndexed
: Struct.typesToMap(this.registry, this.#def); ? this.defKeys.reduce((out: Record<string, number>, key, index): Record<string, number> => {
out[key] = this.#indexes[index];
return out;
}, {})
: this.defKeys;
}
const typeMap = Object
.entries(this.#def)
.reduce((out: Record<string, Constructor>, [key, { Type }]) => {
out[key] = Type;
return out;
}, {});
return Struct.typesToMap(this.registry, typeMap);
} }
/** /**
@@ -335,7 +400,7 @@ export class Enum implements Codec {
*/ */
public toU8a (isBare?: boolean): Uint8Array { public toU8a (isBare?: boolean): Uint8Array {
return u8aConcat( return u8aConcat(
new Uint8Array(isBare ? [] : [this.#indexes[this.#index]]), new Uint8Array(isBare ? [] : [this.index]),
this.#raw.toU8a(isBare) this.#raw.toU8a(isBare)
); );
} }
+2 -2
View File
@@ -1,7 +1,7 @@
// Copyright 2017-2021 @polkadot/types authors & contributors // Copyright 2017-2021 @polkadot/types authors & contributors
// SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: Apache-2.0
import type { H256 } from '../interfaces/runtime'; import type { CodecHash } from '../interfaces/runtime';
import type { AnyJson, Codec, Registry } from '../types'; import type { AnyJson, Codec, Registry } from '../types';
import { isFunction, isUndefined } from '@polkadot/util'; import { isFunction, isUndefined } from '@polkadot/util';
@@ -50,7 +50,7 @@ export class Json extends Map<string, any> implements Codec {
/** /**
* @description returns a hash of the contents * @description returns a hash of the contents
*/ */
public get hash (): H256 { public get hash (): CodecHash {
return this.registry.hash(this.toU8a()); return this.registry.hash(this.toU8a());
} }
+2 -2
View File
@@ -1,7 +1,7 @@
// Copyright 2017-2021 @polkadot/types authors & contributors // Copyright 2017-2021 @polkadot/types authors & contributors
// SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: Apache-2.0
import type { H256 } from '../interfaces/runtime'; import type { CodecHash } from '../interfaces/runtime';
import type { AnyJson, Codec, Constructor, InterfaceTypes, Registry } from '../types'; import type { AnyJson, Codec, Constructor, InterfaceTypes, Registry } from '../types';
import { compactFromU8a, compactToU8a, isHex, isObject, isU8a, logger, u8aConcat, u8aToHex, u8aToU8a } from '@polkadot/util'; import { compactFromU8a, compactToU8a, isHex, isObject, isU8a, logger, u8aConcat, u8aToHex, u8aToU8a } from '@polkadot/util';
@@ -119,7 +119,7 @@ export class CodecMap<K extends Codec = Codec, V extends Codec = Codec> extends
/** /**
* @description Returns a hash of the value * @description Returns a hash of the value
*/ */
public get hash (): H256 { public get hash (): CodecHash {
return this.registry.hash(this.toU8a()); return this.registry.hash(this.toU8a());
} }

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