Compare commits

..
149 Commits
Author SHA1 Message Date
Github Actions a253c4edb5 [CI Skip] release/stable 4.0.3
skip-checks: true
2021-03-08 21:20:51 +00:00
Jaco Greeff 7c96525d35 4.0.3 (#3287) 2021-03-08 22:11:42 +01:00
Zeke MostovandJaco Greeff 3f0457efc2 fix: Allow sudo for polkadot indexed proxy enum (#3286)
* fix: Allow sudo for polkadot indexed proxy enum

* Update packages/types-known/src/spec/polkadot.ts

Co-authored-by: Jaco Greeff <jacogr@gmail.com>
2021-03-08 22:00:35 +01:00
Github Actions bfb241d995 [CI Skip] release/stable 4.0.2
skip-checks: true
2021-03-08 14:23:22 +00:00
Jaco Greeff 314ad8c3f2 4.0.2 (#3283)
* 4.0.2

* Update CHANGELOG.md

* Bump common
2021-03-08 15:14:24 +01:00
Github Actions aa85371f82 [CI Skip] release/beta 4.0.2-0
skip-checks: true
2021-03-08 12:46:02 +00:00
Jaco Greeff d0a08dadd9 Add correct election Phase type (#3280) 2021-03-08 13:38:14 +01:00
Github Actions eeff764345 [CI Skip] release/stable 4.0.1
skip-checks: true
2021-03-07 15:47:19 +00:00
Jaco Greeff 4870ec4f40 4.0 (#3277)
* 4.0

* Correct patch
2021-03-07 16:37:47 +01:00
Github Actions 1c3cfbfa0c [CI Skip] release/beta 4.0.1-14
skip-checks: true
2021-03-07 15:10:20 +00:00
Jaco Greeff 3c9b7de6c7 Add createdAtHash to Codec interface (#3276)
* Add createdAtHash to Codec interface

* Adjust linkedHash (also on )

* createdAtHash
2021-03-07 16:00:30 +01:00
Github Actions 22e5488f16 [CI Skip] release/beta 4.0.1-13
skip-checks: true
2021-03-06 14:57:52 +00:00
Jaco Greeff b37887993e Westend 49 upgrade block (#3273) 2021-03-06 15:49:10 +01:00
Github Actions 75361cb0ff [CI Skip] release/beta 4.0.1-12
skip-checks: true
2021-03-06 07:21:18 +00:00
Jaco Greeff 894992bc4c Bump deps (#3272) 2021-03-06 08:12:35 +01:00
Github Actions d955fab169 [CI Skip] release/beta 4.0.1-11
skip-checks: true
2021-03-05 16:23:50 +00:00
Jaco Greeff 580d225387 Bump common (#3271) 2021-03-05 17:13:37 +01:00
Github Actions d48f59e48d [CI Skip] release/beta 4.0.1-10
skip-checks: true
2021-03-05 12:34:38 +00:00
Jaco Greeff 108b49ea03 Expose the hash field from contract wasm (#3267) 2021-03-05 13:25:00 +01:00
Github Actions 9295349886 [CI Skip] release/beta 4.0.1-9
skip-checks: true
2021-03-05 09:38:48 +00:00
Jaco Greeff a51658ffac Cater for at-genesis best headers (#3264) 2021-03-05 10:28:56 +01:00
Github Actions 47f08e9e04 [CI Skip] release/beta 4.0.1-8
skip-checks: true
2021-03-05 08:45:40 +00:00
iiiiiiiiandJaco Greeff 7906ae63dc Make unknownTypes externally accessible (#3263)
* Make unknownTypes externally accessible

* fix lint

* Update registry.ts

* Update registry.ts

* Update packages/types/src/types/registry.ts

Co-authored-by: Jaco Greeff <jacogr@gmail.com>

* Update packages/types/src/create/registry.ts

Co-authored-by: Jaco Greeff <jacogr@gmail.com>

Co-authored-by: Jaco Greeff <jacogr@gmail.com>
2021-03-05 09:36:01 +01:00
Github Actions 0e76271dba [CI Skip] release/beta 4.0.1-7
skip-checks: true
2021-03-04 08:04:33 +00:00
Jaco Greeff e117619e34 Use the parent header for era info (#3260) 2021-03-04 08:57:22 +01:00
Github Actions 67b416fe80 [CI Skip] release/beta 4.0.1-6
skip-checks: true
2021-03-04 07:13:35 +00:00
Jaco Greeff 78dbfa46fa AccountInfoWithTripleRefCount type & detection (#3228)
* AccountInfoWithTripleRefCount

* Update naming

* build
2021-03-04 08:03:25 +01:00
Github Actions 01db9261d5 [CI Skip] release/beta 4.0.1-5
skip-checks: true
2021-03-03 12:28:40 +00:00
Jaco Greeff 674c38b384 Enum serializes to camelCase (#3024)
* Enum serializes to camelCase

* Dedupe

* rewrite static json

* test for StorageKind enum
2021-03-03 13:18:07 +01:00
Github Actions 0700e824eb [CI Skip] release/beta 4.0.1-4
skip-checks: true
2021-03-03 09:12:10 +00:00
Jaco Greeff 0362eaf472 Bump deps (& berry) (#3259)
* Bump deps (& berry)

* new 4.2.2 linting issues
2021-03-03 10:03:46 +01:00
Github Actions 696b3964e6 [CI Skip] release/beta 4.0.1-3
skip-checks: true
2021-03-02 20:29:13 +00:00
Jaco Greeff 5d0c2eed7b Default build to type: module (#3253)
* Default build to type: module

* 4.0

* pre

* yarn.lock

* packageInfo

* Bump common

* jest & bumps

* additional
2021-03-02 21:19:55 +01:00
Github Actions e4c3289ad8 [CI Skip] release/beta 3.11.2-4
skip-checks: true
2021-03-01 20:51:04 +00:00
Jaco Greeff 4449bdae6f Bump deps (#3252) 2021-03-01 21:43:13 +01:00
Github Actions 064957db81 [CI Skip] release/beta 3.11.2-3
skip-checks: true
2021-03-01 16:07:02 +00:00
Jaco Greeff ccd89ef0a6 Trigger validator shash retrievals on Bonded events (#3251) 2021-03-01 16:57:27 +01:00
Github Actions 47beb5f41f [CI Skip] release/beta 3.11.2-2
skip-checks: true
2021-03-01 08:32:11 +00:00
Jaco Greeff 9f205392a3 Remove old RewardDestination type (#3246)
* Remove old RewardDestination type

* merge master

* adjust

* Adjust
2021-03-01 09:23:37 +01:00
Github Actions adce7ccbee [CI Skip] release/beta 3.11.2-1
skip-checks: true
2021-03-01 08:08:09 +00:00
Jaco Greeff b83b3a9437 Change default ValidatorPrefs (#3244)
* Change default ValidatorPrefs

* Linkage test

* Previous default
2021-03-01 08:59:38 +01:00
Github Actions 147dbcf24f [CI Skip] release/beta 3.11.2-0
skip-checks: true
2021-03-01 07:52:05 +00:00
Alex D 2afff1b41f Use derive customAccount and customLocks for balance overrides (#3248)
* modified api-derive balances to allow use of custom balance storages via derives; current implementation only works with standard call signatures

* type predicate as filter value

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

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

* packageInfo imports

* Dependency array

* Bump common

* Remove detectPackage comments (available in util)

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

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

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

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

* Full decoding on empty

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

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

* Adjust

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

* Type generation updates

* Cleanup createType

* Empty bytes default

* output tests

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

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

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

* Decoding tests

* Fix Call test

* patch-only

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

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

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

* Remove migrateEra

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

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

* Jsdoc comments

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

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

* Adjust (some) tests

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

* new-style

* old-style deploy?

* notice

* Cleanups

* linting

* grrr... Mac case-sensistivity

* Add createContract on BluePrint

* Adjust contracts check

* Adjust

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

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

* Update packages/rpc-provider/src/ws/index.ts
2021-02-05 22:03:31 +01:00
Github Actions 8fe262a712 [CI Skip] release/beta 3.7.4-2
skip-checks: true
2021-02-05 15:55:13 +00:00
Jake Naviasky 122ee968cb Add eth filter RPC endpoints and FilterChanges type. (#3150) 2021-02-05 16:45:31 +01:00
Github Actions d2ff350db9 [CI Skip] release/beta 3.7.4-1
skip-checks: true
2021-02-05 07:34:46 +00:00
Nantian 9100aabbac fix signedExtensions type (#3148) 2021-02-05 08:25:17 +01:00
Github Actions 1e73f69253 [CI Skip] release/beta 3.7.4-0
skip-checks: true
2021-02-04 16:16:08 +00:00
Jaco Greeff 7153cb4158 Extend ProxyType with CancelProxy (#3147) 2021-02-04 17:05:56 +01:00
Github Actions 999dc6f8a5 [CI Skip] release/stable 3.7.3
skip-checks: true
2021-02-02 16:37:56 +00:00
Jaco Greeff 724574afe7 3.7.3 (w/ Polkadot 27 upgrade blocks) (#3139) 2021-02-02 17:29:43 +01:00
Github Actions 0352a30b6b [CI Skip] release/beta 3.7.3-1
skip-checks: true
2021-02-02 10:14:04 +00:00
Jaco Greeff 41b4cd5c55 Adjust known-types to use @polkadot/networks (#3138) 2021-02-02 11:06:52 +01:00
Github Actions 89f16f3123 [CI Skip] release/beta 3.7.3-0
skip-checks: true
2021-02-02 09:22:19 +00:00
Jaco Greeff 261a4eede3 Add 26 checkpoint for Polkadot (#3137) 2021-02-02 10:15:17 +01:00
195 changed files with 5439 additions and 3335 deletions
+8 -2
View File
@@ -1,4 +1,4 @@
25 26
1.4.2 1.4.2
1.6.2 1.6.2
1.11.2 1.11.2
@@ -8,9 +8,15 @@
2.8.2 2.8.2
3.2.2 3.2.2
3.2.3 3.2.3
3.3.2 3.3.2
3.6.2 3.6.2
3.6.3 3.6.3
3.6.4 3.6.4
3.7.2 3.7.2
3.7.3
3.9.2
3.9.3
3.10.2
4.0.2
4.0.3
-2
View File
@@ -24,8 +24,6 @@ module.exports = {
...base.rules, ...base.rules,
// add override for any (a metric ton of them, initial conversion) // add override for any (a metric ton of them, initial conversion)
'@typescript-eslint/no-explicit-any': 'off', '@typescript-eslint/no-explicit-any': 'off',
// these should be removed, there are 8 of them as errors
'@typescript-eslint/no-non-null-assertion': 'off',
// this seems very broken atm, false positives // this seems very broken atm, false positives
'@typescript-eslint/unbound-method': 'off' '@typescript-eslint/unbound-method': 'off'
} }
File diff suppressed because one or more lines are too long
+1 -1
View File
@@ -10,4 +10,4 @@ plugins:
- path: .yarn/plugins/@yarnpkg/plugin-version.cjs - path: .yarn/plugins/@yarnpkg/plugin-version.cjs
spec: "@yarnpkg/plugin-version" spec: "@yarnpkg/plugin-version"
yarnPath: .yarn/releases/yarn-2.4.0.cjs yarnPath: .yarn/releases/yarn-2.4.1.cjs
+151
View File
@@ -1,5 +1,156 @@
# CHANGELOG # CHANGELOG
## 4.0.3 Mar 8, 2021
Upgrade priority: Low. Recommended if you use the API to sync the full chain, most notably Polkadot.
Contributed:
- Re-add unused historical `SudoBalances` to `ProxyType` (Thanks to https://github.com/emostov)
## 4.0.2 Mar 8, 2021
Upgrade priority: High. Required if you are using 4.0.1 in a Node.js environment.
Changes:
- Fix import from `@polkadot/x-rxjs` in Node environments (From common)
- Add correct types for `Phase` is new validator elections module
## 4.0.1 Mar 7, 2021
Upgrade priority: Low. Recommended for users wanting to keep updated with chain changes.
**Important** In the 4.0 version the default package type has been changed to ESM modules by default. This should not affect usage, however since the output formats changed, a new major version is required.
Contributed:
- Expose `unknownTypes` on the registry interface (Thanks to https://github.com/ii-ii-ii)
Changes:
- Build to ESM by default (with cjs versions via export map)
- Enum `.toSON()` now encodes all keys as `camelCase` (aligning with the output from Substrate)
- Add `createdAtHash?: Hash` to `Codec` interface (filled-in by storage retrievals)
- Expose the source hash as `wamHash` on Abi parsed instances
- Use `parentHash` when creating mortal era (handles frequent forks better)
- Add `AccountInfoWithTripleRefCount` to cater for latest Substrate
- Add upgrade block for Westend 49
## 3.11.1 Feb 28, 2021
Upgrade priority: Low. Recommended for users wanting to keep updated with chain changes.
Contributed:
- Clean Websocket states on disconnects (Thanks to https://github.com/ianhe8x)
- Support for C-like indexed enums (Thanks to https://github.com/xlc)
Changes:
- Adjust council derives to cater for current-generation candidate mapping
- Allow for override of codec hasher (& output type)
- Adjust submittables to submit hex-encoded addresses to queries
- Adjust initialization to always retrieve tx version from Metadata only
- Update election types as per latest Substrate
- Add types for the new gilt module
- Upgrade to the latest Substrate metadata
- Adjust package detection to check for local monorepo dependencies
- Ensure that metadata `.toJSON()` does apply type aliasses
## 3.10.2 Feb 23, 2021
Upgrade priority: Medium. Recommended for users of chains where `MultiAddress` is in-use and blocks are decoded.
Changes:
- Fix decoding for `MultiAddress` enum where non-`AccountId` variable-lengths are provided as part of a stream
- Added known Polkadot 28 upgrade block
- Update for latest Substrate contracts `Schedule` types
## 3.10.1 Feb 22, 2021
Upgrade priority: Low.
Changes:
- Adjust ConsumedWeight types to align with Rust module code
- Check for connection status in subscription unsubscribe
- Adjust staking reward derives ordering for better performance
- Adapt detection imports to remove `.json` dependencies (Better behavior using Node.js with ESM)
## 3.9.3 Feb 16, 2021
Upgrade priority: Low. Recommended for parachain builders since it contains the updated parachain types.
Changes:
- Adjusted parachain `PersistedValidationData` structure
## 3.9.2 Feb 15, 2021
Upgrade priority: Low. Recommended for parachain builders since it contains the latest parachain types.
Contributed:
- Update README links (Thanks to https://github.com/wirednkod)
Changes:
- Added missing Culmulus `ParachainInherentData` & `MessageQueueChain` types
- Add alias for `system_unstable_networkState` RPC
## 3.9.1 Feb 14, 2021
Upgrade priority: Low.
- **Important** The `Result<T, E>` has been updated in the generation and the base types to follow the Rust version 100%. This means `{as, is}Error` is now available as `{as, is}Err` on the `Result` type. The older versions can still be used, but the `*Error` interfaces are now marked as deprecated.
Changes:
- Adjust `Result<T, E>` interface to be 100% compatible with the Rust version
- Add the `2028` upgrade to the known upgrades (optimizing certain `.at` queries)
- Adjust council derives to cater for latest Substrate & Polkadot
- Adjust Rococo know type definitions to cater for the latest update
- Update types for latest Polkadot/Substrate
- Add generic arguments for TypeScript users to `.entries/.keys` to deal with the key typings
## 3.8.1 Feb 7, 2021
Upgrade priority: Low. Recommended for users of the latest Substrate master, especially using contracts.
- **Important** The `api-contract` `Code` now supports deploying the code and a contract in on operation. This aligns with the latest Substrate where code cannot be uploaded with a contract. The `createBlueprint` is therefore deprecated, use `code.tx.<constructor>(...)` to deploy code. (Compatible with both old and new versions of Substrate)
Contributed:
- Add support for latest Frontier RPCs (Thanks to https://github.com/jnaviask)
- Fix user-supplied signed extensions type signature (Thanks to https://github.com/ntduan)
Changes:
- Expand `api-contract` to allow for `Code` to deploy contract alongside code. `createBlueprint` is now deprecated, replaced by `createContract` or the preferred `code.tx.<constructor>`, which uploads and deploys the code in one operation. This aligns with the current Substrate master contracts implementation.
- Allow for signed extensions to be supplied inside type bundles
- Ensure that the auto-connect state is checked on auto-connections (respecting disconnect)
- Added `CancelProxy` to `ProxyTypes on Polkadot, Kusama & Westend
- Updated to latest Substrate metadata
## 3.7.3 Feb 2, 2021
Changes:
- Added Polkadot upgrade block for runtime 27 (known checkpoint optimization)
## 3.7.2 Feb 2, 2021 ## 3.7.2 Feb 2, 2021
Changes: Changes:
+2 -2
View File
@@ -7,7 +7,7 @@
# @polkadot/api # @polkadot/api
This library provides a clean wrapper around all the methods exposed by a Polkadot/Substrate network client and defines all the types exposed by a node. For complete documentation around the classes, interfaces and their use, visit the [documentation portal](https://polkadot.js.org/api/). This library provides a clean wrapper around all the methods exposed by a Polkadot/Substrate network client and defines all the types exposed by a node. For complete documentation around the classes, interfaces and their use, visit the [documentation portal](https://polkadot.js.org/docs/api/).
If you are an existing user, please be sure to track the [CHANGELOG](CHANGELOG.md) and [UPGRADING](UPGRADING.md) guides when changing versions. If you are an existing user, please be sure to track the [CHANGELOG](CHANGELOG.md) and [UPGRADING](UPGRADING.md) guides when changing versions.
@@ -22,7 +22,7 @@ The API is split up into a number of internal packages -
- [@polkadot/api](packages/api/) The API library, providing both Promise and RxJS Observable-based interfaces. This is the main user-facing entry point. - [@polkadot/api](packages/api/) The API library, providing both Promise and RxJS Observable-based interfaces. This is the main user-facing entry point.
- [@polkadot/api-derive](packages/api-derive/) Derived results that are injected into the API, allowing for combinations of various query results (only used internally and exposed on the Api instances via `api.derive.*`) - [@polkadot/api-derive](packages/api-derive/) Derived results that are injected into the API, allowing for combinations of various query results (only used internally and exposed on the Api instances via `api.derive.*`)
- [@polkadot/api-metadata](packages/api-metadata/) Base extrinsic, storage and constant injectors for injection - [@polkadot/api-metadata](packages/api-metadata/) Base extrinsic, storage and constant injectors for injection
- [@polkadot/rpc-core](packages/rpc-core/) Wrapper around all [JSON-RPC methods](https://polkadot.js.org/api/substrate/rpc.html) exposed by a Polkadot network client - [@polkadot/rpc-core](packages/rpc-core/) Wrapper around all [JSON-RPC methods](https://polkadot.js.org/docs/substrate/rpc) exposed by a Polkadot network client
- [@polkadot/rpc-provider](packages/rpc-provider/) Providers for connecting to nodes, including WebSockets and Http - [@polkadot/rpc-provider](packages/rpc-provider/) Providers for connecting to nodes, including WebSockets and Http
Type definitions for interfaces as exposed by Polkadot & Substrate clients - Type definitions for interfaces as exposed by Polkadot & Substrate clients -
+1 -1
View File
@@ -26,5 +26,5 @@ module.exports = Object.assign({}, config, {
'<rootDir>/packages/types/build', '<rootDir>/packages/types/build',
'<rootDir>/packages/types-known/build' '<rootDir>/packages/types-known/build'
], ],
resolver: '@polkadot/dev/config/jest-resolver.cjs' transformIgnorePatterns: ['/node_modules/(?!@polkadot|@babel/runtime/helpers/esm/|rxjs/_esm5)']
}); });
+7 -7
View File
@@ -8,7 +8,7 @@
"packages/*" "packages/*"
], ],
"resolutions": { "resolutions": {
"typescript": "^4.1.3" "typescript": "^4.2.3"
}, },
"scripts": { "scripts": {
"build": "yarn build:interfaces && polkadot-dev-build-ts", "build": "yarn build:interfaces && polkadot-dev-build-ts",
@@ -25,14 +25,14 @@
"test:watch": "polkadot-dev-run-test --watch" "test:watch": "polkadot-dev-run-test --watch"
}, },
"devDependencies": { "devDependencies": {
"@babel/core": "^7.12.10", "@babel/core": "^7.13.8",
"@babel/register": "^7.12.10", "@babel/register": "^7.13.8",
"@babel/runtime": "^7.12.5", "@babel/runtime": "^7.13.9",
"@polkadot/dev": "^0.61.24", "@polkadot/dev": "^0.62.5",
"@polkadot/ts": "^0.3.59", "@polkadot/ts": "^0.3.61",
"@polkadot/typegen": "workspace:packages/typegen", "@polkadot/typegen": "workspace:packages/typegen",
"@types/jest": "^26.0.20", "@types/jest": "^26.0.20",
"copyfiles": "^2.4.1" "copyfiles": "^2.4.1"
}, },
"version": "3.7.2" "version": "4.0.3"
} }
+11 -7
View File
@@ -1,9 +1,13 @@
{ {
"name": "@polkadot/api-contract", "name": "@polkadot/api-contract",
"version": "3.7.2", "version": "4.0.3",
"type": "module",
"description": "Interfaces for interacting with contracts and contract ABIs", "description": "Interfaces for interacting with contracts and contract ABIs",
"main": "index.js", "main": "index.js",
"sideEffects": false, "sideEffects": [
"./detectPackage.js",
"./detectPackage.cjs"
],
"author": "Jaco Greeff <jacogr@gmail.com>", "author": "Jaco Greeff <jacogr@gmail.com>",
"maintainers": [], "maintainers": [],
"contributors": [], "contributors": [],
@@ -12,11 +16,11 @@
"bugs": "https://github.com/polkadot-js/api/issues", "bugs": "https://github.com/polkadot-js/api/issues",
"homepage": "https://github.com/polkadot-js/api/tree/master/packages/api-contract#readme", "homepage": "https://github.com/polkadot-js/api/tree/master/packages/api-contract#readme",
"dependencies": { "dependencies": {
"@babel/runtime": "^7.12.5", "@babel/runtime": "^7.13.9",
"@polkadot/api": "3.7.2", "@polkadot/api": "4.0.3",
"@polkadot/types": "3.7.2", "@polkadot/types": "4.0.3",
"@polkadot/util": "^5.5.1", "@polkadot/util": "^6.0.5",
"@polkadot/x-rxjs": "^5.5.1", "@polkadot/x-rxjs": "^6.0.5",
"bn.js": "^4.11.9" "bn.js": "^4.11.9"
} }
} }
+22
View File
@@ -1,10 +1,18 @@
// Copyright 2017-2021 @polkadot/api-contract authors & contributors // Copyright 2017-2021 @polkadot/api-contract authors & contributors
// SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: Apache-2.0
import { blake2AsHex } from '@polkadot/util-crypto';
import abis from '../test/contracts'; import abis from '../test/contracts';
import { Abi } from '.'; import { Abi } from '.';
interface JSONAbi { interface JSONAbi {
source: {
compiler: string,
hash: string,
language: string,
wasm: string
},
spec: { spec: {
messages: { messages: {
name: string[] | string name: string[] | string
@@ -27,4 +35,18 @@ describe('Abi', (): void => {
} }
}); });
}); });
it('has the correct hash for the source', (): void => {
const bundle = abis.ink_flipperBundle as JSONAbi;
const abi = new Abi(bundle as any);
// manual
expect(bundle.source.hash).toEqual(blake2AsHex(bundle.source.wasm));
// the Codec hash
expect(bundle.source.hash).toEqual(abi.project.source.wasm.hash.toHex());
// the hash as per the actual Abi
expect(bundle.source.hash).toEqual(abi.project.source.wasmHash.toHex());
});
}); });
+1 -1
View File
@@ -26,6 +26,6 @@ export abstract class Base<ApiType extends ApiTypes> {
this.registry = this.abi.registry; this.registry = this.abi.registry;
this._decorateMethod = decorateMethod; this._decorateMethod = decorateMethod;
assert(this.api.rx.tx.contracts && this.api.rx.tx.contracts.putCode, 'You need to connect to a node with the contracts module, the metadata does not enable api.tx.contracts on this instance'); assert(api.rx.tx.contracts?.instantiate, 'You need to connect to a node with the contracts module, the metadata does not enable api.tx.contracts on this instance');
} }
} }
+8 -35
View File
@@ -6,44 +6,17 @@ import type { ApiTypes, DecorateMethod } from '@polkadot/api/types';
import type { AccountId, EventRecord, Hash } from '@polkadot/types/interfaces'; import type { AccountId, EventRecord, Hash } from '@polkadot/types/interfaces';
import type { AnyJson, CodecArg, ISubmittableResult } from '@polkadot/types/types'; import type { AnyJson, CodecArg, ISubmittableResult } from '@polkadot/types/types';
import type { AbiConstructor, BlueprintOptions } from '../types'; import type { AbiConstructor, BlueprintOptions } from '../types';
import type { BlueprintDeploy, ContractGeneric, MapConstructorExec } from './types'; import type { ContractGeneric, MapConstructorExec } from './types';
import BN from 'bn.js';
import { SubmittableResult } from '@polkadot/api'; import { SubmittableResult } from '@polkadot/api';
import { ApiBase } from '@polkadot/api/base'; import { ApiBase } from '@polkadot/api/base';
import { Bytes } from '@polkadot/types'; import { isUndefined, stringCamelCase } from '@polkadot/util';
import { compactAddLength, isUndefined, stringCamelCase, u8aToU8a } from '@polkadot/util';
import { randomAsU8a } from '@polkadot/util-crypto';
import { Abi } from '../Abi'; import { Abi } from '../Abi';
import { applyOnEvent, extractOptions, isOptions } from '../util'; import { applyOnEvent } from '../util';
import { Base } from './Base'; import { Base } from './Base';
import { Contract } from './Contract'; import { Contract } from './Contract';
import { createBluePrintTx, createBluePrintWithId, EMPTY_SALT, encodeSalt } from './util';
const EMPTY_SALT = new Uint8Array();
function createTx <ApiType extends ApiTypes> (fn: (options: BlueprintOptions, params: CodecArg[]) => SubmittableExtrinsic<ApiType, BlueprintSubmittableResult<ApiType>>): BlueprintDeploy<ApiType> {
return (options: BigInt | string | number | BN | BlueprintOptions, ...params: CodecArg[]): SubmittableExtrinsic<ApiType, BlueprintSubmittableResult<ApiType>> =>
isOptions(options)
? fn(options, params)
: fn(...extractOptions(options, params));
}
function createWithId <T> (fn: (constructorOrId: AbiConstructor | string | number, options: BlueprintOptions, params: CodecArg[]) => T): ContractGeneric<BlueprintOptions, T> {
return (constructorOrId: AbiConstructor | string | number, options: BigInt | string | number | BN | BlueprintOptions, ...params: CodecArg[]): T =>
isOptions(options)
? fn(constructorOrId, options, params)
: fn(constructorOrId, ...extractOptions(options, params));
}
function encodeSalt (salt: Uint8Array | string | null = randomAsU8a()) {
return salt instanceof Bytes
? salt
: salt && salt.length
? compactAddLength(u8aToU8a(salt))
: EMPTY_SALT;
}
export class BlueprintSubmittableResult<ApiType extends ApiTypes> extends SubmittableResult { export class BlueprintSubmittableResult<ApiType extends ApiTypes> extends SubmittableResult {
public readonly contract?: Contract<ApiType>; public readonly contract?: Contract<ApiType>;
@@ -73,13 +46,13 @@ export class Blueprint<ApiType extends ApiTypes> extends Base<ApiType> {
super(api, abi, decorateMethod); super(api, abi, decorateMethod);
this.codeHash = this.registry.createType('Hash', codeHash); this.codeHash = this.registry.createType('Hash', codeHash);
this.createContract = createWithId(this.#deploy); this.createContract = createBluePrintWithId(this.#deploy);
this.abi.constructors.forEach((c): void => { this.abi.constructors.forEach((c): void => {
const messageName = stringCamelCase(c.identifier); const messageName = stringCamelCase(c.identifier);
if (isUndefined(this.#tx[messageName])) { if (isUndefined(this.#tx[messageName])) {
this.#tx[messageName] = createTx((o, p) => this.#deploy(c, o, p)); this.#tx[messageName] = createBluePrintTx((o, p) => this.#deploy(c, o, p));
} }
}); });
} }
@@ -88,7 +61,7 @@ export class Blueprint<ApiType extends ApiTypes> extends Base<ApiType> {
return this.#tx; return this.#tx;
} }
#deploy = (constructorOrId: AbiConstructor | string| number, { gasLimit = 0, salt, value = 0 }: BlueprintOptions, params: CodecArg[]): SubmittableExtrinsic<ApiType, BlueprintSubmittableResult<ApiType>> => { #deploy = (constructorOrId: AbiConstructor | string | number, { gasLimit = 0, salt, value = 0 }: BlueprintOptions, params: CodecArg[]): SubmittableExtrinsic<ApiType, BlueprintSubmittableResult<ApiType>> => {
const encodedSalt = encodeSalt(salt); const encodedSalt = encodeSalt(salt);
const withSalt = this.api.tx.contracts.instantiate.meta.args.length === 5; const withSalt = this.api.tx.contracts.instantiate.meta.args.length === 5;
const encoded = this.abi.findConstructor(constructorOrId).toU8a(params, withSalt ? EMPTY_SALT : encodedSalt); const encoded = this.abi.findConstructor(constructorOrId).toU8a(params, withSalt ? EMPTY_SALT : encodedSalt);
@@ -99,7 +72,7 @@ export class Blueprint<ApiType extends ApiTypes> extends Base<ApiType> {
: this.api.tx.contracts.instantiate(value, gasLimit, this.codeHash, encoded); : this.api.tx.contracts.instantiate(value, gasLimit, this.codeHash, encoded);
return tx.withResultTransform((result: ISubmittableResult) => return tx.withResultTransform((result: ISubmittableResult) =>
new BlueprintSubmittableResult(result, applyOnEvent(result, 'Instantiated', ([record]: EventRecord[]) => new BlueprintSubmittableResult(result, applyOnEvent(result, ['Instantiated'], ([record]: EventRecord[]) =>
new Contract<ApiType>(this.api, this.abi, record.event.data[1] as AccountId, this._decorateMethod) new Contract<ApiType>(this.api, this.abi, record.event.data[1] as AccountId, this._decorateMethod)
)) ))
); );
+74 -4
View File
@@ -4,30 +4,39 @@
import type { SubmittableExtrinsic } from '@polkadot/api/submittable/types'; import type { SubmittableExtrinsic } from '@polkadot/api/submittable/types';
import type { ApiTypes, DecorateMethod } from '@polkadot/api/types'; import type { ApiTypes, DecorateMethod } from '@polkadot/api/types';
import type { EventRecord, Hash } from '@polkadot/types/interfaces'; import type { EventRecord, Hash } from '@polkadot/types/interfaces';
import type { AnyJson, ISubmittableResult } from '@polkadot/types/types'; import type { AnyJson, CodecArg, ISubmittableResult } from '@polkadot/types/types';
import type { AbiConstructor, BlueprintOptions } from '../types';
import type { MapConstructorExec } from './types';
import { SubmittableResult } from '@polkadot/api'; import { SubmittableResult } from '@polkadot/api';
import { ApiBase } from '@polkadot/api/base'; import { ApiBase } from '@polkadot/api/base';
import { assert, compactAddLength, isWasm, u8aToU8a } from '@polkadot/util'; import { assert, compactAddLength, isFunction, isUndefined, isWasm, stringCamelCase, u8aToU8a } from '@polkadot/util';
import { blake2AsU8a } from '@polkadot/util-crypto';
import { Abi } from '../Abi'; import { Abi } from '../Abi';
import { applyOnEvent } from '../util'; import { applyOnEvent } from '../util';
import { Base } from './Base'; import { Base } from './Base';
import { Blueprint } from './Blueprint'; import { Blueprint } from './Blueprint';
import { Contract } from './Contract';
import { createBluePrintTx, EMPTY_SALT, encodeSalt } from './util';
export class CodeSubmittableResult<ApiType extends ApiTypes> extends SubmittableResult { export class CodeSubmittableResult<ApiType extends ApiTypes> extends SubmittableResult {
public readonly blueprint?: Blueprint<ApiType>; public readonly blueprint?: Blueprint<ApiType>;
public readonly contract?: Contract<ApiType>;
constructor (result: ISubmittableResult, blueprint?: Blueprint<ApiType>) { constructor (result: ISubmittableResult, blueprint?: Blueprint<ApiType>, contract?: Contract<ApiType>) {
super(result); super(result);
this.blueprint = blueprint; this.blueprint = blueprint;
this.contract = contract;
} }
} }
export class Code<ApiType extends ApiTypes> extends Base<ApiType> { export class Code<ApiType extends ApiTypes> extends Base<ApiType> {
public readonly code: Uint8Array; public readonly code: Uint8Array;
readonly #tx: MapConstructorExec<ApiType> = {};
constructor (api: ApiBase<ApiType>, abi: AnyJson | Abi, wasm: Uint8Array | string | Buffer | null | undefined, decorateMethod: DecorateMethod<ApiType>) { constructor (api: ApiBase<ApiType>, abi: AnyJson | Abi, wasm: Uint8Array | string | Buffer | null | undefined, decorateMethod: DecorateMethod<ApiType>) {
super(api, abi, decorateMethod); super(api, abi, decorateMethod);
@@ -36,18 +45,79 @@ export class Code<ApiType extends ApiTypes> extends Base<ApiType> {
: u8aToU8a(wasm); : u8aToU8a(wasm);
assert(isWasm(this.code), 'No WASM code provided'); assert(isWasm(this.code), 'No WASM code provided');
this.abi.constructors.forEach((c): void => {
const messageName = stringCamelCase(c.identifier);
if (isUndefined(this.#tx[messageName])) {
this.#tx[messageName] = createBluePrintTx((o, p) => this.#instantiate(c, o, p));
}
});
} }
/** /**
* @description Deploy the code bundle, creating a Blueprint. * @description Deploy the code bundle, creating a Blueprint.
* @deprecated Use the `code.tx.<constructor>(...) format to put code and deploy
*/ */
public createBlueprint (): SubmittableExtrinsic<ApiType, CodeSubmittableResult<ApiType>> { public createBlueprint (): SubmittableExtrinsic<ApiType, CodeSubmittableResult<ApiType>> {
return this.api.tx.contracts return this.api.tx.contracts
.putCode(compactAddLength(this.code)) .putCode(compactAddLength(this.code))
.withResultTransform((result: ISubmittableResult) => .withResultTransform((result: ISubmittableResult) =>
new CodeSubmittableResult(result, applyOnEvent(result, 'CodeStored', ([record]: EventRecord[]) => new CodeSubmittableResult(result, applyOnEvent(result, ['CodeStored'], ([record]: EventRecord[]) =>
new Blueprint<ApiType>(this.api, this.abi, record.event.data[0] as Hash, this._decorateMethod) new Blueprint<ApiType>(this.api, this.abi, record.event.data[0] as Hash, this._decorateMethod)
)) ))
); );
} }
/**
* @description Deploy the code bundle and the contract, creating a Blueprint.
* @deprecated Use the `code.tx.<constructor>(...) format to put code and deploy
*/
public createContract (constructorOrId: AbiConstructor | string | number, options: BlueprintOptions, params: CodecArg[]): SubmittableExtrinsic<ApiType, CodeSubmittableResult<ApiType>> {
return this.#instantiate(constructorOrId, options, params);
}
public get tx (): MapConstructorExec<ApiType> {
return this.#tx;
}
#instantiate = (constructorOrId: AbiConstructor | string | number, options: BlueprintOptions, params: CodecArg[]): SubmittableExtrinsic<ApiType, CodeSubmittableResult<ApiType>> => {
return isFunction(this.api.tx.contracts.instantiateWithCode)
? this.#instantiateSingle(constructorOrId, options, params)
: this.#instantiateBatch(constructorOrId, options, params);
}
#instantiateSingle = (constructorOrId: AbiConstructor | string | number, { gasLimit = 0, salt, value = 0 }: BlueprintOptions, params: CodecArg[]): SubmittableExtrinsic<ApiType, CodeSubmittableResult<ApiType>> => {
return this.api.tx.contracts
.instantiateWithCode(value, gasLimit, compactAddLength(this.code), this.abi.findConstructor(constructorOrId).toU8a(params), encodeSalt(salt))
.withResultTransform(this.#transformEvents);
}
#instantiateBatch = (constructorOrId: AbiConstructor | string | number, { gasLimit = 0, salt, value = 0 }: BlueprintOptions, params: CodecArg[]): SubmittableExtrinsic<ApiType, CodeSubmittableResult<ApiType>> => {
const encodedSalt = encodeSalt(salt);
const withSalt = this.api.tx.contracts.instantiate.meta.args.length === 5;
const encoded = this.abi.findConstructor(constructorOrId).toU8a(params, withSalt ? EMPTY_SALT : encodedSalt);
const codeHash = blake2AsU8a(this.code);
return this.api.tx.utility.batch([
this.api.tx.contracts.putCode(compactAddLength(this.code)),
withSalt
? this.api.tx.contracts.instantiate(value, gasLimit, codeHash, encoded, encodedSalt)
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore old style with salt included in the params itself
: this.api.tx.contracts.instantiate(value, gasLimit, codeHash, encoded)
]).withResultTransform(this.#transformEvents);
}
#transformEvents = (result: ISubmittableResult): CodeSubmittableResult<ApiType> => {
return new CodeSubmittableResult(result, ...(applyOnEvent(result, ['CodeStored', 'Instantiated'], (records: EventRecord[]) =>
records.reduce(([blueprint, contract], { event }): [Blueprint<ApiType>?, Contract<ApiType>?] =>
this.api.events.contracts.Instantiated.is(event)
? [blueprint, new Contract<ApiType>(this.api, this.abi, event.data[1], this._decorateMethod)]
: this.api.events.contracts.CodeStored.is(event)
? [new Blueprint<ApiType>(this.api, this.abi, event.data[0], this._decorateMethod), contract]
: [blueprint, contract],
[] as [Blueprint<ApiType>?, Contract<ApiType>?])
) || []));
}
} }
+1 -1
View File
@@ -156,7 +156,7 @@ export class Contract<ApiType extends ApiTypes> extends Base<ApiType> {
return this.api.tx.contracts return this.api.tx.contracts
.call(this.address, value, this.#getGas(gasLimit), this.abi.findMessage(messageOrId).toU8a(params)) .call(this.address, value, this.#getGas(gasLimit), this.abi.findMessage(messageOrId).toU8a(params))
.withResultTransform((result: ISubmittableResult) => .withResultTransform((result: ISubmittableResult) =>
new ContractSubmittableResult(result, applyOnEvent(result, 'ContractExecution', (records: EventRecord[]) => new ContractSubmittableResult(result, applyOnEvent(result, ['ContractExecution'], (records: EventRecord[]) =>
records records
.map(({ event: { data: [, data] } }): DecodedEvent | null => { .map(({ event: { data: [, data] } }): DecodedEvent | null => {
try { try {
+3
View File
@@ -11,6 +11,9 @@ export const mockApi = {
rx: { rx: {
tx: { tx: {
contracts: { contracts: {
instantiate: (): never => {
throw new Error('mock');
},
putCode: (): never => { putCode: (): never => {
throw new Error('mock'); throw new Error('mock');
} }
+41
View File
@@ -0,0 +1,41 @@
// Copyright 2017-2021 @polkadot/api-contract authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { SubmittableResult } from '@polkadot/api';
import type { SubmittableExtrinsic } from '@polkadot/api/submittable/types';
import type { ApiTypes } from '@polkadot/api/types';
import type { CodecArg } from '@polkadot/types/types';
import type { AbiConstructor, BlueprintOptions } from '../types';
import type { BlueprintDeploy, ContractGeneric } from './types';
import BN from 'bn.js';
import { Bytes } from '@polkadot/types';
import { compactAddLength, u8aToU8a } from '@polkadot/util';
import { randomAsU8a } from '@polkadot/util-crypto';
import { extractOptions, isOptions } from '../util';
export const EMPTY_SALT = new Uint8Array();
export function createBluePrintTx <ApiType extends ApiTypes, R extends SubmittableResult> (fn: (options: BlueprintOptions, params: CodecArg[]) => SubmittableExtrinsic<ApiType, R>): BlueprintDeploy<ApiType> {
return (options: BigInt | string | number | BN | BlueprintOptions, ...params: CodecArg[]): SubmittableExtrinsic<ApiType, R> =>
isOptions(options)
? fn(options, params)
: fn(...extractOptions(options, params));
}
export function createBluePrintWithId <T> (fn: (constructorOrId: AbiConstructor | string | number, options: BlueprintOptions, params: CodecArg[]) => T): ContractGeneric<BlueprintOptions, T> {
return (constructorOrId: AbiConstructor | string | number, options: BigInt | string | number | BN | BlueprintOptions, ...params: CodecArg[]): T =>
isOptions(options)
? fn(constructorOrId, options, params)
: fn(constructorOrId, ...extractOptions(options, params));
}
export function encodeSalt (salt: Uint8Array | string | null = randomAsU8a()): Uint8Array {
return salt instanceof Bytes
? salt
: salt && salt.length
? compactAddLength(u8aToU8a(salt))
: EMPTY_SALT;
}
@@ -0,0 +1,10 @@
// Copyright 2017-2021 @polkadot/api-contract authors & contributors
// SPDX-License-Identifier: Apache-2.0
import { packageInfo as apiInfo } from '@polkadot/api/packageInfo';
import { packageInfo as typesInfo } from '@polkadot/types/packageInfo';
import { detectPackage } from '@polkadot/util';
import { packageInfo } from './packageInfo';
detectPackage(packageInfo, typeof __dirname !== 'undefined' && __dirname, [apiInfo, typesInfo]);
+4 -2
View File
@@ -1,7 +1,9 @@
// Copyright 2017-2021 @polkadot/api-contract authors & contributors // Copyright 2017-2021 @polkadot/api-contract authors & contributors
// SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: Apache-2.0
export { Abi } from './Abi'; import './detectPackage';
export { Blueprint as BlueprintRx, Code as CodeRx, Contract as ContractRx } from './rx'; export { Abi } from './Abi';
export { packageInfo } from './packageInfo';
export { Blueprint as BlueprintPromise, Code as CodePromise, Contract as ContractPromise } from './promise'; export { Blueprint as BlueprintPromise, Code as CodePromise, Contract as ContractPromise } from './promise';
export { Blueprint as BlueprintRx, Code as CodeRx, Contract as ContractRx } from './rx';
+6
View File
@@ -0,0 +1,6 @@
// Copyright 2017-2021 @polkadot/api-contract authors & contributors
// SPDX-License-Identifier: Apache-2.0
// Auto-generated by @polkadot/dev, do not edit
export const packageInfo = { name: '@polkadot/api-contract', version: '4.0.3' };
+2 -2
View File
@@ -20,9 +20,9 @@ export function formatData (registry: Registry, data: Raw, { type }: TypeDef): C
return createTypeUnsafe(registry, type, [data], { isPedantic: true }); return createTypeUnsafe(registry, type, [data], { isPedantic: true });
} }
export function applyOnEvent <T> (result: SubmittableResult, type: ContractEvents, fn: (records: EventRecord[]) => T): T | undefined { export function applyOnEvent <T> (result: SubmittableResult, types: ContractEvents[], fn: (records: EventRecord[]) => T): T | undefined {
if (result.isInBlock || result.isFinalized) { if (result.isInBlock || result.isFinalized) {
const records = result.filterRecords('contracts', type); const records = result.filterRecords('contracts', types);
if (records.length) { if (records.length) {
return fn(records); return fn(records);
@@ -0,0 +1,6 @@
[
{
"info": 6,
"type": "bool"
}
]
@@ -6,5 +6,6 @@ export { default as dns } from './dns.json';
export { default as erc20 } from './erc20.json'; export { default as erc20 } from './erc20.json';
export { default as erc721 } from './erc721.json'; export { default as erc721 } from './erc721.json';
export { default as flipper } from './flipper.json'; export { default as flipper } from './flipper.json';
export { default as flipperBundle } from './flipper.contract.json';
export { default as incrementer } from './incrementer.json'; export { default as incrementer } from './incrementer.json';
export { default as multisigPlain } from './multisig_plain.json'; export { default as multisigPlain } from './multisig_plain.json';
+15 -11
View File
@@ -1,9 +1,13 @@
{ {
"name": "@polkadot/api-derive", "name": "@polkadot/api-derive",
"version": "3.7.2", "version": "4.0.3",
"type": "module",
"description": "Common functions used across Polkadot, derived from RPC calls and storage queries.", "description": "Common functions used across Polkadot, derived from RPC calls and storage queries.",
"main": "index.js", "main": "index.js",
"sideEffects": false, "sideEffects": [
"./detectPackage.js",
"./detectPackage.cjs"
],
"author": "Jaco Greeff <jacogr@gmail.com>", "author": "Jaco Greeff <jacogr@gmail.com>",
"maintainers": [], "maintainers": [],
"contributors": [], "contributors": [],
@@ -12,17 +16,17 @@
"bugs": "https://github.com/polkadot-js/api/issues", "bugs": "https://github.com/polkadot-js/api/issues",
"homepage": "https://github.com/polkadot-js/api/tree/master/packages/api-derive#readme", "homepage": "https://github.com/polkadot-js/api/tree/master/packages/api-derive#readme",
"dependencies": { "dependencies": {
"@babel/runtime": "^7.12.5", "@babel/runtime": "^7.13.9",
"@polkadot/api": "3.7.2", "@polkadot/api": "4.0.3",
"@polkadot/rpc-core": "3.7.2", "@polkadot/rpc-core": "4.0.3",
"@polkadot/types": "3.7.2", "@polkadot/types": "4.0.3",
"@polkadot/util": "^5.5.1", "@polkadot/util": "^6.0.5",
"@polkadot/util-crypto": "^5.5.1", "@polkadot/util-crypto": "^6.0.5",
"@polkadot/x-rxjs": "^5.5.1", "@polkadot/x-rxjs": "^6.0.5",
"bn.js": "^4.11.9" "bn.js": "^4.11.9"
}, },
"devDependencies": { "devDependencies": {
"@polkadot/keyring": "^5.5.1", "@polkadot/keyring": "^6.0.5",
"@polkadot/rpc-provider": "3.7.2" "@polkadot/rpc-provider": "4.0.3"
} }
} }
+17 -3
View File
@@ -17,6 +17,12 @@ type BalanceResult = [Balance, Balance, Balance, Balance];
type Result = [Index, BalanceResult[]]; type Result = [Index, BalanceResult[]];
type DeriveCustomAccount = ApiInterfaceRx['derive'] & {
[custom: string]: {
customAccount?: ApiInterfaceRx['query']['balances']['account']
}
}
function getBalance (api: ApiInterfaceRx, [freeBalance, reservedBalance, frozenFee, frozenMisc]: BalanceResult): DeriveBalancesAccountData { function getBalance (api: ApiInterfaceRx, [freeBalance, reservedBalance, frozenFee, frozenMisc]: BalanceResult): DeriveBalancesAccountData {
return { return {
freeBalance, freeBalance,
@@ -55,7 +61,13 @@ function queryBalancesFree (api: ApiInterfaceRx, accountId: AccountId): Observab
} }
function queryBalancesAccount (api: ApiInterfaceRx, accountId: AccountId, modules: string[] = ['balances']): Observable<Result> { function queryBalancesAccount (api: ApiInterfaceRx, accountId: AccountId, modules: string[] = ['balances']): Observable<Result> {
const balances = modules.map((m): QueryableStorageMultiArg<'rxjs'> => [api.query[m].account, accountId]); const balances = modules.map(
(m): QueryableStorageMultiArg<'rxjs'> => [
(api.derive as DeriveCustomAccount)[m]?.customAccount || api.query[m].account,
accountId
]
);
const extract = (data: AccountData[]) => const extract = (data: AccountData[]) =>
data.map(({ feeFrozen, free, miscFrozen, reserved }): BalanceResult => [free, reserved, feeFrozen, miscFrozen]); data.map(({ feeFrozen, free, miscFrozen, reserved }): BalanceResult => [free, reserved, feeFrozen, miscFrozen]);
@@ -75,9 +87,11 @@ function queryCurrent (api: ApiInterfaceRx, accountId: AccountId): Observable<Re
const { feeFrozen, free, miscFrozen, reserved } = (infoOrTuple as AccountInfo).nonce const { feeFrozen, free, miscFrozen, reserved } = (infoOrTuple as AccountInfo).nonce
? (infoOrTuple as AccountInfo).data ? (infoOrTuple as AccountInfo).data
: (infoOrTuple as [Index, AccountData])[1]; : (infoOrTuple as [Index, AccountData])[1];
const accountNonce = (infoOrTuple as AccountInfo).nonce || (infoOrTuple as [Index, AccountData])[0];
return [accountNonce, [[free, reserved, feeFrozen, miscFrozen]]]; return [
(infoOrTuple as AccountInfo).nonce || (infoOrTuple as [Index, AccountData])[0],
[[free, reserved, feeFrozen, miscFrozen]]
];
}) })
); );
} }
+19 -10
View File
@@ -9,7 +9,7 @@ import type { DeriveBalancesAccount, DeriveBalancesAccountData, DeriveBalancesAl
import BN from 'bn.js'; import BN from 'bn.js';
import { bnMax } from '@polkadot/util'; import { bnMax, isFunction } from '@polkadot/util';
import { combineLatest, of } from '@polkadot/x-rxjs'; import { combineLatest, of } from '@polkadot/x-rxjs';
import { map, switchMap } from '@polkadot/x-rxjs/operators'; import { map, switchMap } from '@polkadot/x-rxjs/operators';
@@ -27,6 +27,12 @@ interface AllLocked {
vestingLocked: Balance vestingLocked: Balance
} }
type DeriveCustomLocks = ApiInterfaceRx['derive'] & {
[custom: string]: {
customLocks?: ApiInterfaceRx['query']['balances']['locks']
}
}
const VESTING_ID = '0x76657374696e6720'; const VESTING_ID = '0x76657374696e6720';
function calcLocked (api: ApiInterfaceRx, bestNumber: BlockNumber, locks: (BalanceLock | BalanceLockTo212)[]): AllLocked { function calcLocked (api: ApiInterfaceRx, bestNumber: BlockNumber, locks: (BalanceLock | BalanceLockTo212)[]): AllLocked {
@@ -54,11 +60,10 @@ function calcLocked (api: ApiInterfaceRx, bestNumber: BlockNumber, locks: (Balan
function calcShared (api: ApiInterfaceRx, bestNumber: BlockNumber, data: DeriveBalancesAccountData, locks: (BalanceLock | BalanceLockTo212)[]): DeriveBalancesAllAccountData { function calcShared (api: ApiInterfaceRx, bestNumber: BlockNumber, data: DeriveBalancesAccountData, locks: (BalanceLock | BalanceLockTo212)[]): DeriveBalancesAllAccountData {
const { allLocked, lockedBalance, lockedBreakdown, vestingLocked } = calcLocked(api, bestNumber, locks); const { allLocked, lockedBalance, lockedBreakdown, vestingLocked } = calcLocked(api, bestNumber, locks);
const availableBalance = api.registry.createType('Balance', allLocked ? 0 : bnMax(new BN(0), data.freeBalance.sub(lockedBalance)));
return { return {
...data, ...data,
availableBalance, availableBalance: api.registry.createType('Balance', allLocked ? 0 : bnMax(new BN(0), data.freeBalance.sub(lockedBalance))),
lockedBalance, lockedBalance,
lockedBreakdown, lockedBreakdown,
vestingLocked vestingLocked
@@ -75,8 +80,6 @@ function calcBalances (api: ApiInterfaceRx, [data, bestNumber, [vesting, allLock
const vestedNow = isStarted ? perBlock.mul(bestNumber.sub(startingBlock)) : new BN(0); const vestedNow = isStarted ? perBlock.mul(bestNumber.sub(startingBlock)) : new BN(0);
const vestedBalance = vestedNow.gt(vestingTotal) ? vestingTotal : api.registry.createType('Balance', vestedNow); const vestedBalance = vestedNow.gt(vestingTotal) ? vestingTotal : api.registry.createType('Balance', vestedNow);
const isVesting = isStarted && !shared.vestingLocked.isZero(); const isVesting = isStarted && !shared.vestingLocked.isZero();
const vestedClaimable = api.registry.createType('Balance', isVesting ? shared.vestingLocked.sub(vestingTotal.sub(vestedBalance)) : 0);
const vestingEndBlock = api.registry.createType('BlockNumber', isVesting ? vestingTotal.div(perBlock).add(startingBlock) : 0);
return { return {
...shared, ...shared,
@@ -85,8 +88,8 @@ function calcBalances (api: ApiInterfaceRx, [data, bestNumber, [vesting, allLock
additional: allLocks.filter((_, index) => index !== 0).map((l, index) => calcShared(api, bestNumber, data.additional[index], l)), additional: allLocks.filter((_, index) => index !== 0).map((l, index) => calcShared(api, bestNumber, data.additional[index], l)),
isVesting, isVesting,
vestedBalance, vestedBalance,
vestedClaimable, vestedClaimable: api.registry.createType('Balance', isVesting ? shared.vestingLocked.sub(vestingTotal.sub(vestedBalance)) : 0),
vestingEndBlock, vestingEndBlock: api.registry.createType('BlockNumber', isVesting ? vestingTotal.div(perBlock).add(startingBlock) : 0),
vestingPerBlock: perBlock, vestingPerBlock: perBlock,
vestingTotal vestingTotal
}; };
@@ -112,11 +115,17 @@ function queryOld (api: ApiInterfaceRx, accountId: AccountId): Observable<Result
); );
} }
const isNonNullable = <T>(nullable: T): nullable is NonNullable<T> => !!nullable;
// current (balances, vesting) // current (balances, vesting)
function queryCurrent (api: ApiInterfaceRx, accountId: AccountId, balanceInstances: string[] = ['balances']): Observable<ResultBalance> { function queryCurrent (api: ApiInterfaceRx, accountId: AccountId, balanceInstances: string[] = ['balances']): Observable<ResultBalance> {
const lockCalls = balanceInstances.map((m) => api.query[m].locks); const lockCalls = balanceInstances.map(
(m): ApiInterfaceRx['query']['balances']['locks'] | undefined =>
(api.derive as DeriveCustomLocks)[m]?.customLocks || api.query[m as 'balances']?.locks
);
const lockEmpty = lockCalls.map((c) => !c); const lockEmpty = lockCalls.map((c) => !c);
const lockQueries = lockCalls.filter((c) => c).map((c): QueryableStorageMultiArg<'rxjs'> => [c, accountId]); const lockQueries = lockCalls.filter(isNonNullable).map((c): QueryableStorageMultiArg<'rxjs'> => [c, accountId]);
return ( return (
api.query.vesting?.vesting api.query.vesting?.vesting
@@ -166,7 +175,7 @@ export function all (instanceId: string, api: ApiInterfaceRx): (address: Account
? combineLatest([ ? combineLatest([
of(account), of(account),
api.derive.chain.bestNumber(), api.derive.chain.bestNumber(),
api.query.system?.account || api.query.balances?.account isFunction(api.query.system?.account) || isFunction(api.query.balances?.account)
? queryCurrent(api, account.accountId, balanceInstances) ? queryCurrent(api, account.accountId, balanceInstances)
: queryOld(api, account.accountId) : queryOld(api, account.accountId)
]) ])
@@ -23,7 +23,7 @@ describe('bounties derive', () => {
let storageKey: (index: number) => StorageKey; let storageKey: (index: number) => StorageKey;
let defaultBounty: () => Bounty; let defaultBounty: () => Bounty;
let emptyOption: <T extends Codec> (typeName: keyof InterfaceTypes) => Option<T>; let emptyOption: <T extends Codec> (typeName: keyof InterfaceTypes) => Option<T>;
let optionOf: <T extends Codec> (value: T)=> Option<T>; let optionOf: <T extends Codec> (value: T) => Option<T>;
let bountyIndex: (index: number) => BountyIndex; let bountyIndex: (index: number) => BountyIndex;
let proposalIndex: (index: number) => ProposalIndex; let proposalIndex: (index: number) => ProposalIndex;
let bytes: (value: string) => Bytes; let bytes: (value: string) => Bytes;
+4 -4
View File
@@ -3,7 +3,7 @@
import type { ApiInterfaceRx } from '@polkadot/api/types'; import type { ApiInterfaceRx } from '@polkadot/api/types';
import type { DeriveBounties, DeriveCollectiveProposal } from '@polkadot/api-derive/types'; import type { DeriveBounties, DeriveCollectiveProposal } from '@polkadot/api-derive/types';
import type { Bytes, Option, StorageKey } from '@polkadot/types'; import type { Bytes, Option } from '@polkadot/types';
import type { Bounty, BountyIndex, ProposalIndex } from '@polkadot/types/interfaces'; import type { Bounty, BountyIndex, ProposalIndex } from '@polkadot/types/interfaces';
import { memo } from '@polkadot/api-derive/util'; import { memo } from '@polkadot/api-derive/util';
@@ -32,7 +32,7 @@ function parseResult ([maybeBounties, maybeDescriptions, ids, bountyProposals]:
} }
export function bounties (instanceId: string, api: ApiInterfaceRx): () => Observable<DeriveBounties> { export function bounties (instanceId: string, api: ApiInterfaceRx): () => Observable<DeriveBounties> {
const bountyBase = api.query.bounties ? api.query.bounties : api.query.treasury; const bountyBase = api.query.bounties || api.query.treasury;
return memo(instanceId, (): Observable<DeriveBounties> => return memo(instanceId, (): Observable<DeriveBounties> =>
combineLatest([ combineLatest([
@@ -41,12 +41,12 @@ export function bounties (instanceId: string, api: ApiInterfaceRx): () => Observ
]).pipe( ]).pipe(
switchMap(() => switchMap(() =>
combineLatest([ combineLatest([
bountyBase.bounties.keys(), bountyBase.bounties.keys<[BountyIndex]>(),
api.derive.council ? api.derive.council.proposals() : of([]) api.derive.council ? api.derive.council.proposals() : of([])
]) ])
), ),
switchMap(([keys, proposals]): Observable<Result> => { switchMap(([keys, proposals]): Observable<Result> => {
const ids = (keys as StorageKey<[BountyIndex]>[]).map(({ args: [id] }) => id); const ids = keys.map(({ args: [id] }) => id);
return combineLatest([ return combineLatest([
bountyBase.bounties.multi<Option<Bounty>>(ids), bountyBase.bounties.multi<Option<Bounty>>(ids),
@@ -2,8 +2,10 @@
// SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: Apache-2.0
import type { ApiInterfaceRx } from '@polkadot/api/types'; import type { ApiInterfaceRx } from '@polkadot/api/types';
import type { AccountId, EventRecord, SignedBlock } from '@polkadot/types/interfaces'; import type { Vec } from '@polkadot/types';
import type { EventRecord, SignedBlock } from '@polkadot/types/interfaces';
import type { Observable } from '@polkadot/x-rxjs'; import type { Observable } from '@polkadot/x-rxjs';
import type { HeaderExtended } from '../type';
import { combineLatest, of } from '@polkadot/x-rxjs'; import { combineLatest, of } from '@polkadot/x-rxjs';
import { map, switchMap } from '@polkadot/x-rxjs/operators'; import { map, switchMap } from '@polkadot/x-rxjs/operators';
@@ -18,17 +20,17 @@ import { memo } from '../util';
export function subscribeNewBlocks (instanceId: string, api: ApiInterfaceRx): () => Observable<SignedBlockExtended> { export function subscribeNewBlocks (instanceId: string, api: ApiInterfaceRx): () => Observable<SignedBlockExtended> {
return memo(instanceId, (): Observable<SignedBlockExtended> => return memo(instanceId, (): Observable<SignedBlockExtended> =>
api.derive.chain.subscribeNewHeads().pipe( api.derive.chain.subscribeNewHeads().pipe(
switchMap((header): Observable<[SignedBlock, EventRecord[], AccountId[] | undefined]> => { switchMap((header): Observable<[SignedBlock, Vec<EventRecord>, HeaderExtended]> => {
const blockHash = header.hash; const blockHash = header.createdAtHash || header.hash;
return combineLatest( return combineLatest(
api.rpc.chain.getBlock(blockHash), api.rpc.chain.getBlock(blockHash),
api.query.system.events.at(blockHash), api.query.system.events.at(blockHash),
of(header.validators) of(header)
); );
}), }),
map(([block, events, validators]) => map(([block, events, header]) =>
new SignedBlockExtended(api.registry, block, events, validators) new SignedBlockExtended(api.registry, block, events, header.validators)
) )
) )
); );
@@ -29,10 +29,13 @@ export function subscribeNewHeads (instanceId: string, api: ApiInterfaceRx): ()
api.rpc.chain.subscribeNewHeads(), api.rpc.chain.subscribeNewHeads(),
api.query.session api.query.session
? api.query.session.validators() ? api.query.session.validators()
: of([]) : of(undefined)
]).pipe( ]).pipe(
map(([header, validators]): HeaderExtended => map(([header, validators]): HeaderExtended => {
new HeaderExtended(api.registry, header, validators) header.createdAtHash = header.hash;
return new HeaderExtended(api.registry, header, validators);
})
) )
)); );
} }
+19 -9
View File
@@ -3,7 +3,7 @@
import type { ApiInterfaceRx } from '@polkadot/api/types'; import type { ApiInterfaceRx } from '@polkadot/api/types';
import type { Vec } from '@polkadot/types'; import type { Vec } from '@polkadot/types';
import type { AccountId, Balance } from '@polkadot/types/interfaces'; import type { AccountId, Balance, Voter } from '@polkadot/types/interfaces';
import type { ITuple } from '@polkadot/types/types'; import type { ITuple } from '@polkadot/types/types';
import type { Observable } from '@polkadot/x-rxjs'; import type { Observable } from '@polkadot/x-rxjs';
import type { DeriveCouncilVote, DeriveCouncilVotes } from '../types'; import type { DeriveCouncilVote, DeriveCouncilVotes } from '../types';
@@ -13,18 +13,25 @@ import { map } from '@polkadot/x-rxjs/operators';
import { memo } from '../util'; import { memo } from '../util';
// Voter is current tuple is 2.x-era
type VoteEntry = Voter | ITuple<[Balance, Vec<AccountId>]>;
function isVoter (value: VoteEntry): value is Voter {
return !Array.isArray(value);
}
function retrieveStakeOf (api: ApiInterfaceRx): Observable<[AccountId, Balance][]> { function retrieveStakeOf (api: ApiInterfaceRx): Observable<[AccountId, Balance][]> {
return (api.query.electionsPhragmen || api.query.elections).stakeOf.entries<Balance>().pipe( return (api.query.electionsPhragmen || api.query.elections).stakeOf.entries<Balance, [AccountId]>().pipe(
map((entries) => map((entries) =>
entries.map(([key, stake]) => [key.args[0] as AccountId, stake]) entries.map(([{ args: [accountId] }, stake]) => [accountId, stake])
) )
); );
} }
function retrieveVoteOf (api: ApiInterfaceRx): Observable<[AccountId, AccountId[]][]> { function retrieveVoteOf (api: ApiInterfaceRx): Observable<[AccountId, AccountId[]][]> {
return (api.query.electionsPhragmen || api.query.elections).votesOf.entries<Vec<AccountId>>().pipe( return (api.query.electionsPhragmen || api.query.elections).votesOf.entries<Vec<AccountId>, [AccountId]>().pipe(
map((entries) => map((entries) =>
entries.map(([key, votes]) => [key.args[0] as AccountId, votes]) entries.map(([{ args: [accountId] }, votes]) => [accountId, votes])
) )
); );
} }
@@ -56,11 +63,14 @@ function retrievePrev (api: ApiInterfaceRx): Observable<DeriveCouncilVotes> {
function retrieveCurrent (api: ApiInterfaceRx): Observable<DeriveCouncilVotes> { function retrieveCurrent (api: ApiInterfaceRx): Observable<DeriveCouncilVotes> {
const elections = (api.query.electionsPhragmen || api.query.elections); const elections = (api.query.electionsPhragmen || api.query.elections);
return elections.voting.entries<ITuple<[Balance, Vec<AccountId>]>>().pipe( return elections.voting.entries<VoteEntry, [AccountId]>().pipe(
map((entries): DeriveCouncilVotes => map((entries): DeriveCouncilVotes =>
entries.map(([key, [stake, votes]]): [AccountId, DeriveCouncilVote] => entries.map(([{ args: [accountId] }, value]): [AccountId, DeriveCouncilVote] => [
[key.args[0] as AccountId, { stake, votes }] accountId,
) isVoter(value)
? { stake: value.stake, votes: value.votes }
: { stake: value[0], votes: value[1] }
])
) )
); );
} }
@@ -51,7 +51,7 @@ function schedulerEntries (api: ApiInterfaceRx): Observable<[BlockNumber[], Opti
api.query.scheduler.agenda.keys() api.query.scheduler.agenda.keys()
), ),
switchMap((keys) => { switchMap((keys) => {
const blockNumbers = keys.map((key) => key.args[0]); const blockNumbers = keys.map(({ args: [blockNumber] }) => blockNumber);
return combineLatest([ return combineLatest([
of(blockNumbers), of(blockNumbers),
@@ -51,7 +51,7 @@ function parse ([proposals, images, optDepositors]: Result): DeriveProposal[] {
export function proposals (instanceId: string, api: ApiInterfaceRx): () => Observable<DeriveProposal[]> { export function proposals (instanceId: string, api: ApiInterfaceRx): () => Observable<DeriveProposal[]> {
return memo(instanceId, (): Observable<DeriveProposal[]> => return memo(instanceId, (): Observable<DeriveProposal[]> =>
api.query.democracy?.publicProps && api.query.democracy?.preimages isFunction(api.query.democracy?.publicProps) && isFunction(api.query.democracy?.preimages)
? api.query.democracy.publicProps<Proposals>().pipe( ? api.query.democracy.publicProps<Proposals>().pipe(
switchMap((proposals) => switchMap((proposals) =>
combineLatest([ combineLatest([
@@ -67,9 +67,9 @@ function extractVotes (mapped: [AccountId, Voting][], referendumId: BN): DeriveR
} }
function votesCurr (api: ApiInterfaceRx, referendumId: BN): Observable<DeriveReferendumVote[]> { function votesCurr (api: ApiInterfaceRx, referendumId: BN): Observable<DeriveReferendumVote[]> {
return api.query.democracy.votingOf.entries<Voting>().pipe( return api.query.democracy.votingOf.entries<Voting, [AccountId]>().pipe(
map((allVoting): DeriveReferendumVote[] => { map((allVoting): DeriveReferendumVote[] => {
const mapped = allVoting.map(([key, voting]): [AccountId, Voting] => [key.args[0], voting]); const mapped = allVoting.map(([{ args: [accountId] }, voting]): [AccountId, Voting] => [accountId, voting]);
const votes = extractVotes(mapped, referendumId); const votes = extractVotes(mapped, referendumId);
const delegations = mapped const delegations = mapped
.filter(([, voting]) => voting.isDelegating) .filter(([, voting]) => voting.isDelegating)
+11
View File
@@ -0,0 +1,11 @@
// Copyright 2017-2021 @polkadot/api-derive authors & contributors
// SPDX-License-Identifier: Apache-2.0
import { packageInfo as apiInfo } from '@polkadot/api/packageInfo';
import { packageInfo as coreInfo } from '@polkadot/rpc-core/packageInfo';
import { packageInfo as typesInfo } from '@polkadot/types/packageInfo';
import { detectPackage } from '@polkadot/util';
import { packageInfo } from './packageInfo';
detectPackage(packageInfo, typeof __dirname !== 'undefined' && __dirname, [apiInfo, coreInfo, typesInfo]);
+31 -6
View File
@@ -3,7 +3,7 @@
import type { ApiInterfaceRx } from '@polkadot/api/types'; import type { ApiInterfaceRx } from '@polkadot/api/types';
import type { u32, Vec } from '@polkadot/types'; import type { u32, Vec } from '@polkadot/types';
import type { AccountId, Balance, BlockNumber } from '@polkadot/types/interfaces'; import type { AccountId, Balance, BlockNumber, SeatHolder } from '@polkadot/types/interfaces';
import type { ITuple } from '@polkadot/types/types'; import type { ITuple } from '@polkadot/types/types';
import type { Observable } from '@polkadot/x-rxjs'; import type { Observable } from '@polkadot/x-rxjs';
import type { DeriveElectionsInfo } from './types'; import type { DeriveElectionsInfo } from './types';
@@ -12,14 +12,39 @@ import { map } from '@polkadot/x-rxjs/operators';
import { memo } from '../util'; import { memo } from '../util';
function sortAccounts ([, balanceA]: ITuple<[AccountId, Balance]>, [, balanceB]: ITuple<[AccountId, Balance]>): number { // SeatHolder is current tuple is 2.x-era Substrate
type Member = SeatHolder | ITuple<[AccountId, Balance]>;
type Candidate = AccountId | ITuple<[AccountId, Balance]>;
function isSeatHolder (value: Member): value is SeatHolder {
return !Array.isArray(value);
}
function isCandidateTuple (value: Candidate): value is ITuple<[AccountId, Balance]> {
return Array.isArray(value);
}
function getAccountTuple (value: Member): [AccountId, Balance] {
return isSeatHolder(value)
? [value.who, value.stake]
: value;
}
function getCandidate (value: Candidate): AccountId {
return isCandidateTuple(value)
? value[0]
: value;
}
function sortAccounts ([, balanceA]: [AccountId, Balance], [, balanceB]: [AccountId, Balance]): number {
return balanceB.cmp(balanceA); return balanceB.cmp(balanceA);
} }
function queryElections (api: ApiInterfaceRx): Observable<DeriveElectionsInfo> { function queryElections (api: ApiInterfaceRx): Observable<DeriveElectionsInfo> {
const section = api.query.electionsPhragmen ? 'electionsPhragmen' : 'elections'; const section = api.query.electionsPhragmen ? 'electionsPhragmen' : 'elections';
return api.queryMulti<[Vec<AccountId>, Vec<AccountId>, Vec<ITuple<[AccountId, Balance]>>, Vec<ITuple<[AccountId, Balance]>>]>([ return api.queryMulti<[Vec<AccountId>, Vec<Candidate>, Vec<Member>, Vec<Member>]>([
api.query.council.members, api.query.council.members,
api.query[section].candidates, api.query[section].candidates,
api.query[section].members, api.query[section].members,
@@ -28,13 +53,13 @@ function queryElections (api: ApiInterfaceRx): Observable<DeriveElectionsInfo> {
map(([councilMembers, candidates, members, runnersUp]): DeriveElectionsInfo => ({ map(([councilMembers, candidates, members, runnersUp]): DeriveElectionsInfo => ({
candidacyBond: api.consts[section].candidacyBond as Balance, candidacyBond: api.consts[section].candidacyBond as Balance,
candidateCount: api.registry.createType('u32', candidates.length), candidateCount: api.registry.createType('u32', candidates.length),
candidates, candidates: candidates.map(getCandidate),
desiredRunnersUp: api.consts[section].desiredRunnersUp as u32, desiredRunnersUp: api.consts[section].desiredRunnersUp as u32,
desiredSeats: api.consts[section].desiredMembers as u32, desiredSeats: api.consts[section].desiredMembers as u32,
members: members.length members: members.length
? members.sort(sortAccounts) ? members.map(getAccountTuple).sort(sortAccounts)
: councilMembers.map((accountId): [AccountId, Balance] => [accountId, api.registry.createType('Balance')]), : councilMembers.map((accountId): [AccountId, Balance] => [accountId, api.registry.createType('Balance')]),
runnersUp: runnersUp.sort(sortAccounts), runnersUp: runnersUp.map(getAccountTuple).sort(sortAccounts),
termDuration: api.consts[section].termDuration as BlockNumber, termDuration: api.consts[section].termDuration as BlockNumber,
votingBond: api.consts[section].votingBond as Balance votingBond: api.consts[section].votingBond as Balance
})) }))
+3
View File
@@ -1,6 +1,8 @@
// Copyright 2017-2021 @polkadot/api-derive authors & contributors // Copyright 2017-2021 @polkadot/api-derive authors & contributors
// SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: Apache-2.0
import './detectPackage';
import type { ApiInterfaceRx } from '@polkadot/api/types'; import type { ApiInterfaceRx } from '@polkadot/api/types';
import type { AnyFunction } from '@polkadot/types/types'; import type { AnyFunction } from '@polkadot/types/types';
import type { Observable } from '@polkadot/x-rxjs'; import type { Observable } from '@polkadot/x-rxjs';
@@ -22,6 +24,7 @@ import * as technicalCommittee from './technicalCommittee';
import * as treasury from './treasury'; import * as treasury from './treasury';
import * as tx from './tx'; import * as tx from './tx';
export { packageInfo } from './packageInfo';
export * from './type'; export * from './type';
export const derive = { accounts, balances, bounties, chain, contracts, council, democracy, elections, imOnline, parachains, session, society, staking, technicalCommittee, treasury, tx }; export const derive = { accounts, balances, bounties, chain, contracts, council, democracy, elections, imOnline, parachains, session, society, staking, technicalCommittee, treasury, tx };
+6
View File
@@ -0,0 +1,6 @@
// Copyright 2017-2021 @polkadot/api-derive authors & contributors
// SPDX-License-Identifier: Apache-2.0
// Auto-generated by @polkadot/dev, do not edit
export const packageInfo = { name: '@polkadot/api-derive', version: '4.0.3' };
@@ -3,7 +3,7 @@
import type { ApiInterfaceRx } from '@polkadot/api/types'; import type { ApiInterfaceRx } from '@polkadot/api/types';
import type { StorageKey } from '@polkadot/types'; import type { StorageKey } from '@polkadot/types';
import type { EraIndex, Exposure } from '@polkadot/types/interfaces'; import type { AccountId, EraIndex, Exposure } from '@polkadot/types/interfaces';
import type { Observable } from '@polkadot/x-rxjs'; import type { Observable } from '@polkadot/x-rxjs';
import type { DeriveEraExposure, DeriveEraNominatorExposure, DeriveEraValidatorExposure } from '../types'; import type { DeriveEraExposure, DeriveEraNominatorExposure, DeriveEraValidatorExposure } from '../types';
@@ -12,7 +12,7 @@ import { map, switchMap } from '@polkadot/x-rxjs/operators';
import { deriveCache, memo } from '../util'; import { deriveCache, memo } from '../util';
type KeysAndExposures = [StorageKey, Exposure][]; type KeysAndExposures = [StorageKey<[EraIndex, AccountId]>, Exposure][];
const CACHE_KEY = 'eraExposure'; const CACHE_KEY = 'eraExposure';
+17 -35
View File
@@ -1,55 +1,37 @@
// Copyright 2017-2021 @polkadot/api-derive authors & contributors // Copyright 2017-2021 @polkadot/api-derive authors & contributors
// SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: Apache-2.0
import type { ApiInterfaceRx } from '@polkadot/api/types'; import type { ApiInterfaceRx, QueryableStorageMultiArg } from '@polkadot/api/types';
import type { EraIndex, Exposure } from '@polkadot/types/interfaces'; import type { EraIndex, Exposure } from '@polkadot/types/interfaces';
import type { Observable } from '@polkadot/x-rxjs'; import type { Observable } from '@polkadot/x-rxjs';
import type { DeriveOwnExposure } from '../types'; import type { DeriveOwnExposure } from '../types';
import { combineLatest, of } from '@polkadot/x-rxjs'; import { of } from '@polkadot/x-rxjs';
import { map, switchMap } from '@polkadot/x-rxjs/operators'; import { map, switchMap } from '@polkadot/x-rxjs/operators';
import { deriveCache, memo } from '../util'; import { memo } from '../util';
const CACHE_KEY = 'ownExposure'; export function _ownExposures (instanceId: string, api: ApiInterfaceRx): (accountId: Uint8Array | string, eras: EraIndex[], withActive: boolean) => Observable<DeriveOwnExposure[]> {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
export function _ownExposure (instanceId: string, api: ApiInterfaceRx): (accountId: Uint8Array | string, era: EraIndex, withActive: boolean) => Observable<DeriveOwnExposure> { return memo(instanceId, (accountId: Uint8Array | string, eras: EraIndex[], _withActive: boolean): Observable<DeriveOwnExposure[]> =>
return memo(instanceId, (accountId: Uint8Array | string, era: EraIndex, withActive: boolean): Observable<DeriveOwnExposure> => { eras.length
const cacheKey = `${CACHE_KEY}-${era.toString()}-${accountId.toString()}`; ? api.queryMulti<Exposure[]>([
const cached = withActive ...eras.map((era): QueryableStorageMultiArg<'rxjs'> => [api.query.staking.erasStakersClipped, [era, accountId]]),
? undefined ...eras.map((era): QueryableStorageMultiArg<'rxjs'> => [api.query.staking.erasStakers, [era, accountId]])
: deriveCache.get<DeriveOwnExposure>(cacheKey);
return cached
? of(cached)
: api.queryMulti<[Exposure, Exposure]>([
[api.query.staking.erasStakersClipped, [era, accountId]],
[api.query.staking.erasStakers, [era, accountId]]
]).pipe( ]).pipe(
map(([clipped, exposure]): DeriveOwnExposure => { map((all): DeriveOwnExposure[] =>
const value = { clipped, era, exposure }; eras.map((era, index) => ({ clipped: all[index], era, exposure: all[eras.length + index] }))
)
!withActive && deriveCache.set(cacheKey, value); )
: of([])
return value;
})
); );
});
} }
export function ownExposure (instanceId: string, api: ApiInterfaceRx): (accountId: Uint8Array | string, era: EraIndex) => Observable<DeriveOwnExposure> { export function ownExposure (instanceId: string, api: ApiInterfaceRx): (accountId: Uint8Array | string, era: EraIndex) => Observable<DeriveOwnExposure> {
return memo(instanceId, (accountId: Uint8Array | string, era: EraIndex): Observable<DeriveOwnExposure> => return memo(instanceId, (accountId: Uint8Array | string, era: EraIndex): Observable<DeriveOwnExposure> =>
api.derive.staking._ownExposure(accountId, era, true) api.derive.staking._ownExposures(accountId, [era], true).pipe(
); map(([first]) => first)
}
export function _ownExposures (instanceId: string, api: ApiInterfaceRx): (accountId: Uint8Array | string, eras: EraIndex[], withActive: boolean) => Observable<DeriveOwnExposure[]> {
return memo(instanceId, (accountId: Uint8Array | string, eras: EraIndex[], withActive: boolean): Observable<DeriveOwnExposure[]> =>
eras.length
? combineLatest(
eras.map((era) => api.derive.staking._ownExposure(accountId, era, withActive))
) )
: of([])
); );
} }
+21 -39
View File
@@ -1,62 +1,44 @@
// Copyright 2017-2021 @polkadot/api-derive authors & contributors // Copyright 2017-2021 @polkadot/api-derive authors & contributors
// SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: Apache-2.0
import type { ApiInterfaceRx } from '@polkadot/api/types'; import type { ApiInterfaceRx, QueryableStorageMultiArg } from '@polkadot/api/types';
import type { Option } from '@polkadot/types'; import type { Option } from '@polkadot/types';
import type { BalanceOf, EraIndex, Perbill } from '@polkadot/types/interfaces'; import type { BalanceOf, EraIndex, Perbill } from '@polkadot/types/interfaces';
import type { ITuple } from '@polkadot/types/types'; import type { ITuple } from '@polkadot/types/types';
import type { Observable } from '@polkadot/x-rxjs'; import type { Observable } from '@polkadot/x-rxjs';
import type { DeriveStakerSlashes } from '../types'; import type { DeriveStakerSlashes } from '../types';
import { combineLatest, of } from '@polkadot/x-rxjs'; import { of } from '@polkadot/x-rxjs';
import { map, switchMap } from '@polkadot/x-rxjs/operators'; import { map, switchMap } from '@polkadot/x-rxjs/operators';
import { deriveCache, memo } from '../util'; import { memo } from '../util';
const CACHE_KEY = 'ownSlash'; export function _ownSlashes (instanceId: string, api: ApiInterfaceRx): (accountId: Uint8Array | string, eras: EraIndex[], withActive: boolean) => Observable<DeriveStakerSlashes[]> {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
export function _ownSlash (instanceId: string, api: ApiInterfaceRx): (accountId: Uint8Array | string, era: EraIndex, withActive: boolean) => Observable<DeriveStakerSlashes> { return memo(instanceId, (accountId: Uint8Array | string, eras: EraIndex[], _withActive: boolean): Observable<DeriveStakerSlashes[]> =>
return memo(instanceId, (accountId: Uint8Array | string, era: EraIndex, withActive: boolean): Observable<DeriveStakerSlashes> => { eras.length
const cacheKey = `${CACHE_KEY}-${era.toString()}-${accountId.toString()}`; ? api.queryMulti<(Option<ITuple<[Perbill, BalanceOf]>> | Option<BalanceOf>)[]>([
const cached = withActive ...eras.map((era): QueryableStorageMultiArg<'rxjs'> => [api.query.staking.validatorSlashInEra, [era, accountId]]),
? undefined ...eras.map((era): QueryableStorageMultiArg<'rxjs'> => [api.query.staking.nominatorSlashInEra, [era, accountId]])
: deriveCache.get<DeriveStakerSlashes>(cacheKey);
return cached
? of(cached)
: api.queryMulti<[Option<BalanceOf>, Option<ITuple<[Perbill, BalanceOf]>>]>([
[api.query.staking.nominatorSlashInEra, [era, accountId]],
[api.query.staking.validatorSlashInEra, [era, accountId]]
]).pipe( ]).pipe(
map(([optNom, optVal]): DeriveStakerSlashes => { map((values): DeriveStakerSlashes[] =>
const value = { eras.map((era, index) => ({
era, era,
total: optVal.isSome total: values[index].isSome
? optVal.unwrap()[1] ? (values[index].unwrap() as ITuple<[Perbill, BalanceOf]>)[1]
: optNom.unwrapOrDefault() : (values[index + eras.length].unwrapOrDefault() as BalanceOf)
}; }))
)
!withActive && deriveCache.set(cacheKey, value); )
: of([])
return value;
})
); );
});
} }
export function ownSlash (instanceId: string, api: ApiInterfaceRx): (accountId: Uint8Array | string, era: EraIndex) => Observable<DeriveStakerSlashes> { export function ownSlash (instanceId: string, api: ApiInterfaceRx): (accountId: Uint8Array | string, era: EraIndex) => Observable<DeriveStakerSlashes> {
return memo(instanceId, (accountId: Uint8Array | string, era: EraIndex): Observable<DeriveStakerSlashes> => return memo(instanceId, (accountId: Uint8Array | string, era: EraIndex): Observable<DeriveStakerSlashes> =>
api.derive.staking._ownSlash(accountId, era, true) api.derive.staking._ownSlashes(accountId, [era], true).pipe(
); map(([first]) => first)
}
export function _ownSlashes (instanceId: string, api: ApiInterfaceRx): (accountId: Uint8Array | string, eras: EraIndex[], withActive: boolean) => Observable<DeriveStakerSlashes[]> {
return memo(instanceId, (accountId: Uint8Array | string, eras: EraIndex[], withActive: boolean): Observable<DeriveStakerSlashes[]> =>
eras.length
? combineLatest(
eras.map((era) => api.derive.staking._ownSlash(accountId, era, withActive))
) )
: of([])
); );
} }
@@ -10,12 +10,13 @@ import { map, switchMap } from '@polkadot/x-rxjs/operators';
import { memo } from '../util'; import { memo } from '../util';
export function _stakerExposure (instanceId: string, api: ApiInterfaceRx): (accountId: Uint8Array | string, eras: EraIndex[], withActive: boolean) => Observable<DeriveStakerExposure[]> { export function _stakerExposures (instanceId: string, api: ApiInterfaceRx): (accountIds: (Uint8Array | string)[], eras: EraIndex[], withActive: boolean) => Observable<DeriveStakerExposure[][]> {
return memo(instanceId, (accountId: Uint8Array | string, eras: EraIndex[], withActive: boolean): Observable<DeriveStakerExposure[]> => { return memo(instanceId, (accountIds: (Uint8Array | string)[], eras: EraIndex[], withActive: boolean): Observable<DeriveStakerExposure[][]> => {
const stakerId = api.registry.createType('AccountId', accountId).toString(); const stakerIds = accountIds.map((a) => api.registry.createType('AccountId', a).toString());
return api.derive.staking._erasExposure(eras, withActive).pipe( return api.derive.staking._erasExposure(eras, withActive).pipe(
map((exposures): DeriveStakerExposure[] => map((exposures): DeriveStakerExposure[][] =>
stakerIds.map((stakerId) =>
exposures.map(({ era, nominators: allNominators, validators: allValidators }): DeriveStakerExposure => { exposures.map(({ era, nominators: allNominators, validators: allValidators }): DeriveStakerExposure => {
const isValidator = !!allValidators[stakerId]; const isValidator = !!allValidators[stakerId];
const validators: DeriveEraValidatorExposure = {}; const validators: DeriveEraValidatorExposure = {};
@@ -32,14 +33,23 @@ export function _stakerExposure (instanceId: string, api: ApiInterfaceRx): (acco
return { era, isEmpty: !Object.keys(validators).length, isValidator, nominating, validators }; return { era, isEmpty: !Object.keys(validators).length, isValidator, nominating, validators };
}) })
) )
)
); );
}); });
} }
export function stakerExposure (instanceId: string, api: ApiInterfaceRx): (accountId: Uint8Array | string, withActive?: boolean) => Observable<DeriveStakerExposure[]> { export function stakerExposures (instanceId: string, api: ApiInterfaceRx): (accountIds: (Uint8Array | string)[], withActive?: boolean) => Observable<DeriveStakerExposure[][]> {
return memo(instanceId, (accountId: Uint8Array | string, withActive = false): Observable<DeriveStakerExposure[]> => return memo(instanceId, (accountIds: (Uint8Array | string)[], withActive = false): Observable<DeriveStakerExposure[][]> =>
api.derive.staking.erasHistoric(withActive).pipe( api.derive.staking.erasHistoric(withActive).pipe(
switchMap((eras) => api.derive.staking._stakerExposure(accountId, eras, withActive)) switchMap((eras) => api.derive.staking._stakerExposures(accountIds, eras, withActive))
)
);
}
export function stakerExposure (instanceId: string, api: ApiInterfaceRx): (accountId: Uint8Array | string, withActive?: boolean) => Observable<DeriveStakerExposure[]> {
return memo(instanceId, (accountId: Uint8Array | string, withActive = false): Observable<DeriveStakerExposure[]> =>
api.derive.staking.stakerExposures([accountId, withActive]).pipe(
map(([first]) => first)
) )
); );
} }
@@ -2,45 +2,40 @@
// SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: Apache-2.0
import type { ApiInterfaceRx } from '@polkadot/api/types'; import type { ApiInterfaceRx } from '@polkadot/api/types';
import type { Option } from '@polkadot/types'; import type { AccountId, EraIndex, StakingLedger } from '@polkadot/types/interfaces';
import type { AccountId, EraIndex, StakingLedger, StakingLedgerTo240 } from '@polkadot/types/interfaces';
import type { Observable } from '@polkadot/x-rxjs'; import type { Observable } from '@polkadot/x-rxjs';
import type { DeriveEraPoints, DeriveEraPrefs, DeriveEraRewards, DeriveEraValPrefs, DeriveStakerExposure, DeriveStakerReward, DeriveStakerRewardValidator } from '../types'; import type { DeriveEraPoints, DeriveEraPrefs, DeriveEraRewards, DeriveEraValPrefs, DeriveStakerExposure, DeriveStakerReward, DeriveStakerRewardValidator } from '../types';
import type { DeriveStakingQuery } from './types'; import type { DeriveStakingQuery } from './types';
import BN from 'bn.js'; import BN from 'bn.js';
import { isFunction } from '@polkadot/util'; import { BN_BILLION, BN_ZERO } from '@polkadot/util';
import { combineLatest, of } from '@polkadot/x-rxjs'; import { combineLatest, of } from '@polkadot/x-rxjs';
import { map, switchMap } from '@polkadot/x-rxjs/operators'; import { map, switchMap } from '@polkadot/x-rxjs/operators';
import { memo } from '../util'; import { memo } from '../util';
type ErasResult = [{ unwrapOr: (value: BN) => BN }, DeriveEraPoints[], DeriveEraPrefs[], DeriveEraRewards[]]; type ErasResult = [DeriveEraPoints[], DeriveEraPrefs[], DeriveEraRewards[]];
const ZERO = new BN(0); function parseRewards (api: ApiInterfaceRx, stashId: AccountId, [erasPoints, erasPrefs, erasRewards]: ErasResult, exposures: DeriveStakerExposure[]): DeriveStakerReward[] {
const MIN_ONE = new BN(-1);
const COMM_DIV = new BN(1_000_000_000);
function parseRewards (api: ApiInterfaceRx, stashId: AccountId, [, erasPoints, erasPrefs, erasRewards]: ErasResult, exposures: DeriveStakerExposure[]): DeriveStakerReward[] {
return exposures.map(({ era, isEmpty, isValidator, nominating, validators: eraValidators }): DeriveStakerReward => { return exposures.map(({ era, isEmpty, isValidator, nominating, validators: eraValidators }): DeriveStakerReward => {
const { eraPoints, validators: allValPoints } = erasPoints.find((p) => p.era.eq(era)) || { eraPoints: ZERO, validators: {} }; const { eraPoints, validators: allValPoints } = erasPoints.find((p) => p.era.eq(era)) || { eraPoints: BN_ZERO, validators: {} };
const { eraReward } = erasRewards.find((r) => r.era.eq(era)) || { eraReward: api.registry.createType('Balance') }; const { eraReward } = erasRewards.find((r) => r.era.eq(era)) || { eraReward: api.registry.createType('Balance') };
const { validators: allValPrefs } = erasPrefs.find((p) => p.era.eq(era)) || { validators: {} as DeriveEraValPrefs }; const { validators: allValPrefs } = erasPrefs.find((p) => p.era.eq(era)) || { validators: {} as DeriveEraValPrefs };
const validators: Record<string, DeriveStakerRewardValidator> = {}; const validators: Record<string, DeriveStakerRewardValidator> = {};
const stakerId = stashId.toString(); const stakerId = stashId.toString();
Object.entries(eraValidators).forEach(([validatorId, exposure]): void => { Object.entries(eraValidators).forEach(([validatorId, exposure]): void => {
const valPoints = allValPoints[validatorId] || ZERO; const valPoints = allValPoints[validatorId] || BN_ZERO;
const valComm = allValPrefs[validatorId]?.commission.unwrap() || ZERO; const valComm = allValPrefs[validatorId]?.commission.unwrap() || BN_ZERO;
const expTotal = exposure.total.unwrap(); const expTotal = exposure.total.unwrap();
let avail = ZERO; let avail = BN_ZERO;
let value: BN | undefined; let value: BN | undefined;
if (!(expTotal.isZero() || valPoints.isZero() || eraPoints.isZero())) { if (!(expTotal.isZero() || valPoints.isZero() || eraPoints.isZero())) {
avail = eraReward.mul(valPoints).div(eraPoints); avail = eraReward.mul(valPoints).div(eraPoints);
const valCut = valComm.mul(avail).div(COMM_DIV); const valCut = valComm.mul(avail).div(BN_BILLION);
let staked: BN; let staked: BN;
if (validatorId === stakerId) { if (validatorId === stakerId) {
@@ -50,10 +45,10 @@ function parseRewards (api: ApiInterfaceRx, stashId: AccountId, [, erasPoints, e
staked = stakerExp staked = stakerExp
? stakerExp.value.unwrap() ? stakerExp.value.unwrap()
: ZERO; : BN_ZERO;
} }
value = avail.sub(valCut).imul(staked).div(expTotal).iadd(validatorId === stakerId ? valCut : ZERO); value = avail.sub(valCut).imul(staked).div(expTotal).iadd(validatorId === stakerId ? valCut : BN_ZERO);
} }
validators[validatorId] = { validators[validatorId] = {
@@ -73,32 +68,25 @@ function parseRewards (api: ApiInterfaceRx, stashId: AccountId, [, erasPoints, e
}); });
} }
function uniqValidators (rewards: DeriveStakerReward[]): string[] { function allUniqValidators (rewards: DeriveStakerReward[][]): [string[], string[][]] {
return rewards.reduce(([all, perStash]: [string[], string[][]], rewards) => {
const uniq: string[] = []; const uniq: string[] = [];
rewards.forEach(({ validators }): void => { perStash.push(uniq);
rewards.forEach(({ validators }) =>
Object.keys(validators).forEach((validatorId): void => { Object.keys(validators).forEach((validatorId): void => {
if (!uniq.includes(validatorId)) { if (!uniq.includes(validatorId)) {
uniq.push(validatorId); uniq.push(validatorId);
if (!all.includes(validatorId)) {
all.push(validatorId);
} }
}); }
}); })
);
return uniq; return [all, perStash];
} }, [[], []]);
function isOldLedger (ledger?: StakingLedger | StakingLedgerTo240): ledger is StakingLedgerTo240 {
return !!(ledger as StakingLedgerTo240)?.lastReward;
}
function filterEra (era: EraIndex, stakingLedger: StakingLedger): boolean {
return isOldLedger(stakingLedger)
? era.gt(stakingLedger.lastReward.unwrapOr(MIN_ONE))
: !stakingLedger.claimedRewards.some((e) => e.eq(era));
}
function filterEras (eras: EraIndex[], stakingLedger: StakingLedger): EraIndex[] {
return eras.filter((era) => filterEra(era, stakingLedger));
} }
function removeClaimed (validators: string[], queryValidators: DeriveStakingQuery[], reward: DeriveStakerReward): void { function removeClaimed (validators: string[], queryValidators: DeriveStakingQuery[], reward: DeriveStakerReward): void {
@@ -121,20 +109,16 @@ function removeClaimed (validators: string[], queryValidators: DeriveStakingQuer
}); });
} }
function filterRewards (api: ApiInterfaceRx, eras: EraIndex[], { migrateEra, rewards, stakingLedger }: { migrateEra: BN, rewards: DeriveStakerReward[]; stakingLedger: StakingLedger }): Observable<DeriveStakerReward[]> { function filterRewards (eras: EraIndex[], valInfo: [string, DeriveStakingQuery][], { rewards, stakingLedger }: { rewards: DeriveStakerReward[]; stakingLedger: StakingLedger }): DeriveStakerReward[] {
const validators = uniqValidators(rewards); const filter = eras.filter((era) => !stakingLedger.claimedRewards.some((e) => e.eq(era)));
const filter = filterEras(eras, stakingLedger); const validators = valInfo.map(([v]) => v);
const queryValidators = valInfo.map(([, q]) => q);
return api.derive.staking.queryMulti(validators, { withLedger: true }).pipe( return rewards
map((queryValidators): DeriveStakerReward[] =>
rewards
.filter(({ isEmpty }) => !isEmpty) .filter(({ isEmpty }) => !isEmpty)
.filter((reward): boolean => { .filter((reward): boolean => {
if (!filter.some((filter) => reward.era.eq(filter))) { if (!filter.some((filter) => reward.era.eq(filter))) {
return false; return false;
} else if (reward.era.lt(migrateEra)) {
// we filter again here, the actual ledger may have changed, e.g. something has been claimed
return filterEra(reward.era, stakingLedger);
} }
reward.isStakerPayout = true; reward.isStakerPayout = true;
@@ -147,17 +131,12 @@ function filterRewards (api: ApiInterfaceRx, eras: EraIndex[], { migrateEra, rew
.map((reward) => ({ .map((reward) => ({
...reward, ...reward,
nominators: reward.nominating.filter((n) => reward.validators[n.validatorId]) nominators: reward.nominating.filter((n) => reward.validators[n.validatorId])
})) }));
)
);
} }
export function _stakerRewardsEras (instanceId: string, api: ApiInterfaceRx): (eras: EraIndex[], withActive: boolean) => Observable<ErasResult> { export function _stakerRewardsEras (instanceId: string, api: ApiInterfaceRx): (eras: EraIndex[], withActive: boolean) => Observable<ErasResult> {
return memo(instanceId, (eras: EraIndex[], withActive: boolean): Observable<ErasResult> => return memo(instanceId, (eras: EraIndex[], withActive: boolean): Observable<ErasResult> =>
combineLatest([ combineLatest([
isFunction(api.query.staking.migrateEra)
? api.query.staking.migrateEra<Option<EraIndex>>()
: of(api.registry.createType('Option<EraIndex>')),
api.derive.staking._erasPoints(eras, withActive), api.derive.staking._erasPoints(eras, withActive),
api.derive.staking._erasPrefs(eras, withActive), api.derive.staking._erasPrefs(eras, withActive),
api.derive.staking._erasRewards(eras, withActive) api.derive.staking._erasRewards(eras, withActive)
@@ -165,23 +144,39 @@ export function _stakerRewardsEras (instanceId: string, api: ApiInterfaceRx): (e
); );
} }
export function _stakerRewards (instanceId: string, api: ApiInterfaceRx): (accountId: Uint8Array | string, eras: EraIndex[], withActive: boolean) => Observable<DeriveStakerReward[]> { export function _stakerRewards (instanceId: string, api: ApiInterfaceRx): (accountIds: (Uint8Array | string)[], eras: EraIndex[], withActive: boolean) => Observable<DeriveStakerReward[][]> {
return memo(instanceId, (accountId: Uint8Array | string, eras: EraIndex[], withActive: boolean): Observable<DeriveStakerReward[]> => return memo(instanceId, (accountIds: (Uint8Array | string)[], eras: EraIndex[], withActive: boolean): Observable<DeriveStakerReward[][]> =>
combineLatest([ combineLatest([
api.derive.staking.query(accountId, { withLedger: true }), api.derive.staking.queryMulti(accountIds, { withLedger: true }),
api.derive.staking._stakerExposure(accountId, eras, withActive), api.derive.staking._stakerExposures(accountIds, eras, withActive),
api.derive.staking._stakerRewardsEras(eras, withActive) api.derive.staking._stakerRewardsEras(eras, withActive)
]).pipe( ]).pipe(
switchMap(([{ stakingLedger, stashId }, exposures, erasResult]): Observable<DeriveStakerReward[]> => { switchMap(([queries, exposures, erasResult]): Observable<DeriveStakerReward[][]> => {
if (!stashId || !stakingLedger) { const allRewards = queries.map(({ stakingLedger, stashId }, index): DeriveStakerReward[] =>
return of([]); (!stashId || !stakingLedger)
? []
: parseRewards(api, stashId, erasResult, exposures[index])
);
if (withActive) {
return of(allRewards);
} }
const rewards = parseRewards(api, stashId, erasResult, exposures); const [allValidators, stashValidators] = allUniqValidators(allRewards);
return withActive return api.derive.staking.queryMulti(allValidators, { withLedger: true }).pipe(
? of(rewards) map((queriedVals): DeriveStakerReward[][] => {
: filterRewards(api, eras, { migrateEra: erasResult[0].unwrapOr(ZERO), rewards, stakingLedger }); return queries.map(({ stakingLedger }, index): DeriveStakerReward[] => {
const rewards = allRewards[index];
const ownValidators = stashValidators[index].map((validatorId): [string, DeriveStakingQuery] => [
validatorId,
queriedVals.find((q) => q.accountId.eq(validatorId)) as DeriveStakingQuery
]);
return filterRewards(eras, ownValidators, { rewards, stakingLedger });
});
})
);
}) })
) )
); );
@@ -190,7 +185,8 @@ export function _stakerRewards (instanceId: string, api: ApiInterfaceRx): (accou
export function stakerRewards (instanceId: string, api: ApiInterfaceRx): (accountId: Uint8Array | string, withActive?: boolean) => Observable<DeriveStakerReward[]> { export function stakerRewards (instanceId: string, api: ApiInterfaceRx): (accountId: Uint8Array | string, withActive?: boolean) => Observable<DeriveStakerReward[]> {
return memo(instanceId, (accountId: Uint8Array | string, withActive = false): Observable<DeriveStakerReward[]> => return memo(instanceId, (accountId: Uint8Array | string, withActive = false): Observable<DeriveStakerReward[]> =>
api.derive.staking.erasHistoric(withActive).pipe( api.derive.staking.erasHistoric(withActive).pipe(
switchMap((eras) => api.derive.staking._stakerRewards(accountId, eras, withActive)) switchMap((eras) => api.derive.staking._stakerRewards([accountId], eras, withActive)),
map(([first]) => first)
) )
); );
} }
@@ -198,7 +194,7 @@ export function stakerRewards (instanceId: string, api: ApiInterfaceRx): (accoun
export function stakerRewardsMultiEras (instanceId: string, api: ApiInterfaceRx): (accountIds: (Uint8Array | string)[], eras: EraIndex[]) => Observable<DeriveStakerReward[][]> { export function stakerRewardsMultiEras (instanceId: string, api: ApiInterfaceRx): (accountIds: (Uint8Array | string)[], eras: EraIndex[]) => Observable<DeriveStakerReward[][]> {
return memo(instanceId, (accountIds: (Uint8Array | string)[], eras: EraIndex[]): Observable<DeriveStakerReward[][]> => return memo(instanceId, (accountIds: (Uint8Array | string)[], eras: EraIndex[]): Observable<DeriveStakerReward[][]> =>
accountIds.length && eras.length accountIds.length && eras.length
? combineLatest(accountIds.map((acc) => api.derive.staking._stakerRewards(acc, eras, false))) ? api.derive.staking._stakerRewards(accountIds, eras, false)
: of([]) : of([])
); );
} }
+29 -4
View File
@@ -5,17 +5,42 @@ import type { ApiInterfaceRx } from '@polkadot/api/types';
import type { AccountId } from '@polkadot/types/interfaces'; import type { AccountId } from '@polkadot/types/interfaces';
import type { Observable } from '@polkadot/x-rxjs'; import type { Observable } from '@polkadot/x-rxjs';
import { map } from '@polkadot/x-rxjs/operators'; import { map, startWith, switchMap } from '@polkadot/x-rxjs/operators';
import { memo } from '../util'; import { drr, memo } from '../util';
function onBondedEvent (api: ApiInterfaceRx): Observable<number> {
let current = Date.now();
return api.query.system.events().pipe(
map((events): number => {
current = events.filter(({ event, phase }): boolean => {
try {
return phase.isApplyExtrinsic &&
event.section === 'staking' &&
event.method === 'Bonded';
} catch {
return false;
}
})
? Date.now()
: current;
return current;
}),
startWith(current),
drr({ skipTimeout: true })
);
}
/** /**
* @description Retrieve the list of all validator stashes * @description Retrieve the list of all validator stashes
*/ */
export function stashes (instanceId: string, api: ApiInterfaceRx): () => Observable<AccountId[]> { export function stashes (instanceId: string, api: ApiInterfaceRx): () => Observable<AccountId[]> {
return memo(instanceId, (): Observable<AccountId[]> => return memo(instanceId, (): Observable<AccountId[]> =>
api.query.staking.validators.keys().pipe( onBondedEvent(api).pipe(
map((keys) => keys.map((key) => key.args[0]).filter((a) => a)) switchMap(() => api.query.staking.validators.keys()),
map((keys) => keys.map(({ args: [validatorId] }) => validatorId).filter((a) => a))
) )
); );
} }
@@ -18,7 +18,7 @@ export function nextElected (instanceId: string, api: ApiInterfaceRx): () => Obs
// only populate for next era in the last session, so track both here - entries are not // only populate for next era in the last session, so track both here - entries are not
// subscriptions, so we need a trigger - currentIndex acts as that trigger to refresh // subscriptions, so we need a trigger - currentIndex acts as that trigger to refresh
switchMap(({ currentEra }) => api.query.staking.erasStakers.keys(currentEra)), switchMap(({ currentEra }) => api.query.staking.erasStakers.keys(currentEra)),
map((keys) => keys.map((key) => key.args[1])) map((keys) => keys.map(({ args: [, accountId] }) => accountId))
) )
: api.query.staking.currentElected<AccountId[]>() : api.query.staking.currentElected<AccountId[]>()
); );
+12 -3
View File
@@ -33,10 +33,19 @@ function nextNonce (api: ApiInterfaceRx, address: string): Observable<Index> {
function signingHeader (api: ApiInterfaceRx): Observable<Header> { function signingHeader (api: ApiInterfaceRx): Observable<Header> {
return combineLatest([ return combineLatest([
api.rpc.chain.getHeader(), api.rpc.chain.getHeader(),
api.rpc.chain.getFinalizedHead().pipe( api.rpc.chain.getFinalizedHead()
switchMap((hash) => api.rpc.chain.getHeader(hash))
)
]).pipe( ]).pipe(
switchMap(([bestHeader, finHash]) =>
// retrieve the headers - in the case of the current block, we use the parent
// to minimize (not completely remove) the impact that forks do have on the system
// (when at genesis, just return the current header as the last known)
bestHeader.parentHash.isEmpty
? of([bestHeader, bestHeader])
: combineLatest([
api.rpc.chain.getHeader(bestHeader.parentHash),
api.rpc.chain.getHeader(finHash)
])
),
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) current.number.unwrap().sub(finalized.number.unwrap()).gt(MAX_FINALITY_LAG)
@@ -26,6 +26,7 @@ export class HeaderExtended extends _Header {
this.#author = extractAuthor(this.digest, validators); this.#author = extractAuthor(this.digest, validators);
this.#validators = validators; this.#validators = validators;
this.createdAtHash = header?.createdAtHash;
} }
/** /**
@@ -53,12 +53,13 @@ export class SignedBlockExtended extends _SignedBlock {
readonly #events: EventRecord[]; readonly #events: EventRecord[];
readonly #extrinsics: TxWithEvent[]; readonly #extrinsics: TxWithEvent[];
constructor (registry: Registry, block?: SignedBlock, events?: EventRecord[], sessionValidators?: AccountId[]) { constructor (registry: Registry, block?: SignedBlock, events?: EventRecord[], validators?: AccountId[]) {
super(registry, block); super(registry, block);
this.#author = extractAuthor(this.block.header.digest, sessionValidators); this.#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;
} }
/** /**
+2 -4
View File
@@ -5,7 +5,7 @@ import type { DeriveCache } from './types';
const mapCache = new Map<string, any>(); const mapCache = new Map<string, any>();
const deriveMapCache: DeriveCache = { export const deriveMapCache: DeriveCache = {
del: (key: string): void => { del: (key: string): void => {
mapCache.delete(key); mapCache.delete(key);
}, },
@@ -24,11 +24,9 @@ const deriveMapCache: DeriveCache = {
} }
}; };
const deriveNoopCache: DeriveCache = { export const deriveNoopCache: DeriveCache = {
del: (): void => undefined, del: (): void => undefined,
forEach: () => undefined, forEach: () => undefined,
get: (): undefined => undefined, get: (): undefined => undefined,
set: (_: string, value: unknown): unknown => value set: (_: string, value: unknown): unknown => value
}; };
export { deriveMapCache, deriveNoopCache };
+14 -13
View File
@@ -1,11 +1,12 @@
{ {
"name": "@polkadot/api", "name": "@polkadot/api",
"version": "3.7.2", "version": "4.0.3",
"type": "module",
"description": "Promise and RxJS wrappers around the Polkadot JS RPC", "description": "Promise and RxJS wrappers around the Polkadot JS RPC",
"main": "index.js", "main": "index.js",
"sideEffects": [ "sideEffects": [
"./detectPackage.js", "./detectPackage.js",
"./detectPackage.mjs" "./detectPackage.cjs"
], ],
"author": "Jaco Greeff <jacogr@gmail.com>", "author": "Jaco Greeff <jacogr@gmail.com>",
"maintainers": [], "maintainers": [],
@@ -15,17 +16,17 @@
"bugs": "https://github.com/polkadot-js/api/issues", "bugs": "https://github.com/polkadot-js/api/issues",
"homepage": "https://github.com/polkadot-js/api/tree/master/packages/api#readme", "homepage": "https://github.com/polkadot-js/api/tree/master/packages/api#readme",
"dependencies": { "dependencies": {
"@babel/runtime": "^7.12.5", "@babel/runtime": "^7.13.9",
"@polkadot/api-derive": "3.7.2", "@polkadot/api-derive": "4.0.3",
"@polkadot/keyring": "^5.5.1", "@polkadot/keyring": "^6.0.5",
"@polkadot/metadata": "3.7.2", "@polkadot/metadata": "4.0.3",
"@polkadot/rpc-core": "3.7.2", "@polkadot/rpc-core": "4.0.3",
"@polkadot/rpc-provider": "3.7.2", "@polkadot/rpc-provider": "4.0.3",
"@polkadot/types": "3.7.2", "@polkadot/types": "4.0.3",
"@polkadot/types-known": "3.7.2", "@polkadot/types-known": "4.0.3",
"@polkadot/util": "^5.5.1", "@polkadot/util": "^6.0.5",
"@polkadot/util-crypto": "^5.5.1", "@polkadot/util-crypto": "^6.0.5",
"@polkadot/x-rxjs": "^5.5.1", "@polkadot/x-rxjs": "^6.0.5",
"bn.js": "^4.11.9", "bn.js": "^4.11.9",
"eventemitter3": "^4.0.7" "eventemitter3": "^4.0.7"
} }
+24 -3
View File
@@ -107,12 +107,17 @@ declare module '@polkadot/api/types/consts' {
**/ **/
depositPerStorageItem: BalanceOf & AugmentedConst<ApiType>; depositPerStorageItem: BalanceOf & AugmentedConst<ApiType>;
/** /**
* The maximum nesting level of a call/instantiate stack. A reasonable default * The maximum length of a contract code in bytes. This limit applies to the instrumented
* value is 100. * version of the code. Therefore `instantiate_with_code` can fail even when supplying
* a wasm binary below this maximum size.
**/
maxCodeSize: u32 & AugmentedConst<ApiType>;
/**
* The maximum nesting level of a call/instantiate stack.
**/ **/
maxDepth: u32 & AugmentedConst<ApiType>; maxDepth: u32 & AugmentedConst<ApiType>;
/** /**
* The maximum size of a storage value in bytes. A reasonable default is 16 KiB. * The maximum size of a storage value and event payload in bytes.
**/ **/
maxValueSize: u32 & AugmentedConst<ApiType>; maxValueSize: u32 & AugmentedConst<ApiType>;
/** /**
@@ -179,6 +184,22 @@ declare module '@polkadot/api/types/consts' {
**/ **/
votingPeriod: BlockNumber & AugmentedConst<ApiType>; votingPeriod: BlockNumber & AugmentedConst<ApiType>;
}; };
electionProviderMultiPhase: {
[key: string]: Codec;
/**
* Duration of the signed phase.
**/
signedPhase: BlockNumber & AugmentedConst<ApiType>;
/**
* The minimum amount of improvement to the solution score that defines a solution as
* "better" (in any phase).
**/
solutionImprovementThreshold: Perbill & AugmentedConst<ApiType>;
/**
* Duration of the unsigned phase.
**/
unsignedPhase: BlockNumber & AugmentedConst<ApiType>;
};
elections: { elections: {
[key: string]: Codec; [key: string]: Codec;
candidacyBond: BalanceOf & AugmentedConst<ApiType>; candidacyBond: BalanceOf & AugmentedConst<ApiType>;
+27 -7
View File
@@ -184,13 +184,14 @@ declare module '@polkadot/api/types/errors' {
**/ **/
CodeNotFound: AugmentedError<ApiType>; CodeNotFound: AugmentedError<ApiType>;
/** /**
* The code supplied to `put_code` exceeds the limit specified in the current schedule. * The code supplied to `instantiate_with_code` exceeds the limit specified in the
* current schedule.
**/ **/
CodeTooLarge: AugmentedError<ApiType>; CodeTooLarge: AugmentedError<ApiType>;
/** /**
* A contract could not be evicted because it has enough balance to pay rent. * A contract could not be evicted because it has enough balance to pay rent.
* *
* This can be returned from [`Module::claim_surcharge`] because the target * This can be returned from [`Pallet::claim_surcharge`] because the target
* contract has enough balance to pay for its rent. * contract has enough balance to pay for its rent.
**/ **/
ContractNotEvictable: AugmentedError<ApiType>; ContractNotEvictable: AugmentedError<ApiType>;
@@ -205,11 +206,15 @@ declare module '@polkadot/api/types/errors' {
/** /**
* Removal of a contract failed because the deletion queue is full. * Removal of a contract failed because the deletion queue is full.
* *
* This can happen when either calling [`Module::claim_surcharge`] or `seal_terminate`. * This can happen when either calling [`Pallet::claim_surcharge`] or `seal_terminate`.
* The queue is filled by deleting contracts and emptied by a fixed amount each block. * The queue is filled by deleting contracts and emptied by a fixed amount each block.
* Trying again during another block is the only way to resolve this issue. * Trying again during another block is the only way to resolve this issue.
**/ **/
DeletionQueueFull: AugmentedError<ApiType>; DeletionQueueFull: AugmentedError<ApiType>;
/**
* A contract with the same AccountId already exists.
**/
DuplicateContract: AugmentedError<ApiType>;
/** /**
* The topics passed to `seal_deposit_events` contains at least one duplicate. * The topics passed to `seal_deposit_events` contains at least one duplicate.
**/ **/
@@ -494,6 +499,21 @@ declare module '@polkadot/api/types/errors' {
**/ **/
WrongUpperBound: AugmentedError<ApiType>; WrongUpperBound: AugmentedError<ApiType>;
}; };
electionProviderMultiPhase: {
[key: string]: AugmentedError<ApiType>;
/**
* Submission was too early.
**/
PreDispatchEarlySubmission: AugmentedError<ApiType>;
/**
* Submission was too weak, score-wise.
**/
PreDispatchWeakSubmission: AugmentedError<ApiType>;
/**
* Wrong number of winners presented.
**/
PreDispatchWrongWinnerCount: AugmentedError<ApiType>;
};
elections: { elections: {
[key: string]: AugmentedError<ApiType>; [key: string]: AugmentedError<ApiType>;
/** /**
@@ -686,6 +706,10 @@ declare module '@polkadot/api/types/errors' {
* The data to be stored is already stored. * The data to be stored is already stored.
**/ **/
AlreadyStored: AugmentedError<ApiType>; AlreadyStored: AugmentedError<ApiType>;
/**
* The maximum weight information provided was too low.
**/
MaxWeightTooLow: AugmentedError<ApiType>;
/** /**
* Threshold must be 2 or greater. * Threshold must be 2 or greater.
**/ **/
@@ -726,10 +750,6 @@ declare module '@polkadot/api/types/errors' {
* A timepoint was given, yet no multisig operation is underway. * A timepoint was given, yet no multisig operation is underway.
**/ **/
UnexpectedTimepoint: AugmentedError<ApiType>; UnexpectedTimepoint: AugmentedError<ApiType>;
/**
* The maximum weight information provided was too low.
**/
WeightTooLow: AugmentedError<ApiType>;
/** /**
* A different timepoint was given to the multisig operation that is underway. * A different timepoint was given to the multisig operation that is underway.
**/ **/
+76 -19
View File
@@ -160,45 +160,71 @@ declare module '@polkadot/api/types/events' {
contracts: { contracts: {
[key: string]: AugmentedEvent<ApiType>; [key: string]: AugmentedEvent<ApiType>;
/** /**
* Code with the specified hash has been stored. * A code with the specified hash was removed.
* \[code_hash\] * \[code_hash\]
*
* This happens when the last contract that uses this code hash was removed or evicted.
**/
CodeRemoved: AugmentedEvent<ApiType, [Hash]>;
/**
* Code with the specified hash has been stored. \[code_hash\]
**/ **/
CodeStored: AugmentedEvent<ApiType, [Hash]>; CodeStored: AugmentedEvent<ApiType, [Hash]>;
/** /**
* An event deposited upon execution of a contract from the account. * A custom event emitted by the contract.
* \[account, data\] * \[contract, data\]
**/
ContractExecution: AugmentedEvent<ApiType, [AccountId, Bytes]>;
/**
* Contract has been evicted and is now in tombstone state.
* \[contract, tombstone\]
* *
* # Params * # Params
* *
* - `contract`: `AccountId`: The account ID of the evicted contract. * - `contract`: The contract that emitted the event.
* - `tombstone`: `bool`: True if the evicted contract left behind a tombstone. * - `data`: Data supplied by the contract. Metadata generated during contract
* compilation is needed to decode it.
**/ **/
Evicted: AugmentedEvent<ApiType, [AccountId, bool]>; ContractEmitted: AugmentedEvent<ApiType, [AccountId, Bytes]>;
/** /**
* Contract deployed by address at the specified address. \[owner, contract\] * Contract has been evicted and is now in tombstone state. \[contract\]
**/
Evicted: AugmentedEvent<ApiType, [AccountId]>;
/**
* Contract deployed by address at the specified address. \[deployer, contract\]
**/ **/
Instantiated: AugmentedEvent<ApiType, [AccountId, AccountId]>; Instantiated: AugmentedEvent<ApiType, [AccountId, AccountId]>;
/** /**
* Restoration for a contract has been successful. * Restoration of a contract has been successful.
* \[donor, dest, code_hash, rent_allowance\] * \[restorer, dest, code_hash, rent_allowance\]
* *
* # Params * # Params
* *
* - `donor`: `AccountId`: Account ID of the restoring contract * - `restorer`: Account ID of the restoring contract.
* - `dest`: `AccountId`: Account ID of the restored contract * - `dest`: Account ID of the restored contract.
* - `code_hash`: `Hash`: Code hash of the restored contract * - `code_hash`: Code hash of the restored contract.
* - `rent_allowance: `Balance`: Rent allowance of the restored contract * - `rent_allowance`: Rent allowance of the restored contract.
**/ **/
Restored: AugmentedEvent<ApiType, [AccountId, AccountId, Hash, Balance]>; Restored: AugmentedEvent<ApiType, [AccountId, AccountId, Hash, Balance]>;
/** /**
* Triggered when the current \[schedule\] is updated. * Triggered when the current schedule is updated.
* \[version\]
*
* # Params
*
* - `version`: The version of the newly set schedule.
**/ **/
ScheduleUpdated: AugmentedEvent<ApiType, [u32]>; ScheduleUpdated: AugmentedEvent<ApiType, [u32]>;
/**
* Contract has been terminated without leaving a tombstone.
* \[contract, beneficiary\]
*
* # Params
*
* - `contract`: The contract that was terminated.
* - `beneficiary`: The account that received the contracts remaining balance.
*
* # Note
*
* The only way for a contract to be removed without a tombstone and emitting
* this event is by calling `seal_terminate`.
**/
Terminated: AugmentedEvent<ApiType, [AccountId, AccountId]>;
}; };
council: { council: {
[key: string]: AugmentedEvent<ApiType>; [key: string]: AugmentedEvent<ApiType>;
@@ -319,6 +345,37 @@ declare module '@polkadot/api/types/events' {
**/ **/
Vetoed: AugmentedEvent<ApiType, [AccountId, Hash, BlockNumber]>; Vetoed: AugmentedEvent<ApiType, [AccountId, Hash, BlockNumber]>;
}; };
electionProviderMultiPhase: {
[key: string]: AugmentedEvent<ApiType>;
/**
* The election has been finalized, with `Some` of the given computation, or else if the
* election failed, `None`.
**/
ElectionFinalized: AugmentedEvent<ApiType, [Option<ElectionCompute>]>;
/**
* An account has been rewarded for their signed submission being finalized.
**/
Rewarded: AugmentedEvent<ApiType, [AccountId]>;
/**
* The signed phase of the given round has started.
**/
SignedPhaseStarted: AugmentedEvent<ApiType, [u32]>;
/**
* An account has been slashed for submitting an invalid signed submission.
**/
Slashed: AugmentedEvent<ApiType, [AccountId]>;
/**
* A solution was stored with the given compute.
*
* If the solution is signed, this means that it hasn't yet been processed. If the
* solution is unsigned, this means that it has also been processed.
**/
SolutionStored: AugmentedEvent<ApiType, [ElectionCompute]>;
/**
* The unsigned phase of the given round has started.
**/
UnsignedPhaseStarted: AugmentedEvent<ApiType, [u32]>;
};
elections: { elections: {
[key: string]: AugmentedEvent<ApiType>; [key: string]: AugmentedEvent<ApiType>;
/** /**
+62 -6
View File
@@ -19,11 +19,11 @@ import type { CallIndex, LotteryConfig } from '@polkadot/types/interfaces/lotter
import type { DeferredOffenceOf, Kind, OffenceDetails, OpaqueTimeSlot, ReportIdOf } from '@polkadot/types/interfaces/offences'; import type { DeferredOffenceOf, Kind, OffenceDetails, OpaqueTimeSlot, ReportIdOf } from '@polkadot/types/interfaces/offences';
import type { ProxyAnnouncement, ProxyDefinition } from '@polkadot/types/interfaces/proxy'; import type { ProxyAnnouncement, ProxyDefinition } from '@polkadot/types/interfaces/proxy';
import type { ActiveRecovery, RecoveryConfig } from '@polkadot/types/interfaces/recovery'; import type { ActiveRecovery, RecoveryConfig } from '@polkadot/types/interfaces/recovery';
import type { AccountId, AccountIndex, AssetId, Balance, BalanceOf, BlockNumber, Hash, KeyTypeId, Moment, OpaqueCall, Perbill, Releases, ValidatorId } from '@polkadot/types/interfaces/runtime'; import type { AccountId, AccountIndex, AssetId, Balance, BalanceOf, BlockNumber, Hash, KeyTypeId, Moment, OpaqueCall, Perbill, Releases, Slot, ValidatorId } from '@polkadot/types/interfaces/runtime';
import type { Scheduled, TaskAddress } from '@polkadot/types/interfaces/scheduler'; import type { Scheduled, TaskAddress } from '@polkadot/types/interfaces/scheduler';
import type { Keys, SessionIndex } from '@polkadot/types/interfaces/session'; import type { Keys, SessionIndex } from '@polkadot/types/interfaces/session';
import type { Bid, BidKind, SocietyVote, StrikeCount, VouchingStatus } from '@polkadot/types/interfaces/society'; import type { Bid, BidKind, SocietyVote, StrikeCount, VouchingStatus } from '@polkadot/types/interfaces/society';
import type { ActiveEraInfo, ElectionResult, ElectionScore, ElectionStatus, EraIndex, EraRewardPoints, Exposure, Forcing, Nominations, RewardDestination, SeatHolder, SlashingSpans, SpanIndex, SpanRecord, StakingLedger, UnappliedSlash, ValidatorPrefs, Voter } from '@polkadot/types/interfaces/staking'; import type { ActiveEraInfo, ElectionPhase, ElectionResult, ElectionScore, ElectionStatus, EraIndex, EraRewardPoints, Exposure, Forcing, Nominations, ReadySolution, RewardDestination, RoundSnapshot, SeatHolder, SlashingSpans, SolutionOrSnapshotSize, SpanIndex, SpanRecord, StakingLedger, UnappliedSlash, ValidatorPrefs, Voter } from '@polkadot/types/interfaces/staking';
import type { AccountInfo, ConsumedWeight, DigestOf, EventIndex, EventRecord, LastRuntimeUpgradeInfo, Phase } from '@polkadot/types/interfaces/system'; import type { AccountInfo, ConsumedWeight, DigestOf, EventIndex, EventRecord, LastRuntimeUpgradeInfo, Phase } from '@polkadot/types/interfaces/system';
import type { Bounty, BountyIndex, OpenTip, TreasuryProposal } from '@polkadot/types/interfaces/treasury'; import type { Bounty, BountyIndex, OpenTip, TreasuryProposal } from '@polkadot/types/interfaces/treasury';
import type { Multiplier } from '@polkadot/types/interfaces/txpayment'; import type { Multiplier } from '@polkadot/types/interfaces/txpayment';
@@ -78,7 +78,7 @@ declare module '@polkadot/api/types/storage' {
/** /**
* Current slot number. * Current slot number.
**/ **/
currentSlot: AugmentedQuery<ApiType, () => Observable<u64>, []> & QueryableStorageEntry<ApiType, []>; currentSlot: AugmentedQuery<ApiType, () => Observable<Slot>, []> & QueryableStorageEntry<ApiType, []>;
/** /**
* Current epoch index. * Current epoch index.
**/ **/
@@ -87,7 +87,7 @@ declare module '@polkadot/api/types/storage' {
* The slot at which the first epoch actually started. This is 0 * The slot at which the first epoch actually started. This is 0
* until the first block of the chain. * until the first block of the chain.
**/ **/
genesisSlot: AugmentedQuery<ApiType, () => Observable<u64>, []> & QueryableStorageEntry<ApiType, []>; genesisSlot: AugmentedQuery<ApiType, () => Observable<Slot>, []> & QueryableStorageEntry<ApiType, []>;
/** /**
* Temporary value (cleared at block finalization) which is `Some` * Temporary value (cleared at block finalization) which is `Some`
* if per-block initialization has already been called for current block. * if per-block initialization has already been called for current block.
@@ -148,7 +148,7 @@ declare module '@polkadot/api/types/storage' {
/** /**
* The balance of an account. * The balance of an account.
* *
* NOTE: This is only used in the case that this module is used to store balances. * NOTE: This is only used in the case that this pallet is used to store balances.
**/ **/
account: AugmentedQuery<ApiType, (arg: AccountId | string | Uint8Array) => Observable<AccountData>, [AccountId]> & QueryableStorageEntry<ApiType, [AccountId]>; account: AugmentedQuery<ApiType, (arg: AccountId | string | Uint8Array) => Observable<AccountData>, [AccountId]> & QueryableStorageEntry<ApiType, [AccountId]>;
/** /**
@@ -323,6 +323,44 @@ declare module '@polkadot/api/types/storage' {
**/ **/
votingOf: AugmentedQuery<ApiType, (arg: AccountId | string | Uint8Array) => Observable<Voting>, [AccountId]> & QueryableStorageEntry<ApiType, [AccountId]>; votingOf: AugmentedQuery<ApiType, (arg: AccountId | string | Uint8Array) => Observable<Voting>, [AccountId]> & QueryableStorageEntry<ApiType, [AccountId]>;
}; };
electionProviderMultiPhase: {
[key: string]: QueryableStorageEntry<ApiType>;
/**
* Current phase.
**/
currentPhase: AugmentedQuery<ApiType, () => Observable<ElectionPhase>, []> & QueryableStorageEntry<ApiType, []>;
/**
* Desired number of targets to elect for this round.
*
* Only exists when [`Snapshot`] is present.
**/
desiredTargets: AugmentedQuery<ApiType, () => Observable<Option<u32>>, []> & QueryableStorageEntry<ApiType, []>;
/**
* Current best solution, signed or unsigned, queued to be returned upon `elect`.
**/
queuedSolution: AugmentedQuery<ApiType, () => Observable<Option<ReadySolution>>, []> & QueryableStorageEntry<ApiType, []>;
/**
* Internal counter for the number of rounds.
*
* This is useful for de-duplication of transactions submitted to the pool, and general
* diagnostics of the pallet.
*
* This is merely incremented once per every time that an upstream `elect` is called.
**/
round: AugmentedQuery<ApiType, () => Observable<u32>, []> & QueryableStorageEntry<ApiType, []>;
/**
* Snapshot data of the round.
*
* This is created at the beginning of the signed phase and cleared upon calling `elect`.
**/
snapshot: AugmentedQuery<ApiType, () => Observable<Option<RoundSnapshot>>, []> & QueryableStorageEntry<ApiType, []>;
/**
* The metadata of the [`RoundSnapshot`]
*
* Only exists when [`Snapshot`] is present.
**/
snapshotMetadata: AugmentedQuery<ApiType, () => Observable<Option<SolutionOrSnapshotSize>>, []> & QueryableStorageEntry<ApiType, []>;
};
elections: { elections: {
[key: string]: QueryableStorageEntry<ApiType>; [key: string]: QueryableStorageEntry<ApiType>;
/** /**
@@ -421,7 +459,7 @@ declare module '@polkadot/api/types/storage' {
imOnline: { imOnline: {
[key: string]: QueryableStorageEntry<ApiType>; [key: string]: QueryableStorageEntry<ApiType>;
/** /**
* For each session index, we keep a mapping of `T::ValidatorId` to the * For each session index, we keep a mapping of `ValidatorId<T>` to the
* number of blocks authored by the given authority. * number of blocks authored by the given authority.
**/ **/
authoredBlocks: AugmentedQueryDoubleMap<ApiType, (key1: SessionIndex | AnyNumber | Uint8Array, key2: ValidatorId | string | Uint8Array) => Observable<u32>, [SessionIndex, ValidatorId]> & QueryableStorageEntry<ApiType, [SessionIndex, ValidatorId]>; authoredBlocks: AugmentedQueryDoubleMap<ApiType, (key1: SessionIndex | AnyNumber | Uint8Array, key2: ValidatorId | string | Uint8Array) => Observable<u32>, [SessionIndex, ValidatorId]> & QueryableStorageEntry<ApiType, [SessionIndex, ValidatorId]>;
@@ -723,6 +761,12 @@ declare module '@polkadot/api/types/storage' {
* set, it might be active or not. * set, it might be active or not.
**/ **/
currentEra: AugmentedQuery<ApiType, () => Observable<Option<EraIndex>>, []> & QueryableStorageEntry<ApiType, []>; currentEra: AugmentedQuery<ApiType, () => Observable<Option<EraIndex>>, []> & QueryableStorageEntry<ApiType, []>;
/**
* The last planned session scheduled by the session pallet.
*
* This is basically in sync with the call to [`SessionManager::new_session`].
**/
currentPlannedSession: AugmentedQuery<ApiType, () => Observable<SessionIndex>, []> & QueryableStorageEntry<ApiType, []>;
/** /**
* The earliest era for which we have a pending, unapplied slash. * The earliest era for which we have a pending, unapplied slash.
**/ **/
@@ -730,6 +774,8 @@ declare module '@polkadot/api/types/storage' {
/** /**
* Flag to control the execution of the offchain election. When `Open(_)`, we accept * Flag to control the execution of the offchain election. When `Open(_)`, we accept
* solutions to be submitted. * solutions to be submitted.
*
* TWO_PHASE_NOTE: should be removed once we switch to multi-phase.
**/ **/
eraElectionStatus: AugmentedQuery<ApiType, () => Observable<ElectionStatus>, []> & QueryableStorageEntry<ApiType, []>; eraElectionStatus: AugmentedQuery<ApiType, () => Observable<ElectionStatus>, []> & QueryableStorageEntry<ApiType, []>;
/** /**
@@ -809,6 +855,8 @@ declare module '@polkadot/api/types/storage' {
/** /**
* True if the current **planned** session is final. Note that this does not take era * True if the current **planned** session is final. Note that this does not take era
* forcing into account. * forcing into account.
*
* TWO_PHASE_NOTE: should be removed once we switch to multi-phase.
**/ **/
isCurrentSessionFinal: AugmentedQuery<ApiType, () => Observable<bool>, []> & QueryableStorageEntry<ApiType, []>; isCurrentSessionFinal: AugmentedQuery<ApiType, () => Observable<bool>, []> & QueryableStorageEntry<ApiType, []>;
/** /**
@@ -835,10 +883,14 @@ declare module '@polkadot/api/types/storage' {
* The next validator set. At the end of an era, if this is available (potentially from the * The next validator set. At the end of an era, if this is available (potentially from the
* result of an offchain worker), it is immediately used. Otherwise, the on-chain election * result of an offchain worker), it is immediately used. Otherwise, the on-chain election
* is executed. * is executed.
*
* TWO_PHASE_NOTE: should be removed once we switch to multi-phase.
**/ **/
queuedElected: AugmentedQuery<ApiType, () => Observable<Option<ElectionResult>>, []> & QueryableStorageEntry<ApiType, []>; queuedElected: AugmentedQuery<ApiType, () => Observable<Option<ElectionResult>>, []> & QueryableStorageEntry<ApiType, []>;
/** /**
* The score of the current [`QueuedElected`]. * The score of the current [`QueuedElected`].
*
* TWO_PHASE_NOTE: should be removed once we switch to multi-phase.
**/ **/
queuedScore: AugmentedQuery<ApiType, () => Observable<Option<ElectionScore>>, []> & QueryableStorageEntry<ApiType, []>; queuedScore: AugmentedQuery<ApiType, () => Observable<Option<ElectionScore>>, []> & QueryableStorageEntry<ApiType, []>;
/** /**
@@ -854,11 +906,15 @@ declare module '@polkadot/api/types/storage' {
/** /**
* Snapshot of nominators at the beginning of the current election window. This should only * Snapshot of nominators at the beginning of the current election window. This should only
* have a value when [`EraElectionStatus`] == `ElectionStatus::Open(_)`. * have a value when [`EraElectionStatus`] == `ElectionStatus::Open(_)`.
*
* TWO_PHASE_NOTE: should be removed once we switch to multi-phase.
**/ **/
snapshotNominators: AugmentedQuery<ApiType, () => Observable<Option<Vec<AccountId>>>, []> & QueryableStorageEntry<ApiType, []>; snapshotNominators: AugmentedQuery<ApiType, () => Observable<Option<Vec<AccountId>>>, []> & QueryableStorageEntry<ApiType, []>;
/** /**
* Snapshot of validators at the beginning of the current election window. This should only * Snapshot of validators at the beginning of the current election window. This should only
* have a value when [`EraElectionStatus`] == `ElectionStatus::Open(_)`. * have a value when [`EraElectionStatus`] == `ElectionStatus::Open(_)`.
*
* TWO_PHASE_NOTE: should be removed once we switch to multi-phase.
**/ **/
snapshotValidators: AugmentedQuery<ApiType, () => Observable<Option<Vec<AccountId>>>, []> & QueryableStorageEntry<ApiType, []>; snapshotValidators: AugmentedQuery<ApiType, () => Observable<Option<Vec<AccountId>>>, []> & QueryableStorageEntry<ApiType, []>;
/** /**
+27 -3
View File
@@ -11,7 +11,7 @@ import type { PrefixedStorageKey } from '@polkadot/types/interfaces/childstate';
import type { AuthorityId } from '@polkadot/types/interfaces/consensus'; import type { AuthorityId } from '@polkadot/types/interfaces/consensus';
import type { ContractCallRequest, ContractExecResult } from '@polkadot/types/interfaces/contracts'; import type { ContractCallRequest, ContractExecResult } from '@polkadot/types/interfaces/contracts';
import type { CreatedBlock } from '@polkadot/types/interfaces/engine'; import type { CreatedBlock } from '@polkadot/types/interfaces/engine';
import type { EthAccount, EthCallRequest, EthFilter, EthLog, EthReceipt, EthRichBlock, EthSubKind, EthSubParams, EthSyncStatus, EthTransaction, EthTransactionRequest, EthWork } from '@polkadot/types/interfaces/eth'; import type { EthAccount, EthCallRequest, EthFilter, EthFilterChanges, EthLog, EthReceipt, EthRichBlock, EthSubKind, EthSubParams, EthSyncStatus, EthTransaction, EthTransactionRequest, EthWork } from '@polkadot/types/interfaces/eth';
import type { Extrinsic } from '@polkadot/types/interfaces/extrinsics'; import type { Extrinsic } from '@polkadot/types/interfaces/extrinsics';
import type { EncodedFinalityProofs, JustificationNotification, ReportedRoundStates } from '@polkadot/types/interfaces/grandpa'; import type { EncodedFinalityProofs, JustificationNotification, ReportedRoundStates } from '@polkadot/types/interfaces/grandpa';
import type { StorageKind } from '@polkadot/types/interfaces/offchain'; import type { StorageKind } from '@polkadot/types/interfaces/offchain';
@@ -188,6 +188,14 @@ declare module '@polkadot/rpc-core/types.jsonrpc' {
* Returns the code at given address at given time (block number). * Returns the code at given address at given time (block number).
**/ **/
getCode: AugmentedRpc<(address: H160 | string | Uint8Array, number?: BlockNumber | AnyNumber | Uint8Array) => Observable<Bytes>>; getCode: AugmentedRpc<(address: H160 | string | Uint8Array, number?: BlockNumber | AnyNumber | Uint8Array) => Observable<Bytes>>;
/**
* Returns filter changes since last poll.
**/
getFilterChanges: AugmentedRpc<(index: U256 | AnyNumber | Uint8Array) => Observable<EthFilterChanges>>;
/**
* Returns all logs matching given filter (in a range 'from' - 'to').
**/
getFilterLogs: AugmentedRpc<(index: U256 | AnyNumber | Uint8Array) => Observable<Vec<EthLog>>>;
/** /**
* Returns logs matching given filter object. * Returns logs matching given filter object.
**/ **/
@@ -248,6 +256,18 @@ declare module '@polkadot/rpc-core/types.jsonrpc' {
* Returns true if client is actively mining new blocks. * Returns true if client is actively mining new blocks.
**/ **/
mining: AugmentedRpc<() => Observable<bool>>; mining: AugmentedRpc<() => Observable<bool>>;
/**
* Returns id of new block filter.
**/
newBlockFilter: AugmentedRpc<() => Observable<U256>>;
/**
* Returns id of new filter.
**/
newFilter: AugmentedRpc<(filter: EthFilter | { fromBlock?: any; toBlock?: any; blockHash?: any; address?: any; topics?: any } | string | Uint8Array) => Observable<U256>>;
/**
* Returns id of new block filter.
**/
newPendingTransactionFilter: AugmentedRpc<() => Observable<U256>>;
/** /**
* Returns protocol version encoded as a string (quotes are necessary). * Returns protocol version encoded as a string (quotes are necessary).
**/ **/
@@ -276,6 +296,10 @@ declare module '@polkadot/rpc-core/types.jsonrpc' {
* Returns an object with data about the sync status or false. * Returns an object with data about the sync status or false.
**/ **/
syncing: AugmentedRpc<() => Observable<EthSyncStatus>>; syncing: AugmentedRpc<() => Observable<EthSyncStatus>>;
/**
* Uninstalls filter.
**/
uninstallFilter: AugmentedRpc<(index: U256 | AnyNumber | Uint8Array) => Observable<bool>>;
}; };
grandpa: { grandpa: {
/** /**
@@ -309,11 +333,11 @@ declare module '@polkadot/rpc-core/types.jsonrpc' {
/** /**
* Get offchain local storage under given key and prefix * Get offchain local storage under given key and prefix
**/ **/
localStorageGet: AugmentedRpc<(kind: StorageKind | '__UNUSED' | 'PERSISTENT' | 'LOCAL' | number | Uint8Array, key: Bytes | string | Uint8Array) => Observable<Option<Bytes>>>; localStorageGet: AugmentedRpc<(kind: StorageKind | 'PERSISTENT' | 'LOCAL' | number | Uint8Array, key: Bytes | string | Uint8Array) => Observable<Option<Bytes>>>;
/** /**
* Set offchain local storage under given key and prefix * Set offchain local storage under given key and prefix
**/ **/
localStorageSet: AugmentedRpc<(kind: StorageKind | '__UNUSED' | 'PERSISTENT' | 'LOCAL' | number | Uint8Array, key: Bytes | string | Uint8Array, value: Bytes | string | Uint8Array) => Observable<Null>>; localStorageSet: AugmentedRpc<(kind: StorageKind | 'PERSISTENT' | 'LOCAL' | number | Uint8Array, key: Bytes | string | Uint8Array, value: Bytes | string | Uint8Array) => Observable<Null>>;
}; };
payment: { payment: {
/** /**
+49 -18
View File
@@ -6,7 +6,7 @@ import type { AnyNumber, ITuple } from '@polkadot/types/types';
import type { TAssetBalance } from '@polkadot/types/interfaces/assets'; import type { TAssetBalance } from '@polkadot/types/interfaces/assets';
import type { BabeEquivocationProof } from '@polkadot/types/interfaces/babe'; import type { BabeEquivocationProof } from '@polkadot/types/interfaces/babe';
import type { MemberCount, ProposalIndex } from '@polkadot/types/interfaces/collective'; import type { MemberCount, ProposalIndex } from '@polkadot/types/interfaces/collective';
import type { CodeHash, Gas, Schedule } from '@polkadot/types/interfaces/contracts'; import type { CodeHash, Schedule } from '@polkadot/types/interfaces/contracts';
import type { AccountVote, Conviction, PropIndex, Proposal, ReferendumIndex } from '@polkadot/types/interfaces/democracy'; import type { AccountVote, Conviction, PropIndex, Proposal, ReferendumIndex } from '@polkadot/types/interfaces/democracy';
import type { Renouncing } from '@polkadot/types/interfaces/elections'; import type { Renouncing } from '@polkadot/types/interfaces/elections';
import type { Extrinsic, Signature } from '@polkadot/types/interfaces/extrinsics'; import type { Extrinsic, Signature } from '@polkadot/types/interfaces/extrinsics';
@@ -18,7 +18,7 @@ import type { AccountId, AccountIndex, AssetId, Balance, BalanceOf, BlockNumber,
import type { Period, Priority } from '@polkadot/types/interfaces/scheduler'; import type { Period, Priority } from '@polkadot/types/interfaces/scheduler';
import type { Keys } from '@polkadot/types/interfaces/session'; import type { Keys } from '@polkadot/types/interfaces/session';
import type { SocietyJudgement } from '@polkadot/types/interfaces/society'; import type { SocietyJudgement } from '@polkadot/types/interfaces/society';
import type { CompactAssignments, ElectionScore, ElectionSize, EraIndex, RewardDestination, ValidatorIndex, ValidatorPrefs } from '@polkadot/types/interfaces/staking'; import type { CompactAssignments, ElectionScore, ElectionSize, EraIndex, RawSolution, RewardDestination, SolutionOrSnapshotSize, ValidatorIndex, ValidatorPrefs } from '@polkadot/types/interfaces/staking';
import type { Key } from '@polkadot/types/interfaces/system'; import type { Key } from '@polkadot/types/interfaces/system';
import type { BountyIndex } from '@polkadot/types/interfaces/treasury'; import type { BountyIndex } from '@polkadot/types/interfaces/treasury';
import type { Timepoint } from '@polkadot/types/interfaces/utility'; import type { Timepoint } from '@polkadot/types/interfaces/utility';
@@ -396,7 +396,7 @@ declare module '@polkadot/api/types/submittable' {
* *
* 99% of the time you want [`transfer`] instead. * 99% of the time you want [`transfer`] instead.
* *
* [`transfer`]: struct.Module.html#method.transfer * [`transfer`]: struct.Pallet.html#method.transfer
* # <weight> * # <weight>
* - Cheaper than transfer because account cannot be killed. * - Cheaper than transfer because account cannot be killed.
* - Base Weight: 51.4 µs * - Base Weight: 51.4 µs
@@ -538,7 +538,7 @@ declare module '@polkadot/api/types/submittable' {
* * If no account exists and the call value is not less than `existential_deposit`, * * If no account exists and the call value is not less than `existential_deposit`,
* a regular account will be created and any value will be transferred. * a regular account will be created and any value will be transferred.
**/ **/
call: AugmentedSubmittable<(dest: LookupSource | { Id: any } | { Index: any } | { Raw: any } | { Address32: any } | { Address20: any } | string | Uint8Array, value: Compact<BalanceOf> | AnyNumber | Uint8Array, gasLimit: Compact<Gas> | AnyNumber | Uint8Array, data: Bytes | string | Uint8Array) => SubmittableExtrinsic<ApiType>, [LookupSource, Compact<BalanceOf>, Compact<Gas>, Bytes]>; call: AugmentedSubmittable<(dest: LookupSource | { Id: any } | { Index: any } | { Raw: any } | { Address32: any } | { Address20: any } | string | Uint8Array, value: Compact<BalanceOf> | AnyNumber | Uint8Array, gasLimit: Compact<Weight> | AnyNumber | Uint8Array, data: Bytes | string | Uint8Array) => SubmittableExtrinsic<ApiType>, [LookupSource, Compact<BalanceOf>, Compact<Weight>, Bytes]>;
/** /**
* Allows block producers to claim a small reward for evicting a contract. If a block * Allows block producers to claim a small reward for evicting a contract. If a block
* producer fails to do so, a regular users will be allowed to claim the reward. * producer fails to do so, a regular users will be allowed to claim the reward.
@@ -552,26 +552,37 @@ declare module '@polkadot/api/types/submittable' {
**/ **/
claimSurcharge: AugmentedSubmittable<(dest: AccountId | string | Uint8Array, auxSender: Option<AccountId> | null | object | string | Uint8Array) => SubmittableExtrinsic<ApiType>, [AccountId, Option<AccountId>]>; claimSurcharge: AugmentedSubmittable<(dest: AccountId | string | Uint8Array, auxSender: Option<AccountId> | null | object | string | Uint8Array) => SubmittableExtrinsic<ApiType>, [AccountId, Option<AccountId>]>;
/** /**
* Instantiates a new contract from the `code_hash` generated by `put_code`, * Instantiates a contract from a previously deployed wasm binary.
* optionally transferring some balance.
* *
* The supplied `salt` is used for contract address deriviation. See `fn contract_address`. * This function is identical to [`Self::instantiate_with_code`] but without the
* code deployment step. Instead, the `code_hash` of an on-chain deployed wasm binary
* must be supplied.
**/
instantiate: AugmentedSubmittable<(endowment: Compact<BalanceOf> | AnyNumber | Uint8Array, gasLimit: Compact<Weight> | AnyNumber | Uint8Array, codeHash: CodeHash | string | Uint8Array, data: Bytes | string | Uint8Array, salt: Bytes | string | Uint8Array) => SubmittableExtrinsic<ApiType>, [Compact<BalanceOf>, Compact<Weight>, CodeHash, Bytes, Bytes]>;
/**
* Instantiates a new contract from the supplied `code` optionally transferring
* some balance.
*
* This is the only function that can deploy new code to the chain.
*
* # Parameters
*
* * `endowment`: The balance to transfer from the `origin` to the newly created contract.
* * `gas_limit`: The gas limit enforced when executing the constructor.
* * `code`: The contract code to deploy in raw bytes.
* * `data`: The input data to pass to the contract constructor.
* * `salt`: Used for the address derivation. See [`Self::contract_address`].
* *
* Instantiation is executed as follows: * Instantiation is executed as follows:
* *
* - The supplied `code` is instrumented, deployed, and a `code_hash` is created for that code.
* - If the `code_hash` already exists on the chain the underlying `code` will be shared.
* - The destination address is computed based on the sender, code_hash and the salt. * - The destination address is computed based on the sender, code_hash and the salt.
* - The smart-contract account is created at the computed address. * - The smart-contract account is created at the computed address.
* - The `ctor_code` is executed in the context of the newly-created account. Buffer returned * - The `endowment` is transferred to the new account.
* after the execution is saved as the `code` of the account. That code will be invoked * - The `deploy` function is executed in the context of the newly-created account.
* upon any call received by this account.
* - The contract is initialized.
**/ **/
instantiate: AugmentedSubmittable<(endowment: Compact<BalanceOf> | AnyNumber | Uint8Array, gasLimit: Compact<Gas> | AnyNumber | Uint8Array, codeHash: CodeHash | string | Uint8Array, data: Bytes | string | Uint8Array, salt: Bytes | string | Uint8Array) => SubmittableExtrinsic<ApiType>, [Compact<BalanceOf>, Compact<Gas>, CodeHash, Bytes, Bytes]>; instantiateWithCode: AugmentedSubmittable<(endowment: Compact<BalanceOf> | AnyNumber | Uint8Array, gasLimit: Compact<Weight> | AnyNumber | Uint8Array, code: Bytes | string | Uint8Array, data: Bytes | string | Uint8Array, salt: Bytes | string | Uint8Array) => SubmittableExtrinsic<ApiType>, [Compact<BalanceOf>, Compact<Weight>, Bytes, Bytes, Bytes]>;
/**
* Stores the given binary Wasm code into the chain's storage and returns its `codehash`.
* You can instantiate contracts only with stored code.
**/
putCode: AugmentedSubmittable<(code: Bytes | string | Uint8Array) => SubmittableExtrinsic<ApiType>, [Bytes]>;
/** /**
* Updates the schedule for metering contracts. * Updates the schedule for metering contracts.
* *
@@ -1051,6 +1062,26 @@ declare module '@polkadot/api/types/submittable' {
**/ **/
vote: AugmentedSubmittable<(refIndex: Compact<ReferendumIndex> | AnyNumber | Uint8Array, vote: AccountVote | { Standard: any } | { Split: any } | string | Uint8Array) => SubmittableExtrinsic<ApiType>, [Compact<ReferendumIndex>, AccountVote]>; vote: AugmentedSubmittable<(refIndex: Compact<ReferendumIndex> | AnyNumber | Uint8Array, vote: AccountVote | { Standard: any } | { Split: any } | string | Uint8Array) => SubmittableExtrinsic<ApiType>, [Compact<ReferendumIndex>, AccountVote]>;
}; };
electionProviderMultiPhase: {
[key: string]: SubmittableExtrinsicFunction<ApiType>;
/**
* Submit a solution for the unsigned phase.
*
* The dispatch origin fo this call must be __none__.
*
* This submission is checked on the fly. Moreover, this unsigned solution is only
* validated when submitted to the pool from the **local** node. Effectively, this means
* that only active validators can submit this transaction when authoring a block (similar
* to an inherent).
*
* To prevent any incorrect solution (and thus wasted time/weight), this transaction will
* panic if the solution submitted by the validator is invalid in any way, effectively
* putting their authoring reward at risk.
*
* No deposit or reward is associated with this submission.
**/
submitUnsigned: AugmentedSubmittable<(solution: RawSolution | { compact?: any; score?: any; round?: any } | string | Uint8Array, witness: SolutionOrSnapshotSize | { voters?: any; targets?: any } | string | Uint8Array) => SubmittableExtrinsic<ApiType>, [RawSolution, SolutionOrSnapshotSize]>;
};
elections: { elections: {
[key: string]: SubmittableExtrinsicFunction<ApiType>; [key: string]: SubmittableExtrinsicFunction<ApiType>;
/** /**
@@ -3049,7 +3080,7 @@ declare module '@polkadot/api/types/submittable' {
* - Write: Nominators, Validators * - Write: Nominators, Validators
* # </weight> * # </weight>
**/ **/
validate: AugmentedSubmittable<(prefs: ValidatorPrefs | { commission?: any } | string | Uint8Array) => SubmittableExtrinsic<ApiType>, [ValidatorPrefs]>; validate: AugmentedSubmittable<(prefs: ValidatorPrefs | { commission?: any; blocked?: any } | string | Uint8Array) => SubmittableExtrinsic<ApiType>, [ValidatorPrefs]>;
/** /**
* Remove any unlocked chunks from the `unlocking` queue from our management. * Remove any unlocked chunks from the `unlocking` queue from our management.
* *
+2
View File
@@ -492,9 +492,11 @@ export abstract class Decorate<ApiType extends ApiTypes> extends Events {
) )
), ),
tap((keys): void => { tap((keys): void => {
setTimeout((): void => {
keys.length === PAGE_SIZE keys.length === PAGE_SIZE
? startSubject.next(keys[PAGE_SIZE - 1].toHex()) ? startSubject.next(keys[PAGE_SIZE - 1].toHex())
: startSubject.complete(); : startSubject.complete();
}, 0);
}), }),
toArray(), // toArray since we want to startSubject to be completed toArray(), // toArray since we want to startSubject to be completed
map((keysArr: StorageKey[][]) => arrayFlatten(keysArr)) map((keysArr: StorageKey[][]) => arrayFlatten(keysArr))
+1 -1
View File
@@ -9,7 +9,7 @@ import type { ApiInterfaceRx, ApiTypes, DecoratedErrors, DecoratedEvents, Decora
import { assertReturn } from '@polkadot/util'; import { assertReturn } from '@polkadot/util';
import { packageInfo } from '../detectPackage'; import { packageInfo } from '../packageInfo';
import { Init } from './Init'; import { Init } from './Init';
interface PkgJson { interface PkgJson {
+10 -19
View File
@@ -2,7 +2,7 @@
// SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: Apache-2.0
import type { Text } from '@polkadot/types'; import type { Text } from '@polkadot/types';
import type { ChainProperties, Hash, RuntimeVersion, SignedBlock } from '@polkadot/types/interfaces'; import type { ChainProperties, Hash, RuntimeVersion } from '@polkadot/types/interfaces';
import type { Registry } from '@polkadot/types/types'; import type { Registry } from '@polkadot/types/types';
import type { Observable, Subscription } from '@polkadot/x-rxjs'; import type { Observable, Subscription } from '@polkadot/x-rxjs';
import type { ApiBase, ApiOptions, ApiTypes, DecorateMethod } from '../types'; import type { ApiBase, ApiOptions, ApiTypes, DecorateMethod } from '../types';
@@ -12,8 +12,7 @@ import BN from 'bn.js';
import { Metadata } from '@polkadot/metadata'; import { Metadata } from '@polkadot/metadata';
import { TypeRegistry } from '@polkadot/types/create'; import { TypeRegistry } from '@polkadot/types/create';
import { LATEST_EXTRINSIC_VERSION } from '@polkadot/types/extrinsic/Extrinsic'; import { getSpecAlias, getSpecExtensions, getSpecHasher, getSpecRpc, getSpecTypes, getUpgradeVersion } from '@polkadot/types-known';
import { getSpecAlias, getSpecRpc, getSpecTypes, getUpgradeVersion } from '@polkadot/types-known';
import { assert, BN_ZERO, logger, u8aEq, u8aToHex, u8aToU8a } from '@polkadot/util'; import { assert, BN_ZERO, logger, u8aEq, u8aToHex, u8aToU8a } from '@polkadot/util';
import { cryptoWaitReady } from '@polkadot/util-crypto'; import { cryptoWaitReady } from '@polkadot/util-crypto';
import { of } from '@polkadot/x-rxjs'; import { of } from '@polkadot/x-rxjs';
@@ -85,13 +84,17 @@ export abstract class Init<ApiType extends ApiTypes> extends Decorate<ApiType> {
registry.setChainProperties(chainProps || this.registry.getChainProperties()); registry.setChainProperties(chainProps || this.registry.getChainProperties());
registry.setKnownTypes(this._options); registry.setKnownTypes(this._options);
registry.register(getSpecTypes(registry, chain, version.specName, version.specVersion)); registry.register(getSpecTypes(registry, chain, version.specName, version.specVersion));
registry.setHasher(getSpecHasher(registry, chain, version.specName));
// for bundled types, pull through the aliases defined // for bundled types, pull through the aliases defined
if (registry.knownTypes.typesBundle) { if (registry.knownTypes.typesBundle) {
registry.knownTypes.typesAlias = getSpecAlias(registry, chain, version.specName); registry.knownTypes.typesAlias = getSpecAlias(registry, chain, version.specName);
} }
registry.setMetadata(metadata, undefined, this._options.signedExtensions); registry.setMetadata(metadata, undefined, {
...getSpecExtensions(registry, chain, version.specName),
...(this._options.signedExtensions || {})
});
return registry; return registry;
} }
@@ -136,7 +139,7 @@ export abstract class Init<ApiType extends ApiTypes> extends Decorate<ApiType> {
// nothing has been found, construct new // nothing has been found, construct new
const metadata = await this._rpcCore.state.getMetadata(header.parentHash).toPromise(); const metadata = await this._rpcCore.state.getMetadata(header.parentHash).toPromise();
const registry = this._initRegistry(new TypeRegistry(), this._runtimeChain as Text, version, metadata); const registry = this._initRegistry(new TypeRegistry(blockHash), this._runtimeChain as Text, version, metadata);
// For now, since this is new we ignore the capability lookups (this could be useful once proven) // For now, since this is new we ignore the capability lookups (this could be useful once proven)
// this._detectCapabilities(registry, blockHash); // this._detectCapabilities(registry, blockHash);
@@ -282,20 +285,8 @@ export abstract class Init<ApiType extends ApiTypes> extends Decorate<ApiType> {
return [genesisHash, metadata]; return [genesisHash, metadata];
} }
private async _initFromMeta (metadata: Metadata): Promise<boolean> { private _initFromMeta (metadata: Metadata): boolean {
const metaExtrinsic = metadata.asLatest.extrinsic; this._extrinsicType = metadata.asLatest.extrinsic.version.toNumber();
// only inject if we are not a clone (global init)
if (metaExtrinsic.version.gt(BN_ZERO)) {
this._extrinsicType = metaExtrinsic.version.toNumber();
} else if (!this._options.source) {
// detect the extrinsic version in-use based on the last block
const { block: { extrinsics: [firstTx] } }: SignedBlock = await this._rpcCore.chain.getBlock().toPromise();
// If we haven't sync-ed to 1 yes, this won't have any values
this._extrinsicType = firstTx ? firstTx.type : LATEST_EXTRINSIC_VERSION;
}
this._rx.extrinsicType = this._extrinsicType; this._rx.extrinsicType = this._extrinsicType;
this._rx.genesisHash = this._genesisHash; this._rx.genesisHash = this._genesisHash;
this._rx.runtimeVersion = this._runtimeVersion as RuntimeVersion; // must be set here this._rx.runtimeVersion = this._runtimeVersion as RuntimeVersion; // must be set here
+14 -6
View File
@@ -10,25 +10,32 @@ import { combineLatest, Observable, of } from '@polkadot/x-rxjs';
import { map, take } from '@polkadot/x-rxjs/operators'; import { map, take } from '@polkadot/x-rxjs/operators';
// the order and types needs to map with the all array setup below // the order and types needs to map with the all array setup below
type Extracted = [bool | null, bool | null, Releases | null]; type Extracted = [bool | null, bool | null, bool | null, Releases | null];
type DetectedKeys = keyof Pick<InterfaceTypes, 'AccountInfo' | 'ValidatorPrefs'>; type DetectedKeys = keyof Pick<InterfaceTypes, 'AccountInfo' | 'ValidatorPrefs'>;
type DetectedValues = keyof InterfaceTypes; type DetectedValues = keyof InterfaceTypes;
interface DetectedTypes extends Record<DetectedKeys, DetectedValues> { interface DetectedTypes extends Record<DetectedKeys, DetectedValues> {
AccountInfo: 'AccountInfoWithRefCount' | 'AccountInfoWithProviders', AccountInfo: 'AccountInfoWithRefCount' | 'AccountInfoWithDualRefCount' | 'AccountInfoWithTripleRefCount',
RefCount: 'u8' | 'u32',
ValidatorPrefs: 'ValidatorPrefsWithBlocked' | 'ValidatorPrefsWithCommission'; ValidatorPrefs: 'ValidatorPrefsWithBlocked' | 'ValidatorPrefsWithCommission';
} }
function mapCapabilities ([systemRefcount32, systemRefcountDual, stakingVersion]: Extracted): Partial<DetectedTypes> { function mapCapabilities ([systemRefcount32, systemRefcountDual, systemRefcountTriple, stakingVersion]: Extracted): Partial<DetectedTypes> {
const types: Partial<DetectedTypes> = {}; const types: Partial<DetectedTypes> = {};
// AccountInfo // AccountInfo
if (systemRefcountDual && systemRefcountDual.isTrue) { if (systemRefcountTriple && systemRefcountTriple.isTrue) {
types.AccountInfo = 'AccountInfoWithProviders'; types.AccountInfo = 'AccountInfoWithTripleRefCount';
} else if (systemRefcount32 && systemRefcount32.isTrue) { } else if (systemRefcountDual && systemRefcountDual.isTrue) {
types.AccountInfo = 'AccountInfoWithDualRefCount';
} else {
types.AccountInfo = 'AccountInfoWithRefCount'; types.AccountInfo = 'AccountInfoWithRefCount';
if (!systemRefcount32 || systemRefcount32.isFalse) {
types.RefCount = 'u8';
}
} }
// ValidatorPrefs // ValidatorPrefs
@@ -50,6 +57,7 @@ export function detectedCapabilities (api: ApiInterfaceRx, blockHash?: Uint8Arra
const all = [ const all = [
api.query.system?.upgradedToU32RefCount, api.query.system?.upgradedToU32RefCount,
api.query.system?.upgradedToDualRefCount, api.query.system?.upgradedToDualRefCount,
api.query.system?.upgradedToTripleRefCount,
api.query.staking?.storageVersion api.query.staking?.storageVersion
]; ];
const included = all.map((c) => !!c); const included = all.map((c) => !!c);
+8 -19
View File
@@ -1,25 +1,14 @@
// Copyright 2017-2021 @polkadot/api authors & contributors // Copyright 2017-2021 @polkadot/api authors & contributors
// SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: Apache-2.0
// For esm, this should be import.meta.url or to get the same behavior as __dirname, we can use import { packageInfo as deriveInfo } from '@polkadot/api-derive/packageInfo';
// import { packageInfo as metaInfo } from '@polkadot/metadata/packageInfo';
// new URL(import.meta.url).pathname) import { packageInfo as coreInfo } from '@polkadot/rpc-core/packageInfo';
// import { packageInfo as providerInfo } from '@polkadot/rpc-provider/packageInfo';
// The issue is the WP4 has "some" issues with import.meta.url. So because of bundlers, we can't have import { packageInfo as typesInfo } from '@polkadot/types/packageInfo';
// nice things... In this case it is even worse since import.meta.url won't even make it compile, so import { packageInfo as knownInfo } from '@polkadot/types-known/packageInfo';
// there is a complete dead end with usage thereof
//
// When that is fixed, a solution is to have both .js & .mjs files, with the following content -
//
// cjs: util.detectPackage(packageInfo, () => __dirname);
// esm: detectPackage(packageInfo, () => import.meta.url);
//
// With the above we additionally need a .d.ts to just export the packageInfo
import { detectPackage } from '@polkadot/util'; import { detectPackage } from '@polkadot/util';
import packageInfo from './package-info.json'; import { packageInfo } from './packageInfo';
detectPackage(packageInfo, typeof __dirname !== 'undefined' && __dirname); detectPackage(packageInfo, typeof __dirname !== 'undefined' && __dirname, [deriveInfo, metaInfo, coreInfo, providerInfo, typesInfo, knownInfo]);
export { packageInfo };
+2 -2
View File
@@ -6,7 +6,7 @@ import './detectPackage';
export { Keyring } from '@polkadot/keyring'; export { Keyring } from '@polkadot/keyring';
export { WsProvider } from '@polkadot/rpc-provider/ws'; export { WsProvider } from '@polkadot/rpc-provider/ws';
export { packageInfo } from './packageInfo';
export { ApiPromise } from './promise'; export { ApiPromise } from './promise';
export { ApiRx } from './rx';
export { SubmittableResult } from './submittable'; export { SubmittableResult } from './submittable';
export { ApiRx } from './rx';
+6
View File
@@ -0,0 +1,6 @@
// Copyright 2017-2021 @polkadot/api authors & contributors
// SPDX-License-Identifier: Apache-2.0
// Auto-generated by @polkadot/dev, do not edit
export const packageInfo = { name: '@polkadot/api', version: '4.0.3' };
+3 -3
View File
@@ -66,14 +66,14 @@ export class SubmittableResult implements ISubmittableResult {
/** /**
* @description Filters EventRecords for the specified method & section (there could be multiple) * @description Filters EventRecords for the specified method & section (there could be multiple)
*/ */
public filterRecords (section: string, method: string): EventRecord[] { public filterRecords (section: string, method: string | string[]): EventRecord[] {
return filterAndApply(this.events, section, [method], recordIdentity); return filterAndApply(this.events, section, Array.isArray(method) ? method : [method], recordIdentity);
} }
/** /**
* @description Finds an EventRecord for the specified method & section * @description Finds an EventRecord for the specified method & section
*/ */
public findRecord (section: string, method: string): EventRecord | undefined { public findRecord (section: string, method: string | string[]): EventRecord | undefined {
return this.filterRecords(section, method)[0]; return this.filterRecords(section, method)[0];
} }
+1 -1
View File
@@ -60,7 +60,7 @@ export interface ApiOptions extends RegisteredTypes {
/** /**
* @description Any chain-specific signed extensions that are now well-known * @description Any chain-specific signed extensions that are now well-known
*/ */
signedExtensions?: Record<string, ExtDef>; signedExtensions?: ExtDef;
/** /**
* @description An external signer which will be used to sign extrinsic when account passed in is not KeyringPair * @description An external signer which will be used to sign extrinsic when account passed in is not KeyringPair
*/ */
+7 -7
View File
@@ -35,19 +35,19 @@ export type QueryableStorageEntry<ApiType extends ApiTypes, A extends AnyTuple =
// eslint-disable-next-line no-use-before-define // eslint-disable-next-line no-use-before-define
: AugmentedQuery<'promise', GenericStorageEntryFunction, A> & StorageEntryPromiseOverloads; : AugmentedQuery<'promise', GenericStorageEntryFunction, A> & StorageEntryPromiseOverloads;
export interface StorageEntryBase<ApiType extends ApiTypes, F extends AnyFunction, A extends AnyTuple> { export interface StorageEntryBase<ApiType extends ApiTypes, F extends AnyFunction, A extends AnyTuple = AnyTuple> {
at: <T extends Codec | any = ObsInnerType<ReturnType<F>>>(hash: Hash | Uint8Array | string, ...args: Parameters<F>) => PromiseOrObs<ApiType, T>; at: <T extends Codec | any = ObsInnerType<ReturnType<F>>>(hash: Hash | Uint8Array | string, ...args: Parameters<F>) => PromiseOrObs<ApiType, T>;
creator: StorageEntry; creator: StorageEntry;
entries: <T extends Codec | any = ObsInnerType<ReturnType<F>>>(arg?: Parameters<F>[0]) => PromiseOrObs<ApiType, [StorageKey<A>, T][]>; entries: <T extends Codec | any = ObsInnerType<ReturnType<F>>, K extends AnyTuple = A>(arg?: Parameters<F>[0]) => PromiseOrObs<ApiType, [StorageKey<K>, T][]>;
entriesAt: <T extends Codec | any = ObsInnerType<ReturnType<F>>>(hash: Hash | Uint8Array | string, arg?: Parameters<F>[0]) => PromiseOrObs<ApiType, [StorageKey<A>, T][]>; entriesAt: <T extends Codec | any = ObsInnerType<ReturnType<F>>, K extends AnyTuple = A>(hash: Hash | Uint8Array | string, arg?: Parameters<F>[0]) => PromiseOrObs<ApiType, [StorageKey<K>, T][]>;
entriesPaged: <T extends Codec | any = ObsInnerType<ReturnType<F>>>(opts: PaginationOptions<Parameters<F>[0]>) => PromiseOrObs<ApiType, [StorageKey<A>, T][]>; entriesPaged: <T extends Codec | any = ObsInnerType<ReturnType<F>>, K extends AnyTuple = A>(opts: PaginationOptions<Parameters<F>[0]>) => PromiseOrObs<ApiType, [StorageKey<K>, T][]>;
hash: (...args: Parameters<F>) => PromiseOrObs<ApiType, Hash>; hash: (...args: Parameters<F>) => PromiseOrObs<ApiType, Hash>;
is: (key: IStorageKey<AnyTuple>) => key is IStorageKey<A>; is: (key: IStorageKey<AnyTuple>) => key is IStorageKey<A>;
key: (...args: Parameters<F>) => string; key: (...args: Parameters<F>) => string;
keyPrefix: () => string; keyPrefix: () => string;
keys: (arg?: any) => PromiseOrObs<ApiType, StorageKey<A>[]>; keys: <K extends AnyTuple = A> (arg?: any) => PromiseOrObs<ApiType, StorageKey<K>[]>;
keysAt: (hash: Hash | Uint8Array | string, arg?: any) => PromiseOrObs<ApiType, StorageKey<A>[]>; keysAt: <K extends AnyTuple = A> (hash: Hash | Uint8Array | string, arg?: any) => PromiseOrObs<ApiType, StorageKey<K>[]>;
keysPaged: (opts: PaginationOptions<Parameters<F>[0]>) => PromiseOrObs<ApiType, StorageKey<A>[]>; keysPaged: <K extends AnyTuple = A> (opts: PaginationOptions<Parameters<F>[0]>) => PromiseOrObs<ApiType, StorageKey<K>[]>;
// @deprecated The underlying RPC this been marked unsafe and is generally not exposed // @deprecated The underlying RPC this been marked unsafe and is generally not exposed
range: <T extends Codec | any = ObsInnerType<ReturnType<F>>>([from, to]: [Hash | Uint8Array | string, Hash | Uint8Array | string | undefined] | [Hash | Uint8Array | string], ...args: Parameters<F>) => PromiseOrObs<ApiType, [Hash, T][]>; range: <T extends Codec | any = ObsInnerType<ReturnType<F>>>([from, to]: [Hash | Uint8Array | string, Hash | Uint8Array | string | undefined] | [Hash | Uint8Array | string], ...args: Parameters<F>) => PromiseOrObs<ApiType, [Hash, T][]>;
size: (...args: Parameters<F>) => PromiseOrObs<ApiType, u64>; size: (...args: Parameters<F>) => PromiseOrObs<ApiType, u64>;
+9 -8
View File
@@ -1,11 +1,12 @@
{ {
"name": "@polkadot/metadata", "name": "@polkadot/metadata",
"version": "3.7.2", "version": "4.0.3",
"type": "module",
"description": "Helpers to extract information from runtime metadata", "description": "Helpers to extract information from runtime metadata",
"main": "index.js", "main": "index.js",
"sideEffects": [ "sideEffects": [
"./detectPackage.js", "./detectPackage.js",
"./detectPackage.mjs" "./detectPackage.cjs"
], ],
"repository": "github:polkadot-js/api", "repository": "github:polkadot-js/api",
"author": "Jaco Greeff <jacogr@gmail.com>", "author": "Jaco Greeff <jacogr@gmail.com>",
@@ -15,14 +16,14 @@
"bugs": "https://github.com/polkadot-js/api/issues", "bugs": "https://github.com/polkadot-js/api/issues",
"homepage": "https://github.com/polkadot-js/api/tree/master/packages/type-metadata#readme", "homepage": "https://github.com/polkadot-js/api/tree/master/packages/type-metadata#readme",
"dependencies": { "dependencies": {
"@babel/runtime": "^7.12.5", "@babel/runtime": "^7.13.9",
"@polkadot/types": "3.7.2", "@polkadot/types": "4.0.3",
"@polkadot/types-known": "3.7.2", "@polkadot/types-known": "4.0.3",
"@polkadot/util": "^5.5.1", "@polkadot/util": "^6.0.5",
"@polkadot/util-crypto": "^5.5.1", "@polkadot/util-crypto": "^6.0.5",
"bn.js": "^4.11.9" "bn.js": "^4.11.9"
}, },
"devDependencies": { "devDependencies": {
"@polkadot/keyring": "^5.5.1" "@polkadot/keyring": "^6.0.5"
} }
} }
+13 -1
View File
@@ -2,7 +2,7 @@
// SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: Apache-2.0
import type { MetadataAll, MetadataLatest, MetadataV9, MetadataV10, MetadataV11, MetadataV12 } from '@polkadot/types/interfaces/metadata'; import type { MetadataAll, MetadataLatest, MetadataV9, MetadataV10, MetadataV11, MetadataV12 } from '@polkadot/types/interfaces/metadata';
import type { Registry } from '@polkadot/types/types'; import type { AnyJson, Registry } from '@polkadot/types/types';
import { Struct } from '@polkadot/types/codec'; import { Struct } from '@polkadot/types/codec';
import { assert } from '@polkadot/util'; import { assert } from '@polkadot/util';
@@ -126,4 +126,16 @@ export class MetadataVersioned extends Struct {
public getUniqTypes (throwError: boolean): string[] { public getUniqTypes (throwError: boolean): string[] {
return getUniqTypes(this.registry, this.asLatest, throwError); return getUniqTypes(this.registry, this.asLatest, throwError);
} }
/**
* @description Converts the Object to JSON, typically used for RPC transfers
*/
public toJSON (): Record<string, AnyJson> {
// HACK(y): ensure that we apply the aliasses if we have not done so already, this is
// needed to ensure we have the overrides as intended (only applied in toLatest)
// eslint-disable-next-line no-unused-expressions
this.asLatest;
return super.toJSON();
}
} }
+1 -1
View File
@@ -30,4 +30,4 @@ export function expandMetadata (registry: Registry, metadata: Metadata): Decorat
}; };
} }
export { decorateConstants, decorateExtrinsics, decorateStorage }; export { decorateConstants, decorateErrors, decorateEvents, decorateExtrinsics, decorateStorage };
+4 -19
View File
@@ -1,25 +1,10 @@
// Copyright 2017-2021 @polkadot/metadata authors & contributors // Copyright 2017-2021 @polkadot/metadata authors & contributors
// SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: Apache-2.0
// For esm, this should be import.meta.url or to get the same behavior as __dirname, we can use import { packageInfo as typesInfo } from '@polkadot/types/packageInfo';
// import { packageInfo as knownInfo } from '@polkadot/types-known/packageInfo';
// new URL(import.meta.url).pathname)
//
// The issue is the WP4 has "some" issues with import.meta.url. So because of bundlers, we can't have
// nice things... In this case it is even worse since import.meta.url won't even make it compile, so
// there is a complete dead end with usage thereof
//
// When that is fixed, a solution is to have both .js & .mjs files, with the following content -
//
// cjs: util.detectPackage(packageInfo, () => __dirname);
// esm: detectPackage(packageInfo, () => import.meta.url);
//
// With the above we additionally need a .d.ts to just export the packageInfo
import { detectPackage } from '@polkadot/util'; import { detectPackage } from '@polkadot/util';
import packageInfo from './package-info.json'; import { packageInfo } from './packageInfo';
detectPackage(packageInfo, typeof __dirname !== 'undefined' && __dirname); detectPackage(packageInfo, typeof __dirname !== 'undefined' && __dirname, [typesInfo, knownInfo]);
export { packageInfo };
+1
View File
@@ -5,3 +5,4 @@ import './detectPackage';
export { Metadata } from './Metadata'; export { Metadata } from './Metadata';
export { decorateConstants, decorateExtrinsics, decorateStorage, expandMetadata } from './decorate'; export { decorateConstants, decorateExtrinsics, decorateStorage, expandMetadata } from './decorate';
export { packageInfo } from './packageInfo';
+6
View File
@@ -0,0 +1,6 @@
// Copyright 2017-2021 @polkadot/metadata authors & contributors
// SPDX-License-Identifier: Apache-2.0
// Auto-generated by @polkadot/dev, do not edit
export const packageInfo = { name: '@polkadot/metadata', version: '4.0.3' };
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because one or more lines are too long
File diff suppressed because it is too large Load Diff
+13 -9
View File
@@ -1,9 +1,13 @@
{ {
"name": "@polkadot/rpc-core", "name": "@polkadot/rpc-core",
"version": "3.7.2", "version": "4.0.3",
"type": "module",
"description": "A JavaScript wrapper for the Polkadot JsonRPC interface", "description": "A JavaScript wrapper for the Polkadot JsonRPC interface",
"main": "index.js", "main": "index.js",
"sideEffects": false, "sideEffects": [
"./detectPackage.js",
"./detectPackage.cjs"
],
"author": "Jaco Greeff <jacogr@gmail.com>", "author": "Jaco Greeff <jacogr@gmail.com>",
"maintainers": [], "maintainers": [],
"contributors": [], "contributors": [],
@@ -12,14 +16,14 @@
"bugs": "https://github.com/polkadot-js/api/issues", "bugs": "https://github.com/polkadot-js/api/issues",
"homepage": "https://github.com/polkadot-js/api/tree/master/packages/rpc-core#readme", "homepage": "https://github.com/polkadot-js/api/tree/master/packages/rpc-core#readme",
"dependencies": { "dependencies": {
"@babel/runtime": "^7.12.5", "@babel/runtime": "^7.13.9",
"@polkadot/metadata": "3.7.2", "@polkadot/metadata": "4.0.3",
"@polkadot/rpc-provider": "3.7.2", "@polkadot/rpc-provider": "4.0.3",
"@polkadot/types": "3.7.2", "@polkadot/types": "4.0.3",
"@polkadot/util": "^5.5.1", "@polkadot/util": "^6.0.5",
"@polkadot/x-rxjs": "^5.5.1" "@polkadot/x-rxjs": "^6.0.5"
}, },
"devDependencies": { "devDependencies": {
"@polkadot/keyring": "^5.5.1" "@polkadot/keyring": "^6.0.5"
} }
} }
+11
View File
@@ -0,0 +1,11 @@
// Copyright 2017-2021 @polkadot/rpc-core authors & contributors
// SPDX-License-Identifier: Apache-2.0
import { packageInfo as metaInfo } from '@polkadot/metadata/packageInfo';
import { packageInfo as providerInfo } from '@polkadot/rpc-provider/packageInfo';
import { packageInfo as typesInfo } from '@polkadot/types/packageInfo';
import { detectPackage } from '@polkadot/util';
import { packageInfo } from './packageInfo';
detectPackage(packageInfo, typeof __dirname !== 'undefined' && __dirname, [metaInfo, providerInfo, typesInfo]);
+37 -27
View File
@@ -1,6 +1,8 @@
// Copyright 2017-2021 @polkadot/rpc-core authors & contributors // Copyright 2017-2021 @polkadot/rpc-core authors & contributors
// SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: Apache-2.0
import './detectPackage';
import type { ProviderInterface, ProviderInterfaceCallback } from '@polkadot/rpc-provider/types'; import type { ProviderInterface, ProviderInterfaceCallback } from '@polkadot/rpc-provider/types';
import type { StorageKey, Vec } from '@polkadot/types'; import type { StorageKey, Vec } from '@polkadot/types';
import type { Hash } from '@polkadot/types/interfaces'; import type { Hash } from '@polkadot/types/interfaces';
@@ -18,6 +20,8 @@ import { publishReplay, refCount } from '@polkadot/x-rxjs/operators';
import { drr, refCountDelay } from './util'; import { drr, refCountDelay } from './util';
export { packageInfo } from './packageInfo';
interface StorageChangeSetJSON { interface StorageChangeSetJSON {
block: string; block: string;
changes: [string, string | null][]; changes: [string, string | null][];
@@ -240,17 +244,17 @@ export class RpcCore implements RpcInterface {
// execute the RPC call, doing a registry swap for historic as applicable // execute the RPC call, doing a registry swap for historic as applicable
const callWithRegistry = async (outputAs: OutputType, values: any[]): Promise<Codec | Codec[]> => { const callWithRegistry = async (outputAs: OutputType, values: any[]): Promise<Codec | Codec[]> => {
const hash = hashIndex === -1 const blockHash = hashIndex === -1
? undefined ? null
: values[hashIndex] as Uint8Array; : values[hashIndex] as Uint8Array;
const { registry } = hash && this.#getBlockRegistry const { registry } = blockHash && this.#getBlockRegistry
? await this.#getBlockRegistry(hash) ? await this.#getBlockRegistry(blockHash)
: { registry: this.#registryDefault }; : { registry: this.#registryDefault };
const params = this._formatInputs(registry, def, values); const params = this._formatInputs(registry, null, def, values);
const data = await this.provider.send(rpcName, params.map((param): AnyJson => param.toJSON())) as AnyJson; const data = await this.provider.send(rpcName, params.map((param): AnyJson => param.toJSON())) as AnyJson;
return outputAs === 'scale' return outputAs === 'scale'
? this._formatOutput(registry, method, def, params, data) ? this._formatOutput(registry, blockHash, method, def, params, data)
: registry.createType(outputAs === 'raw' ? 'Raw' : 'Json', data); : registry.createType(outputAs === 'raw' ? 'Raw' : 'Json', data);
}; };
@@ -320,7 +324,7 @@ export class RpcCore implements RpcInterface {
}; };
try { try {
const params = this._formatInputs(registry, def, values); const params = this._formatInputs(registry, null, def, values);
const paramsJson = params.map((param): AnyJson => param.toJSON()); const paramsJson = params.map((param): AnyJson => param.toJSON());
const update = (error?: Error | null, result?: any): void => { const update = (error?: Error | null, result?: any): void => {
@@ -333,7 +337,7 @@ export class RpcCore implements RpcInterface {
try { try {
observer.next( observer.next(
outputAs === 'scale' outputAs === 'scale'
? this._formatOutput(registry, method, def, params, result) ? this._formatOutput(registry, null, method, def, params, result)
: registry.createType(outputAs === 'raw' ? 'Raw' : 'Json', result) : registry.createType(outputAs === 'raw' ? 'Raw' : 'Json', result)
); );
} catch (error) { } catch (error) {
@@ -368,8 +372,8 @@ export class RpcCore implements RpcInterface {
return memoized; return memoized;
} }
private _formatInputs (registry: Registry, def: DefinitionRpc, inputs: any[]): Codec[] { private _formatInputs (registry: Registry, blockHash: Uint8Array | string | null | undefined, def: DefinitionRpc, inputs: any[]): Codec[] {
const reqArgCount = def.params.filter(({ isOptional }): boolean => !isOptional).length; const reqArgCount = def.params.filter(({ isOptional }) => !isOptional).length;
const optText = reqArgCount === def.params.length const optText = reqArgCount === def.params.length
? '' ? ''
: ` (${def.params.length - reqArgCount} optional)`; : ` (${def.params.length - reqArgCount} optional)`;
@@ -377,25 +381,25 @@ export class RpcCore implements RpcInterface {
assert(inputs.length >= reqArgCount && inputs.length <= def.params.length, `Expected ${def.params.length} parameters${optText}, ${inputs.length} found instead`); assert(inputs.length >= reqArgCount && inputs.length <= def.params.length, `Expected ${def.params.length} parameters${optText}, ${inputs.length} found instead`);
return inputs.map((input, index): Codec => return inputs.map((input, index): Codec =>
createTypeUnsafe(registry, def.params[index].type, [input]) createTypeUnsafe(registry, def.params[index].type, [input], { blockHash })
); );
} }
private _formatOutput (registry: Registry, method: string, rpc: DefinitionRpc, params: Codec[], result?: any): Codec | Codec[] { private _formatOutput (registry: Registry, blockHash: Uint8Array | string | null | undefined, method: string, rpc: DefinitionRpc, params: Codec[], result?: any): Codec | Codec[] {
if (rpc.type === 'StorageData') { if (rpc.type === 'StorageData') {
const key = params[0] as StorageKey; const key = params[0] as StorageKey;
return this._formatStorageData(registry, key, result); return this._formatStorageData(registry, blockHash, key, result);
} else if (rpc.type === 'StorageChangeSet') { } else if (rpc.type === 'StorageChangeSet') {
const keys = params[0] as Vec<StorageKey>; const keys = params[0] as Vec<StorageKey>;
return keys return keys
? this._formatStorageSet(registry, keys, (result as StorageChangeSetJSON).changes) ? this._formatStorageSet(registry, (result as StorageChangeSetJSON).block, keys, (result as StorageChangeSetJSON).changes)
: registry.createType('StorageChangeSet', result); : registry.createType('StorageChangeSet', result);
} else if (rpc.type === 'Vec<StorageChangeSet>') { } else if (rpc.type === 'Vec<StorageChangeSet>') {
const mapped = (result as StorageChangeSetJSON[]).map(({ block, changes }): [Hash, Codec[]] => [ const mapped = (result as StorageChangeSetJSON[]).map(({ block, changes }): [Hash, Codec[]] => [
registry.createType('Hash', block), registry.createType('Hash', block),
this._formatStorageSet(registry, params[0] as Vec<StorageKey>, changes) this._formatStorageSet(registry, block, params[0] as Vec<StorageKey>, changes)
]); ]);
// we only query at a specific block, not a range - flatten // we only query at a specific block, not a range - flatten
@@ -404,10 +408,10 @@ export class RpcCore implements RpcInterface {
: mapped as unknown as Codec[]; : mapped as unknown as Codec[];
} }
return createTypeUnsafe(registry, rpc.type, [result]); return createTypeUnsafe(registry, rpc.type, [result], { blockHash });
} }
private _formatStorageData (registry: Registry, key: StorageKey, value: string | null): Codec { private _formatStorageData (registry: Registry, blockHash: Uint8Array | string | null | undefined, key: StorageKey, value: string | null): Codec {
const isEmpty = isNull(value); const isEmpty = isNull(value);
// we convert to Uint8Array since it maps to the raw encoding, all // we convert to Uint8Array since it maps to the raw encoding, all
@@ -418,10 +422,10 @@ export class RpcCore implements RpcInterface {
? value ? value
: u8aToU8a(value); : u8aToU8a(value);
return this._newType(registry, key, input, isEmpty); return this._newType(registry, blockHash, key, input, isEmpty);
} }
private _formatStorageSet (registry: Registry, keys: Vec<StorageKey>, changes: [string, string | null][]): Codec[] { private _formatStorageSet (registry: Registry, blockHash: string, keys: Vec<StorageKey>, changes: [string, string | null][]): Codec[] {
// For StorageChangeSet, the changes has the [key, value] mappings // For StorageChangeSet, the changes has the [key, value] mappings
const withCache = keys.length !== 1; const withCache = keys.length !== 1;
@@ -430,13 +434,13 @@ export class RpcCore implements RpcInterface {
// - Codec - There is a valid value, non-empty // - Codec - There is a valid value, non-empty
// - null - The storage key is empty // - null - The storage key is empty
return keys.reduce((results: Codec[], key: StorageKey, index): Codec[] => { return keys.reduce((results: Codec[], key: StorageKey, index): Codec[] => {
results.push(this._formatStorageSetEntry(registry, key, changes, withCache, index)); results.push(this._formatStorageSetEntry(registry, blockHash, key, changes, withCache, index));
return results; return results;
}, []); }, []);
} }
private _formatStorageSetEntry (registry: Registry, key: StorageKey, changes: [string, string | null][], witCache: boolean, entryIndex: number): Codec { private _formatStorageSetEntry (registry: Registry, blockHash: string, key: StorageKey, changes: [string, string | null][], witCache: boolean, entryIndex: number): Codec {
const hexKey = key.toHex(); const hexKey = key.toHex();
const found = changes.find(([key]) => key === hexKey); const found = changes.find(([key]) => key === hexKey);
@@ -457,10 +461,10 @@ export class RpcCore implements RpcInterface {
// will increase memory beyond what is allowed. // will increase memory beyond what is allowed.
this.#storageCache.set(hexKey, value); this.#storageCache.set(hexKey, value);
return this._newType(registry, key, input, isEmpty, entryIndex); return this._newType(registry, blockHash, key, input, isEmpty, entryIndex);
} }
private _newType (registry: Registry, key: StorageKey, input: string | Uint8Array | null, isEmpty: boolean, entryIndex = -1): Codec { private _newType (registry: Registry, blockHash: Uint8Array | string | null | undefined, key: StorageKey, input: string | Uint8Array | null, isEmpty: boolean, entryIndex = -1): Codec {
// single return value (via state.getStorage), decode the value based on the // single return value (via state.getStorage), decode the value based on the
// outputType that we have specified. Fallback to Raw on nothing // outputType that we have specified. Fallback to Raw on nothing
const type = key.outputType || 'Raw'; const type = key.outputType || 'Raw';
@@ -474,13 +478,19 @@ export class RpcCore implements RpcInterface {
if (!isEmpty) { if (!isEmpty) {
try { try {
inner = createTypeUnsafe(registry, type, [input], { isPedantic: true }); inner = createTypeUnsafe(registry, type, [input], { blockHash, isPedantic: true });
} catch (error) { } catch (error) {
l.error(`Unable to decode storage ${key.section || 'unknown'}.${key.method || 'unknown'}:${entryNum}`, (error as Error).message); l.error(`Unable to decode storage ${key.section || 'unknown'}.${key.method || 'unknown'}:${entryNum}`, (error as Error).message);
} }
} }
return new Option(registry, createClass(registry, type), inner); const option = new Option(registry, createClass(registry, type), inner);
if (blockHash) {
option.createdAtHash = registry.createType('Hash', blockHash);
}
return option;
} }
try { try {
@@ -490,11 +500,11 @@ export class RpcCore implements RpcInterface {
? hexToU8a(meta.fallback.toHex()) ? hexToU8a(meta.fallback.toHex())
: undefined : undefined
: input : input
], { isPedantic: true }); ], { blockHash, isPedantic: true });
} catch (error) { } catch (error) {
l.error(`Unable to decode storage ${key.section || 'unknown'}.${key.method || 'unknown'}:${entryNum}`, (error as Error).message); l.error(`Unable to decode storage ${key.section || 'unknown'}.${key.method || 'unknown'}:${entryNum}`, (error as Error).message);
return registry.createType('Raw', input); return createTypeUnsafe(registry, 'Raw', [input], { blockHash });
} }
} }
} }
+6
View File
@@ -0,0 +1,6 @@
// Copyright 2017-2021 @polkadot/rpc-core authors & contributors
// SPDX-License-Identifier: Apache-2.0
// Auto-generated by @polkadot/dev, do not edit
export const packageInfo = { name: '@polkadot/rpc-core', version: '4.0.3' };
+16 -12
View File
@@ -1,9 +1,13 @@
{ {
"name": "@polkadot/rpc-provider", "name": "@polkadot/rpc-provider",
"version": "3.7.2", "version": "4.0.3",
"type": "module",
"description": "Transport providers for the API", "description": "Transport providers for the API",
"main": "index.js", "main": "index.js",
"sideEffects": false, "sideEffects": [
"./detectPackage.js",
"./detectPackage.cjs"
],
"author": "Jaco Greeff <jacogr@gmail.com>", "author": "Jaco Greeff <jacogr@gmail.com>",
"maintainers": [], "maintainers": [],
"contributors": [], "contributors": [],
@@ -12,20 +16,20 @@
"bugs": "https://github.com/polkadot-js/api/issues", "bugs": "https://github.com/polkadot-js/api/issues",
"homepage": "https://github.com/polkadot-js/api/tree/master/packages/rpc-provider#readme", "homepage": "https://github.com/polkadot-js/api/tree/master/packages/rpc-provider#readme",
"dependencies": { "dependencies": {
"@babel/runtime": "^7.12.5", "@babel/runtime": "^7.13.9",
"@polkadot/types": "3.7.2", "@polkadot/types": "4.0.3",
"@polkadot/util": "^5.5.1", "@polkadot/util": "^6.0.5",
"@polkadot/util-crypto": "^5.5.1", "@polkadot/util-crypto": "^6.0.5",
"@polkadot/x-fetch": "^5.5.1", "@polkadot/x-fetch": "^6.0.5",
"@polkadot/x-global": "^5.5.1", "@polkadot/x-global": "^6.0.5",
"@polkadot/x-ws": "^5.5.1", "@polkadot/x-ws": "^6.0.5",
"bn.js": "^4.11.9", "bn.js": "^4.11.9",
"eventemitter3": "^4.0.7" "eventemitter3": "^4.0.7"
}, },
"devDependencies": { "devDependencies": {
"@polkadot/keyring": "^5.5.1", "@polkadot/keyring": "^6.0.5",
"@polkadot/metadata": "3.7.2", "@polkadot/metadata": "4.0.3",
"mock-socket": "^9.0.3", "mock-socket": "^9.0.3",
"nock": "^13.0.7" "nock": "^13.0.10"
} }
} }
@@ -0,0 +1,9 @@
// Copyright 2017-2021 @polkadot/rpc-provider authors & contributors
// SPDX-License-Identifier: Apache-2.0
import { packageInfo as typesInfo } from '@polkadot/types/packageInfo';
import { detectPackage } from '@polkadot/util';
import { packageInfo } from './packageInfo';
detectPackage(packageInfo, typeof __dirname !== 'undefined' && __dirname, [typesInfo]);
+3
View File
@@ -1,5 +1,8 @@
// Copyright 2017-2021 @polkadot/rpc-provider authors & contributors // Copyright 2017-2021 @polkadot/rpc-provider authors & contributors
// SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: Apache-2.0
import './detectPackage';
export { HttpProvider } from './http'; export { HttpProvider } from './http';
export { packageInfo } from './packageInfo';
export { WsProvider } from './ws'; export { WsProvider } from './ws';
+6
View File
@@ -0,0 +1,6 @@
// Copyright 2017-2021 @polkadot/rpc-provider authors & contributors
// SPDX-License-Identifier: Apache-2.0
// Auto-generated by @polkadot/dev, do not edit
export const packageInfo = { name: '@polkadot/rpc-provider', version: '4.0.3' };
+30 -11
View File
@@ -42,6 +42,16 @@ const RETRY_DELAY = 1000;
const l = logger('api-ws'); const l = logger('api-ws');
function eraseRecord<T> (record: Record<string, T>, cb?: (item: T) => void): void {
Object.keys(record).forEach((key): void => {
if (cb) {
cb(record[key]);
}
delete record[key];
});
}
/** /**
* # @polkadot/rpc-provider/ws * # @polkadot/rpc-provider/ws
* *
@@ -189,6 +199,7 @@ export class WsProvider implements ProviderInterface {
* @description Connect, never throwing an error, but rather forcing a retry * @description Connect, never throwing an error, but rather forcing a retry
*/ */
public async connectWithRetry (): Promise<void> { public async connectWithRetry (): Promise<void> {
if (this.#autoConnectMs > 0) {
try { try {
await this.connect(); await this.connect();
} catch (error) { } catch (error) {
@@ -196,7 +207,8 @@ export class WsProvider implements ProviderInterface {
this.connectWithRetry().catch((): void => { this.connectWithRetry().catch((): void => {
// does not throw // does not throw
}); });
}, this.#autoConnectMs || RETRY_DELAY); }, this.#autoConnectMs);
}
} }
} }
@@ -243,8 +255,8 @@ export class WsProvider implements ProviderInterface {
* @param params Encoded parameters as applicable for the method * @param params Encoded parameters as applicable for the method
* @param subscription Subscription details (internally used) * @param subscription Subscription details (internally used)
*/ */
public send (method: string, params: any[], subscription?: SubscriptionHandler): Promise<any> { public send <T = any> (method: string, params: any[], subscription?: SubscriptionHandler): Promise<T> {
return new Promise((resolve, reject): void => { return new Promise<T>((resolve, reject): void => {
try { try {
assert(this.isConnected && !isNull(this.#websocket), 'WebSocket is not connected'); assert(this.isConnected && !isNull(this.#websocket), 'WebSocket is not connected');
@@ -296,10 +308,8 @@ export class WsProvider implements ProviderInterface {
* }) * })
* ``` * ```
*/ */
public async subscribe (type: string, method: string, params: any[], callback: ProviderInterfaceCallback): Promise<number | string> { public subscribe (type: string, method: string, params: any[], callback: ProviderInterfaceCallback): Promise<number | string> {
const id = await this.send(method, params, { callback, type }) as Promise<number | string>; return this.send<number | string>(method, params, { callback, type });
return id;
} }
/** /**
@@ -320,9 +330,13 @@ export class WsProvider implements ProviderInterface {
delete this.#subscriptions[subscription]; delete this.#subscriptions[subscription];
const result = await this.send(method, [id]) as Promise<boolean>; try {
return this.isConnected && !isNull(this.#websocket)
return result; ? this.send<boolean>(method, [id])
: true;
} catch (error) {
return false;
}
} }
#emit = (type: ProviderInterfaceEmitted, ...args: any[]): void => { #emit = (type: ProviderInterfaceEmitted, ...args: any[]): void => {
@@ -330,12 +344,17 @@ export class WsProvider implements ProviderInterface {
} }
#onSocketClose = (event: CloseEvent): void => { #onSocketClose = (event: CloseEvent): void => {
const error = new Error(`disconnected from ${this.#endpoints[this.#endpointIndex]}: ${event.code}:: ${event.reason || getWSErrorString(event.code)}`);
if (this.#autoConnectMs > 0) { if (this.#autoConnectMs > 0) {
l.error(`disconnected from ${this.#endpoints[this.#endpointIndex]}: ${event.code}:: ${event.reason || getWSErrorString(event.code)}`); l.error(error.message);
} }
this.#isConnected = false; this.#isConnected = false;
this.#emit('disconnected'); this.#emit('disconnected');
// reject all hanging requests
eraseRecord(this.#handlers, (handler) => handler.callback(error, undefined));
eraseRecord(this.#waitingForId);
if (this.#autoConnectMs > 0) { if (this.#autoConnectMs > 0) {
setTimeout((): void => { setTimeout((): void => {
+2 -7
View File
@@ -5,9 +5,9 @@
import nock from 'nock'; import nock from 'nock';
const TEST_HTTP_URL = 'http://localhost:9944'; export const TEST_HTTP_URL = 'http://localhost:9944';
function mockHttp (requests: any[]): any { export function mockHttp (requests: any[]): any {
nock.cleanAll(); nock.cleanAll();
return requests.reduce((scope, request: any): nock.Scope => { return requests.reduce((scope, request: any): nock.Scope => {
@@ -21,8 +21,3 @@ function mockHttp (requests: any[]): any {
}); });
}, nock(TEST_HTTP_URL)); }, nock(TEST_HTTP_URL));
} }
export {
TEST_HTTP_URL,
mockHttp
};
+3 -8
View File
@@ -3,8 +3,6 @@
import { Server, WebSocket } from 'mock-socket'; import { Server, WebSocket } from 'mock-socket';
const TEST_WS_URL = 'ws://localhost:9955';
interface Scope { interface Scope {
body: { [index: string]: Record<string, any> }; body: { [index: string]: Record<string, any> };
requests: number; requests: number;
@@ -29,6 +27,8 @@ interface ReplyDef {
global.WebSocket = WebSocket; global.WebSocket = WebSocket;
export const TEST_WS_URL = 'ws://localhost:9955';
// should be JSONRPC def return // should be JSONRPC def return
function createError ({ error: { code, message }, id }: ErrorDef): any { function createError ({ error: { code, message }, id }: ErrorDef): any {
return { return {
@@ -51,7 +51,7 @@ function createReply ({ id, reply: { result } }: ReplyDef): any {
} }
// scope definition returned // scope definition returned
function mockWs (requests: ({ method: string } & ErrorDef)[], wsUrl: string = TEST_WS_URL): Scope { export function mockWs (requests: ({ method: string } & ErrorDef)[], wsUrl: string = TEST_WS_URL): Scope {
const server = new Server(wsUrl); const server = new Server(wsUrl);
let requestCount = 0; let requestCount = 0;
@@ -85,8 +85,3 @@ function mockWs (requests: ({ method: string } & ErrorDef)[], wsUrl: string = TE
return scope; return scope;
} }
export {
TEST_WS_URL,
mockWs
};
+22 -18
View File
@@ -1,15 +1,19 @@
{ {
"name": "@polkadot/typegen", "name": "@polkadot/typegen",
"version": "3.7.2", "version": "4.0.3",
"type": "module",
"description": "Type generation scripts", "description": "Type generation scripts",
"main": "index.js", "main": "index.js",
"sideEffects": false, "sideEffects": [
"./detectPackage.js",
"./detectPackage.cjs"
],
"bin": { "bin": {
"polkadot-types-chain-info": "./scripts/polkadot-types-chain-info.js", "polkadot-types-chain-info": "./scripts/polkadot-types-chain-info.cjs",
"polkadot-types-from-chain": "./scripts/polkadot-types-from-chain.js", "polkadot-types-from-chain": "./scripts/polkadot-types-from-chain.cjs",
"polkadot-types-from-defs": "./scripts/polkadot-types-from-defs.js", "polkadot-types-from-defs": "./scripts/polkadot-types-from-defs.cjs",
"polkadot-types-internal-interfaces": "./scripts/polkadot-types-internal-interfaces.js", "polkadot-types-internal-interfaces": "./scripts/polkadot-types-internal-interfaces.cjs",
"polkadot-types-internal-metadata": "./scripts/polkadot-types-internal-metadata.js" "polkadot-types-internal-metadata": "./scripts/polkadot-types-internal-metadata.cjs"
}, },
"repository": "github:polkadot-js/api", "repository": "github:polkadot-js/api",
"author": "Jaco Greeff <jacogr@gmail.com>", "author": "Jaco Greeff <jacogr@gmail.com>",
@@ -19,20 +23,20 @@
"bugs": "https://github.com/polkadot-js/api/issues", "bugs": "https://github.com/polkadot-js/api/issues",
"homepage": "https://github.com/polkadot-js/api/tree/master/packages/typegen#readme", "homepage": "https://github.com/polkadot-js/api/tree/master/packages/typegen#readme",
"dependencies": { "dependencies": {
"@babel/core": "^7.12.10", "@babel/core": "^7.13.8",
"@babel/register": "^7.12.10", "@babel/register": "^7.13.8",
"@babel/runtime": "^7.12.5", "@babel/runtime": "^7.13.9",
"@polkadot/api": "3.7.2", "@polkadot/api": "4.0.3",
"@polkadot/metadata": "3.7.2", "@polkadot/metadata": "4.0.3",
"@polkadot/rpc-provider": "3.7.2", "@polkadot/rpc-provider": "4.0.3",
"@polkadot/types": "3.7.2", "@polkadot/types": "4.0.3",
"@polkadot/util": "^5.5.1", "@polkadot/util": "^6.0.5",
"handlebars": "^4.7.6", "handlebars": "^4.7.7",
"websocket": "^1.0.33", "websocket": "^1.0.33",
"yargs": "^16.2.0" "yargs": "^16.2.0"
}, },
"devDependencies": { "devDependencies": {
"@types/websocket": "^1.0.1", "@types/websocket": "^1.0.2",
"@types/yargs": "^15.0.13" "@types/yargs": "^16.0.0"
} }
} }
@@ -7,8 +7,10 @@
let main; let main;
try { try {
main = require('../extractChain').main; main = require('../extractChain.cjs').main;
} catch (error) { } catch (error) {
process.env.JEST_WORKER_ID = '123';
require('@babel/register')({ require('@babel/register')({
extensions: ['.js', '.ts'], extensions: ['.js', '.ts'],
plugins: [ plugins: [
@@ -7,8 +7,10 @@
let main; let main;
try { try {
main = require('../fromChain').main; main = require('../fromChain.cjs').main;
} catch (error) { } catch (error) {
process.env.JEST_WORKER_ID = '123';
require('@babel/register')({ require('@babel/register')({
extensions: ['.js', '.ts'], extensions: ['.js', '.ts'],
plugins: [ plugins: [
@@ -7,8 +7,10 @@
let main; let main;
try { try {
main = require('../fromDefs').main; main = require('../fromDefs.cjs').main;
} catch (error) { } catch (error) {
process.env.JEST_WORKER_ID = '123';
require('@babel/register')({ require('@babel/register')({
extensions: ['.js', '.ts'], extensions: ['.js', '.ts'],
plugins: [ plugins: [
@@ -7,8 +7,10 @@
let main; let main;
try { try {
main = require('../interfacesTs').main; main = require('../interfacesTs.cjs').main;
} catch (error) { } catch (error) {
process.env.JEST_WORKER_ID = '123';
require('@babel/register')({ require('@babel/register')({
extensions: ['.js', '.ts'], extensions: ['.js', '.ts'],
plugins: [ plugins: [
@@ -7,8 +7,10 @@
let main; let main;
try { try {
main = require('../metadataMd').main; main = require('../metadataMd.cjs').main;
} catch (error) { } catch (error) {
process.env.JEST_WORKER_ID = '123';
require('@babel/register')({ require('@babel/register')({
extensions: ['.js', '.ts'], extensions: ['.js', '.ts'],
plugins: [ plugins: [
+12
View File
@@ -0,0 +1,12 @@
// Copyright 2017-2021 @polkadot/typegen authors & contributors
// SPDX-License-Identifier: Apache-2.0
import { packageInfo as apiInfo } from '@polkadot/api/packageInfo';
import { packageInfo as metaInfo } from '@polkadot/metadata/packageInfo';
import { packageInfo as providerInfo } from '@polkadot/rpc-provider/packageInfo';
import { packageInfo as typesInfo } from '@polkadot/types/packageInfo';
import { detectPackage } from '@polkadot/util';
import { packageInfo } from './packageInfo';
detectPackage(packageInfo, typeof __dirname !== 'undefined' && __dirname, [apiInfo, metaInfo, providerInfo, typesInfo]);
+5 -3
View File
@@ -87,12 +87,12 @@ function tsInt (definitions: Record<string, ModuleTypes>, def: TypeDef, imports:
} }
/** @internal */ /** @internal */
function tsResultGetter (definitions: Record<string, ModuleTypes>, resultName = '', getter: 'Ok' | 'Error', def: TypeDef, imports: TypeImports): string { function tsResultGetter (definitions: Record<string, ModuleTypes>, resultName = '', getter: 'Ok' | 'Err' | 'Error', def: TypeDef, imports: TypeImports): string {
const { info, type } = def; const { info, type } = def;
const asGetter = type === 'Null' const asGetter = type === 'Null'
? '' ? ''
: createGetter(definitions, `as${getter}`, info === TypeDefInfo.Tuple ? formatType(definitions, def, imports) : type, imports); : (getter === 'Error' ? ' /** @deprecated Use asErr */\n' : '') + createGetter(definitions, `as${getter}`, info === TypeDefInfo.Tuple ? formatType(definitions, def, imports) : type, imports);
const isGetter = createGetter(definitions, `is${getter}`, 'boolean', imports); const isGetter = (getter === 'Error' ? ' /** @deprecated Use isErr */\n' : '') + createGetter(definitions, `is${getter}`, 'boolean', imports);
switch (info) { switch (info) {
case TypeDefInfo.Plain: case TypeDefInfo.Plain:
@@ -110,6 +110,8 @@ function tsResultGetter (definitions: Record<string, ModuleTypes>, resultName =
function tsResult (definitions: Record<string, ModuleTypes>, def: TypeDef, imports: TypeImports): string { function tsResult (definitions: Record<string, ModuleTypes>, def: TypeDef, imports: TypeImports): string {
const [okDef, errorDef] = (def.sub as TypeDef[]); const [okDef, errorDef] = (def.sub as TypeDef[]);
const inner = [ const inner = [
tsResultGetter(definitions, def.name, 'Err', errorDef, imports),
// @deprecated, use Err
tsResultGetter(definitions, def.name, 'Error', errorDef, imports), tsResultGetter(definitions, def.name, 'Error', errorDef, imports),
tsResultGetter(definitions, def.name, 'Ok', okDef, imports) tsResultGetter(definitions, def.name, 'Ok', okDef, imports)
].join(''); ].join('');
+3
View File
@@ -1,4 +1,7 @@
// Copyright 2017-2021 @polkadot/typegen authors & contributors // Copyright 2017-2021 @polkadot/typegen authors & contributors
// SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: Apache-2.0
import './detectPackage';
export { packageInfo } from './packageInfo';
export { formatType } from './util/formatting'; export { formatType } from './util/formatting';
+6
View File
@@ -0,0 +1,6 @@
// Copyright 2017-2021 @polkadot/typegen authors & contributors
// SPDX-License-Identifier: Apache-2.0
// Auto-generated by @polkadot/dev, do not edit
export const packageInfo = { name: '@polkadot/typegen', version: '4.0.3' };
+2 -2
View File
@@ -70,8 +70,8 @@ export function setImports (allDefs: Record<string, ModuleTypes>, imports: TypeI
setImports(allDefs, imports, [typeDef.sub.type]); setImports(allDefs, imports, [typeDef.sub.type]);
} }
} else if (type.includes('[') && type.includes('|')) { } else if (type.includes('[') && type.includes('|')) {
// We split the types // We split the types (we already dod the check above, so safe-path should not be caught)
const splitTypes = /\[\s?(.+?)\s?\]/.exec(type)![1].split(/\s?\|\s?/); const splitTypes = (/\[\s?(.+?)\s?\]/.exec(type) || ['', ''])[1].split(/\s?\|\s?/);
setImports(allDefs, imports, splitTypes); setImports(allDefs, imports, splitTypes);
} else { } else {
+10 -5
View File
@@ -1,9 +1,13 @@
{ {
"name": "@polkadot/types-known", "name": "@polkadot/types-known",
"version": "3.7.2", "version": "4.0.3",
"type": "module",
"description": "A JavaScript wrapper for the Polkadot JsonRPC interface", "description": "A JavaScript wrapper for the Polkadot JsonRPC interface",
"main": "index.js", "main": "index.js",
"sideEffects": false, "sideEffects": [
"./detectPackage.js",
"./detectPackage.cjs"
],
"author": "Jaco Greeff <jacogr@gmail.com>", "author": "Jaco Greeff <jacogr@gmail.com>",
"maintainers": [], "maintainers": [],
"contributors": [], "contributors": [],
@@ -12,9 +16,10 @@
"bugs": "https://github.com/polkadot-js/api/issues", "bugs": "https://github.com/polkadot-js/api/issues",
"homepage": "https://github.com/polkadot-js/api/tree/master/packages/types-known#readme", "homepage": "https://github.com/polkadot-js/api/tree/master/packages/types-known#readme",
"dependencies": { "dependencies": {
"@babel/runtime": "^7.12.5", "@babel/runtime": "^7.13.9",
"@polkadot/types": "3.7.2", "@polkadot/networks": "^6.0.5",
"@polkadot/util": "^5.5.1", "@polkadot/types": "4.0.3",
"@polkadot/util": "^6.0.5",
"bn.js": "^4.11.9" "bn.js": "^4.11.9"
}, },
"devDependencies": { "devDependencies": {

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