Compare commits

..
107 Commits
Author SHA1 Message Date
github-actions[bot] e4a19dcefd [CI Skip] release/stable 9.0.1
skip-checks: true
2022-07-30 04:39:21 +00:00
Jaco 11d5a4edf0 9.0.1 (#5119) 2022-07-30 07:31:39 +03:00
github-actions[bot] 2eb901a954 [CI Skip] bump/beta 8.14.2-14-x
skip-checks: true
2022-07-29 15:36:45 +00:00
Jaco b63164d6ea Bump Substrate, Polkadot & Kusama static metadata (#5118)
* Bump Substrate, Polkadot & Kusama static metadata

* continue-on-error: true
2022-07-29 18:28:34 +03:00
github-actions[bot] c40fa16217 [CI Skip] bump/beta 8.14.2-13-x
skip-checks: true
2022-07-29 10:34:03 +00:00
Jaco afcbe96fd1 Bump common (#5117) 2022-07-29 13:25:00 +03:00
github-actions[bot] 7d53c4b45d [CI Skip] release/beta 8.14.2-12
skip-checks: true
2022-07-29 08:18:14 +00:00
Jaco 62bfcf84dd Ensure call is exposed on rx (#5116)
* Ensure call is exposed on rx

* Adjust to only top-level detection

* .123npm

* Adjust check for contractsApi
2022-07-29 11:10:05 +03:00
github-actions[bot] b2cfac4edd [CI Skip] release/beta 8.14.2-11
skip-checks: true
2022-07-29 07:23:24 +00:00
Jaco 7b2e5ed59f Publish beta to npm (#5115) 2022-07-29 10:12:55 +03:00
github-actions[bot] fdab9818d5 [CI Skip] bump/beta 8.14.2-10-x
skip-checks: true
2022-07-29 06:39:53 +00:00
Jaco 85fc0bff7d Rename alliance derive location (#5114) 2022-07-29 09:31:37 +03:00
github-actions[bot] 7a545de0c2 [CI Skip] bump/beta 8.14.2-9-x
skip-checks: true
2022-07-28 08:55:28 +00:00
Jaco b22b26d021 Support for alliance motion derives (#5113)
* Support for alliance motion derives

* allianceMotion
2022-07-28 11:46:45 +03:00
github-actions[bot] 30f72f915e [CI Skip] bump/beta 8.14.2-8-x
skip-checks: true
2022-07-26 11:06:22 +00:00
Jaco b522bc76af Upgrade blocks (#5111)
* Upgrade blocks

* CHANGELOG
2022-07-26 13:55:59 +03:00
github-actions[bot] fee3c6b1be [CI Skip] bump/beta 8.14.2-7-x
skip-checks: true
2022-07-26 06:42:45 +00:00
Jaco 79bed8eda3 Prototype static init Enum/Set/Struct (#5087)
* Prototype static init Enum/Set/Struct

* Adjust (similar, logic extracted - further local testing)

* Adjust with latest util (no prototype atm)

* Introduce prototype assignment

* Old Enum tests

* Fix toCallsOnly spread

* Adjust

* Use objectSpread in derives (decorated objects only)

* Adjust

* Remove extra map from bag get

* Additional spreads

* Signer spread

* Formatting

* typo

* Adjust spreads for session

* Additional spread

* Adjust spread

* Formatting

* CHANGELOG

* Adjust

* slice

* CHANGELOG
2022-07-26 09:34:59 +03:00
github-actions[bot] 1aae7b59bb [CI Skip] bump/beta 8.14.2-6-x
skip-checks: true
2022-07-26 06:25:24 +00:00
Jaco 2d84bac287 Remove API deprecated interfaces (#5109)
* Remove API deprecated interfaces

* Adjust checkTypes

* CHANGELOG
2022-07-26 09:17:23 +03:00
github-actions[bot] 789957b0af [CI Skip] bump/beta 8.14.2-5-x
skip-checks: true
2022-07-26 06:01:27 +00:00
Jaco d26f289199 Remove deprecated api-contract methods (#5110)
* Remove deprecated api-contract methods

* Remove checkTypes deprecated
2022-07-26 08:53:05 +03:00
github-actions[bot] 1fe06e63e5 [CI Skip] bump/beta 8.14.2-4-x
skip-checks: true
2022-07-26 04:56:00 +00:00
Jaco 3790f48e03 Specific check for storageDepositLimit support (#5108)
* Specific check for storageDepositLimit support

* Adjust asserts
2022-07-26 07:48:21 +03:00
github-actions[bot] fc5aae8a84 [CI Skip] bump/beta 8.14.2-3-x
skip-checks: true
2022-07-25 13:33:46 +00:00
Jaco 0c79e13aba Convert api-contract usage of api.rpc.* to api.call.* (#5107)
* Convert api-contract usage of api.rpc.* to api.call.*

* Cast call (augmentation not available in build)

* Revert tx check assert

* Call mock
2022-07-25 16:22:26 +03:00
github-actions[bot] 6e65bdbb5c [CI Skip] bump/beta 8.14.2-2-x
skip-checks: true
2022-07-25 11:36:02 +00:00
Jaco 95d113e03f Export api.rx.call.* (#5106)
* Export api.rx.call.*

* Adjust
2022-07-25 14:27:48 +03:00
github-actions[bot] a9a92d0bf8 [CI Skip] bump/beta 8.14.2-1-x
skip-checks: true
2022-07-25 11:25:21 +00:00
Jaco c1fb6e8218 CHANGELOG 2022-07-25 14:17:08 +03:00
github-actions[bot] 7cfc1950ae [CI Skip] bump/beta 8.14.2-0-x
skip-checks: true
2022-07-25 06:36:11 +00:00
Jaco fabf9e9160 Adjust augmentation methods (#5104) 2022-07-25 09:27:59 +03:00
github-actions[bot] a2ff40f735 [CI Skip] release/stable 8.14.1
skip-checks: true
2022-07-23 14:56:53 +00:00
Jaco 9c51ea14be 8.14.1 (#5102) 2022-07-23 17:48:54 +03:00
github-actions[bot] e3f912cef5 [CI Skip] bump/beta 8.13.2-13-x
skip-checks: true
2022-07-22 14:41:02 +00:00
Jaco 21808f0283 Auto-extract Meta* interface types based on version list (#5100)
* Auto-extract Meta* interface types based on version list

* Additional dedupe

* s/ALL_VERSIONS/KNOWN_VERSIONS/

* Restore type addition

* Additional <const> specifiers

* Handle contracts similar to metadata
2022-07-22 17:30:12 +03:00
github-actions[bot] 714380575c [CI Skip] bump/beta 8.13.2-12-x
skip-checks: true
2022-07-22 04:17:30 +00:00
Jaco ec76f2cefd Shortcut balance instances check (#5099) 2022-07-22 07:06:55 +03:00
github-actions[bot] 2121a1eea0 [CI Skip] bump/beta 8.13.2-11-x
skip-checks: true
2022-07-21 18:14:01 +00:00
Jaco c0e0346987 Fix for derive.balances.account (instances check) (#5098) 2022-07-21 21:06:02 +03:00
github-actions[bot] 9b5004df9b [CI Skip] bump/beta 8.13.2-10-x
skip-checks: true
2022-07-21 09:14:03 +00:00
Jaco dd7ad37dbf Bump Kusama metadata (#5096) 2022-07-21 12:05:19 +03:00
github-actions[bot] 92d6f6b98f [CI Skip] bump/beta 8.13.2-9-x
skip-checks: true
2022-07-21 06:03:26 +00:00
Jaco fcb317d65b Bump common (#5095) 2022-07-21 08:54:49 +03:00
github-actions[bot] b8d4b034ab [CI Skip] bump/beta 8.13.2-8-x
skip-checks: true
2022-07-21 04:27:26 +00:00
Jaco 60398d9f47 TransactionPaymentCallApi runtime definition (#5094) 2022-07-21 07:18:52 +03:00
github-actions[bot] 7a1525d3e2 [CI Skip] bump/beta 8.13.2-7-x
skip-checks: true
2022-07-20 11:02:12 +00:00
Jaco 1ee461dd59 Adjust CHANGELOG (#5091)
* Adjust CHANGELOG

* Bump deps
2022-07-20 13:51:23 +03:00
github-actions[bot] cfa15f98f7 [CI Skip] bump/beta 8.13.2-6-x
skip-checks: true
2022-07-20 09:21:26 +00:00
Jaco 18671cc650 Apply objectSpread on metadata conversion (as missing) (#5090) 2022-07-20 12:12:53 +03:00
github-actions[bot] a790e8c3ee [CI Skip] bump/beta 8.13.2-5-x
skip-checks: true
2022-07-19 18:39:45 +00:00
Nikos Kontakis bb6e16eac7 Bump substrate connect to 0.7.9 (Add CommonJS Support) (#5088)
* Bump substrate connect to 0.7.9

* Remove comment about ESM-only at bundle
2022-07-19 21:31:52 +03:00
github-actions[bot] 23e191eaf7 [CI Skip] bump/beta 8.13.2-4-x
skip-checks: true
2022-07-19 05:53:58 +00:00
Jaco cec0325820 Bump dev deps (#5084) 2022-07-19 08:44:10 +03:00
github-actions[bot] ffd8d74e3a [CI Skip] bump/beta 8.13.2-3-x
skip-checks: true
2022-07-18 11:19:15 +00:00
Jaco 91a04ad159 Add Codec toPrimitive (#5080) 2022-07-18 14:10:46 +03:00
github-actions[bot] 434f969208 [CI Skip] bump/beta 8.13.2-2-x
skip-checks: true
2022-07-18 07:42:59 +00:00
Jaco 34a5cbed90 Adjust instance check to handle Call paths (#5082) 2022-07-18 10:35:14 +03:00
github-actions[bot] 72469ae6da [CI Skip] bump/beta 8.13.2-1-x
skip-checks: true
2022-07-18 06:22:21 +00:00
Jaco 14f2a9da39 Adjust lazyVariants with internal $type (#5081)
* Adjust lazyVariants with internal $type

* Adjust

* Allow for empty paths

* Allow any $ override

* Adjust

* Small usage fixes, dedupe
2022-07-18 09:12:14 +03:00
github-actions[bot] 12750bc83d [CI Skip] bump/beta 8.13.2-0-x
skip-checks: true
2022-07-16 11:24:15 +00:00
Jaco 9a2b67aa25 Adjust CodecMap toHuman key representation (Bytes, if isAscii) (#5079)
* Adjust CodecMap toHuman key representation (Bytes, if isAscii)

* Use Raw instead of Bytes

* old typo
2022-07-16 14:16:29 +03:00
github-actions[bot] 5e891f68ca [CI Skip] release/stable 8.13.1
skip-checks: true
2022-07-16 06:19:09 +00:00
Jaco 040e8cbe94 8.13.1 (#5078) 2022-07-16 09:11:01 +03:00
github-actions[bot] 1b5a772a4a [CI Skip] bump/beta 8.12.3-18-x
skip-checks: true
2022-07-16 05:58:22 +00:00
Jaco 12d8465cf4 Update to latest Substrate, Polkadot & Kusama metadata (#5077) 2022-07-16 08:50:15 +03:00
github-actions[bot] 190f4194cc [CI Skip] bump/beta 8.12.3-17-x
skip-checks: true
2022-07-15 17:59:01 +00:00
Jaco c01a6001fc Deupe decodeU8a result format on failure (#5076) 2022-07-15 20:50:18 +03:00
github-actions[bot] c847920f86 [CI Skip] bump/beta 8.12.3-16-x
skip-checks: true
2022-07-15 15:49:36 +00:00
Jaco 67325dbc09 Additional historic DispatchError variant (#5075) 2022-07-15 18:39:59 +03:00
github-actions[bot] 63d72e7d36 [CI Skip] bump/beta 8.12.3-15-x
skip-checks: true
2022-07-15 10:04:43 +00:00
Jaco 64ddc05bc8 Support DebugRuntimeApi runtime calls (frontier) (#5073) 2022-07-15 12:57:11 +03:00
github-actions[bot] d15dec1e58 [CI Skip] bump/beta 8.12.3-14-x
skip-checks: true
2022-07-15 08:22:01 +00:00
Jaco cb283c410b Use type asserts for json imports (#5072) 2022-07-15 11:13:12 +03:00
github-actions[bot] 7c6ca42c10 [CI Skip] bump/beta 8.12.3-13-x
skip-checks: true
2022-07-15 07:15:32 +00:00
Jaco bd6ad3a2ef Asupport for NimbusApi on runtime (#5071) 2022-07-15 10:08:11 +03:00
github-actions[bot] 1a29d7950c [CI Skip] bump/beta 8.12.3-12-x
skip-checks: true
2022-07-15 06:37:43 +00:00
Jaco 7049186928 Support for NominationPoolsApi runtime (#5069)
* Support for NominationPoolsApi runtime

* CHANGELOG
2022-07-15 09:27:30 +03:00
github-actions[bot] dc34974a06 [CI Skip] bump/beta 8.12.3-11-x
skip-checks: true
2022-07-15 06:05:10 +00:00
Jaco 932e02e018 Remove old test infrastructure (#5070) 2022-07-15 08:57:17 +03:00
github-actions[bot] 6f91fbd847 [CI Skip] bump/beta 8.12.3-10-x
skip-checks: true
2022-07-14 11:37:39 +00:00
Jaco af7c4609f2 Add Kusama 9250 upgrade block (#5068) 2022-07-14 14:29:20 +03:00
github-actions[bot] 3600a4bdd7 [CI Skip] bump/beta 8.12.3-9-x
skip-checks: true
2022-07-14 11:12:10 +00:00
Jaco 3bf4e905e9 BlockBuilder 2/3/4 & GrandpaApi 2 runtime interface definitions (#5067) 2022-07-14 14:03:15 +03:00
github-actions[bot] 38984af858 [CI Skip] bump/beta 8.12.3-8-x
skip-checks: true
2022-07-13 14:07:26 +00:00
Jaco 60384ad850 Adjust blockNumber extract (w & w/o Compact) (#5066)
* Adjust blockNumber extract (w & w/o Compact)

* Adjust unused test file
2022-07-13 16:59:39 +03:00
github-actions[bot] 998f88be05 [CI Skip] bump/beta 8.12.3-7-x
skip-checks: true
2022-07-13 09:25:42 +00:00
Jaco 551a081990 Support for Moonbeam author extraction in derive.chain.* (#5065)
* Support for Moonbeam author extraction in derive.chain.*

* use unwrapOr

* Adjust logic
2022-07-13 12:18:07 +03:00
github-actions[bot] 51e6e528ce [CI Skip] bump/beta 8.12.3-6-x
skip-checks: true
2022-07-13 06:54:31 +00:00
Jaco 1f5e939b73 derive.subscribeFinalizedBlocks w/ events & author (#5064)
* derive.subscribeFinalizedBlocks w/ events & author

* Apply createdAtHash (some)

* Pass through events registry

* Throw on use
2022-07-13 09:44:47 +03:00
github-actions[bot] 3813152b46 [CI Skip] bump/beta 8.12.3-5-x
skip-checks: true
2022-07-13 05:12:42 +00:00
Jaco cfec580956 derive.chain.subscribeFinalizedHeads (#5063)
* derive.chain.subscribeFinalizedHeads

* Remove extra map
2022-07-13 08:02:49 +03:00
github-actions[bot] 859ce51eab [CI Skip] bump/beta 8.12.3-4-x
skip-checks: true
2022-07-12 05:41:05 +00:00
Jaco aa5cc1eef1 Use ReturnType<typeof setInterval> for timerIds (#5060)
* Use ReturnType<typeof setInterval> for timerIds

* Remove as number casts for clearInterval
2022-07-12 08:31:50 +03:00
Jaco 2548601c9f Bump rxjs (#5059) 2022-07-12 08:07:41 +03:00
github-actions[bot] 51ceede446 [CI Skip] bump/beta 8.12.3-3-x
skip-checks: true
2022-07-12 05:00:18 +00:00
Nikos Kontakis a16ba9f2ac Bump substrate connect to 0.7.8 (#5058) 2022-07-12 07:48:54 +03:00
github-actions[bot] 9926fcd14f [CI Skip] bump/beta 8.12.3-2-x
skip-checks: true
2022-07-11 12:53:27 +00:00
Jaco fa5ec1b4a8 Adjust assert usage in api-contract (#5057) 2022-07-11 15:43:03 +03:00
github-actions[bot] 29d9c8a279 [CI Skip] bump/beta 8.12.3-1-x
skip-checks: true
2022-07-11 11:00:34 +00:00
Jaco 6a9428943d Adjust some API assertions (#5056) 2022-07-11 13:52:48 +03:00
github-actions[bot] ea9cd6981d [CI Skip] bump/beta 8.12.3-0-x
skip-checks: true
2022-07-11 05:27:13 +00:00
Jaco c7d37c9504 Bump dev (#5053) 2022-07-11 08:19:08 +03:00
github-actions[bot] a41bc2113d [CI Skip] release/stable 8.12.2
skip-checks: true
2022-07-10 09:21:43 +00:00
Jaco e514d9b5a9 8.12.2 (#5052) 2022-07-10 12:14:17 +03:00
github-actions[bot] 3b4310a418 [CI Skip] bump/beta 8.12.2-0-x
skip-checks: true
2022-07-10 06:55:16 +00:00
Jaco 0ec32636a9 Bump common (#5051) 2022-07-10 09:47:21 +03:00
234 changed files with 4230 additions and 3503 deletions
-1
View File
@@ -1 +0,0 @@
8.12.1
-60
View File
@@ -1,60 +0,0 @@
40
1.4.2
1.6.2
1.11.2
1.12.2
1.17.2
1.31.2
2.8.2
3.2.2
3.2.3
3.3.2
3.6.2
3.6.3
3.6.4
3.7.2
3.7.3
3.9.2
3.9.3
3.10.2
4.0.2
4.0.3
4.6.2
4.7.2
4.9.2
4.11.2
4.16.2
5.3.2
5.5.2
5.8.2
5.8.3
6.0.2
6.0.3
6.0.4
6.0.5
6.1.2
6.4.2
6.5.2
6.7.2
6.9.2
6.10.2
6.10.3
7.0.2
7.14.2
7.14.3
8.0.2
8.3.2
8.4.2
8.6.2
8.8.2
8.11.2
8.11.3
+1 -2
View File
@@ -6,8 +6,7 @@ const base = require('@polkadot/dev/config/eslint.cjs');
module.exports = { module.exports = {
...base, ...base,
ignorePatterns: [ ignorePatterns: [
...base.ignorePatterns, ...base.ignorePatterns
'**/deno/*.ts'
], ],
parserOptions: { parserOptions: {
...base.parserOptions, ...base.parserOptions,
+1
View File
@@ -17,6 +17,7 @@ jobs:
deno-version: vx.x.x deno-version: vx.x.x
- name: ${{ matrix.step }} - name: ${{ matrix.step }}
if: always() if: always()
continue-on-error: true
run: | run: |
yarn install --immutable | grep -v 'YN0013' yarn install --immutable | grep -v 'YN0013'
yarn ${{ matrix.step }} yarn ${{ matrix.step }}
+1 -6
View File
@@ -1,12 +1,7 @@
_book/ _book/
build/ build/
build-cjs/ build-*/
build-esm/
build-deno/
build-docs/
coverage/ coverage/
docs/.vuepress/dist/
docs/substrate/*.md
node_modules/ node_modules/
tmp/ tmp/
/import_map.json /import_map.json
+61 -1
View File
@@ -1,5 +1,65 @@
# CHANGELOG # CHANGELOG
## 9.0.1 Jul 30, 2022
- **Breaking change** The decorated field getters on `Struct` were moved to the prototype class for performance reasons. While `struct.<field>` access still behaves in the same way, with the same results, this does mean that the prototype getters are not visible when doing an `Object.keys(struct)` or when doing an object spread.
- **Breaking change** Deprecated interfaces have been removed including `tx.sign(...)` (use `signAsync`), `Result.{is, as}Error` (use `{is, as}Err`) as well as storage `.range(...)` operations.
- **Breaking change** Deprecated interfaces on `api-contract` have been removed. Always ensure you pass an options object to construction and query methods.
- **Breaking change** Contracts access via `api-contract` will now detect the usage of `storageDepositLimit` in params, if not available the contract interfaces will not be decorated.
Changes:
- Decorate `Struct/Enum/Set` field getters on class prototypes
- Convert `api-contract` usage of `api.rpc.*` to `api.call.*`
- Drop support for contract runtimes without `storageDepositLimit` (runtime `contractsApi` only has support for latest)
- Export `api.rx.call.*` for internal usage (derive, contracts)
- Remove old-style param passing as opposed to options in `api-contract`
- Support for alliance/motion collective derives
- Add Kusama 9260 upgrade block
- Add Polkadot 9230 & 9250 upgrade blocks
- Add Westend 9251, 9260 & 9261 upgrade blocks
- Update to latest Substrate, Polkadot & Kusama metadata
## 8.14.1 Jul 23, 2022
Contributed:
- Update `@substrate/connect` with dual ESM/CJS support (Thanks to https://github.com/wirednkod)
Changes:
- `{BTree|Hash}Map.toHuman()` now display `Raw` keys as ascii (if detected)
- Add `toPrimitive()` to all base `Codec` interfaces (string/boolean/number)
- Adjust metadata conversion with `objectSpread` (where missing)
- Support for `TransactionPaymentCallApi` runtime interface
- Check `registry.getModuleInstances` against metadata paths (fallback)
- Update to `@polkadot/util` 10.1.1
- Update to latest Kusama metadata (Substrate & Polkadot are current)
## 8.13.1 Jul 16, 2022
Changes:
- Add `derive.chain.subscribeFinalized{Heads, Blocks}` which returns all finalized, no skips
- Support Moonbeam author extraction on `derive.chain.*` (w/ shared logic dedupe)
- Cater for older `BlockBuilder 2/3/4` & `GrandpaApi 2` runtime interface definitions
- Support for `NominationPoolsApi` runtime interface
- Support for `DebugRuntimeApi` runtime interface, Frontier-specific
- Support for `NimbusApi` runtime interface (& older `AuthorFilterAPI`)
- Add additional historic `DispatchError` enum variant for asset chains
- Add Kusama 9250 upgrade block
- Update to latest Substrate, Polkadot & Kusama metadata
## 8.12.2 Jul 10, 2022
Changes:
- Update to `@polkadot/util` 10.0.2
## 8.12.1 Jul 9, 2022 ## 8.12.1 Jul 9, 2022
Changes: Changes:
@@ -310,7 +370,7 @@ Changes:
- Only explicitly support LSB on `BitVec` types - Only explicitly support LSB on `BitVec` types
- Change `toHuman()` on `BitVec` to output default LSB - Change `toHuman()` on `BitVec` to output default LSB
- Add `bytes{Sent, Recv}` to provider stats - Add `bytes{Sent, Recv}` to provider stats
- Clear connection timout on provider `disconnect()` - Clear connection timeout on provider `disconnect()`
- Add support for `dev_getBlockStats` RPC - Add support for `dev_getBlockStats` RPC
+2 -2
View File
@@ -1,4 +1,4 @@
3114 Jaco 8.12.1 (#5050) 3166 Jaco 9.0.1 (#5119)
83 Amaury Martiny StatementKind: Regular and Saft (#2303) 83 Amaury Martiny StatementKind: Regular and Saft (#2303)
37 Keith Ingram Update contract types and rpc (#4541) 37 Keith Ingram Update contract types and rpc (#4541)
35 Stefanie Doll Updated child storage parameters (#1709) 35 Stefanie Doll Updated child storage parameters (#1709)
@@ -7,9 +7,9 @@
15 Jeremías Díaz feat(types): add correct tuple type to storage key (#3054) 15 Jeremías Díaz feat(types): add correct tuple type to storage key (#3054)
11 Ian He HttpProvider support clone() (#3949) 11 Ian He HttpProvider support clone() (#3949)
10 Axel Chalon Make Enum/Tuple constructor use value directly if instance (#1954) 10 Axel Chalon Make Enum/Tuple constructor use value directly if instance (#1954)
7 Nikos Kontakis Bump substrate connect to 0.7.9 (Add CommonJS Support) (#5088)
5 Chevdor Fix metadata package link (#3458) 5 Chevdor Fix metadata package link (#3458)
5 Jake Naviasky Fixing approvalFlagsToBools. (#1250) 5 Jake Naviasky Fixing approvalFlagsToBools. (#1250)
5 Nikos Kontakis Bump substrate connect to 0.7.7 (#4962)
4 Alex D Use derive customAccount and customLocks for balance overrides (#3248) 4 Alex D Use derive customAccount and customLocks for balance overrides (#3248)
4 Alex Wang fix issue that creates duplicate providers (#983) 4 Alex Wang fix issue that creates duplicate providers (#983)
4 Alexander Popiak Add asset id in signing (#4009) 4 Alexander Popiak Add asset id in signing (#4009)
+10 -6
View File
@@ -11,7 +11,11 @@
}, },
"sideEffects": false, "sideEffects": false,
"type": "module", "type": "module",
"version": "8.12.1", "version": "9.0.1",
"versions": {
"git": "9.0.1",
"npm": "9.0.1"
},
"workspaces": [ "workspaces": [
"packages/*" "packages/*"
], ],
@@ -30,12 +34,12 @@
"test:one": "NODE_OPTIONS=--experimental-vm-modules polkadot-dev-run-test --detectOpenHandles --forceExit" "test:one": "NODE_OPTIONS=--experimental-vm-modules polkadot-dev-run-test --detectOpenHandles --forceExit"
}, },
"devDependencies": { "devDependencies": {
"@babel/core": "^7.18.6", "@babel/core": "^7.18.9",
"@babel/register": "^7.18.6", "@babel/register": "^7.18.9",
"@babel/runtime": "^7.18.6", "@babel/runtime": "^7.18.9",
"@polkadot/dev": "^0.67.65", "@polkadot/dev": "^0.67.86",
"@polkadot/typegen": "workspace:packages/typegen", "@polkadot/typegen": "workspace:packages/typegen",
"@types/jest": "^28.1.4", "@types/jest": "^28.1.6",
"copyfiles": "^2.4.1" "copyfiles": "^2.4.1"
}, },
"resolutions": { "resolutions": {
+9 -9
View File
@@ -20,18 +20,18 @@
"./detectPackage.cjs" "./detectPackage.cjs"
], ],
"type": "module", "type": "module",
"version": "8.12.1", "version": "9.0.1",
"main": "index.js", "main": "index.js",
"dependencies": { "dependencies": {
"@babel/runtime": "^7.18.6", "@babel/runtime": "^7.18.9",
"@polkadot/api-base": "8.12.1", "@polkadot/api-base": "9.0.1",
"@polkadot/rpc-augment": "8.12.1", "@polkadot/rpc-augment": "9.0.1",
"@polkadot/types": "8.12.1", "@polkadot/types": "9.0.1",
"@polkadot/types-augment": "8.12.1", "@polkadot/types-augment": "9.0.1",
"@polkadot/types-codec": "8.12.1", "@polkadot/types-codec": "9.0.1",
"@polkadot/util": "^10.0.1" "@polkadot/util": "^10.1.2"
}, },
"devDependencies": { "devDependencies": {
"@polkadot/types-support": "8.12.1" "@polkadot/types-support": "9.0.1"
} }
} }
+9 -2
View File
@@ -463,13 +463,20 @@ declare module '@polkadot/api-base/types/consts' {
}; };
nominationPools: { nominationPools: {
/** /**
* The minimum pool points-to-balance ratio that must be maintained for it to be `open`. * The maximum pool points-to-balance ratio that an `open` pool can have.
*
* This is important in the event slashing takes place and the pool's points-to-balance * This is important in the event slashing takes place and the pool's points-to-balance
* ratio becomes disproportional. * ratio becomes disproportional.
*
* Moreover, this relates to the `RewardCounter` type as well, as the arithmetic operations
* are a function of number of points, and by setting this value to e.g. 10, you ensure
* that the total number of points in the system are at most 10 times the total_issuance of
* the chain, in the absolute worse case.
*
* For a value of 10, the threshold would be a pool points-to-balance ratio of 10:1. * For a value of 10, the threshold would be a pool points-to-balance ratio of 10:1.
* Such a scenario would also be the equivalent of the pool being 90% slashed. * Such a scenario would also be the equivalent of the pool being 90% slashed.
**/ **/
minPointsToBalance: u32 & AugmentedConst<ApiType>; maxPointsToBalance: u8 & AugmentedConst<ApiType>;
/** /**
* The nomination pool's pallet id. * The nomination pool's pallet id.
**/ **/
+8 -13
View File
@@ -945,6 +945,10 @@ declare module '@polkadot/api-base/types/errors' {
MetadataExceedsMaxLen: AugmentedError<ApiType>; MetadataExceedsMaxLen: AugmentedError<ApiType>;
/** /**
* The amount does not meet the minimum bond to either join or create a pool. * The amount does not meet the minimum bond to either join or create a pool.
*
* The depositor can never unbond to a value less than
* `Pallet::depositor_min_bond`. The caller does not have nominating
* permissions for the pool. Members can never unbond to a value below `MinJoinBond`.
**/ **/
MinimumBondNotMet: AugmentedError<ApiType>; MinimumBondNotMet: AugmentedError<ApiType>;
/** /**
@@ -952,10 +956,6 @@ declare module '@polkadot/api-base/types/errors' {
* other members to be permissionlessly unbonded. * other members to be permissionlessly unbonded.
**/ **/
NotDestroying: AugmentedError<ApiType>; NotDestroying: AugmentedError<ApiType>;
/**
* Not enough points. Ty unbonding less.
**/
NotEnoughPointsToUnbond: AugmentedError<ApiType>;
/** /**
* Either a) the caller cannot make a valid kick or b) the pool is not destroying. * Either a) the caller cannot make a valid kick or b) the pool is not destroying.
**/ **/
@@ -964,11 +964,6 @@ declare module '@polkadot/api-base/types/errors' {
* The caller does not have nominating permissions for the pool. * The caller does not have nominating permissions for the pool.
**/ **/
NotNominator: AugmentedError<ApiType>; NotNominator: AugmentedError<ApiType>;
/**
* The depositor must be the only member in the bonded pool in order to unbond. And the
* depositor must be the only member in the sub pools in order to withdraw unbonded.
**/
NotOnlyPoolMember: AugmentedError<ApiType>;
/** /**
* The pool is not open to join * The pool is not open to join
**/ **/
@@ -1296,14 +1291,14 @@ declare module '@polkadot/api-base/types/errors' {
* Must vote for at least one candidate. * Must vote for at least one candidate.
**/ **/
NoVotes: AugmentedError<ApiType>; NoVotes: AugmentedError<ApiType>;
/**
* Cannot report self.
**/
ReportSelf: AugmentedError<ApiType>;
/** /**
* Runner cannot re-submit candidacy. * Runner cannot re-submit candidacy.
**/ **/
RunnerUpSubmit: AugmentedError<ApiType>; RunnerUpSubmit: AugmentedError<ApiType>;
/**
* Too many candidates have been created.
**/
TooManyCandidates: AugmentedError<ApiType>;
/** /**
* Cannot vote more than candidates. * Cannot vote more than candidates.
**/ **/
+2 -2
View File
@@ -585,12 +585,12 @@ declare module '@polkadot/api-base/types/events' {
* pool. * pool.
* - `points` is the number of points that are issued as a result of `balance` being * - `points` is the number of points that are issued as a result of `balance` being
* dissolved into the corresponding unbonding pool. * dissolved into the corresponding unbonding pool.
* * - `era` is the era in which the balance will be unbonded.
* In the absence of slashing, these values will match. In the presence of slashing, the * In the absence of slashing, these values will match. In the presence of slashing, the
* number of points that are issued in the unbonding pool will be less than the amount * number of points that are issued in the unbonding pool will be less than the amount
* requested to be unbonded. * requested to be unbonded.
**/ **/
Unbonded: AugmentedEvent<ApiType, [member: AccountId32, poolId: u32, balance: u128, points: u128], { member: AccountId32, poolId: u32, balance: u128, points: u128 }>; Unbonded: AugmentedEvent<ApiType, [member: AccountId32, poolId: u32, balance: u128, points: u128, era: u32], { member: AccountId32, poolId: u32, balance: u128, points: u128, era: u32 }>;
/** /**
* The unbond pool at `era` of pool `pool_id` has been slashed to `balance`. * The unbond pool at `era` of pool `pool_id` has been slashed to `balance`.
**/ **/
-4
View File
@@ -1532,10 +1532,6 @@ declare module '@polkadot/api-base/types/storage' {
* This is basically in sync with the call to [`pallet_session::SessionManager::new_session`]. * This is basically in sync with the call to [`pallet_session::SessionManager::new_session`].
**/ **/
currentPlannedSession: AugmentedQuery<ApiType, () => Observable<u32>, []> & QueryableStorageEntry<ApiType, []>; currentPlannedSession: AugmentedQuery<ApiType, () => Observable<u32>, []> & QueryableStorageEntry<ApiType, []>;
/**
* The earliest era for which we have a pending, unapplied slash.
**/
earliestUnappliedSlash: AugmentedQuery<ApiType, () => Observable<Option<u32>>, []> & QueryableStorageEntry<ApiType, []>;
/** /**
* Rewards for the last `HISTORY_DEPTH` eras. * Rewards for the last `HISTORY_DEPTH` eras.
* If reward hasn't been set or has been removed then 0 reward is returned. * If reward hasn't been set or has been removed then 0 reward is returned.
+13 -1
View File
@@ -17,9 +17,10 @@ import type { Extrinsic } from '@polkadot/types/interfaces/extrinsics';
import type { AuthorityList, GrandpaEquivocationProof, SetId } from '@polkadot/types/interfaces/grandpa'; import type { AuthorityList, GrandpaEquivocationProof, SetId } from '@polkadot/types/interfaces/grandpa';
import type { OpaqueMetadata } from '@polkadot/types/interfaces/metadata'; import type { OpaqueMetadata } from '@polkadot/types/interfaces/metadata';
import type { MmrBatchProof, MmrEncodableOpaqueLeaf, MmrError, MmrLeafIndex, MmrProof } from '@polkadot/types/interfaces/mmr'; import type { MmrBatchProof, MmrEncodableOpaqueLeaf, MmrError, MmrLeafIndex, MmrProof } from '@polkadot/types/interfaces/mmr';
import type { NpApiError } from '@polkadot/types/interfaces/nompools';
import type { CandidateCommitments, CandidateEvent, CommittedCandidateReceipt, CoreState, GroupRotationInfo, InboundDownwardMessage, InboundHrmpMessage, OccupiedCoreAssumption, ParaId, ParaValidatorIndex, PersistedValidationData, PvfCheckStatement, ScrapedOnChainVotes, SessionInfo, ValidationCode, ValidationCodeHash, ValidatorSignature } from '@polkadot/types/interfaces/parachains'; import type { CandidateCommitments, CandidateEvent, CommittedCandidateReceipt, CoreState, GroupRotationInfo, InboundDownwardMessage, InboundHrmpMessage, OccupiedCoreAssumption, ParaId, ParaValidatorIndex, PersistedValidationData, PvfCheckStatement, ScrapedOnChainVotes, SessionInfo, ValidationCode, ValidationCodeHash, ValidatorSignature } from '@polkadot/types/interfaces/parachains';
import type { FeeDetails, RuntimeDispatchInfo } from '@polkadot/types/interfaces/payment'; import type { FeeDetails, RuntimeDispatchInfo } from '@polkadot/types/interfaces/payment';
import type { AccountId, Block, Hash, Header, Index, KeyTypeId, Slot, ValidatorId } from '@polkadot/types/interfaces/runtime'; import type { AccountId, Balance, Block, Hash, Header, Index, KeyTypeId, Slot, ValidatorId } from '@polkadot/types/interfaces/runtime';
import type { SessionIndex } from '@polkadot/types/interfaces/session'; import type { SessionIndex } from '@polkadot/types/interfaces/session';
import type { RuntimeVersion } from '@polkadot/types/interfaces/state'; import type { RuntimeVersion } from '@polkadot/types/interfaces/state';
import type { ApplyExtrinsicResult } from '@polkadot/types/interfaces/system'; import type { ApplyExtrinsicResult } from '@polkadot/types/interfaces/system';
@@ -206,6 +207,17 @@ declare module '@polkadot/api-base/types/calls' {
**/ **/
[key: string]: DecoratedCallBase<ApiType>; [key: string]: DecoratedCallBase<ApiType>;
}; };
/** 0x17a6bc0d0062aeb3/1 */
nominationPoolsApi: {
/**
* Returns the pending rewards for the given member.
**/
pendingRewards: AugmentedCall<ApiType, (member: AccountId | string | Uint8Array) => Observable<Result<Balance, NpApiError>>>;
/**
* Generic call
**/
[key: string]: DecoratedCallBase<ApiType>;
};
/** 0xf78b278be53f454c/2 */ /** 0xf78b278be53f454c/2 */
offchainWorkerApi: { offchainWorkerApi: {
/** /**
+16 -4
View File
@@ -2129,6 +2129,8 @@ declare module '@polkadot/api-base/types/submittable' {
* *
* Additional funds can come from either the free balance of the account, of from the * Additional funds can come from either the free balance of the account, of from the
* accumulated rewards, see [`BondExtra`]. * accumulated rewards, see [`BondExtra`].
*
* Bonding extra funds implies an automatic payout of all pending rewards as well.
**/ **/
bondExtra: AugmentedSubmittable<(extra: PalletNominationPoolsBondExtra | { FreeBalance: any } | { Rewards: any } | string | Uint8Array) => SubmittableExtrinsic<ApiType>, [PalletNominationPoolsBondExtra]>; bondExtra: AugmentedSubmittable<(extra: PalletNominationPoolsBondExtra | { FreeBalance: any } | { Rewards: any } | string | Uint8Array) => SubmittableExtrinsic<ApiType>, [PalletNominationPoolsBondExtra]>;
/** /**
@@ -2225,8 +2227,14 @@ declare module '@polkadot/api-base/types/submittable' {
/** /**
* Set a new state for the pool. * Set a new state for the pool.
* *
* The dispatch origin of this call must be signed by the state toggler, or the root role * If a pool is already in the `Destroying` state, then under no condition can its state
* of the pool. * change again.
*
* The dispatch origin of this call must be either:
*
* 1. signed by the state toggler, or the root role of the pool,
* 2. if the pool conditions to be open are NOT met (as described by `ok_to_be_open`), and
* then the state of the pool can be permissionlessly changed to `Destroying`.
**/ **/
setState: AugmentedSubmittable<(poolId: u32 | AnyNumber | Uint8Array, state: PalletNominationPoolsPoolState | 'Open' | 'Blocked' | 'Destroying' | number | Uint8Array) => SubmittableExtrinsic<ApiType>, [u32, PalletNominationPoolsPoolState]>; setState: AugmentedSubmittable<(poolId: u32 | AnyNumber | Uint8Array, state: PalletNominationPoolsPoolState | 'Open' | 'Blocked' | 'Destroying' | number | Uint8Array) => SubmittableExtrinsic<ApiType>, [u32, PalletNominationPoolsPoolState]>;
/** /**
@@ -2402,7 +2410,11 @@ declare module '@polkadot/api-base/types/submittable' {
* the outgoing member is slashed. * the outgoing member is slashed.
* *
* If a runner-up is available, then the best runner-up will be removed and replaces the * If a runner-up is available, then the best runner-up will be removed and replaces the
* outgoing member. Otherwise, a new phragmen election is started. * outgoing member. Otherwise, if `rerun_election` is `true`, a new phragmen election is
* started, else, nothing happens.
*
* If `slash_bond` is set to true, the bond of the member being removed is slashed. Else,
* it is returned.
* *
* The dispatch origin of this call must be root. * The dispatch origin of this call must be root.
* *
@@ -2413,7 +2425,7 @@ declare module '@polkadot/api-base/types/submittable' {
* will go into phragmen, we assume full block for now. * will go into phragmen, we assume full block for now.
* # </weight> * # </weight>
**/ **/
removeMember: AugmentedSubmittable<(who: MultiAddress | { Id: any } | { Index: any } | { Raw: any } | { Address32: any } | { Address20: any } | string | Uint8Array, hasReplacement: bool | boolean | Uint8Array) => SubmittableExtrinsic<ApiType>, [MultiAddress, bool]>; removeMember: AugmentedSubmittable<(who: MultiAddress | { Id: any } | { Index: any } | { Raw: any } | { Address32: any } | { Address20: any } | string | Uint8Array, slashBond: bool | boolean | Uint8Array, rerunElection: bool | boolean | Uint8Array) => SubmittableExtrinsic<ApiType>, [MultiAddress, bool, bool]>;
/** /**
* Remove `origin` as a voter. * Remove `origin` as a voter.
* *
+1 -1
View File
@@ -3,4 +3,4 @@
// Do not edit, auto-generated by @polkadot/dev // Do not edit, auto-generated by @polkadot/dev
export const packageInfo = { name: '@polkadot/api-augment', path: 'auto', type: 'auto', version: '8.12.1' }; export const packageInfo = { name: '@polkadot/api-augment', path: 'auto', type: 'auto', version: '9.0.1' };
+4 -4
View File
@@ -1154,14 +1154,14 @@ declare module '@polkadot/api-base/types/errors' {
* Must vote for at least one candidate. * Must vote for at least one candidate.
**/ **/
NoVotes: AugmentedError<ApiType>; NoVotes: AugmentedError<ApiType>;
/**
* Cannot report self.
**/
ReportSelf: AugmentedError<ApiType>;
/** /**
* Runner cannot re-submit candidacy. * Runner cannot re-submit candidacy.
**/ **/
RunnerUpSubmit: AugmentedError<ApiType>; RunnerUpSubmit: AugmentedError<ApiType>;
/**
* Too many candidates have been created.
**/
TooManyCandidates: AugmentedError<ApiType>;
/** /**
* Cannot vote more than candidates. * Cannot vote more than candidates.
**/ **/
@@ -1320,10 +1320,6 @@ declare module '@polkadot/api-base/types/storage' {
* This is basically in sync with the call to [`pallet_session::SessionManager::new_session`]. * This is basically in sync with the call to [`pallet_session::SessionManager::new_session`].
**/ **/
currentPlannedSession: AugmentedQuery<ApiType, () => Observable<u32>, []> & QueryableStorageEntry<ApiType, []>; currentPlannedSession: AugmentedQuery<ApiType, () => Observable<u32>, []> & QueryableStorageEntry<ApiType, []>;
/**
* The earliest era for which we have a pending, unapplied slash.
**/
earliestUnappliedSlash: AugmentedQuery<ApiType, () => Observable<Option<u32>>, []> & QueryableStorageEntry<ApiType, []>;
/** /**
* Rewards for the last `HISTORY_DEPTH` eras. * Rewards for the last `HISTORY_DEPTH` eras.
* If reward hasn't been set or has been removed then 0 reward is returned. * If reward hasn't been set or has been removed then 0 reward is returned.
+6 -2
View File
@@ -2177,7 +2177,11 @@ declare module '@polkadot/api-base/types/submittable' {
* the outgoing member is slashed. * the outgoing member is slashed.
* *
* If a runner-up is available, then the best runner-up will be removed and replaces the * If a runner-up is available, then the best runner-up will be removed and replaces the
* outgoing member. Otherwise, a new phragmen election is started. * outgoing member. Otherwise, if `rerun_election` is `true`, a new phragmen election is
* started, else, nothing happens.
*
* If `slash_bond` is set to true, the bond of the member being removed is slashed. Else,
* it is returned.
* *
* The dispatch origin of this call must be root. * The dispatch origin of this call must be root.
* *
@@ -2188,7 +2192,7 @@ declare module '@polkadot/api-base/types/submittable' {
* will go into phragmen, we assume full block for now. * will go into phragmen, we assume full block for now.
* # </weight> * # </weight>
**/ **/
removeMember: AugmentedSubmittable<(who: MultiAddress | { Id: any } | { Index: any } | { Raw: any } | { Address32: any } | { Address20: any } | string | Uint8Array, hasReplacement: bool | boolean | Uint8Array) => SubmittableExtrinsic<ApiType>, [MultiAddress, bool]>; removeMember: AugmentedSubmittable<(who: MultiAddress | { Id: any } | { Index: any } | { Raw: any } | { Address32: any } | { Address20: any } | string | Uint8Array, slashBond: bool | boolean | Uint8Array, rerunElection: bool | boolean | Uint8Array) => SubmittableExtrinsic<ApiType>, [MultiAddress, bool, bool]>;
/** /**
* Remove `origin` as a voter. * Remove `origin` as a voter.
* *
+9 -2
View File
@@ -683,13 +683,20 @@ declare module '@polkadot/api-base/types/consts' {
}; };
nominationPools: { nominationPools: {
/** /**
* The minimum pool points-to-balance ratio that must be maintained for it to be `open`. * The maximum pool points-to-balance ratio that an `open` pool can have.
*
* This is important in the event slashing takes place and the pool's points-to-balance * This is important in the event slashing takes place and the pool's points-to-balance
* ratio becomes disproportional. * ratio becomes disproportional.
*
* Moreover, this relates to the `RewardCounter` type as well, as the arithmetic operations
* are a function of number of points, and by setting this value to e.g. 10, you ensure
* that the total number of points in the system are at most 10 times the total_issuance of
* the chain, in the absolute worse case.
*
* For a value of 10, the threshold would be a pool points-to-balance ratio of 10:1. * For a value of 10, the threshold would be a pool points-to-balance ratio of 10:1.
* Such a scenario would also be the equivalent of the pool being 90% slashed. * Such a scenario would also be the equivalent of the pool being 90% slashed.
**/ **/
minPointsToBalance: u32 & AugmentedConst<ApiType>; maxPointsToBalance: u8 & AugmentedConst<ApiType>;
/** /**
* The nomination pool's pallet id. * The nomination pool's pallet id.
**/ **/
+28 -17
View File
@@ -17,6 +17,14 @@ declare module '@polkadot/api-base/types/errors' {
* nominated. * nominated.
**/ **/
AccountNonGrata: AugmentedError<ApiType>; AccountNonGrata: AugmentedError<ApiType>;
/**
* The founders/fellows/allies have already been initialized.
**/
AllianceAlreadyInitialized: AugmentedError<ApiType>;
/**
* The Alliance has not been initialized yet, therefore accounts cannot join it.
**/
AllianceNotYetInitialized: AugmentedError<ApiType>;
/** /**
* Account is already an elevated (fellow) member. * Account is already an elevated (fellow) member.
**/ **/
@@ -33,10 +41,6 @@ declare module '@polkadot/api-base/types/errors' {
* Balance is insufficient for the required deposit. * Balance is insufficient for the required deposit.
**/ **/
InsufficientFunds: AugmentedError<ApiType>; InsufficientFunds: AugmentedError<ApiType>;
/**
* The founders/fellows/allies have already been initialized.
**/
MembersAlreadyInitialized: AugmentedError<ApiType>;
/** /**
* The announcement is not found. * The announcement is not found.
**/ **/
@@ -855,14 +859,14 @@ declare module '@polkadot/api-base/types/errors' {
* Must vote for at least one candidate. * Must vote for at least one candidate.
**/ **/
NoVotes: AugmentedError<ApiType>; NoVotes: AugmentedError<ApiType>;
/**
* Cannot report self.
**/
ReportSelf: AugmentedError<ApiType>;
/** /**
* Runner cannot re-submit candidacy. * Runner cannot re-submit candidacy.
**/ **/
RunnerUpSubmit: AugmentedError<ApiType>; RunnerUpSubmit: AugmentedError<ApiType>;
/**
* Too many candidates have been created.
**/
TooManyCandidates: AugmentedError<ApiType>;
/** /**
* Cannot vote more than candidates. * Cannot vote more than candidates.
**/ **/
@@ -1207,6 +1211,10 @@ declare module '@polkadot/api-base/types/errors' {
MetadataExceedsMaxLen: AugmentedError<ApiType>; MetadataExceedsMaxLen: AugmentedError<ApiType>;
/** /**
* The amount does not meet the minimum bond to either join or create a pool. * The amount does not meet the minimum bond to either join or create a pool.
*
* The depositor can never unbond to a value less than
* `Pallet::depositor_min_bond`. The caller does not have nominating
* permissions for the pool. Members can never unbond to a value below `MinJoinBond`.
**/ **/
MinimumBondNotMet: AugmentedError<ApiType>; MinimumBondNotMet: AugmentedError<ApiType>;
/** /**
@@ -1214,10 +1222,6 @@ declare module '@polkadot/api-base/types/errors' {
* other members to be permissionlessly unbonded. * other members to be permissionlessly unbonded.
**/ **/
NotDestroying: AugmentedError<ApiType>; NotDestroying: AugmentedError<ApiType>;
/**
* Not enough points. Ty unbonding less.
**/
NotEnoughPointsToUnbond: AugmentedError<ApiType>;
/** /**
* Either a) the caller cannot make a valid kick or b) the pool is not destroying. * Either a) the caller cannot make a valid kick or b) the pool is not destroying.
**/ **/
@@ -1226,11 +1230,6 @@ declare module '@polkadot/api-base/types/errors' {
* The caller does not have nominating permissions for the pool. * The caller does not have nominating permissions for the pool.
**/ **/
NotNominator: AugmentedError<ApiType>; NotNominator: AugmentedError<ApiType>;
/**
* The depositor must be the only member in the bonded pool in order to unbond. And the
* depositor must be the only member in the sub pools in order to withdraw unbonded.
**/
NotOnlyPoolMember: AugmentedError<ApiType>;
/** /**
* The pool is not open to join * The pool is not open to join
**/ **/
@@ -2058,6 +2057,10 @@ declare module '@polkadot/api-base/types/errors' {
* Invalid witness data given. * Invalid witness data given.
**/ **/
BadWitness: AugmentedError<ApiType>; BadWitness: AugmentedError<ApiType>;
/**
* The provided bid is too low.
**/
BidTooLow: AugmentedError<ApiType>;
/** /**
* The item or collection is frozen. * The item or collection is frozen.
**/ **/
@@ -2090,6 +2093,10 @@ declare module '@polkadot/api-base/types/errors' {
* The signing account has no permission to do the operation. * The signing account has no permission to do the operation.
**/ **/
NoPermission: AugmentedError<ApiType>; NoPermission: AugmentedError<ApiType>;
/**
* Item is not for sale.
**/
NotForSale: AugmentedError<ApiType>;
/** /**
* The named owner has not signed ownership of the collection is acceptable. * The named owner has not signed ownership of the collection is acceptable.
**/ **/
@@ -2102,6 +2109,10 @@ declare module '@polkadot/api-base/types/errors' {
* The given item ID is unknown. * The given item ID is unknown.
**/ **/
UnknownCollection: AugmentedError<ApiType>; UnknownCollection: AugmentedError<ApiType>;
/**
* The given item ID is unknown.
**/
UnknownItem: AugmentedError<ApiType>;
/** /**
* The delegate turned out to be different to what was expected. * The delegate turned out to be different to what was expected.
**/ **/
+14 -2
View File
@@ -755,12 +755,12 @@ declare module '@polkadot/api-base/types/events' {
* pool. * pool.
* - `points` is the number of points that are issued as a result of `balance` being * - `points` is the number of points that are issued as a result of `balance` being
* dissolved into the corresponding unbonding pool. * dissolved into the corresponding unbonding pool.
* * - `era` is the era in which the balance will be unbonded.
* In the absence of slashing, these values will match. In the presence of slashing, the * In the absence of slashing, these values will match. In the presence of slashing, the
* number of points that are issued in the unbonding pool will be less than the amount * number of points that are issued in the unbonding pool will be less than the amount
* requested to be unbonded. * requested to be unbonded.
**/ **/
Unbonded: AugmentedEvent<ApiType, [member: AccountId32, poolId: u32, balance: u128, points: u128], { member: AccountId32, poolId: u32, balance: u128, points: u128 }>; Unbonded: AugmentedEvent<ApiType, [member: AccountId32, poolId: u32, balance: u128, points: u128, era: u32], { member: AccountId32, poolId: u32, balance: u128, points: u128, era: u32 }>;
/** /**
* The unbond pool at `era` of pool `pool_id` has been slashed to `balance`. * The unbond pool at `era` of pool `pool_id` has been slashed to `balance`.
**/ **/
@@ -1469,6 +1469,18 @@ declare module '@polkadot/api-base/types/events' {
* An `item` was issued. * An `item` was issued.
**/ **/
Issued: AugmentedEvent<ApiType, [collection: u32, item: u32, owner: AccountId32], { collection: u32, item: u32, owner: AccountId32 }>; Issued: AugmentedEvent<ApiType, [collection: u32, item: u32, owner: AccountId32], { collection: u32, item: u32, owner: AccountId32 }>;
/**
* An item was bought.
**/
ItemBought: AugmentedEvent<ApiType, [collection: u32, item: u32, price: u128, seller: AccountId32, buyer: AccountId32], { collection: u32, item: u32, price: u128, seller: AccountId32, buyer: AccountId32 }>;
/**
* The price for the instance was removed.
**/
ItemPriceRemoved: AugmentedEvent<ApiType, [collection: u32, item: u32], { collection: u32, item: u32 }>;
/**
* The price was set for the instance.
**/
ItemPriceSet: AugmentedEvent<ApiType, [collection: u32, item: u32, price: u128, whitelistedBuyer: Option<AccountId32>], { collection: u32, item: u32, price: u128, whitelistedBuyer: Option<AccountId32> }>;
/** /**
* A `collection` has had its attributes changed by the `Force` origin. * A `collection` has had its attributes changed by the `Force` origin.
**/ **/
+4 -4
View File
@@ -1295,10 +1295,6 @@ declare module '@polkadot/api-base/types/storage' {
* This is basically in sync with the call to [`pallet_session::SessionManager::new_session`]. * This is basically in sync with the call to [`pallet_session::SessionManager::new_session`].
**/ **/
currentPlannedSession: AugmentedQuery<ApiType, () => Observable<u32>, []> & QueryableStorageEntry<ApiType, []>; currentPlannedSession: AugmentedQuery<ApiType, () => Observable<u32>, []> & QueryableStorageEntry<ApiType, []>;
/**
* The earliest era for which we have a pending, unapplied slash.
**/
earliestUnappliedSlash: AugmentedQuery<ApiType, () => Observable<Option<u32>>, []> & QueryableStorageEntry<ApiType, []>;
/** /**
* Rewards for the last `HISTORY_DEPTH` eras. * Rewards for the last `HISTORY_DEPTH` eras.
* If reward hasn't been set or has been removed then 0 reward is returned. * If reward hasn't been set or has been removed then 0 reward is returned.
@@ -1779,6 +1775,10 @@ declare module '@polkadot/api-base/types/storage' {
* Metadata of an item. * Metadata of an item.
**/ **/
instanceMetadataOf: AugmentedQuery<ApiType, (arg1: u32 | AnyNumber | Uint8Array, arg2: u32 | AnyNumber | Uint8Array) => Observable<Option<PalletUniquesItemMetadata>>, [u32, u32]> & QueryableStorageEntry<ApiType, [u32, u32]>; instanceMetadataOf: AugmentedQuery<ApiType, (arg1: u32 | AnyNumber | Uint8Array, arg2: u32 | AnyNumber | Uint8Array) => Observable<Option<PalletUniquesItemMetadata>>, [u32, u32]> & QueryableStorageEntry<ApiType, [u32, u32]>;
/**
* Price of an asset instance.
**/
itemPriceOf: AugmentedQuery<ApiType, (arg1: u32 | AnyNumber | Uint8Array, arg2: u32 | AnyNumber | Uint8Array) => Observable<Option<ITuple<[u128, Option<AccountId32>]>>>, [u32, u32]> & QueryableStorageEntry<ApiType, [u32, u32]>;
/** /**
* The collection, if any, of which an account is willing to take ownership. * The collection, if any, of which an account is willing to take ownership.
**/ **/
@@ -17,6 +17,7 @@ import type { Extrinsic } from '@polkadot/types/interfaces/extrinsics';
import type { AuthorityList, GrandpaEquivocationProof, SetId } from '@polkadot/types/interfaces/grandpa'; import type { AuthorityList, GrandpaEquivocationProof, SetId } from '@polkadot/types/interfaces/grandpa';
import type { OpaqueMetadata } from '@polkadot/types/interfaces/metadata'; import type { OpaqueMetadata } from '@polkadot/types/interfaces/metadata';
import type { MmrBatchProof, MmrEncodableOpaqueLeaf, MmrError, MmrLeafIndex, MmrProof } from '@polkadot/types/interfaces/mmr'; import type { MmrBatchProof, MmrEncodableOpaqueLeaf, MmrError, MmrLeafIndex, MmrProof } from '@polkadot/types/interfaces/mmr';
import type { NpApiError } from '@polkadot/types/interfaces/nompools';
import type { FeeDetails, RuntimeDispatchInfo } from '@polkadot/types/interfaces/payment'; import type { FeeDetails, RuntimeDispatchInfo } from '@polkadot/types/interfaces/payment';
import type { AccountId, Balance, Block, Hash, Header, Index, KeyTypeId, Slot } from '@polkadot/types/interfaces/runtime'; import type { AccountId, Balance, Block, Hash, Header, Index, KeyTypeId, Slot } from '@polkadot/types/interfaces/runtime';
import type { RuntimeVersion } from '@polkadot/types/interfaces/state'; import type { RuntimeVersion } from '@polkadot/types/interfaces/state';
@@ -216,6 +217,17 @@ declare module '@polkadot/api-base/types/calls' {
**/ **/
[key: string]: DecoratedCallBase<ApiType>; [key: string]: DecoratedCallBase<ApiType>;
}; };
/** 0x17a6bc0d0062aeb3/1 */
nominationPoolsApi: {
/**
* Returns the pending rewards for the given member.
**/
pendingRewards: AugmentedCall<ApiType, (member: AccountId | string | Uint8Array) => Observable<Result<Balance, NpApiError>>>;
/**
* Generic call
**/
[key: string]: DecoratedCallBase<ApiType>;
};
/** 0xf78b278be53f454c/2 */ /** 0xf78b278be53f454c/2 */
offchainWorkerApi: { offchainWorkerApi: {
/** /**
+42 -4
View File
@@ -1937,7 +1937,11 @@ declare module '@polkadot/api-base/types/submittable' {
* the outgoing member is slashed. * the outgoing member is slashed.
* *
* If a runner-up is available, then the best runner-up will be removed and replaces the * If a runner-up is available, then the best runner-up will be removed and replaces the
* outgoing member. Otherwise, a new phragmen election is started. * outgoing member. Otherwise, if `rerun_election` is `true`, a new phragmen election is
* started, else, nothing happens.
*
* If `slash_bond` is set to true, the bond of the member being removed is slashed. Else,
* it is returned.
* *
* The dispatch origin of this call must be root. * The dispatch origin of this call must be root.
* *
@@ -1948,7 +1952,7 @@ declare module '@polkadot/api-base/types/submittable' {
* will go into phragmen, we assume full block for now. * will go into phragmen, we assume full block for now.
* # </weight> * # </weight>
**/ **/
removeMember: AugmentedSubmittable<(who: MultiAddress | { Id: any } | { Index: any } | { Raw: any } | { Address32: any } | { Address20: any } | string | Uint8Array, hasReplacement: bool | boolean | Uint8Array) => SubmittableExtrinsic<ApiType>, [MultiAddress, bool]>; removeMember: AugmentedSubmittable<(who: MultiAddress | { Id: any } | { Index: any } | { Raw: any } | { Address32: any } | { Address20: any } | string | Uint8Array, slashBond: bool | boolean | Uint8Array, rerunElection: bool | boolean | Uint8Array) => SubmittableExtrinsic<ApiType>, [MultiAddress, bool, bool]>;
/** /**
* Remove `origin` as a voter. * Remove `origin` as a voter.
* *
@@ -2714,6 +2718,8 @@ declare module '@polkadot/api-base/types/submittable' {
* *
* Additional funds can come from either the free balance of the account, of from the * Additional funds can come from either the free balance of the account, of from the
* accumulated rewards, see [`BondExtra`]. * accumulated rewards, see [`BondExtra`].
*
* Bonding extra funds implies an automatic payout of all pending rewards as well.
**/ **/
bondExtra: AugmentedSubmittable<(extra: PalletNominationPoolsBondExtra | { FreeBalance: any } | { Rewards: any } | string | Uint8Array) => SubmittableExtrinsic<ApiType>, [PalletNominationPoolsBondExtra]>; bondExtra: AugmentedSubmittable<(extra: PalletNominationPoolsBondExtra | { FreeBalance: any } | { Rewards: any } | string | Uint8Array) => SubmittableExtrinsic<ApiType>, [PalletNominationPoolsBondExtra]>;
/** /**
@@ -2810,8 +2816,14 @@ declare module '@polkadot/api-base/types/submittable' {
/** /**
* Set a new state for the pool. * Set a new state for the pool.
* *
* The dispatch origin of this call must be signed by the state toggler, or the root role * If a pool is already in the `Destroying` state, then under no condition can its state
* of the pool. * change again.
*
* The dispatch origin of this call must be either:
*
* 1. signed by the state toggler, or the root role of the pool,
* 2. if the pool conditions to be open are NOT met (as described by `ok_to_be_open`), and
* then the state of the pool can be permissionlessly changed to `Destroying`.
**/ **/
setState: AugmentedSubmittable<(poolId: u32 | AnyNumber | Uint8Array, state: PalletNominationPoolsPoolState | 'Open' | 'Blocked' | 'Destroying' | number | Uint8Array) => SubmittableExtrinsic<ApiType>, [u32, PalletNominationPoolsPoolState]>; setState: AugmentedSubmittable<(poolId: u32 | AnyNumber | Uint8Array, state: PalletNominationPoolsPoolState | 'Open' | 'Blocked' | 'Destroying' | number | Uint8Array) => SubmittableExtrinsic<ApiType>, [u32, PalletNominationPoolsPoolState]>;
/** /**
@@ -4983,6 +4995,18 @@ declare module '@polkadot/api-base/types/submittable' {
* Modes: `check_owner.is_some()`. * Modes: `check_owner.is_some()`.
**/ **/
burn: AugmentedSubmittable<(collection: u32 | AnyNumber | Uint8Array, item: u32 | AnyNumber | Uint8Array, checkOwner: Option<MultiAddress> | null | Uint8Array | MultiAddress | { Id: any } | { Index: any } | { Raw: any } | { Address32: any } | { Address20: any } | string) => SubmittableExtrinsic<ApiType>, [u32, u32, Option<MultiAddress>]>; burn: AugmentedSubmittable<(collection: u32 | AnyNumber | Uint8Array, item: u32 | AnyNumber | Uint8Array, checkOwner: Option<MultiAddress> | null | Uint8Array | MultiAddress | { Id: any } | { Index: any } | { Raw: any } | { Address32: any } | { Address20: any } | string) => SubmittableExtrinsic<ApiType>, [u32, u32, Option<MultiAddress>]>;
/**
* Allows to buy an item if it's up for sale.
*
* Origin must be Signed and must not be the owner of the `item`.
*
* - `collection`: The collection of the item.
* - `item`: The item the sender wants to buy.
* - `bid_price`: The price the sender is willing to pay.
*
* Emits `ItemBought` on success.
**/
buyItem: AugmentedSubmittable<(collection: u32 | AnyNumber | Uint8Array, item: u32 | AnyNumber | Uint8Array, bidPrice: u128 | AnyNumber | Uint8Array) => SubmittableExtrinsic<ApiType>, [u32, u32, u128]>;
/** /**
* Cancel the prior approval for the transfer of an item by a delegate. * Cancel the prior approval for the transfer of an item by a delegate.
* *
@@ -5271,6 +5295,20 @@ declare module '@polkadot/api-base/types/submittable' {
* Weight: `O(1)` * Weight: `O(1)`
**/ **/
setMetadata: AugmentedSubmittable<(collection: u32 | AnyNumber | Uint8Array, item: u32 | AnyNumber | Uint8Array, data: Bytes | string | Uint8Array, isFrozen: bool | boolean | Uint8Array) => SubmittableExtrinsic<ApiType>, [u32, u32, Bytes, bool]>; setMetadata: AugmentedSubmittable<(collection: u32 | AnyNumber | Uint8Array, item: u32 | AnyNumber | Uint8Array, data: Bytes | string | Uint8Array, isFrozen: bool | boolean | Uint8Array) => SubmittableExtrinsic<ApiType>, [u32, u32, Bytes, bool]>;
/**
* Set (or reset) the price for an item.
*
* Origin must be Signed and must be the owner of the asset `item`.
*
* - `collection`: The collection of the item.
* - `item`: The item to set the price for.
* - `price`: The price for the item. Pass `None`, to reset the price.
* - `buyer`: Restricts the buy operation to a specific account.
*
* Emits `ItemPriceSet` on success if the price is not `None`.
* Emits `ItemPriceRemoved` on success if the price is `None`.
**/
setPrice: AugmentedSubmittable<(collection: u32 | AnyNumber | Uint8Array, item: u32 | AnyNumber | Uint8Array, price: Option<u128> | null | Uint8Array | u128 | AnyNumber, whitelistedBuyer: Option<MultiAddress> | null | Uint8Array | MultiAddress | { Id: any } | { Index: any } | { Raw: any } | { Address32: any } | { Address20: any } | string) => SubmittableExtrinsic<ApiType>, [u32, u32, Option<u128>, Option<MultiAddress>]>;
/** /**
* Change the Issuer, Admin and Freezer of a collection. * Change the Issuer, Admin and Freezer of a collection.
* *
+6 -6
View File
@@ -20,13 +20,13 @@
"./detectPackage.cjs" "./detectPackage.cjs"
], ],
"type": "module", "type": "module",
"version": "8.12.1", "version": "9.0.1",
"main": "index.js", "main": "index.js",
"dependencies": { "dependencies": {
"@babel/runtime": "^7.18.6", "@babel/runtime": "^7.18.9",
"@polkadot/rpc-core": "8.12.1", "@polkadot/rpc-core": "9.0.1",
"@polkadot/types": "8.12.1", "@polkadot/types": "9.0.1",
"@polkadot/util": "^10.0.1", "@polkadot/util": "^10.1.2",
"rxjs": "^7.5.5" "rxjs": "^7.5.6"
} }
} }
+1 -1
View File
@@ -3,4 +3,4 @@
// Do not edit, auto-generated by @polkadot/dev // Do not edit, auto-generated by @polkadot/dev
export const packageInfo = { name: '@polkadot/api-base', path: 'auto', type: 'auto', version: '8.12.1' }; export const packageInfo = { name: '@polkadot/api-base', path: 'auto', type: 'auto', version: '9.0.1' };
+2 -1
View File
@@ -2,7 +2,7 @@
// SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: Apache-2.0
import type { Observable } from 'rxjs'; import type { Observable } from 'rxjs';
import type { DecoratedRpc, QueryableConsts, QueryableStorage, QueryableStorageMulti, SubmittableExtrinsics } from '@polkadot/api-base/types'; import type { DecoratedRpc, QueryableCalls, QueryableConsts, QueryableStorage, QueryableStorageMulti, SubmittableExtrinsics } from '@polkadot/api-base/types';
import type { RpcInterface } from '@polkadot/rpc-core/types'; import type { RpcInterface } from '@polkadot/rpc-core/types';
import type { Metadata } from '@polkadot/types'; import type { Metadata } from '@polkadot/types';
import type { Hash, RuntimeVersion } from '@polkadot/types/interfaces'; import type { Hash, RuntimeVersion } from '@polkadot/types/interfaces';
@@ -10,6 +10,7 @@ import type { Registry, Signer } from '@polkadot/types/types';
// A smaller interface of ApiRx, used in derive and in SubmittableExtrinsic // A smaller interface of ApiRx, used in derive and in SubmittableExtrinsic
export interface ApiInterfaceRx { export interface ApiInterfaceRx {
call: QueryableCalls<'rxjs'>,
consts: QueryableConsts<'rxjs'>; consts: QueryableConsts<'rxjs'>;
extrinsicType: number; extrinsicType: number;
genesisHash?: Hash; genesisHash?: Hash;
-4
View File
@@ -58,10 +58,6 @@ export interface StorageEntryBase<ApiType extends ApiTypes, F extends AnyFunctio
* @deprecated Use api.at(<blockHash>) * @deprecated Use api.at(<blockHash>)
*/ */
keysAt: <K extends AnyTuple = A> (hash: Hash | Uint8Array | string, ...args: DropLast<Parameters<F>>) => PromiseOrObs<ApiType, StorageKey<K>[]>; keysAt: <K extends AnyTuple = A> (hash: Hash | Uint8Array | string, ...args: DropLast<Parameters<F>>) => PromiseOrObs<ApiType, StorageKey<K>[]>;
/**
* @deprecated The underlying RPC this been marked unsafe and is generally not exposed
*/
range: <T extends Codec | any = ReturnCodec<F>>([from, to]: [Hash | Uint8Array | string, Hash | Uint8Array | string | undefined] | [Hash | Uint8Array | string], ...args: Parameters<F>) => PromiseOrObs<ApiType, [Hash, T][]>;
/** /**
* @deprecated Use api.at(<blockHash>) * @deprecated Use api.at(<blockHash>)
*/ */
@@ -58,11 +58,6 @@ export interface SubmittableExtrinsic<ApiType extends ApiTypes, R extends ISubmi
send (statusCb: Callback<R>): SubmittableResultSubscription<ApiType, R>; send (statusCb: Callback<R>): SubmittableResultSubscription<ApiType, R>;
/**
* @deprecated
*/
sign (account: IKeyringPair, _options?: Partial<SignerOptions>): this;
signAsync (account: AddressOrPair, _options?: Partial<SignerOptions>): PromiseOrObs<ApiType, this>; signAsync (account: AddressOrPair, _options?: Partial<SignerOptions>): PromiseOrObs<ApiType, this>;
signAndSend (account: AddressOrPair, options?: Partial<SignerOptions>): SubmittableResultResult<ApiType, R>; signAndSend (account: AddressOrPair, options?: Partial<SignerOptions>): SubmittableResultResult<ApiType, R>;
+11 -11
View File
@@ -20,20 +20,20 @@
"./detectPackage.cjs" "./detectPackage.cjs"
], ],
"type": "module", "type": "module",
"version": "8.12.1", "version": "9.0.1",
"main": "index.js", "main": "index.js",
"dependencies": { "dependencies": {
"@babel/runtime": "^7.18.6", "@babel/runtime": "^7.18.9",
"@polkadot/api": "8.12.1", "@polkadot/api": "9.0.1",
"@polkadot/types": "8.12.1", "@polkadot/types": "9.0.1",
"@polkadot/types-codec": "8.12.1", "@polkadot/types-codec": "9.0.1",
"@polkadot/types-create": "8.12.1", "@polkadot/types-create": "9.0.1",
"@polkadot/util": "^10.0.1", "@polkadot/util": "^10.1.2",
"@polkadot/util-crypto": "^10.0.1", "@polkadot/util-crypto": "^10.1.2",
"rxjs": "^7.5.5" "rxjs": "^7.5.6"
}, },
"devDependencies": { "devDependencies": {
"@polkadot/api-augment": "8.12.1", "@polkadot/api-augment": "9.0.1",
"@polkadot/keyring": "^10.0.1" "@polkadot/keyring": "^10.1.2"
} }
} }
+16 -6
View File
@@ -8,7 +8,7 @@ import type { AbiConstructor, AbiEvent, AbiMessage, AbiParam, DecodedEvent, Deco
import { TypeRegistry } from '@polkadot/types'; import { TypeRegistry } from '@polkadot/types';
import { TypeDefInfo } from '@polkadot/types-create'; import { TypeDefInfo } from '@polkadot/types-create';
import { assert, assertReturn, compactAddLength, compactStripLength, isNumber, isObject, isString, logger, stringCamelCase, stringify, u8aConcat, u8aToHex } from '@polkadot/util'; import { assertReturn, compactAddLength, compactStripLength, isNumber, isObject, isString, logger, stringCamelCase, stringify, u8aConcat, u8aToHex } from '@polkadot/util';
import { convertVersions, enumVersions } from './toLatest'; import { convertVersions, enumVersions } from './toLatest';
@@ -35,7 +35,9 @@ function getLatestMeta (registry: Registry, json: Record<string, unknown>): Cont
) as unknown as ContractMetadata; ) as unknown as ContractMetadata;
const converter = convertVersions.find(([v]) => metadata[`is${v}`]); const converter = convertVersions.find(([v]) => metadata[`is${v}`]);
assert(converter, () => `Unable to convert ABI with version ${metadata.type} to latest`); if (!converter) {
throw new Error(`Unable to convert ABI with version ${metadata.type} to latest`);
}
return converter[1](registry, metadata[`as${converter[0]}`]); return converter[1](registry, metadata[`as${converter[0]}`]);
} }
@@ -112,7 +114,9 @@ export class Abi {
const index = data[0]; const index = data[0];
const event = this.events[index]; const event = this.events[index];
assert(event, () => `Unable to find event with index ${index}`); if (!event) {
throw new Error(`Unable to find event with index ${index}`);
}
return event.fromU8a(data.subarray(1)); return event.fromU8a(data.subarray(1));
} }
@@ -142,7 +146,9 @@ export class Abi {
#createArgs = (args: ContractMessageParamSpecLatest[], spec: unknown): AbiParam[] => { #createArgs = (args: ContractMessageParamSpecLatest[], spec: unknown): AbiParam[] => {
return args.map(({ label, type }, index): AbiParam => { return args.map(({ label, type }, index): AbiParam => {
try { try {
assert(isObject(type), 'Invalid type definition found'); if (!isObject(type)) {
throw new Error('Invalid type definition found');
}
const displayName = type.displayName.length const displayName = type.displayName.length
? type.displayName[type.displayName.length - 1].toString() ? type.displayName[type.displayName.length - 1].toString()
@@ -233,13 +239,17 @@ export class Abi {
const selector = trimmed.subarray(0, 4); const selector = trimmed.subarray(0, 4);
const message = list.find((m) => m.selector.eq(selector)); const message = list.find((m) => m.selector.eq(selector));
assert(message, `Unable to find ${type} with selector ${u8aToHex(selector)}`); if (!message) {
throw new Error(`Unable to find ${type} with selector ${u8aToHex(selector)}`);
}
return message.fromU8a(trimmed.subarray(4)); return message.fromU8a(trimmed.subarray(4));
}; };
#encodeArgs = ({ label, selector }: ContractMessageSpecLatest | ContractConstructorSpecLatest, args: AbiParam[], data: unknown[]): Uint8Array => { #encodeArgs = ({ label, selector }: ContractMessageSpecLatest | ContractConstructorSpecLatest, args: AbiParam[], data: unknown[]): Uint8Array => {
assert(data.length === args.length, () => `Expected ${args.length} arguments to contract message '${label.toString()}', found ${data.length}`); if (data.length !== args.length) {
throw new Error(`Expected ${args.length} arguments to contract message '${label.toString()}', found ${data.length}`);
}
return compactAddLength( return compactAddLength(
u8aConcat( u8aConcat(
+5 -5
View File
@@ -8,7 +8,11 @@ import { v0ToV1 } from './toV1';
import { v1ToV2 } from './toV2'; import { v1ToV2 } from './toV2';
import { v2ToV3 } from './toV3'; import { v2ToV3 } from './toV3';
type Versions = 'V3' | 'V2' | 'V1' | 'V0'; // The versions where an enum is used, aka V0 is missing
// (Order from newest, i.e. we expect more on newest vs oldest)
export const enumVersions = <const> ['V3', 'V2', 'V1'];
type Versions = typeof enumVersions[number] | 'V0';
type Converter = (registry: Registry, vx: any) => ContractMetadataLatest; type Converter = (registry: Registry, vx: any) => ContractMetadataLatest;
@@ -26,10 +30,6 @@ export const v2ToLatest = createConverter(v3ToLatest, v2ToV3);
export const v1ToLatest = createConverter(v2ToLatest, v1ToV2); export const v1ToLatest = createConverter(v2ToLatest, v1ToV2);
export const v0ToLatest = createConverter(v1ToLatest, v0ToV1); export const v0ToLatest = createConverter(v1ToLatest, v0ToV1);
// The versions where an enum is used, aka V0 is missing
// (Order from newest, i.e. we expect more on newest vs oldest)
export const enumVersions = ['V3', 'V2', 'V1'];
export const convertVersions: [Versions, Converter][] = [ export const convertVersions: [Versions, Converter][] = [
['V3', v3ToLatest], ['V3', v3ToLatest],
['V2', v2ToLatest], ['V2', v2ToLatest],
+1 -1
View File
@@ -23,7 +23,7 @@ interface ArgsEntry <T extends WithArgs> extends NamedEntry {
args: GetArgsType<T>['args'][0][]; args: GetArgsType<T>['args'][0][];
} }
const ARG_TYPES = { const ARG_TYPES = <const> {
ContractConstructorSpec: 'ContractMessageParamSpecV2', ContractConstructorSpec: 'ContractMessageParamSpecV2',
ContractEventSpec: 'ContractEventParamSpecV2', ContractEventSpec: 'ContractEventParamSpecV2',
ContractMessageSpec: 'ContractMessageParamSpecV2' ContractMessageSpec: 'ContractMessageParamSpecV2'
+8 -4
View File
@@ -5,7 +5,7 @@ import type { ApiTypes, DecorateMethod } from '@polkadot/api/types';
import type { Registry } from '@polkadot/types/types'; import type { Registry } from '@polkadot/types/types';
import { ApiBase } from '@polkadot/api/base'; import { ApiBase } from '@polkadot/api/base';
import { assert, isFunction } from '@polkadot/util'; import { isFunction } from '@polkadot/util';
import { Abi } from '../Abi'; import { Abi } from '../Abi';
@@ -24,9 +24,13 @@ export abstract class Base<ApiType extends ApiTypes> {
this._decorateMethod = decorateMethod; this._decorateMethod = decorateMethod;
assert(!!(api && api.isConnected && api.tx), 'Your API has not been initialized correctly and is not connected to a chain'); if (!api || !api.isConnected || !api.tx) {
assert(!!(api.tx.contracts && Object.keys(api.tx.contracts).length), 'You need to connect to a chain with a runtime that supports contracts'); throw new Error('Your API has not been initialized correctly and is not connected to a chain');
assert(isFunction(api.tx.contracts.instantiateWithCode), 'You need to connect to a chain with a runtime with a V3 contracts module. The runtime does not expose api.tx.contracts.instantiateWithCode'); } else if (!api.tx.contracts || !isFunction(api.tx.contracts.instantiateWithCode) || api.tx.contracts.instantiateWithCode.meta.args.length !== 6) {
throw new Error('The runtime does not expose api.tx.contracts.instantiateWithCode with storageDepositLimit');
} else if (!api.call.contractsApi || !isFunction(api.call.contractsApi.call)) {
throw new Error('Your runtime does not expose the api.call.contractsApi.call runtime interfaces');
}
} }
public get registry (): Registry { public get registry (): Registry {
+7 -11
View File
@@ -57,20 +57,16 @@ export class Blueprint<ApiType extends ApiTypes> extends Base<ApiType> {
} }
#deploy = (constructorOrId: AbiConstructor | string | number, { gasLimit = BN_ZERO, salt, storageDepositLimit = null, value = BN_ZERO }: BlueprintOptions, params: unknown[]): SubmittableExtrinsic<ApiType, BlueprintSubmittableResult<ApiType>> => { #deploy = (constructorOrId: AbiConstructor | string | number, { gasLimit = BN_ZERO, salt, storageDepositLimit = null, value = BN_ZERO }: BlueprintOptions, params: unknown[]): SubmittableExtrinsic<ApiType, BlueprintSubmittableResult<ApiType>> => {
const hasStorageDeposit = this.api.tx.contracts.instantiate.meta.args.length === 6;
const encParams = this.abi.findConstructor(constructorOrId).toU8a(params); const encParams = this.abi.findConstructor(constructorOrId).toU8a(params);
const encSalt = encodeSalt(salt); const encSalt = encodeSalt(salt);
const tx = hasStorageDeposit
? this.api.tx.contracts.instantiate(value, gasLimit, storageDepositLimit, this.codeHash, encParams, encSalt)
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore old style without storage deposit
: this.api.tx.contracts.instantiate(value, gasLimit, this.codeHash, encParams, encSalt);
return tx.withResultTransform((result: ISubmittableResult) => return this.api.tx.contracts
new BlueprintSubmittableResult(result, applyOnEvent(result, ['Instantiated'], ([record]: EventRecord[]) => .instantiate(value, gasLimit, storageDepositLimit, this.codeHash, encParams, encSalt)
new Contract<ApiType>(this.api, this.abi, record.event.data[1] as AccountId, this._decorateMethod) .withResultTransform((result: ISubmittableResult) =>
)) new BlueprintSubmittableResult(result, applyOnEvent(result, ['Instantiated'], ([record]: EventRecord[]) =>
); new Contract<ApiType>(this.api, this.abi, record.event.data[1] as AccountId, this._decorateMethod)
))
);
}; };
} }
+3 -3
View File
@@ -6,9 +6,9 @@ import path from 'path';
import { toPromiseMethod } from '@polkadot/api'; import { toPromiseMethod } from '@polkadot/api';
import v0contractFlipper from '../test/contracts/ink/v0/flipper.contract.json'; import v0contractFlipper from '../test/contracts/ink/v0/flipper.contract.json' assert { type: 'json' };
import v0abiFlipper from '../test/contracts/ink/v0/flipper.json'; import v0abiFlipper from '../test/contracts/ink/v0/flipper.json' assert { type: 'json' };
import v1contractFlipper from '../test/contracts/ink/v1/flipper.contract.json'; import v1contractFlipper from '../test/contracts/ink/v1/flipper.contract.json' assert { type: 'json' };
import { Code } from './Code'; import { Code } from './Code';
import { mockApi } from './mock'; import { mockApi } from './mock';
+17 -19
View File
@@ -11,7 +11,7 @@ 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, BN_ZERO, compactAddLength, isUndefined, isWasm, u8aToU8a } from '@polkadot/util'; import { BN_ZERO, compactAddLength, isUndefined, isWasm, u8aToU8a } from '@polkadot/util';
import { Abi } from '../Abi'; import { Abi } from '../Abi';
import { applyOnEvent } from '../util'; import { applyOnEvent } from '../util';
@@ -48,7 +48,9 @@ export class Code<ApiType extends ApiTypes> extends Base<ApiType> {
? this.abi.info.source.wasm ? this.abi.info.source.wasm
: u8aToU8a(wasm); : u8aToU8a(wasm);
assert(isWasm(this.code), 'No WASM code provided'); if (!isWasm(this.code)) {
throw new Error('No WASM code provided');
}
this.abi.constructors.forEach((c): void => { this.abi.constructors.forEach((c): void => {
if (isUndefined(this.#tx[c.method])) { if (isUndefined(this.#tx[c.method])) {
@@ -62,27 +64,23 @@ export class Code<ApiType extends ApiTypes> extends Base<ApiType> {
} }
#instantiate = (constructorOrId: AbiConstructor | string | number, { gasLimit = BN_ZERO, salt, storageDepositLimit = null, value = BN_ZERO }: BlueprintOptions, params: unknown[]): SubmittableExtrinsic<ApiType, CodeSubmittableResult<ApiType>> => { #instantiate = (constructorOrId: AbiConstructor | string | number, { gasLimit = BN_ZERO, salt, storageDepositLimit = null, value = BN_ZERO }: BlueprintOptions, params: unknown[]): SubmittableExtrinsic<ApiType, CodeSubmittableResult<ApiType>> => {
const hasStorageDeposit = this.api.tx.contracts.instantiateWithCode.meta.args.length === 6;
const encCode = compactAddLength(this.code); const encCode = compactAddLength(this.code);
const encParams = this.abi.findConstructor(constructorOrId).toU8a(params); const encParams = this.abi.findConstructor(constructorOrId).toU8a(params);
const encSalt = encodeSalt(salt); const encSalt = encodeSalt(salt);
const tx = hasStorageDeposit
? this.api.tx.contracts.instantiateWithCode(value, gasLimit, storageDepositLimit, encCode, encParams, encSalt)
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore old style without storage deposit
: this.api.tx.contracts.instantiateWithCode(value, gasLimit, encCode, encParams, encSalt);
return tx.withResultTransform((result: ISubmittableResult) => return this.api.tx.contracts
new CodeSubmittableResult(result, ...(applyOnEvent(result, ['CodeStored', 'Instantiated'], (records: EventRecord[]) => .instantiateWithCode(value, gasLimit, storageDepositLimit, encCode, encParams, encSalt)
records.reduce<[Blueprint<ApiType>?, Contract<ApiType>?]>(([blueprint, contract], { event }) => .withResultTransform((result: ISubmittableResult) =>
this.api.events.contracts.Instantiated.is(event) new CodeSubmittableResult(result, ...(applyOnEvent(result, ['CodeStored', 'Instantiated'], (records: EventRecord[]) =>
? [blueprint, new Contract<ApiType>(this.api, this.abi, (event as unknown as { data: [Codec, AccountId] }).data[1], this._decorateMethod)] records.reduce<[Blueprint<ApiType>?, Contract<ApiType>?]>(([blueprint, contract], { event }) =>
: this.api.events.contracts.CodeStored.is(event) this.api.events.contracts.Instantiated.is(event)
? [new Blueprint<ApiType>(this.api, this.abi, (event as unknown as { data: [AccountId] }).data[0], this._decorateMethod), contract] ? [blueprint, new Contract<ApiType>(this.api, this.abi, (event as unknown as { data: [Codec, AccountId] }).data[1], this._decorateMethod)]
: [blueprint, contract], : this.api.events.contracts.CodeStored.is(event)
[]) ? [new Blueprint<ApiType>(this.api, this.abi, (event as unknown as { data: [AccountId] }).data[0], this._decorateMethod), contract]
) || [])) : [blueprint, contract],
); [])
) || []))
);
}; };
} }
+41 -62
View File
@@ -13,10 +13,10 @@ import { map } from 'rxjs';
import { SubmittableResult } from '@polkadot/api'; import { SubmittableResult } from '@polkadot/api';
import { ApiBase } from '@polkadot/api/base'; import { ApiBase } from '@polkadot/api/base';
import { assert, BN, BN_HUNDRED, BN_ONE, BN_ZERO, bnToBn, isFunction, isUndefined, logger } from '@polkadot/util'; import { BN, BN_HUNDRED, BN_ONE, BN_ZERO, bnToBn, isUndefined, logger } from '@polkadot/util';
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 { withMeta } from './util'; import { withMeta } from './util';
@@ -26,23 +26,18 @@ export interface ContractConstructor<ApiType extends ApiTypes> {
// As per Rust, 5 * GAS_PER_SEC // As per Rust, 5 * GAS_PER_SEC
const MAX_CALL_GAS = new BN(5_000_000_000_000).isub(BN_ONE); const MAX_CALL_GAS = new BN(5_000_000_000_000).isub(BN_ONE);
const ERROR_NO_CALL = 'Your node does not expose the contracts.call RPC. This is most probably due to a runtime configuration.';
const l = logger('Contract'); const l = logger('Contract');
function createQuery <ApiType extends ApiTypes> (meta: AbiMessage, fn: (origin: string | AccountId | Uint8Array, options: ContractOptions, params: unknown[]) => ContractCallResult<ApiType, ContractCallOutcome>): ContractQuery<ApiType> { function createQuery <ApiType extends ApiTypes> (meta: AbiMessage, fn: (origin: string | AccountId | Uint8Array, options: ContractOptions, params: unknown[]) => ContractCallResult<ApiType, ContractCallOutcome>): ContractQuery<ApiType> {
return withMeta(meta, (origin: string | AccountId | Uint8Array, options: bigint | string | number | BN | ContractOptions, ...params: unknown[]): ContractCallResult<ApiType, ContractCallOutcome> => return withMeta(meta, (origin: string | AccountId | Uint8Array, options: ContractOptions, ...params: unknown[]): ContractCallResult<ApiType, ContractCallOutcome> =>
isOptions(options) fn(origin, options, params)
? fn(origin, options, params)
: fn(origin, ...extractOptions<ContractOptions>(options, params))
); );
} }
function createTx <ApiType extends ApiTypes> (meta: AbiMessage, fn: (options: ContractOptions, params: unknown[]) => SubmittableExtrinsic<ApiType>): ContractTx<ApiType> { function createTx <ApiType extends ApiTypes> (meta: AbiMessage, fn: (options: ContractOptions, params: unknown[]) => SubmittableExtrinsic<ApiType>): ContractTx<ApiType> {
return withMeta(meta, (options: bigint | string | number | BN | ContractOptions, ...params: unknown[]): SubmittableExtrinsic<ApiType> => return withMeta(meta, (options: ContractOptions, ...params: unknown[]): SubmittableExtrinsic<ApiType> =>
isOptions(options) fn(options, params)
? fn(options, params)
: fn(...extractOptions<ContractOptions>(options, params))
); );
} }
@@ -82,13 +77,7 @@ export class Contract<ApiType extends ApiTypes> extends Base<ApiType> {
}); });
} }
public get hasRpcContractsCall (): boolean {
return isFunction(this.api.rx.rpc.contracts?.call);
}
public get query (): MapMessageQuery<ApiType> { public get query (): MapMessageQuery<ApiType> {
assert(this.hasRpcContractsCall, ERROR_NO_CALL);
return this.#query; return this.#query;
} }
@@ -110,62 +99,52 @@ export class Contract<ApiType extends ApiTypes> extends Base<ApiType> {
}; };
#exec = (messageOrId: AbiMessage | string | number, { gasLimit = BN_ZERO, storageDepositLimit = null, value = BN_ZERO }: ContractOptions, params: unknown[]): SubmittableExtrinsic<ApiType> => { #exec = (messageOrId: AbiMessage | string | number, { gasLimit = BN_ZERO, storageDepositLimit = null, value = BN_ZERO }: ContractOptions, params: unknown[]): SubmittableExtrinsic<ApiType> => {
const hasStorageDeposit = this.api.tx.contracts.call.meta.args.length === 5;
const gas = this.#getGas(gasLimit); const gas = this.#getGas(gasLimit);
const encParams = this.abi.findMessage(messageOrId).toU8a(params); const encParams = this.abi.findMessage(messageOrId).toU8a(params);
const tx = hasStorageDeposit
? this.api.tx.contracts.call(this.address, value, gas, storageDepositLimit, encParams)
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore old style without storage deposit
: this.api.tx.contracts.call(this.address, value, gas, encParams);
return tx.withResultTransform((result: ISubmittableResult) => return this.api.tx.contracts
// ContractEmitted is the current generation, ContractExecution is the previous generation .call(this.address, value, gas, storageDepositLimit, encParams)
new ContractSubmittableResult(result, applyOnEvent(result, ['ContractEmitted', 'ContractExecution'], (records: EventRecord[]) => .withResultTransform((result: ISubmittableResult) =>
records // ContractEmitted is the current generation, ContractExecution is the previous generation
.map(({ event: { data: [, data] } }): DecodedEvent | null => { new ContractSubmittableResult(result, applyOnEvent(result, ['ContractEmitted', 'ContractExecution'], (records: EventRecord[]) =>
try { records
return this.abi.decodeEvent(data as Bytes); .map(({ event: { data: [, data] } }): DecodedEvent | null => {
} catch (error) { try {
l.error(`Unable to decode contract event: ${(error as Error).message}`); return this.abi.decodeEvent(data as Bytes);
} catch (error) {
l.error(`Unable to decode contract event: ${(error as Error).message}`);
return null; return null;
} }
}) })
.filter((decoded): decoded is DecodedEvent => !!decoded) .filter((decoded): decoded is DecodedEvent => !!decoded)
)) ))
); );
}; };
#read = (messageOrId: AbiMessage | string | number, { gasLimit = BN_ZERO, storageDepositLimit = null, value = BN_ZERO }: ContractOptions, params: unknown[]): ContractCallSend<ApiType> => { #read = (messageOrId: AbiMessage | string | number, { gasLimit = BN_ZERO, storageDepositLimit = null, value = BN_ZERO }: ContractOptions, params: unknown[]): ContractCallSend<ApiType> => {
assert(this.hasRpcContractsCall, ERROR_NO_CALL);
const message = this.abi.findMessage(messageOrId); const message = this.abi.findMessage(messageOrId);
return { return {
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
send: this._decorateMethod((origin: string | AccountId | Uint8Array) => { send: this._decorateMethod((origin: string | AccountId | Uint8Array) =>
const hasStorageDeposit = this.api.tx.contracts.call.meta.args.length === 5; this.api.rx.call.contractsApi
const inputData = message.toU8a(params); .call<ContractExecResult>(origin, this.address, value, this.#getGas(gasLimit, true), storageDepositLimit, message.toU8a(params))
const rpc = hasStorageDeposit .pipe(
? this.api.rx.rpc.contracts.call({ dest: this.address, gasLimit: this.#getGas(gasLimit, true), inputData, origin, storageDepositLimit, value }) map(({ debugMessage, gasConsumed, gasRequired, result, storageDeposit }): ContractCallOutcome => ({
: this.api.rx.rpc.contracts.call({ dest: this.address, gasLimit: this.#getGas(gasLimit, true), inputData, origin, value }); debugMessage,
gasConsumed,
const mapFn = ({ debugMessage, gasConsumed, gasRequired, result, storageDeposit }: ContractExecResult): ContractCallOutcome => ({ gasRequired: gasRequired && !gasRequired.isZero()
debugMessage, ? gasRequired
gasConsumed, : gasConsumed,
gasRequired: gasRequired && !gasRequired.isZero() output: result.isOk && message.returnType
? gasRequired ? this.abi.registry.createTypeUnsafe(message.returnType.lookupName || message.returnType.type, [result.asOk.data.toU8a(true)], { isPedantic: true })
: gasConsumed, : null,
output: result.isOk && message.returnType result,
? this.abi.registry.createTypeUnsafe(message.returnType.lookupName || message.returnType.type, [result.asOk.data.toU8a(true)], { isPedantic: true }) storageDeposit
: null, }))
result, )
storageDeposit )
});
return rpc.pipe(map(mapFn));
})
}; };
}; };
} }
+14 -3
View File
@@ -6,14 +6,25 @@ import { TypeRegistry } from '@polkadot/types';
const registry = new TypeRegistry(); const registry = new TypeRegistry();
const instantiateWithCode = (): never => {
throw new Error('mock');
};
instantiateWithCode.meta = { args: new Array(6) };
export const mockApi = { export const mockApi = {
call: {
contractsApi: {
call: (): never => {
throw new Error('mock');
}
}
},
isConnected: true, isConnected: true,
registry, registry,
tx: { tx: {
contracts: { contracts: {
instantiateWithCode: (): never => { instantiateWithCode
throw new Error('mock');
}
} }
} }
} as unknown as ApiBase<'promise'>; } as unknown as ApiBase<'promise'>;
-9
View File
@@ -5,7 +5,6 @@ import type { Observable } from 'rxjs';
import type { SubmittableExtrinsic } from '@polkadot/api/submittable/types'; import type { SubmittableExtrinsic } from '@polkadot/api/submittable/types';
import type { ApiTypes, ObsInnerType } from '@polkadot/api/types'; import type { ApiTypes, ObsInnerType } from '@polkadot/api/types';
import type { AccountId } from '@polkadot/types/interfaces'; import type { AccountId } from '@polkadot/types/interfaces';
import type { BN } from '@polkadot/util';
import type { AbiMessage, BlueprintOptions, ContractCallOutcome, ContractOptions } from '../types'; import type { AbiMessage, BlueprintOptions, ContractCallOutcome, ContractOptions } from '../types';
export interface MessageMeta { export interface MessageMeta {
@@ -14,26 +13,18 @@ export interface MessageMeta {
export interface BlueprintDeploy<ApiType extends ApiTypes> extends MessageMeta { export interface BlueprintDeploy<ApiType extends ApiTypes> extends MessageMeta {
(options: BlueprintOptions, ...params: unknown[]): SubmittableExtrinsic<ApiType>; (options: BlueprintOptions, ...params: unknown[]): SubmittableExtrinsic<ApiType>;
// @deprecated Use options form (to be dropped in a major update)
(value: bigint | string | number | BN, gasLimit: bigint | string | number | BN, ...params: unknown[]): SubmittableExtrinsic<ApiType>;
} }
export interface ContractQuery<ApiType extends ApiTypes> extends MessageMeta { export interface ContractQuery<ApiType extends ApiTypes> extends MessageMeta {
(origin: AccountId | string | Uint8Array, options: ContractOptions, ...params: unknown[]): ContractCallResult<ApiType, ContractCallOutcome>; (origin: AccountId | string | Uint8Array, options: ContractOptions, ...params: unknown[]): ContractCallResult<ApiType, ContractCallOutcome>;
// @deprecated Use options form (to be dropped in a major update)
(origin: AccountId | string | Uint8Array, value: bigint | BN | string | number, gasLimit: bigint | BN | string | number, ...params: unknown[]): ContractCallResult<ApiType, ContractCallOutcome>;
} }
export interface ContractTx<ApiType extends ApiTypes> extends MessageMeta { export interface ContractTx<ApiType extends ApiTypes> extends MessageMeta {
(options: ContractOptions, ...params: unknown[]): SubmittableExtrinsic<ApiType>; (options: ContractOptions, ...params: unknown[]): SubmittableExtrinsic<ApiType>;
// @deprecated Use options form (to be dropped in a major update)
(value: bigint | BN | string | number, gasLimit: bigint | BN | string | number, ...params: unknown[]): SubmittableExtrinsic<ApiType>;
} }
export interface ContractGeneric<O, T> { export interface ContractGeneric<O, T> {
(messageOrId: AbiMessage | string | number, options: O, ...params: unknown[]): T; (messageOrId: AbiMessage | string | number, options: O, ...params: unknown[]): T;
// @deprecated Use options form (to be dropped in a major update)
(messageOrId: AbiMessage | string | number, value: bigint | BN | string | number, gasLimit: bigint | BN | string | number, ...params: unknown[]): T;
} }
export type ContractCallResult<ApiType extends ApiTypes, T> = ApiType extends 'rxjs' export type ContractCallResult<ApiType extends ApiTypes, T> = ApiType extends 'rxjs'
+4 -11
View File
@@ -4,7 +4,6 @@
import type { SubmittableResult } from '@polkadot/api'; import type { SubmittableResult } from '@polkadot/api';
import type { SubmittableExtrinsic } from '@polkadot/api/submittable/types'; import type { SubmittableExtrinsic } from '@polkadot/api/submittable/types';
import type { ApiTypes } from '@polkadot/api/types'; import type { ApiTypes } from '@polkadot/api/types';
import type { BN } from '@polkadot/util';
import type { AbiConstructor, AbiMessage, BlueprintOptions } from '../types'; import type { AbiConstructor, AbiMessage, BlueprintOptions } from '../types';
import type { BlueprintDeploy, ContractGeneric } from './types'; import type { BlueprintDeploy, ContractGeneric } from './types';
@@ -12,8 +11,6 @@ import { Bytes } from '@polkadot/types';
import { compactAddLength, u8aToU8a } from '@polkadot/util'; import { compactAddLength, u8aToU8a } from '@polkadot/util';
import { randomAsU8a } from '@polkadot/util-crypto'; import { randomAsU8a } from '@polkadot/util-crypto';
import { extractOptions, isOptions } from '../util';
export const EMPTY_SALT = new Uint8Array(); export const EMPTY_SALT = new Uint8Array();
export function withMeta <T extends { meta: AbiMessage }> (meta: AbiMessage, creator: Omit<T, 'meta'>): T { export function withMeta <T extends { meta: AbiMessage }> (meta: AbiMessage, creator: Omit<T, 'meta'>): T {
@@ -23,18 +20,14 @@ export function withMeta <T extends { meta: AbiMessage }> (meta: AbiMessage, cre
} }
export function createBluePrintTx <ApiType extends ApiTypes, R extends SubmittableResult> (meta: AbiMessage, fn: (options: BlueprintOptions, params: unknown[]) => SubmittableExtrinsic<ApiType, R>): BlueprintDeploy<ApiType> { export function createBluePrintTx <ApiType extends ApiTypes, R extends SubmittableResult> (meta: AbiMessage, fn: (options: BlueprintOptions, params: unknown[]) => SubmittableExtrinsic<ApiType, R>): BlueprintDeploy<ApiType> {
return withMeta(meta, (options: bigint | string | number | BN | BlueprintOptions, ...params: unknown[]): SubmittableExtrinsic<ApiType, R> => return withMeta(meta, (options: BlueprintOptions, ...params: unknown[]): SubmittableExtrinsic<ApiType, R> =>
isOptions(options) fn(options, params)
? fn(options, params)
: fn(...extractOptions<BlueprintOptions>(options, params))
); );
} }
export function createBluePrintWithId <T> (fn: (constructorOrId: AbiConstructor | string | number, options: BlueprintOptions, params: unknown[]) => T): ContractGeneric<BlueprintOptions, T> { export function createBluePrintWithId <T> (fn: (constructorOrId: AbiConstructor | string | number, options: BlueprintOptions, params: unknown[]) => T): ContractGeneric<BlueprintOptions, T> {
return (constructorOrId: AbiConstructor | string | number, options: bigint | string | number | BN | BlueprintOptions, ...params: unknown[]): T => return (constructorOrId: AbiConstructor | string | number, options: BlueprintOptions, ...params: unknown[]): T =>
isOptions(options) fn(constructorOrId, options, params);
? fn(constructorOrId, options, params)
: fn(constructorOrId, ...extractOptions<BlueprintOptions>(options, params));
} }
export function encodeSalt (salt: Uint8Array | string | null = randomAsU8a()): Uint8Array { export function encodeSalt (salt: Uint8Array | string | null = randomAsU8a()): Uint8Array {
@@ -9,17 +9,13 @@ import { ApiPromise } from '@polkadot/api';
import { BlueprintPromise, ContractPromise } from '@polkadot/api-contract'; import { BlueprintPromise, ContractPromise } from '@polkadot/api-contract';
import { createTestPairs, TestKeyringMap } from '@polkadot/keyring/testingPairs'; import { createTestPairs, TestKeyringMap } from '@polkadot/keyring/testingPairs';
import abiIncrementer from './test/contracts/ink/v0/incrementer.json'; import abiIncrementer from './test/contracts/ink/v0/incrementer.json' assert { type: 'json' };
async function checkBlueprint (api: ApiPromise, pairs: TestKeyringMap): Promise<void> { async function checkBlueprint (api: ApiPromise, pairs: TestKeyringMap): Promise<void> {
const blueprint = new BlueprintPromise(api, abiIncrementer as Record<string, unknown>, '0x1234'); const blueprint = new BlueprintPromise(api, abiIncrementer as Record<string, unknown>, '0x1234');
// new style
await blueprint.tx.new({ gasLimit: 456, salt: '0x1234', value: 123 }, 42).signAndSend(pairs.bob); await blueprint.tx.new({ gasLimit: 456, salt: '0x1234', value: 123 }, 42).signAndSend(pairs.bob);
await blueprint.tx.new({ gasLimit: 456, value: 123 }, 42).signAndSend(pairs.bob); await blueprint.tx.new({ gasLimit: 456, value: 123 }, 42).signAndSend(pairs.bob);
// old style
await blueprint.tx.new(123, 456, 42).signAndSend(pairs.bob);
} }
async function checkContract (api: ApiPromise, pairs: TestKeyringMap): Promise<void> { async function checkContract (api: ApiPromise, pairs: TestKeyringMap): Promise<void> {
@@ -27,11 +23,9 @@ async function checkContract (api: ApiPromise, pairs: TestKeyringMap): Promise<v
// queries // queries
await contract.query.get(pairs.alice.address, {}); await contract.query.get(pairs.alice.address, {});
await contract.query.get(pairs.alice.address, 0, 0);
// execute // execute
await contract.tx.inc({ gasLimit: 1234 }, 123).signAndSend(pairs.eve); await contract.tx.inc({ gasLimit: 1234 }, 123).signAndSend(pairs.eve);
await contract.tx.inc(123, 456, 69).signAndSend(pairs.eve);
} }
async function main (): Promise<void> { async function main (): Promise<void> {
+1 -1
View File
@@ -3,4 +3,4 @@
// Do not edit, auto-generated by @polkadot/dev // Do not edit, auto-generated by @polkadot/dev
export const packageInfo = { name: '@polkadot/api-contract', path: 'auto', type: 'auto', version: '8.12.1' }; export const packageInfo = { name: '@polkadot/api-contract', path: 'auto', type: 'auto', version: '9.0.1' };
@@ -1,11 +1,11 @@
// Copyright 2017-2022 @polkadot/api-contract authors & contributors // Copyright 2017-2022 @polkadot/api-contract authors & contributors
// SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: Apache-2.0
export { default as delegator } from './delegator.json'; export { default as delegator } from './delegator.json' assert { type: 'json' };
export { default as dns } from './dns.json'; export { default as dns } from './dns.json' assert { type: 'json' };
export { default as erc20 } from './erc20.json'; export { default as erc20 } from './erc20.json' assert { type: 'json' };
export { default as erc721 } from './erc721.json'; export { default as erc721 } from './erc721.json' assert { type: 'json' };
export { default as flipper } from './flipper.json'; export { default as flipper } from './flipper.json' assert { type: 'json' };
export { default as flipperBundle } from './flipper.contract.json'; export { default as flipperBundle } from './flipper.contract.json' assert { type: 'json' };
export { default as incrementer } from './incrementer.json'; export { default as incrementer } from './incrementer.json' assert { type: 'json' };
export { default as multisigPlain } from './multisig_plain.json'; export { default as multisigPlain } from './multisig_plain.json' assert { type: 'json' };
@@ -1,6 +1,6 @@
// Copyright 2017-2022 @polkadot/api-contract authors & contributors // Copyright 2017-2022 @polkadot/api-contract authors & contributors
// SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: Apache-2.0
export { default as flipper } from './flipper.contract.json'; export { default as flipper } from './flipper.contract.json' assert { type: 'json' };
// A complex contract example with traits. // A complex contract example with traits.
export { default as psp22 } from './psp22_minter_pauser.contract.json'; export { default as psp22 } from './psp22_minter_pauser.contract.json' assert { type: 'json' };
@@ -1,5 +1,5 @@
// Copyright 2017-2022 @polkadot/api-contract authors & contributors // Copyright 2017-2022 @polkadot/api-contract authors & contributors
// SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: Apache-2.0
export { default as erc20 } from './erc20.contract.json'; export { default as erc20 } from './erc20.contract.json' assert { type: 'json' };
export { default as flipper } from './flipper.contract.json'; export { default as flipper } from './flipper.contract.json' assert { type: 'json' };
@@ -1,6 +1,6 @@
// Copyright 2017-2022 @polkadot/api-contract authors & contributors // Copyright 2017-2022 @polkadot/api-contract authors & contributors
// SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: Apache-2.0
export { default as flipper } from './flipper.contract.json'; export { default as flipper } from './flipper.contract.json' assert { type: 'json' };
// A complex contract example with traits. // A complex contract example with traits.
export { default as traitErc20 } from './trait_erc20.contract.json'; export { default as traitErc20 } from './trait_erc20.contract.json' assert { type: 'json' };
@@ -1,4 +1,4 @@
// Copyright 2017-2022 @polkadot/api-contract authors & contributors // Copyright 2017-2022 @polkadot/api-contract authors & contributors
// SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: Apache-2.0
export { default as ints256 } from './ints256.json'; export { default as ints256 } from './ints256.json' assert { type: 'json' };
@@ -1,7 +1,7 @@
// Copyright 2017-2022 @polkadot/api-contract authors & contributors // Copyright 2017-2022 @polkadot/api-contract authors & contributors
// SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: Apache-2.0
export { default as assetTransfer } from './assetTransfer.json'; export { default as assetTransfer } from './assetTransfer.json' assert { type: 'json' };
export { default as enumExample } from './enumExample.json'; export { default as enumExample } from './enumExample.json' assert { type: 'json' };
export { default as recursive } from './recursive.contract.json'; export { default as recursive } from './recursive.contract.json' assert { type: 'json' };
export { default as withString } from './withString.json'; export { default as withString } from './withString.json' assert { type: 'json' };
-16
View File
@@ -3,15 +3,9 @@
import type { SubmittableResult } from '@polkadot/api'; import type { SubmittableResult } from '@polkadot/api';
import type { EventRecord } from '@polkadot/types/interfaces'; import type { EventRecord } from '@polkadot/types/interfaces';
import type { BN } from '@polkadot/util';
import type { BlueprintOptions, ContractOptions } from './types';
import { isBigInt, isBn, isNumber, isString } from '@polkadot/util';
type ContractEvents = 'CodeStored' | 'ContractEmitted' | 'ContractExecution' | 'Instantiated'; type ContractEvents = 'CodeStored' | 'ContractEmitted' | 'ContractExecution' | 'Instantiated';
type TOptions = BlueprintOptions | ContractOptions;
export function applyOnEvent <T> (result: SubmittableResult, types: 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', types); const records = result.filterRecords('contracts', types);
@@ -23,13 +17,3 @@ export function applyOnEvent <T> (result: SubmittableResult, types: ContractEven
return undefined; return undefined;
} }
export function isOptions <T> (options: bigint | string | number | BN | T): options is T {
return !(isBn(options) || isBigInt(options) || isNumber(options) || isString(options));
}
export function extractOptions <T extends TOptions> (value: bigint | string | number | BN, params: unknown[]): [T, unknown[]] {
const gasLimit = params.shift() as BN;
return [{ gasLimit, value } as T, params];
}
+16 -16
View File
@@ -20,25 +20,25 @@
"./detectPackage.cjs" "./detectPackage.cjs"
], ],
"type": "module", "type": "module",
"version": "8.12.1", "version": "9.0.1",
"main": "index.js", "main": "index.js",
"dependencies": { "dependencies": {
"@babel/runtime": "^7.18.6", "@babel/runtime": "^7.18.9",
"@polkadot/api": "8.12.1", "@polkadot/api": "9.0.1",
"@polkadot/api-augment": "8.12.1", "@polkadot/api-augment": "9.0.1",
"@polkadot/api-base": "8.12.1", "@polkadot/api-base": "9.0.1",
"@polkadot/rpc-core": "8.12.1", "@polkadot/rpc-core": "9.0.1",
"@polkadot/types": "8.12.1", "@polkadot/types": "9.0.1",
"@polkadot/types-codec": "8.12.1", "@polkadot/types-codec": "9.0.1",
"@polkadot/util": "^10.0.1", "@polkadot/util": "^10.1.2",
"@polkadot/util-crypto": "^10.0.1", "@polkadot/util-crypto": "^10.1.2",
"rxjs": "^7.5.5" "rxjs": "^7.5.6"
}, },
"devDependencies": { "devDependencies": {
"@polkadot/api": "8.12.1", "@polkadot/api": "9.0.1",
"@polkadot/api-augment": "8.12.1", "@polkadot/api-augment": "9.0.1",
"@polkadot/rpc-augment": "8.12.1", "@polkadot/rpc-augment": "9.0.1",
"@polkadot/rpc-provider": "8.12.1", "@polkadot/rpc-provider": "9.0.1",
"@polkadot/types-support": "8.12.1" "@polkadot/types-support": "9.0.1"
} }
} }
+14
View File
@@ -0,0 +1,14 @@
// Copyright 2017-2022 @polkadot/api-derive authors & contributors
// SPDX-License-Identifier: Apache-2.0
import { hasProposals as collectiveHasProposals, members as collectiveMembers, prime as collectivePrime, proposal as collectiveProposal, proposalCount as collectiveProposalCount, proposalHashes as collectiveProposalHashes, proposals as collectiveProposals } from '../collective';
export const members = collectiveMembers('allianceMotion');
export const hasProposals = collectiveHasProposals('allianceMotion');
export const proposal = collectiveProposal('allianceMotion');
export const proposalCount = collectiveProposalCount('allianceMotion');
export const proposalHashes = collectiveProposalHashes('allianceMotion');
export const proposals = collectiveProposals('allianceMotion');
export const prime = collectivePrime('allianceMotion');
+10 -13
View File
@@ -10,7 +10,7 @@ import type { Bag } from './types';
import { map, of, switchMap } from 'rxjs'; import { map, of, switchMap } from 'rxjs';
import { BN_ZERO, bnToBn } from '@polkadot/util'; import { BN_ZERO, bnToBn, objectSpread } from '@polkadot/util';
import { memo } from '../util'; import { memo } from '../util';
@@ -21,20 +21,17 @@ function orderBags (ids: BN[], bags: Option<PalletBagsListListBag>[]): Bag[] {
id, id,
key: id.toString() key: id.toString()
})) }))
.sort((a, b) => b.id.cmp(a.id)) .sort((a, b) => b.id.cmp(a.id));
.map((base, index): Bag => ({
...base,
bagLower: BN_ZERO,
bagUpper: base.id,
index
}));
const max = sorted.length - 1; const max = sorted.length - 1;
return sorted.map((entry, index) => return sorted.map((entry, index): Bag =>
index === max objectSpread(entry, {
? entry bagLower: index === max
// We could probably use a .add(BN_ONE) here ? BN_ZERO
: { ...entry, bagLower: sorted[index + 1].bagUpper } : sorted[index + 1].id,
bagUpper: entry.id,
index
})
); );
} }
@@ -8,12 +8,14 @@ import type { Bag, BagExpanded } from './types';
import { map, switchMap } from 'rxjs'; import { map, switchMap } from 'rxjs';
import { objectSpread } from '@polkadot/util';
import { memo } from '../util'; import { memo } from '../util';
export function expand (instanceId: string, api: DeriveApi): (bag: Bag) => Observable<BagExpanded> { export function expand (instanceId: string, api: DeriveApi): (bag: Bag) => Observable<BagExpanded> {
return memo(instanceId, (bag: Bag): Observable<BagExpanded> => return memo(instanceId, (bag: Bag): Observable<BagExpanded> =>
api.derive.bagsList.listNodes(bag.bag).pipe( api.derive.bagsList.listNodes(bag.bag).pipe(
map((nodes) => ({ ...bag, nodes })) map((nodes) => objectSpread({ nodes }, bag))
) )
); );
} }
+7 -7
View File
@@ -9,7 +9,7 @@ import type { DeriveApi, DeriveBalancesAccount, DeriveBalancesAccountData } from
import { combineLatest, map, of, switchMap } from 'rxjs'; import { combineLatest, map, of, switchMap } from 'rxjs';
import { isFunction } from '@polkadot/util'; import { isFunction, objectSpread } from '@polkadot/util';
import { memo } from '../util'; import { memo } from '../util';
@@ -40,12 +40,11 @@ function getBalance (api: DeriveApi, [freeBalance, reservedBalance, frozenFee, f
} }
function calcBalances (api: DeriveApi, [accountId, [accountNonce, [primary, ...additional]]]: [AccountId, Result]): DeriveBalancesAccount { function calcBalances (api: DeriveApi, [accountId, [accountNonce, [primary, ...additional]]]: [AccountId, Result]): DeriveBalancesAccount {
return { return objectSpread({
accountId, accountId,
accountNonce, accountNonce,
additional: additional.map((b) => getBalance(api, b)), additional: additional.map((b) => getBalance(api, b))
...getBalance(api, primary) }, getBalance(api, primary));
};
} }
// old // old
@@ -150,7 +149,8 @@ function querySystemAccount (api: DeriveApi, accountId: AccountId): Observable<R
* ``` * ```
*/ */
export function account (instanceId: string, api: DeriveApi): (address: AccountIndex | AccountId | Address | string) => Observable<DeriveBalancesAccount> { export function account (instanceId: string, api: DeriveApi): (address: AccountIndex | AccountId | Address | string) => Observable<DeriveBalancesAccount> {
const balanceInstances = api.registry.getModuleInstances(api.runtimeVersion.specName.toString(), 'balances'); const balanceInstances = api.registry.getModuleInstances(api.runtimeVersion.specName, 'balances');
const nonDefaultBalances = balanceInstances && (balanceInstances.length !== 1 || balanceInstances[0] !== 'balances');
return memo(instanceId, (address: AccountIndex | AccountId | Address | string): Observable<DeriveBalancesAccount> => return memo(instanceId, (address: AccountIndex | AccountId | Address | string): Observable<DeriveBalancesAccount> =>
api.derive.accounts.accountId(address).pipe( api.derive.accounts.accountId(address).pipe(
@@ -158,7 +158,7 @@ export function account (instanceId: string, api: DeriveApi): (address: AccountI
(accountId (accountId
? combineLatest([ ? combineLatest([
of(accountId), of(accountId),
balanceInstances nonDefaultBalances
? queryBalancesAccount(api, accountId, balanceInstances) ? queryBalancesAccount(api, accountId, balanceInstances)
: isFunction(api.query.system?.account) : isFunction(api.query.system?.account)
? querySystemAccount(api, accountId) ? querySystemAccount(api, accountId)
+7 -10
View File
@@ -9,7 +9,7 @@ import type { DeriveApi, DeriveBalancesAccount, DeriveBalancesAccountData, Deriv
import { combineLatest, map, of, switchMap } from 'rxjs'; import { combineLatest, map, of, switchMap } from 'rxjs';
import { BN, BN_ZERO, bnMax, bnMin, isFunction } from '@polkadot/util'; import { BN, BN_ZERO, bnMax, bnMin, isFunction, objectSpread } from '@polkadot/util';
import { memo } from '../util'; import { memo } from '../util';
@@ -57,13 +57,12 @@ function calcLocked (api: DeriveApi, bestNumber: BlockNumber, locks: (PalletBala
function calcShared (api: DeriveApi, bestNumber: BlockNumber, data: DeriveBalancesAccountData, locks: (PalletBalancesBalanceLock | BalanceLockTo212)[]): DeriveBalancesAllAccountData { function calcShared (api: DeriveApi, bestNumber: BlockNumber, data: DeriveBalancesAccountData, locks: (PalletBalancesBalanceLock | BalanceLockTo212)[]): DeriveBalancesAllAccountData {
const { allLocked, lockedBalance, lockedBreakdown, vestingLocked } = calcLocked(api, bestNumber, locks); const { allLocked, lockedBalance, lockedBreakdown, vestingLocked } = calcLocked(api, bestNumber, locks);
return { return objectSpread({}, data, {
...data,
availableBalance: api.registry.createType('Balance', allLocked ? 0 : bnMax(new BN(0), data.freeBalance.sub(lockedBalance))), availableBalance: api.registry.createType('Balance', allLocked ? 0 : bnMax(new BN(0), data.freeBalance.sub(lockedBalance))),
lockedBalance, lockedBalance,
lockedBreakdown, lockedBreakdown,
vestingLocked vestingLocked
}; });
} }
function calcVesting (bestNumber: BlockNumber, shared: DeriveBalancesAllAccountData, _vesting: PalletVestingVestingInfo[] | null): DeriveBalancesAllVesting { function calcVesting (bestNumber: BlockNumber, shared: DeriveBalancesAllAccountData, _vesting: PalletVestingVestingInfo[] | null): DeriveBalancesAllVesting {
@@ -102,16 +101,14 @@ function calcVesting (bestNumber: BlockNumber, shared: DeriveBalancesAllAccountD
function calcBalances (api: DeriveApi, [data, [vesting, allLocks, namedReserves], bestNumber]: Result): DeriveBalancesAll { function calcBalances (api: DeriveApi, [data, [vesting, allLocks, namedReserves], bestNumber]: Result): DeriveBalancesAll {
const shared = calcShared(api, bestNumber, data, allLocks[0]); const shared = calcShared(api, bestNumber, data, allLocks[0]);
return { return objectSpread(shared, calcVesting(bestNumber, shared, vesting), {
...shared,
...calcVesting(bestNumber, shared, vesting),
accountId: data.accountId, accountId: data.accountId,
accountNonce: data.accountNonce, accountNonce: data.accountNonce,
additional: allLocks additional: allLocks
.filter((_, index) => index !== 0) .slice(1)
.map((l, index) => calcShared(api, bestNumber, data.additional[index], l)), .map((l, index) => calcShared(api, bestNumber, data.additional[index], l)),
namedReserves namedReserves
}; });
} }
// old // old
@@ -211,7 +208,7 @@ function queryCurrent (api: DeriveApi, accountId: AccountId | string, balanceIns
* ``` * ```
*/ */
export function all (instanceId: string, api: DeriveApi): (address: AccountId | string) => Observable<DeriveBalancesAll> { export function all (instanceId: string, api: DeriveApi): (address: AccountId | string) => Observable<DeriveBalancesAll> {
const balanceInstances = api.registry.getModuleInstances(api.runtimeVersion.specName.toString(), 'balances'); const balanceInstances = api.registry.getModuleInstances(api.runtimeVersion.specName, 'balances');
return memo(instanceId, (address: AccountId | string): Observable<DeriveBalancesAll> => return memo(instanceId, (address: AccountId | string): Observable<DeriveBalancesAll> =>
combineLatest([ combineLatest([
+7 -3
View File
@@ -2,7 +2,7 @@
// SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: Apache-2.0
import type { DeriveCustom } from '@polkadot/api-base/types'; import type { DeriveCustom } from '@polkadot/api-base/types';
import type { AnyFunction } from '@polkadot/types/types'; import type { AnyFunction, AnyString } from '@polkadot/types/types';
import type { ExactDerive } from './derive'; import type { ExactDerive } from './derive';
import type { DeriveApi } from './types'; import type { DeriveApi } from './types';
@@ -22,6 +22,10 @@ export { lazyDeriveSection };
// Enable derive only if some of these modules are available // Enable derive only if some of these modules are available
const checks: Record<string, Avail> = { const checks: Record<string, Avail> = {
allianceMotion: {
instances: ['allianceMotion'],
methods: []
},
bagsList: { bagsList: {
instances: ['voterList', 'bagsList'], instances: ['voterList', 'bagsList'],
methods: [], methods: [],
@@ -84,7 +88,7 @@ const checks: Record<string, Avail> = {
} }
}; };
function getModuleInstances (api: DeriveApi, specName: string, moduleName: string): string[] { function getModuleInstances (api: DeriveApi, specName: AnyString, moduleName: string): string[] {
return api.registry.getModuleInstances(specName, moduleName) || []; return api.registry.getModuleInstances(specName, moduleName) || [];
} }
@@ -97,7 +101,7 @@ function injectFunctions (instanceId: string, api: DeriveApi, derives: DeriveCus
const result: Record<string, Record<string, AnyFunction>> = {}; const result: Record<string, Record<string, AnyFunction>> = {};
const names = Object.keys(derives); const names = Object.keys(derives);
const keys = Object.keys(api.query); const keys = Object.keys(api.query);
const specName = api.runtimeVersion.specName.toString(); const specName = api.runtimeVersion.specName;
const filterKeys = (q: string) => keys.includes(q); const filterKeys = (q: string) => keys.includes(q);
const filterInstances = (q: string) => getModuleInstances(api, specName, q).some(filterKeys); const filterInstances = (q: string) => getModuleInstances(api, specName, q).some(filterKeys);
+3 -3
View File
@@ -3,7 +3,7 @@
import type { DeriveApi } from '../types'; import type { DeriveApi } from '../types';
import { unwrapBlockNumber } from './util'; import { createBlockNumberDerive } from './util';
/** /**
* @name bestNumber * @name bestNumber
@@ -17,7 +17,7 @@ import { unwrapBlockNumber } from './util';
* }); * });
* ``` * ```
*/ */
export const bestNumber = unwrapBlockNumber( export const bestNumber = createBlockNumberDerive(
(api: DeriveApi) => (api: DeriveApi) =>
api.derive.chain.subscribeNewHeads() api.rpc.chain.subscribeNewHeads()
); );
@@ -3,7 +3,7 @@
import type { DeriveApi } from '../types'; import type { DeriveApi } from '../types';
import { unwrapBlockNumber } from './util'; import { createBlockNumberDerive } from './util';
/** /**
* @name bestNumberFinalized * @name bestNumberFinalized
@@ -18,7 +18,7 @@ import { unwrapBlockNumber } from './util';
* }); * });
* ``` * ```
*/ */
export const bestNumberFinalized = unwrapBlockNumber( export const bestNumberFinalized = createBlockNumberDerive(
(api: DeriveApi) => (api: DeriveApi) =>
api.rpc.chain.subscribeFinalizedHeads() api.rpc.chain.subscribeFinalizedHeads()
); );
+15 -21
View File
@@ -5,10 +5,11 @@ import type { Observable } from 'rxjs';
import type { SignedBlockExtended } from '../type/types'; import type { SignedBlockExtended } from '../type/types';
import type { DeriveApi } from '../types'; import type { DeriveApi } from '../types';
import { catchError, combineLatest, map, of, switchMap } from 'rxjs'; import { combineLatest, map, of, switchMap } from 'rxjs';
import { createSignedBlockExtended } from '../type'; import { createSignedBlockExtended } from '../type';
import { memo } from '../util'; import { memo } from '../util';
import { getAuthorDetails } from './util';
/** /**
* @name getBlock * @name getBlock
@@ -23,29 +24,22 @@ import { memo } from '../util';
* console.log(`block #${block.header.number} was authored by ${author}`); * console.log(`block #${block.header.number} was authored by ${author}`);
* ``` * ```
*/ */
export function getBlock (instanceId: string, api: DeriveApi): (hash: Uint8Array | string) => Observable<SignedBlockExtended | undefined> { export function getBlock (instanceId: string, api: DeriveApi): (hash: Uint8Array | string) => Observable<SignedBlockExtended> {
return memo(instanceId, (blockHash: Uint8Array | string): Observable<SignedBlockExtended | undefined> => return memo(instanceId, (blockHash: Uint8Array | string): Observable<SignedBlockExtended> =>
combineLatest([ combineLatest([
api.rpc.chain.getBlock(blockHash), api.rpc.chain.getBlock(blockHash),
api.queryAt(blockHash).pipe( api.queryAt(blockHash)
switchMap((queryAt) =>
combineLatest([
queryAt.system.events(),
queryAt.session
? queryAt.session.validators()
: of([])
])
)
)
]).pipe( ]).pipe(
map(([signedBlock, [events, validators]]) => switchMap(([signedBlock, queryAt]) =>
createSignedBlockExtended(api.registry, signedBlock, events, validators) combineLatest([
of(signedBlock),
queryAt.system.events(),
getAuthorDetails(signedBlock.block.header, queryAt)
])
), ),
catchError((): Observable<undefined> => map(([signedBlock, events, [, validators, author]]) =>
// where rpc.chain.getHeader throws, we will land here - it can happen that createSignedBlockExtended(events.registry, signedBlock, events, validators, author)
// we supplied an invalid hash. (Due to defaults, storage will have an
// empty value, so only the RPC is affected). So return undefined
of()
) )
)); )
);
} }
@@ -10,8 +10,8 @@ import { switchMap } from 'rxjs';
import { memo } from '../util'; import { memo } from '../util';
export function getBlockByNumber (instanceId: string, api: DeriveApi): (blockNumber: AnyNumber) => Observable<SignedBlockExtended | undefined> { export function getBlockByNumber (instanceId: string, api: DeriveApi): (blockNumber: AnyNumber) => Observable<SignedBlockExtended> {
return memo(instanceId, (blockNumber: AnyNumber): Observable<SignedBlockExtended | undefined> => return memo(instanceId, (blockNumber: AnyNumber): Observable<SignedBlockExtended> =>
api.rpc.chain.getBlockHash(blockNumber).pipe( api.rpc.chain.getBlockHash(blockNumber).pipe(
switchMap((h) => api.derive.chain.getBlock(h)) switchMap((h) => api.derive.chain.getBlock(h))
) )
+11 -19
View File
@@ -2,14 +2,14 @@
// SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: Apache-2.0
import type { Observable } from 'rxjs'; import type { Observable } from 'rxjs';
import type { AccountId } from '@polkadot/types/interfaces';
import type { HeaderExtended } from '../type/types'; import type { HeaderExtended } from '../type/types';
import type { DeriveApi } from '../types'; import type { DeriveApi } from '../types';
import { catchError, combineLatest, map, of, switchMap } from 'rxjs'; import { combineLatest, map, switchMap } from 'rxjs';
import { createHeaderExtended } from '../type'; import { createHeaderExtended } from '../type';
import { memo } from '../util'; import { memo } from '../util';
import { getAuthorDetails } from './util';
/** /**
* @name getHeader * @name getHeader
@@ -25,26 +25,18 @@ import { memo } from '../util';
* console.log(`block #${number} was authored by ${author}`); * console.log(`block #${number} was authored by ${author}`);
* ``` * ```
*/ */
export function getHeader (instanceId: string, api: DeriveApi): (blockHash: Uint8Array | string) => Observable<HeaderExtended | undefined> { export function getHeader (instanceId: string, api: DeriveApi): (blockHash: Uint8Array | string) => Observable<HeaderExtended> {
return memo(instanceId, (blockHash: Uint8Array | string): Observable<HeaderExtended | undefined> => return memo(instanceId, (blockHash: Uint8Array | string): Observable<HeaderExtended> =>
combineLatest([ combineLatest([
api.rpc.chain.getHeader(blockHash), api.rpc.chain.getHeader(blockHash),
api.queryAt(blockHash).pipe( api.queryAt(blockHash)
switchMap((queryAt) =>
queryAt.session
? queryAt.session.validators()
: of([] as AccountId[])
)
)
]).pipe( ]).pipe(
map(([header, validators]) => switchMap(([header, queryAt]) =>
createHeaderExtended(header.registry, header, validators) getAuthorDetails(header, queryAt)
), ),
catchError((): Observable<undefined> => map(([header, validators, author]) =>
// where rpc.chain.getHeader throws, we will land here - it can happen that createHeaderExtended((validators || header).registry, header, validators, author)
// we supplied an invalid hash. (Due to defaults, storeage will have an
// empty value, so only the RPC is affected). So return undefined
of()
) )
)); )
);
} }
+1
View File
@@ -7,5 +7,6 @@ export * from './bestNumberLag';
export * from './getHeader'; export * from './getHeader';
export * from './getBlock'; export * from './getBlock';
export * from './getBlockByNumber'; export * from './getBlockByNumber';
export * from './subscribeFinalizedHeads';
export * from './subscribeNewBlocks'; export * from './subscribeNewBlocks';
export * from './subscribeNewHeads'; export * from './subscribeNewHeads';
@@ -0,0 +1,24 @@
// Copyright 2017-2022 @polkadot/api-derive authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { Observable } from 'rxjs';
import type { SignedBlockExtended } from '../type/types';
import type { DeriveApi } from '../types';
import { switchMap } from 'rxjs';
import { memo } from '../util';
/**
* @name subscribeFinalizedBlocks
* @returns The finalized block & events for that block
*/
export function subscribeFinalizedBlocks (instanceId: string, api: DeriveApi): () => Observable<SignedBlockExtended> {
return memo(instanceId, (): Observable<SignedBlockExtended> =>
api.derive.chain.subscribeFinalizedHeads().pipe(
switchMap((header) =>
api.derive.chain.getBlock(header.createdAtHash || header.hash)
)
)
);
}
@@ -0,0 +1,56 @@
// Copyright 2017-2022 @polkadot/api-derive authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { Observable } from 'rxjs';
import type { Hash, Header } from '@polkadot/types/interfaces';
import type { DeriveApi } from '../types';
import { from, of, switchMap } from 'rxjs';
import { memo } from '../util';
/**
* Returns a header range from startHash to to (not including) endHash, i.e. lastBlock.parentHash === endHash
*/
export function _getHeaderRange (instanceId: string, api: DeriveApi): (startHash: Hash, endHash: Hash, prev?: Header[]) => Observable<Header[]> {
return memo(instanceId, (startHash: Hash, endHash: Hash, prev: Header[] = []): Observable<Header[]> =>
api.rpc.chain.getHeader(startHash).pipe(
switchMap((header) =>
header.parentHash.eq(endHash)
? of([header, ...prev])
: api.derive.chain._getHeaderRange(header.parentHash, endHash, [header, ...prev])
)
)
);
}
/**
* @name subscribeFinalizedHeads
* @description An observable of the finalized block headers. Unlike the base
* chain.subscribeFinalizedHeads this does not skip any headers. Since finalization
* may skip specific blocks (finalization happens in terms of chains), this version
* of the derive tracks missing headers (since last retrieved) and provides them
* to the caller
*/
export function subscribeFinalizedHeads (instanceId: string, api: DeriveApi): () => Observable<Header> {
return memo(instanceId, (): Observable<Header> => {
let prevHash: Hash | null = null;
return api.rpc.chain.subscribeFinalizedHeads().pipe(
switchMap((header) => {
const endHash = prevHash;
const startHash = header.parentHash;
prevHash = header.createdAtHash = header.hash;
return endHash === null || startHash.eq(endHash)
? of(header)
: api.derive.chain._getHeaderRange(startHash, endHash, [header]).pipe(
switchMap((headers) =>
from(headers)
)
);
})
);
});
}
@@ -5,9 +5,8 @@ import type { Observable } from 'rxjs';
import type { SignedBlockExtended } from '../type/types'; import type { SignedBlockExtended } from '../type/types';
import type { DeriveApi } from '../types'; import type { DeriveApi } from '../types';
import { combineLatest, map, of, switchMap } from 'rxjs'; import { switchMap } from 'rxjs';
import { createSignedBlockExtended } from '../type';
import { memo } from '../util'; import { memo } from '../util';
/** /**
@@ -17,22 +16,8 @@ import { memo } from '../util';
export function subscribeNewBlocks (instanceId: string, api: DeriveApi): () => Observable<SignedBlockExtended> { export function subscribeNewBlocks (instanceId: string, api: DeriveApi): () => Observable<SignedBlockExtended> {
return memo(instanceId, (): Observable<SignedBlockExtended> => return memo(instanceId, (): Observable<SignedBlockExtended> =>
api.derive.chain.subscribeNewHeads().pipe( api.derive.chain.subscribeNewHeads().pipe(
switchMap((header) => { switchMap((header) =>
const blockHash = header.createdAtHash || header.hash; api.derive.chain.getBlock(header.createdAtHash || header.hash)
// we get the block first, setting up the registry
return combineLatest([
of(header),
api.rpc.chain.getBlock(blockHash),
api.queryAt(blockHash).pipe(
switchMap((queryAt) =>
queryAt.system.events()
)
)
]);
}),
map(([header, block, events]) =>
createSignedBlockExtended(block.registry, block, events, header.validators)
) )
) )
); );
@@ -5,10 +5,11 @@ import type { Observable } from 'rxjs';
import type { HeaderExtended } from '../type/types'; import type { HeaderExtended } from '../type/types';
import type { DeriveApi } from '../types'; import type { DeriveApi } from '../types';
import { combineLatest, map, of } from 'rxjs'; import { combineLatest, map, of, switchMap } from 'rxjs';
import { createHeaderExtended } from '../type'; import { createHeaderExtended } from '../type';
import { memo } from '../util'; import { memo } from '../util';
import { getAuthorDetails } from './util';
/** /**
* @name subscribeNewHeads * @name subscribeNewHeads
@@ -25,16 +26,20 @@ import { memo } from '../util';
*/ */
export function subscribeNewHeads (instanceId: string, api: DeriveApi): () => Observable<HeaderExtended> { export function subscribeNewHeads (instanceId: string, api: DeriveApi): () => Observable<HeaderExtended> {
return memo(instanceId, (): Observable<HeaderExtended> => return memo(instanceId, (): Observable<HeaderExtended> =>
combineLatest([ api.rpc.chain.subscribeNewHeads().pipe(
api.rpc.chain.subscribeNewHeads(), switchMap((header) =>
api.query.session combineLatest([
? api.query.session.validators() of(header),
: of(undefined) api.queryAt(header.hash)
]).pipe( ])
map(([header, validators]): HeaderExtended => { ),
switchMap(([header, queryAt]) =>
getAuthorDetails(header, queryAt)
),
map(([header, validators, author]): HeaderExtended => {
header.createdAtHash = header.hash; header.createdAtHash = header.hash;
return createHeaderExtended(header.registry, header, validators); return createHeaderExtended(header.registry, header, validators, author);
}) })
) )
); );
+45 -8
View File
@@ -2,21 +2,58 @@
// SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: Apache-2.0
import type { Observable } from 'rxjs'; import type { Observable } from 'rxjs';
import type { Compact } from '@polkadot/types'; import type { QueryableStorage } from '@polkadot/api-base/types';
import type { BlockNumber } from '@polkadot/types/interfaces'; import type { Compact, Vec } from '@polkadot/types';
import type { AccountId, BlockNumber, Header } from '@polkadot/types/interfaces';
import type { Codec, IOption } from '@polkadot/types/types';
import type { DeriveApi } from '../types'; import type { DeriveApi } from '../types';
import { map } from 'rxjs'; import { combineLatest, map, of } from 'rxjs';
import { memo } from '../util'; import { memo, unwrapBlockNumber } from '../util';
// re-export these - since these needs to be resolvable from api-derive, i.e. without this // re-export these - since these needs to be resolvable from api-derive, i.e. without this
// we would emit code with ../<somewhere>/src embedded in the *.d.ts files // we would emit code with ../<somewhere>/src embedded in the *.d.ts files
export type { BlockNumber } from '@polkadot/types/interfaces'; export type { BlockNumber } from '@polkadot/types/interfaces';
export function unwrapBlockNumber <T extends { number: Compact<BlockNumber> }> (fn: (api: DeriveApi) => Observable<T>): (instanceId: string, api: DeriveApi) => () => Observable<BlockNumber> { export function createBlockNumberDerive <T extends { number: Compact<BlockNumber> | BlockNumber }> (fn: (api: DeriveApi) => Observable<T>): (instanceId: string, api: DeriveApi) => () => Observable<BlockNumber> {
return (instanceId: string, api: DeriveApi) => return (instanceId: string, api: DeriveApi) =>
memo(instanceId, () => fn(api).pipe( memo(instanceId, () =>
map((r) => r.number.unwrap()) fn(api).pipe(
)); map(unwrapBlockNumber)
)
);
}
export function getAuthorDetails (header: Header, queryAt: QueryableStorage<'rxjs'>): Observable<[Header, Vec<AccountId> | null, AccountId | null]> {
// this is Moonbeam specific
if (queryAt.authorMapping && queryAt.authorMapping.mappingWithDeposit) {
const mapId = header.digest.logs[0] && (
(header.digest.logs[0].isConsensus && header.digest.logs[0].asConsensus[1]) ||
(header.digest.logs[0].isPreRuntime && header.digest.logs[0].asPreRuntime[1])
);
if (mapId) {
return combineLatest([
of(header),
queryAt.session
? queryAt.session.validators()
: of(null),
queryAt.authorMapping.mappingWithDeposit<IOption<{ account: AccountId } & Codec>>(mapId).pipe(
map((opt) =>
opt.unwrapOr({ account: null }).account
)
)
]);
}
}
// normal operation, non-mapping
return combineLatest([
of(header),
queryAt.session
? queryAt.session.validators()
: of(null),
of(null)
]);
} }
@@ -12,7 +12,7 @@ import { isFunction } from '@polkadot/util';
import { memo } from '../util'; import { memo } from '../util';
export function getInstance (api: DeriveApi, section: string): DeriveApi['query']['council'] { export function getInstance (api: DeriveApi, section: string): DeriveApi['query']['council'] {
const instances = api.registry.getModuleInstances(api.runtimeVersion.specName.toString(), section); const instances = api.registry.getModuleInstances(api.runtimeVersion.specName, section);
const name = instances && instances.length const name = instances && instances.length
? instances[0] ? instances[0]
: section; : section;
@@ -58,7 +58,7 @@ export function hasProposals (section: Collective): (instanceId: string, api: De
export function proposals (section: Collective): (instanceId: string, api: DeriveApi) => () => Observable<DeriveCollectiveProposal[]> { export function proposals (section: Collective): (instanceId: string, api: DeriveApi) => () => Observable<DeriveCollectiveProposal[]> {
return withSection(section, (query, api) => return withSection(section, (query, api) =>
(): Observable<DeriveCollectiveProposal[]> => (): Observable<DeriveCollectiveProposal[]> =>
api.derive[section].proposalHashes().pipe( api.derive[section as 'council'].proposalHashes().pipe(
switchMap((all) => _proposalsFrom(api, query, all)) switchMap((all) => _proposalsFrom(api, query, all))
) )
); );
+1 -1
View File
@@ -1,4 +1,4 @@
// Copyright 2017-2022 @polkadot/api-derive authors & contributors // Copyright 2017-2022 @polkadot/api-derive authors & contributors
// SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: Apache-2.0
export type Collective = 'council' | 'membership' | 'technicalCommittee'; export type Collective = 'allianceMotion' | 'council' | 'membership' | 'technicalCommittee';
@@ -7,6 +7,8 @@ import type { DeriveApi, DeriveOwnContributions } from '../types';
import { combineLatest, EMPTY, map, of, startWith, switchMap } from 'rxjs'; import { combineLatest, EMPTY, map, of, startWith, switchMap } from 'rxjs';
import { objectSpread } from '@polkadot/util';
import { memo } from '../util'; import { memo } from '../util';
import { extractContributed } from './util'; import { extractContributed } from './util';
@@ -21,10 +23,8 @@ function _getValues (api: DeriveApi, childKey: string, keys: string[]): Observab
? api.registry.createType('Balance', o.unwrap()) ? api.registry.createType('Balance', o.unwrap())
: api.registry.createType('Balance') : api.registry.createType('Balance')
) )
.reduce((all: DeriveOwnContributions, b, index): DeriveOwnContributions => ({ .reduce((all: DeriveOwnContributions, b, index): DeriveOwnContributions =>
...all, objectSpread(all, { [keys[index]]: b }), {})
[keys[index]]: b
}), {})
) )
); );
} }
@@ -51,10 +51,9 @@ function _contributions (api: DeriveApi, paraId: string | number | BN, childKey:
_getValues(api, childKey, keys), _getValues(api, childKey, keys),
_watchOwnChanges(api, paraId, childKey, keys) _watchOwnChanges(api, paraId, childKey, keys)
]).pipe( ]).pipe(
map(([all, latest]) => ({ map(([all, latest]) =>
...all, objectSpread({}, all, latest)
...latest )
}))
); );
} }
@@ -11,7 +11,7 @@ import type { DeriveApi, DeriveDispatch, DeriveProposalImage } from '../types';
import { catchError, combineLatest, map, of, switchMap } from 'rxjs'; import { catchError, combineLatest, map, of, switchMap } from 'rxjs';
import { Enum } from '@polkadot/types'; import { Enum } from '@polkadot/types';
import { isFunction, stringToHex } from '@polkadot/util'; import { isFunction, objectSpread, stringToHex } from '@polkadot/util';
import { memo } from '../util'; import { memo } from '../util';
@@ -107,7 +107,7 @@ function queryScheduler (api: DeriveApi): Observable<DeriveDispatch[]> {
]); ]);
}), }),
map(([infos, images]): DeriveDispatch[] => map(([infos, images]): DeriveDispatch[] =>
infos.map((info, index) => ({ ...info, image: images[index] })) infos.map((info, index) => objectSpread({ image: images[index] }, info))
) )
); );
} }
+16 -14
View File
@@ -9,7 +9,7 @@ import type { DeriveApi, DeriveProposal, DeriveProposalImage } from '../types';
import { combineLatest, map, of, switchMap } from 'rxjs'; import { combineLatest, map, of, switchMap } from 'rxjs';
import { isFunction } from '@polkadot/util'; import { isFunction, objectSpread } from '@polkadot/util';
import { memo } from '../util'; import { memo } from '../util';
@@ -33,17 +33,17 @@ function parse ([proposals, images, optDepositors]: Result): DeriveProposal[] {
.map(([index, imageHash, proposer], proposalIndex): DeriveProposal => { .map(([index, imageHash, proposer], proposalIndex): DeriveProposal => {
const depositors = optDepositors[proposalIndex].unwrap(); const depositors = optDepositors[proposalIndex].unwrap();
return { return objectSpread(
...( {
isNewDepositors(depositors) image: images[proposalIndex],
? { balance: depositors[1], seconds: depositors[0] } imageHash,
: { balance: depositors[0], seconds: depositors[1] } index,
), proposer
image: images[proposalIndex], },
imageHash, isNewDepositors(depositors)
index, ? { balance: depositors[1], seconds: depositors[0] }
proposer : { balance: depositors[0], seconds: depositors[1] }
}; );
}); });
} }
@@ -56,9 +56,11 @@ export function proposals (instanceId: string, api: DeriveApi): () => Observable
? combineLatest([ ? combineLatest([
of(proposals), of(proposals),
api.derive.democracy.preimages( api.derive.democracy.preimages(
proposals.map(([, hash]) => hash)), proposals.map(([, hash]) => hash)
),
api.query.democracy.depositOf.multi( api.query.democracy.depositOf.multi(
proposals.map(([index]) => index)) proposals.map(([index]) => index)
)
]) ])
: of<Result>([[], [], []]) : of<Result>([[], [], []])
), ),
@@ -6,6 +6,8 @@ import type { DeriveApi, DeriveReferendumExt } from '../types';
import { combineLatest, map, of, switchMap } from 'rxjs'; import { combineLatest, map, of, switchMap } from 'rxjs';
import { objectSpread } from '@polkadot/util';
import { memo } from '../util'; import { memo } from '../util';
export function referendums (instanceId: string, api: DeriveApi): () => Observable<DeriveReferendumExt[]> { export function referendums (instanceId: string, api: DeriveApi): () => Observable<DeriveReferendumExt[]> {
@@ -20,10 +22,9 @@ export function referendums (instanceId: string, api: DeriveApi): () => Observab
: of([[], []]) : of([[], []])
), ),
map(([referendums, votes]) => map(([referendums, votes]) =>
referendums.map((referendum, index): DeriveReferendumExt => ({ referendums.map((referendum, index): DeriveReferendumExt =>
...referendum, objectSpread({}, referendum, votes[index])
...votes[index] )
}))
) )
) )
); );
@@ -10,7 +10,7 @@ import type { DeriveApi, DeriveBalancesAccount, DeriveReferendum, DeriveReferend
import { combineLatest, map, of, switchMap } from 'rxjs'; import { combineLatest, map, of, switchMap } from 'rxjs';
import { isFunction } from '@polkadot/util'; import { isFunction, objectSpread } from '@polkadot/util';
import { memo } from '../util'; import { memo } from '../util';
import { calcVotes, getStatus } from './util'; import { calcVotes, getStatus } from './util';
@@ -57,11 +57,12 @@ function extractVotes (mapped: [AccountId, PalletDemocracyVoteVoting][], referen
// FIXME We are ignoring split votes // FIXME We are ignoring split votes
votes.reduce((result: DeriveReferendumVote[], [, vote]): DeriveReferendumVote[] => { votes.reduce((result: DeriveReferendumVote[], [, vote]): DeriveReferendumVote[] => {
if (vote.isStandard) { if (vote.isStandard) {
result.push({ result.push(
accountId, objectSpread({
isDelegating: false, accountId,
...vote.asStandard isDelegating: false
}); }, vote.asStandard)
);
} }
return result; return result;
+3 -4
View File
@@ -6,7 +6,7 @@ import type { PalletDemocracyReferendumInfo, PalletDemocracyReferendumStatus, Pa
import type { Option } from '@polkadot/types-codec'; import type { Option } from '@polkadot/types-codec';
import type { DeriveReferendum, DeriveReferendumVote, DeriveReferendumVotes, DeriveReferendumVoteState } from '../types'; import type { DeriveReferendum, DeriveReferendumVote, DeriveReferendumVotes, DeriveReferendumVoteState } from '../types';
import { BN, bnSqrt } from '@polkadot/util'; import { BN, bnSqrt, objectSpread } from '@polkadot/util';
interface ApproxState { interface ApproxState {
votedAye: BN; votedAye: BN;
@@ -119,11 +119,10 @@ export function calcVotes (sqrtElectorate: BN, referendum: DeriveReferendum, vot
? calcVotesCurrent(referendum.status.tally, votes) ? calcVotesCurrent(referendum.status.tally, votes)
: calcVotesPrev(votes); : calcVotesPrev(votes);
return { return objectSpread({}, state, {
...state,
isPassing: calcPassing(referendum.status.threshold, sqrtElectorate, state), isPassing: calcPassing(referendum.status.threshold, sqrtElectorate, state),
votes votes
}; });
} }
export function getStatus (info: Option<PalletDemocracyReferendumInfo | ReferendumInfoTo239>): PalletDemocracyReferendumStatus | ReferendumInfoTo239 | null { export function getStatus (info: Option<PalletDemocracyReferendumInfo | ReferendumInfoTo239>): PalletDemocracyReferendumStatus | ReferendumInfoTo239 | null {
+2 -1
View File
@@ -4,6 +4,7 @@
import type { AnyFunction } from '@polkadot/types/types'; import type { AnyFunction } from '@polkadot/types/types';
import * as accounts from './accounts'; import * as accounts from './accounts';
import * as alliance from './alliance';
import * as bagsList from './bagsList'; import * as bagsList from './bagsList';
import * as balances from './balances'; import * as balances from './balances';
import * as bounties from './bounties'; import * as bounties from './bounties';
@@ -23,7 +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 const derive = { accounts, bagsList, balances, bounties, chain, contracts, council, crowdloan, democracy, elections, imOnline, membership, parachains, session, society, staking, technicalCommittee, treasury, tx }; export const derive = { accounts, alliance, bagsList, balances, bounties, chain, contracts, council, crowdloan, democracy, elections, imOnline, membership, parachains, session, society, staking, technicalCommittee, treasury, tx };
type DeriveSection<Section> = { type DeriveSection<Section> = {
[M in keyof Section]: Section[M] extends AnyFunction [M in keyof Section]: Section[M] extends AnyFunction
+13 -10
View File
@@ -11,6 +11,8 @@ import type { DeriveElectionsInfo } from './types';
import { combineLatest, map, of } from 'rxjs'; import { combineLatest, map, of } from 'rxjs';
import { objectSpread } from '@polkadot/util';
import { memo } from '../util'; import { memo } from '../util';
// SeatHolder is current tuple is 2.x-era Substrate // SeatHolder is current tuple is 2.x-era Substrate
@@ -55,7 +57,7 @@ function getConstants (api: DeriveApi, elections: string | null): Partial<Derive
} }
function getModules (api: DeriveApi): [string, string | null] { function getModules (api: DeriveApi): [string, string | null] {
const [council] = api.registry.getModuleInstances(api.runtimeVersion.specName.toString(), 'council') || ['council']; const [council] = api.registry.getModuleInstances(api.runtimeVersion.specName, 'council') || ['council'];
const elections = api.query.phragmenElection const elections = api.query.phragmenElection
? 'phragmenElection' ? 'phragmenElection'
: api.query.electionsPhragmen : api.query.electionsPhragmen
@@ -107,15 +109,16 @@ export function info (instanceId: string, api: DeriveApi): () => Observable<Deri
? queryAll(api, council, elections) ? queryAll(api, council, elections)
: queryCouncil(api, council) : queryCouncil(api, council)
).pipe( ).pipe(
map(([councilMembers, candidates, members, runnersUp]): DeriveElectionsInfo => ({ map(([councilMembers, candidates, members, runnersUp]): DeriveElectionsInfo =>
...getConstants(api, elections), objectSpread({}, getConstants(api, elections), {
candidateCount: api.registry.createType('u32', candidates.length), candidateCount: api.registry.createType('u32', candidates.length),
candidates: candidates.map(getCandidate), candidates: candidates.map(getCandidate),
members: members.length members: members.length
? members.map(getAccountTuple).sort(sortAccounts) ? members.map(getAccountTuple).sort(sortAccounts)
: councilMembers.map((a): [AccountId32, Balance] => [a, api.registry.createType('Balance')]), : councilMembers.map((a): [AccountId32, Balance] => [a, api.registry.createType('Balance')]),
runnersUp: runnersUp.map(getAccountTuple).sort(sortAccounts) runnersUp: runnersUp.map(getAccountTuple).sort(sortAccounts)
})) })
)
); );
}); });
} }
+1 -1
View File
@@ -3,4 +3,4 @@
// Do not edit, auto-generated by @polkadot/dev // Do not edit, auto-generated by @polkadot/dev
export const packageInfo = { name: '@polkadot/api-derive', path: 'auto', type: 'auto', version: '8.12.1' }; export const packageInfo = { name: '@polkadot/api-derive', path: 'auto', type: 'auto', version: '9.0.1' };
+15 -15
View File
@@ -8,6 +8,8 @@ import type { Active, DidUpdate, Heads, ParaInfoResult, PendingSwap, RelayDispat
import { map, of } from 'rxjs'; import { map, of } from 'rxjs';
import { objectSpread } from '@polkadot/util';
import { memo } from '../util'; import { memo } from '../util';
import { didUpdateToBool } from './util'; import { didUpdateToBool } from './util';
@@ -28,20 +30,18 @@ function parseActive (id: ParaId, active: Active): DeriveParachainActive | null
if (found && found[1].isSome) { if (found && found[1].isSome) {
const [collatorId, retriable] = found[1].unwrap(); const [collatorId, retriable] = found[1].unwrap();
return { return objectSpread<DeriveParachainActive>(
collatorId, { collatorId },
...( retriable.isWithRetries
retriable.isWithRetries ? {
? { isRetriable: true,
isRetriable: true, retries: retriable.asWithRetries.toNumber()
retries: retriable.asWithRetries.toNumber() }
} : {
: { isRetriable: false,
isRetriable: false, retries: 0
retries: 0 }
} );
)
};
} }
return null; return null;
@@ -65,7 +65,7 @@ function parse (id: ParaId, [active, retryQueue, selectedThreads, didUpdate, inf
didUpdate: didUpdateToBool(didUpdate, id), didUpdate: didUpdateToBool(didUpdate, id),
heads, heads,
id, id,
info: { id, ...info.unwrap() } as DeriveParachainInfo, info: objectSpread<DeriveParachainInfo>({ id }, info.unwrap()),
pendingSwapId: pendingSwap.unwrapOr(null), pendingSwapId: pendingSwap.unwrapOr(null),
relayDispatchQueue, relayDispatchQueue,
retryCollators: parseCollators(id, retryQueue), retryCollators: parseCollators(id, retryQueue),
@@ -8,6 +8,8 @@ import type { DidUpdate, ParaInfoResult, PendingSwap, RelayDispatchQueueSize } f
import { combineLatest, map, of, switchMap } from 'rxjs'; import { combineLatest, map, of, switchMap } from 'rxjs';
import { objectSpread } from '@polkadot/util';
import { memo } from '../util'; import { memo } from '../util';
import { didUpdateToBool } from './util'; import { didUpdateToBool } from './util';
@@ -23,7 +25,7 @@ function parse ([ids, didUpdate, infos, pendingSwaps, relayDispatchQueueSizes]:
return ids.map((id, index): DeriveParachain => ({ return ids.map((id, index): DeriveParachain => ({
didUpdate: didUpdateToBool(didUpdate, id), didUpdate: didUpdateToBool(didUpdate, id),
id, id,
info: { id, ...infos[index].unwrapOr(null) } as DeriveParachainInfo, info: objectSpread<DeriveParachainInfo>({ id }, infos[index].unwrapOr(null)),
pendingSwapId: pendingSwaps[index].unwrapOr(null), pendingSwapId: pendingSwaps[index].unwrapOr(null),
relayDispatchQueueSize: relayDispatchQueueSizes[index][0].toNumber() relayDispatchQueueSize: relayDispatchQueueSizes[index][0].toNumber()
})); }));
+4 -3
View File
@@ -6,6 +6,8 @@ import type { DeriveApi, DeriveSessionInfo } from '../types';
import { map } from 'rxjs'; import { map } from 'rxjs';
import { objectSpread } from '@polkadot/util';
import { memo } from '../util'; import { memo } from '../util';
/** /**
@@ -18,13 +20,12 @@ export function info (instanceId: string, api: DeriveApi): () => Observable<Deri
const sessionLength = api.consts?.babe?.epochDuration || api.registry.createType('u64', 1); const sessionLength = api.consts?.babe?.epochDuration || api.registry.createType('u64', 1);
const sessionsPerEra = api.consts?.staking?.sessionsPerEra || api.registry.createType('SessionIndex', 1); const sessionsPerEra = api.consts?.staking?.sessionsPerEra || api.registry.createType('SessionIndex', 1);
return { return objectSpread({
...indexes,
eraLength: api.registry.createType('BlockNumber', sessionsPerEra.mul(sessionLength)), eraLength: api.registry.createType('BlockNumber', sessionsPerEra.mul(sessionLength)),
isEpoch: !!api.query.babe, isEpoch: !!api.query.babe,
sessionLength, sessionLength,
sessionsPerEra sessionsPerEra
}; }, indexes);
}) })
) )
); );
+10 -8
View File
@@ -8,6 +8,8 @@ import type { DeriveApi, DeriveSessionInfo, DeriveSessionProgress } from '../typ
import { combineLatest, map, of, switchMap } from 'rxjs'; import { combineLatest, map, of, switchMap } from 'rxjs';
import { objectSpread } from '@polkadot/util';
import { memo } from '../util'; import { memo } from '../util';
type ResultSlotsNoSession = [u64, u64, u64]; type ResultSlotsNoSession = [u64, u64, u64];
@@ -28,20 +30,20 @@ function createDerive (api: DeriveApi, info: DeriveSessionInfo, [currentSlot, ep
const sessionProgress = currentSlot.sub(epochStartSlot); const sessionProgress = currentSlot.sub(epochStartSlot);
const eraProgress = info.currentIndex.sub(activeEraStartSessionIndex).imul(info.sessionLength).iadd(sessionProgress); const eraProgress = info.currentIndex.sub(activeEraStartSessionIndex).imul(info.sessionLength).iadd(sessionProgress);
return { return objectSpread({
...info,
eraProgress: api.registry.createType('BlockNumber', eraProgress), eraProgress: api.registry.createType('BlockNumber', eraProgress),
sessionProgress: api.registry.createType('BlockNumber', sessionProgress) sessionProgress: api.registry.createType('BlockNumber', sessionProgress)
}; }, info);
} }
function queryAura (api: DeriveApi): Observable<DeriveSessionProgress> { function queryAura (api: DeriveApi): Observable<DeriveSessionProgress> {
return api.derive.session.info().pipe( return api.derive.session.info().pipe(
map((info): DeriveSessionProgress => ({ map((info): DeriveSessionProgress =>
...info, objectSpread({
eraProgress: api.registry.createType('BlockNumber'), eraProgress: api.registry.createType('BlockNumber'),
sessionProgress: api.registry.createType('BlockNumber') sessionProgress: api.registry.createType('BlockNumber')
})) }, info)
)
); );
} }
+3 -5
View File
@@ -9,7 +9,7 @@ import type { StakingQueryFlags } from './types';
import { combineLatest, map, switchMap } from 'rxjs'; import { combineLatest, map, switchMap } from 'rxjs';
import { BN, BN_ZERO } from '@polkadot/util'; import { BN, BN_ZERO, objectSpread } from '@polkadot/util';
import { firstMemo, memo } from '../util'; import { firstMemo, memo } from '../util';
@@ -54,12 +54,10 @@ function redeemableSum (api: DeriveApi, stakingLedger: PalletStakingStakingLedge
} }
function parseResult (api: DeriveApi, sessionInfo: DeriveSessionInfo, keys: DeriveStakingKeys, query: DeriveStakingQuery): DeriveStakingAccount { function parseResult (api: DeriveApi, sessionInfo: DeriveSessionInfo, keys: DeriveStakingKeys, query: DeriveStakingQuery): DeriveStakingAccount {
return { return objectSpread({}, keys, query, {
...keys,
...query,
redeemable: redeemableSum(api, query.stakingLedger, sessionInfo), redeemable: redeemableSum(api, query.stakingLedger, sessionInfo),
unlocking: calculateUnlocking(api, query.stakingLedger, sessionInfo) unlocking: calculateUnlocking(api, query.stakingLedger, sessionInfo)
}; });
} }
/** /**
+8 -5
View File
@@ -6,6 +6,8 @@ import type { DeriveApi, DeriveStakingOverview } from '../types';
import { combineLatest, map } from 'rxjs'; import { combineLatest, map } from 'rxjs';
import { objectSpread } from '@polkadot/util';
import { memo } from '../util'; import { memo } from '../util';
/** /**
@@ -17,10 +19,11 @@ export function overview (instanceId: string, api: DeriveApi): () => Observable<
api.derive.session.indexes(), api.derive.session.indexes(),
api.derive.staking.validators() api.derive.staking.validators()
]).pipe( ]).pipe(
map(([indexes, { nextElected, validators }]): DeriveStakingOverview => ({ map(([indexes, { nextElected, validators }]): DeriveStakingOverview =>
...indexes, objectSpread({}, indexes, {
nextElected, nextElected,
validators validators
})) })
)
)); ));
} }
@@ -10,7 +10,7 @@ import type { DeriveStakingQuery } from './types';
import { combineLatest, map, of, switchMap } from 'rxjs'; import { combineLatest, map, of, switchMap } from 'rxjs';
import { BN_BILLION, BN_ZERO } from '@polkadot/util'; import { BN_BILLION, BN_ZERO, objectSpread } from '@polkadot/util';
import { firstMemo, memo } from '../util'; import { firstMemo, memo } from '../util';
@@ -125,10 +125,11 @@ function filterRewards (eras: EraIndex[], valInfo: [string, DeriveStakingQuery][
return true; return true;
}) })
.filter(({ validators }) => Object.keys(validators).length !== 0) .filter(({ validators }) => Object.keys(validators).length !== 0)
.map((reward) => ({ .map((reward) =>
...reward, objectSpread({}, 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: DeriveApi): (eras: EraIndex[], withActive?: boolean) => Observable<ErasResult> { export function _stakerRewardsEras (instanceId: string, api: DeriveApi): (eras: EraIndex[], withActive?: boolean) => Observable<ErasResult> {
+2 -1
View File
@@ -10,6 +10,7 @@ import { combineLatest, map, of, switchMap } from 'rxjs';
import { isNumber, isUndefined } from '@polkadot/util'; import { isNumber, isUndefined } from '@polkadot/util';
import { unwrapBlockNumber } from '../util';
import { FALLBACK_MAX_HASH_COUNT, FALLBACK_PERIOD, MAX_FINALITY_LAG, MORTAL_PERIOD } from './constants'; import { FALLBACK_MAX_HASH_COUNT, FALLBACK_PERIOD, MAX_FINALITY_LAG, MORTAL_PERIOD } from './constants';
interface Result { interface Result {
@@ -51,7 +52,7 @@ function signingHeader (api: DeriveApi): Observable<Header> {
]).pipe( ]).pipe(
map(([current, finalized]) => map(([current, finalized]) =>
// determine the hash to use, current when lag > max, else finalized // determine the hash to use, current when lag > max, else finalized
current.number.unwrap().sub(finalized.number.unwrap()).gt(MAX_FINALITY_LAG) unwrapBlockNumber(current).sub(unwrapBlockNumber(finalized)).gt(MAX_FINALITY_LAG)
? current ? current
: finalized : finalized
) )
+4 -13
View File
@@ -7,19 +7,17 @@ import type { HeaderExtended } from './types';
import { extractAuthor } from './util'; import { extractAuthor } from './util';
export function createHeaderExtended (registry: Registry, header?: Header, validators?: AccountId[]): HeaderExtended { export function createHeaderExtended (registry: Registry, header?: Header, validators?: AccountId[] | null, author?: AccountId | null): HeaderExtended {
// an instance of the base extrinsic for us to extend // an instance of the base extrinsic for us to extend
const HeaderBase = registry.createClass('Header'); const HeaderBase = registry.createClass('Header');
class Implementation extends HeaderBase implements HeaderExtended { class Implementation extends HeaderBase implements HeaderExtended {
readonly #author?: AccountId; readonly #author?: AccountId;
readonly #validators?: AccountId[];
constructor (registry: Registry, header?: Header, validators?: AccountId[]) { constructor (registry: Registry, header?: Header, validators?: AccountId[] | null, author?: AccountId | null) {
super(registry, header); super(registry, header);
this.#author = extractAuthor(this.digest, validators); this.#author = author || extractAuthor(this.digest, validators || []);
this.#validators = validators;
this.createdAtHash = header?.createdAtHash; this.createdAtHash = header?.createdAtHash;
} }
@@ -29,14 +27,7 @@ export function createHeaderExtended (registry: Registry, header?: Header, valid
public get author (): AccountId | undefined { public get author (): AccountId | undefined {
return this.#author; return this.#author;
} }
/**
* @description Convenience method, returns the validators for the block
*/
public get validators (): AccountId[] | undefined {
return this.#validators;
}
} }
return new Implementation(registry, header, validators); return new Implementation(registry, header, validators, author);
} }
@@ -31,7 +31,7 @@ function mapExtrinsics (extrinsics: Extrinsic[], records: EventRecord[]): TxWith
}); });
} }
export function createSignedBlockExtended (registry: Registry, block?: SignedBlock, events?: EventRecord[], validators?: AccountId[]): SignedBlockExtended { export function createSignedBlockExtended (registry: Registry, block?: SignedBlock, events?: EventRecord[], validators?: AccountId[] | null, author?: AccountId | null): SignedBlockExtended {
// an instance of the base extrinsic for us to extend // an instance of the base extrinsic for us to extend
const SignedBlockBase = registry.createClass('SignedBlock'); const SignedBlockBase = registry.createClass('SignedBlock');
@@ -40,10 +40,10 @@ export function createSignedBlockExtended (registry: Registry, block?: SignedBlo
readonly #events: EventRecord[]; readonly #events: EventRecord[];
readonly #extrinsics: TxWithEvent[]; readonly #extrinsics: TxWithEvent[];
constructor (registry: Registry, block?: SignedBlock, events?: EventRecord[], validators?: AccountId[]) { constructor (registry: Registry, block?: SignedBlock, events?: EventRecord[], validators?: AccountId[] | null, author?: AccountId | null) {
super(registry, block); super(registry, block);
this.#author = extractAuthor(this.block.header.digest, validators); this.#author = author || extractAuthor(this.block.header.digest, validators || []);
this.#events = events || ([] as EventRecord[]); this.#events = events || ([] as EventRecord[]);
this.#extrinsics = mapExtrinsics(this.block.extrinsics, this.#events); this.#extrinsics = mapExtrinsics(this.block.extrinsics, this.#events);
this.createdAtHash = block?.createdAtHash; this.createdAtHash = block?.createdAtHash;
@@ -71,5 +71,5 @@ export function createSignedBlockExtended (registry: Registry, block?: SignedBlo
} }
} }
return new Implementation(registry, block, events, validators); return new Implementation(registry, block, events, validators, author);
} }
-1
View File
@@ -5,7 +5,6 @@ import type { AccountId, DispatchError, DispatchInfo, Event, EventRecord, Extrin
export interface HeaderExtended extends Header { export interface HeaderExtended extends Header {
readonly author: AccountId | undefined; readonly author: AccountId | undefined;
readonly validators: AccountId[] | undefined;
} }
export interface SignedBlockExtended extends SignedBlock { export interface SignedBlockExtended extends SignedBlock {
@@ -0,0 +1,15 @@
// Copyright 2017-2022 @polkadot/api-derive authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { Compact } from '@polkadot/types';
import type { BlockNumber } from '@polkadot/types/interfaces';
import { isCompact } from '@polkadot/util';
type CompatHeader = { number: Compact<BlockNumber> | BlockNumber };
export function unwrapBlockNumber (hdr: CompatHeader): BlockNumber {
return isCompact<BlockNumber>(hdr.number)
? hdr.number.unwrap()
: hdr.number;
}
+1
View File
@@ -4,6 +4,7 @@
export { drr, memo } from '@polkadot/rpc-core'; export { drr, memo } from '@polkadot/rpc-core';
export * from './approvalFlagsToBools'; export * from './approvalFlagsToBools';
export * from './blockNumber';
export * from './cache'; export * from './cache';
export * from './cacheImpl'; export * from './cacheImpl';
export * from './first'; export * from './first';
+19 -19
View File
@@ -20,29 +20,29 @@
"./detectPackage.cjs" "./detectPackage.cjs"
], ],
"type": "module", "type": "module",
"version": "8.12.1", "version": "9.0.1",
"main": "index.js", "main": "index.js",
"dependencies": { "dependencies": {
"@babel/runtime": "^7.18.6", "@babel/runtime": "^7.18.9",
"@polkadot/api-augment": "8.12.1", "@polkadot/api-augment": "9.0.1",
"@polkadot/api-base": "8.12.1", "@polkadot/api-base": "9.0.1",
"@polkadot/api-derive": "8.12.1", "@polkadot/api-derive": "9.0.1",
"@polkadot/keyring": "^10.0.1", "@polkadot/keyring": "^10.1.2",
"@polkadot/rpc-augment": "8.12.1", "@polkadot/rpc-augment": "9.0.1",
"@polkadot/rpc-core": "8.12.1", "@polkadot/rpc-core": "9.0.1",
"@polkadot/rpc-provider": "8.12.1", "@polkadot/rpc-provider": "9.0.1",
"@polkadot/types": "8.12.1", "@polkadot/types": "9.0.1",
"@polkadot/types-augment": "8.12.1", "@polkadot/types-augment": "9.0.1",
"@polkadot/types-codec": "8.12.1", "@polkadot/types-codec": "9.0.1",
"@polkadot/types-create": "8.12.1", "@polkadot/types-create": "9.0.1",
"@polkadot/types-known": "8.12.1", "@polkadot/types-known": "9.0.1",
"@polkadot/util": "^10.0.1", "@polkadot/util": "^10.1.2",
"@polkadot/util-crypto": "^10.0.1", "@polkadot/util-crypto": "^10.1.2",
"eventemitter3": "^4.0.7", "eventemitter3": "^4.0.7",
"rxjs": "^7.5.5" "rxjs": "^7.5.6"
}, },
"devDependencies": { "devDependencies": {
"@polkadot/api-augment": "8.12.1", "@polkadot/api-augment": "9.0.1",
"@polkadot/types-support": "8.12.1" "@polkadot/types-support": "9.0.1"
} }
} }
+20 -24
View File
@@ -4,7 +4,7 @@
import type { Observable } from 'rxjs'; import type { Observable } from 'rxjs';
import type { AugmentedCall, DeriveCustom, QueryableCalls } from '@polkadot/api-base/types'; import type { AugmentedCall, DeriveCustom, QueryableCalls } from '@polkadot/api-base/types';
import type { RpcInterface } from '@polkadot/rpc-core/types'; import type { RpcInterface } from '@polkadot/rpc-core/types';
import type { Option, Raw, StorageKey, Text, u64 } from '@polkadot/types'; import type { StorageKey, Text, u64 } from '@polkadot/types';
import type { Call, Hash, RuntimeVersion } from '@polkadot/types/interfaces'; import type { Call, Hash, RuntimeVersion } from '@polkadot/types/interfaces';
import type { DecoratedMeta } from '@polkadot/types/metadata/decorate/types'; import type { DecoratedMeta } from '@polkadot/types/metadata/decorate/types';
import type { StorageEntry } from '@polkadot/types/primitive/types'; import type { StorageEntry } from '@polkadot/types/primitive/types';
@@ -19,9 +19,9 @@ import { BehaviorSubject, combineLatest, from, map, of, switchMap, tap, toArray
import { getAvailableDerives } from '@polkadot/api-derive'; import { getAvailableDerives } from '@polkadot/api-derive';
import { memo, RpcCore } from '@polkadot/rpc-core'; import { memo, RpcCore } from '@polkadot/rpc-core';
import { WsProvider } from '@polkadot/rpc-provider'; import { WsProvider } from '@polkadot/rpc-provider';
import { expandMetadata, Metadata, typeDefinitions, TypeRegistry, unwrapStorageType } from '@polkadot/types'; import { expandMetadata, Metadata, typeDefinitions, TypeRegistry } from '@polkadot/types';
import { getSpecRuntime } from '@polkadot/types-known'; import { getSpecRuntime } from '@polkadot/types-known';
import { arrayChunk, arrayFlatten, assert, assertReturn, BN, compactStripLength, lazyMethod, lazyMethods, logger, nextTick, objectSpread, stringCamelCase, stringUpperFirst, u8aConcatStrict, u8aToHex } from '@polkadot/util'; import { arrayChunk, arrayFlatten, assertReturn, BN, compactStripLength, lazyMethod, lazyMethods, logger, nextTick, objectSpread, stringCamelCase, stringUpperFirst, u8aConcatStrict, u8aToHex } from '@polkadot/util';
import { blake2AsHex } from '@polkadot/util-crypto'; import { blake2AsHex } from '@polkadot/util-crypto';
import { createSubmittable } from '../submittable'; import { createSubmittable } from '../submittable';
@@ -108,6 +108,7 @@ export abstract class Decorate<ApiType extends ApiTypes> extends Events {
protected _runtimeVersion?: RuntimeVersion; protected _runtimeVersion?: RuntimeVersion;
protected _rx: ApiInterfaceRx = { protected _rx: ApiInterfaceRx = {
call: {} as QueryableCalls<'rxjs'>,
consts: {} as QueryableConsts<'rxjs'>, consts: {} as QueryableConsts<'rxjs'>,
query: {} as QueryableStorage<'rxjs'>, query: {} as QueryableStorage<'rxjs'>,
tx: {} as SubmittableExtrinsics<'rxjs'> tx: {} as SubmittableExtrinsics<'rxjs'>
@@ -220,6 +221,7 @@ export abstract class Decorate<ApiType extends ApiTypes> extends Events {
query: {}, query: {},
registry, registry,
rx: { rx: {
call: {},
query: {} query: {}
}, },
tx: createSubmittable(this._type, this._rx, this._decorateMethod, registry, blockHash) tx: createSubmittable(this._type, this._rx, this._decorateMethod, registry, blockHash)
@@ -236,8 +238,9 @@ export abstract class Decorate<ApiType extends ApiTypes> extends Events {
} }
const runtime = this._decorateCalls(registry, this._decorateMethod, blockHash); const runtime = this._decorateCalls(registry, this._decorateMethod, blockHash);
const runtimeRx = this._decorateCalls<'rxjs'>(registry, this._rxDecorateMethod, blockHash);
const storage = this._decorateStorage(registry.decoratedMeta, this._decorateMethod, blockHash); const storage = this._decorateStorage(registry.decoratedMeta, this._decorateMethod, blockHash);
const storageRx = this._decorateStorage(registry.decoratedMeta, this._rxDecorateMethod, blockHash); const storageRx = this._decorateStorage<'rxjs'>(registry.decoratedMeta, this._rxDecorateMethod, blockHash);
augmentObject('consts', registry.decoratedMeta.consts, decoratedApi.consts, fromEmpty); augmentObject('consts', registry.decoratedMeta.consts, decoratedApi.consts, fromEmpty);
augmentObject('errors', registry.decoratedMeta.errors, decoratedApi.errors, fromEmpty); augmentObject('errors', registry.decoratedMeta.errors, decoratedApi.errors, fromEmpty);
@@ -245,6 +248,7 @@ export abstract class Decorate<ApiType extends ApiTypes> extends Events {
augmentObject('query', storage, decoratedApi.query, fromEmpty); augmentObject('query', storage, decoratedApi.query, fromEmpty);
augmentObject('query', storageRx, decoratedApi.rx.query, fromEmpty); augmentObject('query', storageRx, decoratedApi.rx.query, fromEmpty);
augmentObject('call', runtime, decoratedApi.call, fromEmpty); augmentObject('call', runtime, decoratedApi.call, fromEmpty);
augmentObject('call', runtimeRx, decoratedApi.rx.call, fromEmpty);
decoratedApi.findCall = (callIndex: Uint8Array | string): CallFunction => decoratedApi.findCall = (callIndex: Uint8Array | string): CallFunction =>
findCall(registry.registry, callIndex); findCall(registry.registry, callIndex);
@@ -274,6 +278,8 @@ export abstract class Decorate<ApiType extends ApiTypes> extends Events {
this._errors = decoratedApi.errors; this._errors = decoratedApi.errors;
this._events = decoratedApi.events; this._events = decoratedApi.events;
this._query = decoratedApi.query; this._query = decoratedApi.query;
this._rx.call = decoratedApi.rx.call;
this._rx.query = decoratedApi.rx.query; this._rx.query = decoratedApi.rx.query;
const tx = this._decorateExtrinsics(decoratedMeta, this._decorateMethod); const tx = this._decorateExtrinsics(decoratedMeta, this._decorateMethod);
@@ -488,7 +494,7 @@ export abstract class Decorate<ApiType extends ApiTypes> extends Events {
} }
// pre-metadata decoration // pre-metadata decoration
protected _decorateCalls<ApiType extends ApiTypes> ({ registry, runtimeVersion: { apis, specName } }: VersionedRegistry<ApiType>, decorateMethod: DecorateMethod<ApiType>, blockHash?: Uint8Array | string | null): QueryableCalls<ApiType> { protected _decorateCalls<ApiType extends ApiTypes> ({ registry, runtimeVersion: { apis, specName } }: VersionedRegistry<any>, decorateMethod: DecorateMethod<ApiType>, blockHash?: Uint8Array | string | null): QueryableCalls<ApiType> {
const result = {} as QueryableCalls<ApiType>; const result = {} as QueryableCalls<ApiType>;
const named: Record<string, Record<string, DefinitionCallNamed>> = {}; const named: Record<string, Record<string, DefinitionCallNamed>> = {};
const hashes: Record<HexString, boolean> = {}; const hashes: Record<HexString, boolean> = {};
@@ -626,7 +632,9 @@ export abstract class Decorate<ApiType extends ApiTypes> extends Events {
const lazySection = (section: string) => const lazySection = (section: string) =>
lazyMethods({}, Object.keys(tx[section]), (method: string) => lazyMethods({}, Object.keys(tx[section]), (method: string) =>
this._decorateExtrinsicEntry(tx[section][method], result) method.startsWith('$')
? tx[section][method]
: this._decorateExtrinsicEntry(tx[section][method], result)
); );
const sections = Object.keys(tx); const sections = Object.keys(tx);
@@ -701,9 +709,6 @@ export abstract class Decorate<ApiType extends ApiTypes> extends Events {
decorated.keyPrefix = (...args: unknown[]): string => decorated.keyPrefix = (...args: unknown[]): string =>
u8aToHex(creator.keyPrefix(...args)); u8aToHex(creator.keyPrefix(...args));
decorated.range = decorateMethod((range: [Hash, Hash?], ...args: unknown[]): Observable<[Hash, Codec][]> =>
this._decorateStorageRange(decorated, args, range));
decorated.size = decorateMethod((...args: unknown[]): Observable<u64> => decorated.size = decorateMethod((...args: unknown[]): Observable<u64> =>
this._rpcCore.state.getStorageSize(getArgs(args))); this._rpcCore.state.getStorageSize(getArgs(args)));
@@ -877,19 +882,6 @@ export abstract class Decorate<ApiType extends ApiTypes> extends Events {
}); });
} }
private _decorateStorageRange<ApiType extends ApiTypes> (decorated: QueryableStorageEntry<ApiType>, args: unknown[], range: [Hash, Hash?]): Observable<[Hash, Codec][]> {
const outputType = unwrapStorageType(this.#registry, decorated.creator.meta.type, decorated.creator.meta.modifier.isOptional);
return this._rpcCore.state
.queryStorage<[Option<Raw>]>([decorated.key(...args)], ...range)
.pipe(map((result: [Hash, [Option<Raw>]][]): [Hash, Codec][] =>
result.map(([blockHash, [value]]) => [
blockHash,
this.createType<Codec>(outputType, value.isSome ? value.unwrap().toHex() : undefined)
])
));
}
// retrieve a set of values for a specific set of keys - here we chunk the keys into PAGE_SIZE sizes // retrieve a set of values for a specific set of keys - here we chunk the keys into PAGE_SIZE sizes
private _retrieveMulti (keys: [StorageEntry, unknown[]][], blockHash?: Uint8Array): Observable<Codec[]> { private _retrieveMulti (keys: [StorageEntry, unknown[]][], blockHash?: Uint8Array): Observable<Codec[]> {
if (!keys.length) { if (!keys.length) {
@@ -918,7 +910,9 @@ export abstract class Decorate<ApiType extends ApiTypes> extends Events {
} }
private _retrieveMapKeys ({ iterKey, meta, method, section }: StorageEntry, at: Hash | Uint8Array | string | null, args: unknown[]): Observable<StorageKey[]> { private _retrieveMapKeys ({ iterKey, meta, method, section }: StorageEntry, at: Hash | Uint8Array | string | null, args: unknown[]): Observable<StorageKey[]> {
assert(iterKey && meta.type.isMap, 'keys can only be retrieved on maps'); if (!iterKey || !meta.type.isMap) {
throw new Error('keys can only be retrieved on maps');
}
const headKey = iterKey(...args).toHex(); const headKey = iterKey(...args).toHex();
const startSubject = new BehaviorSubject<string>(headKey); const startSubject = new BehaviorSubject<string>(headKey);
@@ -945,7 +939,9 @@ export abstract class Decorate<ApiType extends ApiTypes> extends Events {
} }
private _retrieveMapKeysPaged ({ iterKey, meta, method, section }: StorageEntry, at: Hash | Uint8Array | string | undefined, opts: PaginationOptions): Observable<StorageKey[]> { private _retrieveMapKeysPaged ({ iterKey, meta, method, section }: StorageEntry, at: Hash | Uint8Array | string | undefined, opts: PaginationOptions): Observable<StorageKey[]> {
assert(iterKey && meta.type.isMap, 'keys can only be retrieved on maps'); if (!iterKey || !meta.type.isMap) {
throw new Error('keys can only be retrieved on maps');
}
const setMeta = (key: StorageKey) => key.setMeta(meta, section, method); const setMeta = (key: StorageKey) => key.setMeta(meta, section, method);
const query = at const query = at
+2 -2
View File
@@ -194,8 +194,8 @@ export abstract class Getters<ApiType extends ApiTypes> extends Init<ApiType> im
/** /**
* @description The underlying Rx API interface * @description The underlying Rx API interface
*/ */
public get rx (): Pick<ApiInterfaceRx, 'tx' | 'rpc' | 'query'> { public get rx (): Pick<ApiInterfaceRx, 'tx' | 'rpc' | 'query' | 'call'> {
return assertResult(this._rx as Pick<ApiInterfaceRx, 'tx' | 'rpc' | 'query'>); return assertResult(this._rx as Pick<ApiInterfaceRx, 'tx' | 'rpc' | 'query' | 'call'>);
} }
/** /**
+9 -7
View File
@@ -15,7 +15,7 @@ import { firstValueFrom, map, of, switchMap } from 'rxjs';
import { Metadata, TypeRegistry } from '@polkadot/types'; import { Metadata, TypeRegistry } from '@polkadot/types';
import { getSpecAlias, getSpecExtensions, getSpecHasher, getSpecRpc, getSpecTypes, getUpgradeVersion } from '@polkadot/types-known'; import { getSpecAlias, getSpecExtensions, getSpecHasher, getSpecRpc, getSpecTypes, getUpgradeVersion } from '@polkadot/types-known';
import { assert, assertReturn, BN_ZERO, isUndefined, logger, objectSpread, u8aEq, u8aToHex, u8aToU8a } from '@polkadot/util'; import { assertReturn, BN_ZERO, isUndefined, logger, objectSpread, u8aEq, u8aToHex, u8aToU8a } from '@polkadot/util';
import { cryptoWaitReady } from '@polkadot/util-crypto'; import { cryptoWaitReady } from '@polkadot/util-crypto';
import { Decorate } from './Decorate'; import { Decorate } from './Decorate';
@@ -29,8 +29,7 @@ function textToString (t: Text): string {
} }
export abstract class Init<ApiType extends ApiTypes> extends Decorate<ApiType> { export abstract class Init<ApiType extends ApiTypes> extends Decorate<ApiType> {
// Browser/Deno = number, Node = Timeout #healthTimer: ReturnType<typeof setInterval> | null = null;
#healthTimer: unknown | null = null;
#registries: VersionedRegistry<ApiType>[] = []; #registries: VersionedRegistry<ApiType>[] = [];
@@ -180,7 +179,9 @@ export abstract class Init<ApiType extends ApiTypes> extends Decorate<ApiType> {
private async _getBlockRegistryViaHash (blockHash: Uint8Array): Promise<VersionedRegistry<ApiType>> { private async _getBlockRegistryViaHash (blockHash: Uint8Array): Promise<VersionedRegistry<ApiType>> {
// ensure we have everything required // ensure we have everything required
assert(this._genesisHash && this._runtimeVersion, 'Cannot retrieve data on an uninitialized chain'); if (!this._genesisHash || !this._runtimeVersion) {
throw new Error('Cannot retrieve data on an uninitialized chain');
}
// We have to assume that on the RPC layer the calls used here does not call back into // We have to assume that on the RPC layer the calls used here does not call back into
// the registry swap, so getHeader & getRuntimeVersion should not be historic // the registry swap, so getHeader & getRuntimeVersion should not be historic
@@ -190,7 +191,9 @@ export abstract class Init<ApiType extends ApiTypes> extends Decorate<ApiType> {
: await firstValueFrom(this._rpcCore.chain.getHeader.raw(blockHash)) : await firstValueFrom(this._rpcCore.chain.getHeader.raw(blockHash))
); );
assert(!header.parentHash.isEmpty, 'Unable to retrieve header and parent from supplied hash'); if (header.parentHash.isEmpty) {
throw new Error('Unable to retrieve header and parent from supplied hash');
}
// get the runtime version, either on-chain or via an known upgrade history // get the runtime version, either on-chain or via an known upgrade history
const [firstVersion, lastVersion] = getUpgradeVersion(this._genesisHash, header.number); const [firstVersion, lastVersion] = getUpgradeVersion(this._genesisHash, header.number);
@@ -370,8 +373,7 @@ export abstract class Init<ApiType extends ApiTypes> extends Decorate<ApiType> {
private _unsubscribeHealth (): void { private _unsubscribeHealth (): void {
if (this.#healthTimer) { if (this.#healthTimer) {
// different method signatures for Node vs Browser/Deno clearInterval(this.#healthTimer);
clearInterval(this.#healthTimer as number);
this.#healthTimer = null; this.#healthTimer = null;
} }
} }
+4 -2
View File
@@ -4,7 +4,7 @@
import type { SignerPayloadRawBase } from '@polkadot/types/types'; import type { SignerPayloadRawBase } from '@polkadot/types/types';
import type { ApiOptions, ApiTypes, DecorateMethod, Signer } from '../types'; import type { ApiOptions, ApiTypes, DecorateMethod, Signer } from '../types';
import { assert, isString, objectSpread, u8aToHex, u8aToU8a } from '@polkadot/util'; import { isString, objectSpread, u8aToHex, u8aToU8a } from '@polkadot/util';
import { Getters } from './Getters'; import { Getters } from './Getters';
@@ -69,7 +69,9 @@ export abstract class ApiBase<ApiType extends ApiTypes> extends Getters<ApiType>
if (isString(address)) { if (isString(address)) {
const _signer = signer || this._rx.signer; const _signer = signer || this._rx.signer;
assert(_signer?.signRaw, 'No signer exists with a signRaw interface. You possibly need to pass through an explicit keypair for the origin so it can be used for signing.'); if (!_signer || !_signer.signRaw) {
throw new Error('No signer exists with a signRaw interface. You possibly need to pass through an explicit keypair for the origin so it can be used for signing.');
}
return ( return (
await _signer.signRaw( await _signer.signRaw(
+2 -10
View File
@@ -125,7 +125,7 @@ async function query (api: ApiPromise, pairs: TestKeyringMap): Promise<void> {
console.log('query types:', bar, bal, bal2, override, oldBal, multia, multib); console.log('query types:', bar, bal, bal2, override, oldBal, multia, multib);
} }
async function queryExtra (api: ApiPromise, pairs: TestKeyringMap): Promise<void> { async function queryExtra (api: ApiPromise): Promise<void> {
// events destructing // events destructing
await api.query.system.events((records): void => { await api.query.system.events((records): void => {
records.forEach(({ event, phase }): void => { records.forEach(({ event, phase }): void => {
@@ -155,14 +155,6 @@ async function queryExtra (api: ApiPromise, pairs: TestKeyringMap): Promise<void
await api.query.assets.account.entries(123); await api.query.assets.account.entries(123);
await api.query.assets.blah.keys(); await api.query.assets.blah.keys();
// check range
await api.query.balances.freeBalance.range<Balance>(['0x1234'], pairs.bob.address);
// check range types
const entries = await api.query.system.events.range(['0x12345', '0x7890']);
console.log(`Received ${entries.length} entries, ${entries.map(([hash, events]) => `${hash.toHex()}: ${events.length} events`).join(', ')}`);
// is // is
const key = {} as StorageKey; const key = {} as StorageKey;
@@ -313,7 +305,7 @@ async function main (): Promise<void> {
errors(api), errors(api),
events(api), events(api),
query(api, pairs), query(api, pairs),
queryExtra(api, pairs), queryExtra(api),
queryMulti(api, pairs), queryMulti(api, pairs),
rpc(api), rpc(api),
types(api), types(api),

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