Compare commits

...
165 Commits
Author SHA1 Message Date
Github Actions 9f2c3016d7 [CI Skip] 1.16.1
skip-checks: true
2020-05-26 15:03:50 +00:00
Jaco Greeff 938ace2342 1.16 (#2310) 2020-05-26 16:51:10 +02:00
Github Actions e5d2607dff [CI Skip] 1.16.0-beta.6
skip-checks: true
2020-05-26 12:58:13 +00:00
Jaco Greeff 50b8db2263 Update with new Babe digests (#2309)
* Update with new Babe digests

* Naming cleanups
2020-05-26 14:46:06 +02:00
Github Actions 91766a6885 [CI Skip] 1.16.0-beta.5
skip-checks: true
2020-05-26 12:02:14 +00:00
Jaco Greeff 4b1a9ab9e1 Perbill/Permill toHuman as percentage (#2307)
* Perbill/Permill toHuman as percentage

* Expectation to percentage
2020-05-26 13:51:05 +02:00
Github Actions 9a14c65336 [CI Skip] 1.16.0-beta.4
skip-checks: true
2020-05-26 07:30:37 +00:00
Jaco Greeff 4aa66fd4c6 Adjust Polkadot spec version/types (#2306)
* Adjust Polkadot spec version/types

* CHANGELOG
2020-05-26 09:20:15 +02:00
Github Actions 3d9c62d538 [CI Skip] 1.16.0-beta.3
skip-checks: true
2020-05-25 06:31:48 +00:00
Jaco Greeff 4156eb44ab Bump metadata (#2305)
* Bump metadata

* Rewrite yarn.lock
2020-05-25 08:20:45 +02:00
Github Actions 4b2d33693c [CI Skip] 1.16.0-beta.2
skip-checks: true
2020-05-24 16:49:59 +00:00
Jaco Greeff e8b127e177 Adjust sign options (#2304) 2020-05-24 18:40:39 +02:00
Github Actions b052b03f31 [CI Skip] 1.16.0-beta.1
skip-checks: true
2020-05-24 14:41:32 +00:00
Amaury Martiny 6727e12468 StatementKind: Regular and Saft (#2303) 2020-05-24 16:30:12 +02:00
Github Actions c130285651 [CI Skip] 1.16.0-beta.0
skip-checks: true
2020-05-24 07:36:17 +00:00
Jaco Greeff 47fc4a2b3c Bump deps w/ eslint (#2302)
* Bump deps w/ eslint

* Additional cleanups

* Additional

* @polkadot/types done

* Additional

* @polkadot/typegen done

* Additional

* @polkadot/rpc-core done

* Additional

* Additional

* Additional

* docs

* @polkadot/api-derive done

* @polkadot/api done

* @polkadot/api-contracts done

* Update tests
2020-05-24 09:24:45 +02:00
Github Actions 97cb408f36 [CI Skip] 1.15.1
skip-checks: true
2020-05-23 09:35:31 +00:00
Jaco Greeff dde7c8085a 1.15 (#2301) 2020-05-23 11:26:05 +02:00
Github Actions 8b02fafb99 [CI Skip] 1.15.0-beta.9
skip-checks: true
2020-05-23 09:05:12 +00:00
Jaco Greeff 393f46ba4a Bump metadata (#2300) 2020-05-23 10:54:28 +02:00
455f5ad834 Allow keyPrefix to accept an additional argument for double maps (#2230)
* Allow keyPrefix to accept an additional argument for double maps

* Make key creators accept an optional parameter for key construction

* Remove .only from a test case

Co-authored-by: Xiliang Chen <xlchen1291@gmail.com>

* Cache prefix key when no arguments are supplied

* Address review comments

* Update packages/metadata/src/Decorated/storage/fromMetadata/createFunction.spec.ts

Co-authored-by: Xiliang Chen <xlchen1291@gmail.com>
Co-authored-by: Jaco Greeff <jacogr@gmail.com>
2020-05-23 10:51:38 +02:00
Github Actions 674324e7f9 [CI Skip] 1.15.0-beta.8
skip-checks: true
2020-05-21 09:08:13 +00:00
Jaco Greeff b0dc7cf451 Bump metadata (#2297)
* Bump metadata

* Deps

* Regen

* Update sig for new signed extensions
2020-05-21 10:56:56 +02:00
Github Actions cbe1b2b1ce [CI Skip] 1.15.0-beta.7
skip-checks: true
2020-05-20 22:08:39 +00:00
Dan Forbes 4bd2f2fc32 Add WeightToFeeCoefficient type (#2296)
Added to support paritytech/substrate#6076
2020-05-20 23:56:04 +02:00
Github Actions 053112470d [CI Skip] 1.15.0-beta.6
skip-checks: true
2020-05-19 14:38:35 +00:00
Joshy Orndorff acdf27a272 spelling; efect -> effect (#2295) 2020-05-19 16:15:58 +02:00
Github Actions f70b32ba76 [CI Skip] 1.15.0-beta.5
skip-checks: true
2020-05-19 08:41:46 +00:00
Jaco Greeff 67a3376ef8 POC for a rough derive cache (#2293)
* POC for a rough derive cache

* With expiry

* Cache cleanups

* Memory cache

* Small cleanups
2020-05-19 10:29:40 +02:00
Github Actions eb06bb6e93 [CI Skip] 1.15.0-beta.4
skip-checks: true
2020-05-19 05:42:16 +00:00
Paweł Nguyen f8f7e92da4 Fix a minor typo in cookbook blocks docs (#2294) 2020-05-19 07:29:27 +02:00
Github Actions d0fd3eca25 [CI Skip] 1.15.0-beta.3
skip-checks: true
2020-05-18 08:32:29 +00:00
Jaco Greeff dac1df35de stakerRewards filters, re-org (#2292) 2020-05-18 10:20:09 +02:00
Github Actions 597563d2bb [CI Skip] 1.15.0-beta.2
skip-checks: true
2020-05-16 12:04:58 +00:00
Jaco Greeff f825c7f187 Fixed128 -> Fixed64 in old versions 2020-05-16 13:54:36 +02:00
Jaco Greeff 2e71a6160e Multiplier -> Fixed128 (#2290) 2020-05-16 13:52:56 +02:00
Github Actions c076c37119 [CI Skip] 1.15.0-beta.1
skip-checks: true
2020-05-16 06:49:21 +00:00
Amaury Martiny 0e18fdbccc Add transactionVersion to ExtrinsicPayload (#2287) 2020-05-16 08:37:29 +02:00
Github Actions c3eebd8fbe [CI Skip] 1.15.0-beta.0
skip-checks: true
2020-05-15 11:46:27 +00:00
Jaco Greeff 45786b31da Bump deps (#2286)
* Bump deps

* Linting cleanups
2020-05-15 13:35:15 +02:00
Github Actions f348e34de7 [CI Skip] 1.14.1
skip-checks: true
2020-05-14 14:02:15 +00:00
Jaco Greeff 337de79bef 1.14 (#2281) 2020-05-14 15:51:48 +02:00
Github Actions a13b51b985 [CI Skip] 1.14.0-beta.20
skip-checks: true
2020-05-14 06:17:01 +00:00
Jaco Greeff c5c77c9b52 Bump deps (#2280) 2020-05-14 08:05:15 +02:00
Drew StoneandJaco Greeff 2a033e5634 Update evm definitions to include vicinity (#2279)
* Update definitions.ts

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

Co-authored-by: Jaco Greeff <jacogr@gmail.com>
2020-05-14 07:51:29 +02:00
Github Actions 00ffb358cb [CI Skip] 1.14.0-beta.19
skip-checks: true
2020-05-13 16:07:57 +00:00
Jaco Greeff 66d1bbe4cb Don't re-calculate extinsic hash (status updates) (#2277) 2020-05-13 17:56:26 +02:00
Github Actions 3baf36e9e6 [CI Skip] 1.14.0-beta.18
skip-checks: true
2020-05-13 07:44:25 +00:00
Jaco Greeff e3abb95111 Bump metadata (#2276) 2020-05-13 09:32:26 +02:00
Github Actions da281c9531 [CI Skip] 1.14.0-beta.17
skip-checks: true
2020-05-13 06:59:03 +00:00
Jaco Greeff c0e3026772 Add signedExtensions to SignerPayload (#2275) 2020-05-13 08:49:31 +02:00
Github Actions 757da68675 [CI Skip] 1.14.0-beta.16
skip-checks: true
2020-05-12 21:27:47 +00:00
Jaco Greeff f145488314 Add StatementKind & PrevalidateAttests for Polkadot claims (#2273)
* Add StatementKind for Polkadot claims

* PrevalidateAttests extension
2020-05-12 23:14:32 +02:00
Github Actions 0ce10d2938 [CI Skip] 1.14.0-beta.15
skip-checks: true
2020-05-12 20:58:34 +00:00
Jaco Greeff 6f2d62bb3b Cater for old/new style DepositOf tuples (#2272)
* Cater for old/new style DepositOf tuples

* Remove unused api on parse
2020-05-12 22:45:53 +02:00
Github Actions fc7c8310ae [CI Skip] 1.14.0-beta.14
skip-checks: true
2020-05-12 20:16:47 +00:00
Jaco Greeff c9921f002f Cater for Check{Spec, Tx}Version extensions (#2270)
* Cater for Check{Spec, Tx}Version extensions

* Fix tests
2020-05-12 22:03:20 +02:00
Github Actions 6b8a65eb31 [CI Skip] 1.14.0-beta.13
skip-checks: true
2020-05-12 19:09:51 +00:00
Jaco Greeff 0cf29719b3 Fix ProxyState type (#2269)
* Fix ProxyState type

* Generate
2020-05-12 20:58:40 +02:00
Github Actions abecabdaed [CI Skip] 1.14.0-beta.12
skip-checks: true
2020-05-12 18:31:46 +00:00
Jaco Greeff 0c5b69bea1 Extra signedExtensions retrieved via specVersion (#2268)
* Extra signedExtensions retrieved via  specVersion

* Fix tests
2020-05-12 20:20:24 +02:00
Github Actions 7b3f24b1f5 [CI Skip] 1.14.0-beta.11
skip-checks: true
2020-05-12 16:43:19 +00:00
Jaco Greeff d1f8f8b5e8 Extend SignerPayload with extra tx/extensions (#2267)
* Extend SignerPayload with extra tx/extensions

* Update registry.ts

* Update extrinsic.ts

* Linting options
2020-05-12 18:32:18 +02:00
Github Actions 3f060b9e0d [CI Skip] 1.14.0-beta.10
skip-checks: true
2020-05-12 15:00:09 +00:00
Jaco Greeff fe69f70539 DispatchInfo paysFee to Pays enum (#2266)
* DispatchInfo paysFee to Pays enum

* Update Kusama types
2020-05-12 16:46:07 +02:00
Github Actions 578c4ffb69 [CI Skip] 1.14.0-beta.9
skip-checks: true
2020-05-12 09:56:51 +00:00
Jaco Greeff 66aa38000b Derive for democracy locks (#2264)
* Derive for democracy locks

* Cater for old referendums

* Split lock parsing
2020-05-12 11:44:54 +02:00
Github Actions 50ddff6907 [CI Skip] 1.14.0-beta.8
skip-checks: true
2020-05-11 16:16:49 +00:00
Paweł Nguyen 14874f41f7 Fix a typo in Query docs - freee -> free (#2263)
This fixes a typo in Query Subscriptions with params docs. `freee` -> `free`
2020-05-11 18:05:43 +02:00
Github Actions 5a11b0c701 [CI Skip] 1.14.0-beta.7
skip-checks: true
2020-05-11 12:56:11 +00:00
Jaco Greeff 8491ab8ca6 import type BN (as applicable) (#2262) 2020-05-11 14:45:14 +02:00
Github Actions 4f5cb0f35e [CI Skip] 1.14.0-beta.6
skip-checks: true
2020-05-11 10:14:17 +00:00
Jaco Greeff 53d081df65 Bump berry (#2261) 2020-05-11 12:02:05 +02:00
Github Actions 6b5dbb6948 [CI Skip] 1.14.0-beta.5
skip-checks: true
2020-05-11 08:29:29 +00:00
Jaco Greeff 3879986a75 Bump common (#2260) 2020-05-11 10:20:21 +02:00
Github Actions 378ca10580 [CI Skip] 1.14.0-beta.4
skip-checks: true
2020-05-11 07:05:13 +00:00
Jaco Greeff d75d8bec0e Additional mortal era tests (#2259)
* Additional moratl era tests

* birth !== current (output the same)
2020-05-11 08:53:05 +02:00
Github Actions 6f6a32a7a2 [CI Skip] 1.14.0-beta.3
skip-checks: true
2020-05-08 09:59:57 +00:00
Jaco Greeff 226426e67e Add older heartbeats struct (#2255) 2020-05-08 11:50:18 +02:00
Github Actions 66e2a4d298 [CI Skip] 1.14.0-beta.2
skip-checks: true
2020-05-08 08:41:41 +00:00
Arjan Zijderveld 664151f829 Added validatorsLen to Heartbeat struct (#2254) 2020-05-08 10:31:04 +02:00
Github Actions 49b00524b1 [CI Skip] 1.14.0-beta.1
skip-checks: true
2020-05-07 07:17:07 +00:00
Jaco Greeff 401784b7e6 Historic queries FAQ (#2253) 2020-05-07 09:05:51 +02:00
Github Actions 99873e901a [CI Skip] 1.14.0-beta.0
skip-checks: true
2020-05-07 07:02:00 +00:00
Jaco Greeff 72d131f62f Ensure metadata is only retrieved once on startup (#2252)
* Ensure metadata is only retrieved once on startup

* Ensure we set rx.runtimeVersion
2020-05-07 08:50:36 +02:00
Github Actions c412f7fa11 [CI Skip] 1.13.1
skip-checks: true
2020-05-06 18:33:13 +00:00
Jaco Greeff a1ad90c2b4 1.13 (#2248)
* 1.13

* Add grandpa_roundState RPC

* RPC interfaces
2020-05-06 20:22:18 +02:00
Github Actions 92f62bfa15 [CI Skip] 1.13.0-beta.19
skip-checks: true
2020-05-06 16:48:28 +00:00
Jaco Greeff fa9c5778be Adjust Centrifuge versions (#2247) 2020-05-06 18:37:44 +02:00
Github Actions e6f877621a [CI Skip] 1.13.0-beta.18
skip-checks: true
2020-05-06 15:22:36 +00:00
Jaco Greeff 5c35a70e9d Centrifuge Chain Node (#2246) 2020-05-06 17:11:33 +02:00
Github Actions a287096cc3 [CI Skip] 1.13.0-beta.17
skip-checks: true
2020-05-06 13:47:59 +00:00
Jaco Greeff c35f31bfbd Adjust mock timeouts (#2244)
* Adjust mock timeouts

* Play with timeouts some more...

* Ooops, overzealous search-and-replace
2020-05-06 15:36:20 +02:00
Jaco Greeff 718afa91e3 Multiple endpoints CHANGELOG (#2243) 2020-05-06 15:10:37 +02:00
Hoani BrysonandJaco Greeff 102a06b0f2 Multiple Endpoint support for WsProvider (#2234)
* Fix incorrect ws connect test cases

* Make endpoint an array of endpoints

* Add requirement that WsProvider endpoint arrays must not be empty

* Simple endpoint increment

* Add multi-endpoint test for endpoint closing its connection

* Implement endpoint round robin

* Revert change to mock's TEST_WS_URL

* Address Lint errors

* Change endpoint variable to plural in WsProvider

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

* Review corrections to WsProvider

* Grouping improvement in WsProvider connect

* Correct endpoint logging to only show the specific endpoint involved

* Correct ordering of endpoint increment on connect

Co-authored-by: Jaco Greeff <jacogr@gmail.com>
2020-05-06 14:42:30 +02:00
Github Actions 58f0df1ef0 [CI Skip] 1.13.0-beta.16
skip-checks: true
2020-05-06 12:08:40 +00:00
Jaco Greeff a458589222 Fix CompactAssignment decoding (#2242)
* Fix CompactAssignment decoding

* CHANGELOG
2020-05-06 13:56:17 +02:00
Github Actions deef4ce4c7 [CI Skip] 1.13.0-beta.15
skip-checks: true
2020-05-06 08:36:29 +00:00
Jaco Greeff f5d2449407 Grandpa Equivocation types (#2239)
* Grandpa Equivocation types

* typo
2020-05-06 10:25:37 +02:00
Github Actions 8bb1d1259e [CI Skip] 1.13.0-beta.14
skip-checks: true
2020-05-06 08:23:10 +00:00
Jaco Greeff abd860d548 Bump deps (#2240)
* Bump deps

* Jest revert
2020-05-06 10:11:58 +02:00
Github Actions 25936d882f [CI Skip] 1.13.0-beta.13
skip-checks: true
2020-05-06 06:29:54 +00:00
Keith YeungandJaco Greeff 9deaff54e4 Make the 2nd argument to SubmittableExtrinsic.sign/signAsync optional (#2238)
* Make the 2nd argument to SubmittableExtrinsic.sign/signAsync optional

* Use default argument for optionsOrNonce

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

Co-authored-by: Jaco Greeff <jacogr@gmail.com>
2020-05-06 08:17:51 +02:00
Github Actions bc479a995b [CI Skip] 1.13.0-beta.12
skip-checks: true
2020-05-05 09:44:03 +00:00
Jaco Greeff 458b7fa7e4 Update with latest Substrate metadata (#2233) 2020-05-05 11:33:04 +02:00
Github Actions 2fc17a66e1 [CI Skip] 1.13.0-beta.11
skip-checks: true
2020-05-05 05:26:31 +00:00
codingsh 94f81db568 #2182 - add: search for docs (#2232) 2020-05-05 07:16:39 +02:00
Github Actions e83d97c849 [CI Skip] 1.13.0-beta.10
skip-checks: true
2020-05-05 05:09:33 +00:00
Joshy Orndorff 4a497fa970 minor typo: RC -> RPC (#2229) 2020-05-05 06:58:52 +02:00
Github Actions cb40d459b5 [CI Skip] 1.13.0-beta.9
skip-checks: true
2020-05-04 18:40:00 +00:00
Jaco Greeff c70cdb351f Additional modules/methods in RPC samples 2020-05-04 20:29:02 +02:00
Github Actions 001aa0d011 [CI Skip] 1.13.0-beta.8
skip-checks: true
2020-05-04 15:58:01 +00:00
Jaco Greeff 961d27ad46 Update CHANGELOG.md 2020-05-04 17:47:09 +02:00
Github Actions 1c09bb69dd [CI Skip] 1.13.0-beta.7
skip-checks: true
2020-05-04 13:32:30 +00:00
Xiliang ChenandJaco Greeff 174510a928 use handlebars for code generation (#2228)
* use handlebars for code generation

* update docs

* fix isStrict

* fix lint

* Apply suggestions from code review

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

* convert consts

* keep empty lines in doc comments

* update rpc

* update tx

* update interfaceRegistry

* update tsDef

* remove no longer used code

Co-authored-by: Jaco Greeff <jacogr@gmail.com>
2020-05-04 15:21:09 +02:00
Github Actions 39ed76f2de [CI Skip] 1.13.0-beta.6
skip-checks: true
2020-05-04 12:20:51 +00:00
Jaco Greeff 7d1c93db59 Update CHANGELOG.md 2020-05-04 14:08:18 +02:00
Github Actions e9b1b4ee77 [CI Skip] 1.13.0-beta.5
skip-checks: true
2020-05-01 19:11:49 +00:00
Jaco Greeff 2367978f6e Remove polkadot metadata (not mainatained, outdated) (#2227) 2020-05-01 21:01:08 +02:00
Github Actions e77050b9f5 [CI Skip] 1.13.0-beta.4
skip-checks: true
2020-04-30 13:24:43 +00:00
Jaco Greeff 844d1a2928 Allow failures on preimage (instead of swallow) (#2225) 2020-04-30 15:14:56 +02:00
Github Actions 6a70beda0f [CI Skip] 1.13.0-beta.3
skip-checks: true
2020-04-30 09:16:39 +00:00
Alexander Krupenkin 05a834b822 Fix extrinsic ECDSA signatures (#2222)
* Fix extrinsic ECDSA signatures

* Fix lint
2020-04-30 11:04:55 +02:00
Github Actions 6a3af506a4 [CI Skip] 1.13.0-beta.2
skip-checks: true
2020-04-30 07:37:46 +00:00
Jaco Greeff c82b85ef79 Bump deps (#2224) 2020-04-30 09:27:04 +02:00
Github Actions 91ab81ef60 [CI Skip] 1.13.0-beta.1
skip-checks: true
2020-04-30 05:47:17 +00:00
Jaco Greeff 3665690444 Beta bump (#2223) 2020-04-30 07:37:12 +02:00
Github Actions 03dcefceb5 [CI Skip] 1.12.2
skip-checks: true
2020-04-29 22:56:16 +00:00
Jaco Greeff e84be032f4 1.12.2 (stable util) 2020-04-30 00:46:45 +02:00
Github Actions 033ff7a28c [CI Skip] 1.12.1
skip-checks: true
2020-04-29 22:23:45 +00:00
Jaco Greeff 7c8b2abf92 1.12 (#2221) 2020-04-30 00:13:27 +02:00
Github Actions 5312ec1f3a [CI Skip] 1.12.0-beta.15
skip-checks: true
2020-04-29 16:13:00 +00:00
Matej Nemček cdfbf91ee6 added Kodadot to @polkadot/api users section (#2220) 2020-04-29 18:00:50 +02:00
Github Actions 14f2abdc37 [CI Skip] 1.12.0-beta.14
skip-checks: true
2020-04-29 15:50:05 +00:00
Jake Naviasky 04c8d49e9d Add configurable provider auto-reconnect time. (#2215) 2020-04-29 17:39:31 +02:00
Github Actions 722929d0d4 [CI Skip] 1.12.0-beta.13
skip-checks: true
2020-04-29 14:57:15 +00:00
Jaco Greeff d1fae523ac Fix CompactAssignments types (#2219)
* Fix CompactAssignments types

* Cleanup mistaken type adjustments
2020-04-29 16:45:59 +02:00
Github Actions ce9a92cdc0 [CI Skip] 1.12.0-beta.12
skip-checks: true
2020-04-27 17:09:59 +00:00
Jaco Greeff 3de09a2e27 Hack around preimage failures (#2217) 2020-04-27 18:59:18 +02:00
Github Actions f28479180f [CI Skip] 1.12.0-beta.11
skip-checks: true
2020-04-27 14:04:29 +00:00
Jaco Greeff 0d1d42f6c2 Update promise combineLatest with generics (#2214) 2020-04-27 15:53:17 +02:00
Github Actions c93dad0bc5 [CI Skip] 1.12.0-beta.10
skip-checks: true
2020-04-27 07:04:47 +00:00
Jaco Greeff e3d3a1ff71 Handle no keysReturn StorageChangeSet with no keys (#2212) 2020-04-27 08:54:02 +02:00
Github Actions 1c8bd896e1 [CI Skip] 1.12.0-beta.9
skip-checks: true
2020-04-26 11:56:32 +00:00
Jaco Greeff e0119c1873 Bump metadata to current Substrate master (incl. types) (#2210) 2020-04-26 13:46:36 +02:00
Github Actions defe81e560 [CI Skip] 1.12.0-beta.8
skip-checks: true
2020-04-26 11:42:47 +00:00
Xiliang Chen 932122cd21 subscribeStorage parameter should be optional (#2208) 2020-04-26 13:32:43 +02:00
Github Actions 40d035eca7 [CI Skip] 1.12.0-beta.7
skip-checks: true
2020-04-25 07:58:44 +00:00
Jaco Greeff a135abaea2 Fix flags (council may not exist) (#2207) 2020-04-25 09:47:46 +02:00
Github Actions 00b8c10881 [CI Skip] 1.12.0-beta.6
skip-checks: true
2020-04-24 14:34:08 +00:00
Jaco Greeff 11e7b90918 Bump deps (#2206) 2020-04-24 16:22:18 +02:00
Github Actions ae74467e6a [CI Skip] 1.12.0-beta.5
skip-checks: true
2020-04-24 13:40:02 +00:00
Jeremías Díaz 5a929d3810 remove unnecessary parentheses and duplicate types (#2204)
* remove unnecessary parentheses and duplicate types

* fix: remove test code
2020-04-24 15:28:47 +02:00
Github Actions 63732f1456 [CI Skip] 1.12.0-beta.4
skip-checks: true
2020-04-24 08:54:04 +00:00
Jaco Greeff ea6bb83c01 Voting delegations (#2205) 2020-04-24 10:41:30 +02:00
Github Actions d6a443ca2a [CI Skip] 1.12.0-beta.3
skip-checks: true
2020-04-23 09:50:46 +00:00
Jaco Greeff d983ee106c migrateEra is first stakerPayouts era (#2202) 2020-04-23 11:39:39 +02:00
Github Actions beed1df5bd [CI Skip] 1.12.0-beta.2
skip-checks: true
2020-04-22 09:04:55 +00:00
Jaco Greeff 426aef6088 Update .123trigger 2020-04-22 10:55:01 +02:00
Github Actions 9be9b3fb83 [CI Skip] 1.12.0-beta.1
skip-checks: true
2020-04-22 07:56:01 +00:00
Jaco Greeff 8676f30cbf Reset to beta 2020-04-22 09:44:59 +02:00
Github Actions 154561c34c [CI Skip] 1.11.2
skip-checks: true
2020-04-22 07:40:26 +00:00
Jaco Greeff 714b242ec0 0.11.2 (#2200) 2020-04-22 09:30:02 +02:00
Github Actions 32ce650ee1 [CI Skip] 1.12.0-beta.0
skip-checks: true
2020-04-21 17:05:00 +00:00
Jaco Greeff 3715df2f5b Additional parachains types (#2199)
* Additional parachains types

* missing extensions listing

* trigger
2020-04-21 18:53:00 +02:00
296 changed files with 9502 additions and 12326 deletions
+3 -1
View File
@@ -1,3 +1,5 @@
22 24
1.4.2 1.4.2
1.6.2 1.6.2
1.11.2
1.12.2
+1
View File
@@ -1,3 +1,4 @@
.eslintrc.js
**/build/* **/build/*
**/coverage/* **/coverage/*
**/node_modules/* **/node_modules/*
+14 -8
View File
File diff suppressed because one or more lines are too long
+70
View File
@@ -1,3 +1,73 @@
# 1.16.1 May 26, 2020
- Support for Polkadot CC1 types & signed extensions
- Add support for Babe VRF secondary digests (author extraction)
- Adjust `Perbill/Permill` `toHuman()` formatting to output percentage
- Support for latest Substrate types & metadata
- Update to latest TypeScript, eslint & typescript-eslint
- `@polkadot/util` 2.11
# 1.15.1 May 23, 2020
- Adjust `keyPrefix()` with DoubleMap args (Thanks to https://github.com/KiChjang)
- Added `WeightToFeeCoefficient` type (Thanks to https://github.com/danforbes)
- Spelling fixes for console logs (Thanks to https://github.com/JoshOrndorff)
- Spelling fixes in cookbook (Thanks to https://github.com/pawelnguyen)
- Add `transactionVersion` getter in payloads (Thanks to https://github.com/amaurymartiny)
- Adjust `stakerRewards` derive ordering for improved on-payout refreshes
- Baseline implementation for derive caching infrastructure
- Adjust `Multiplier` type to `Fixed128` (as per latest Substrate)
- Updated to latest Substrate metadata & add new types
# 1.14.1 May 14, 2020
- **Important** `DispatchInfo` changed `paysFee` to an enum, if using an older version use, `DispatchInfo: 'DispatchInfoTo244'`
- Align imOnline `Heartbeat` with Substrate (Thanks to https://github.com/arjanz)
- Adust EVM types to include `Vicinity` (Thanks to https://github.com/drewstone)
- Add `derive.democracy.locks` to return extended lock info based on votes
- Ensure metadata is only requested once upon startup (bypass on upgrade subscriptions)
- Expand testing around `ExtrinsicEra` construction
- Expand `Registry` to direct access to available signed extensions (in addition to exposed types)
- Cater for new `CheckSpecVersion` and `CheckTxVersion` signed extensions (with `SignerPayload` adjustments)
- Cater for new `PrevalidateAttests` signed extensions (Polkadot claims)
- Don't re-calculate submittable extrinsic hash on status checks (optimization)
- Support for both old/new Tuples in `democracy.depositOf` in derives
- Fix democracy `ProxyState` types
- Extends types for Polkadot claims
- Update `@polkadot/util` to 2.10
# 1.13.1 May 6, 2020
- Add support for ECDSA keypairs in extrinsic signers (Thanks to https://github.com/akru)
- Rework type generation to use templating for better maintenance (Thanks to https://github.com/xlc)
- Adjust extrinsic `sign/signAsync` signature to optional options (Thanks to https://github.com/KiChjang)
- Support round-robin endpoints in the `WsProvider` with array of urls (Thanks to https://github.com/hoani)
- Remove static test-only metadata for Polkadot dev chains (not updated regularly, Substrate dev to remain)
- Revert error swallow for wrong preimage data (temp. override for Kusama upgrade with no migration)
- Fix `.encodedLength` calculation on `[Type; N]` types
- Add new `rpc.grandpa.roundState` RPC
- Update types & metadata as per latest Substrate master
- Adjust Centrifuge starting version
# 1.12.2 Apr 30, 2020
- Update `@polkadot/util` to stable 2.9.1 (sadly missed in the previous version, stable should match to stable)
# 1.12.1 Apr 29, 2020
- Fix `CompactAssignments` types (Thanks to https://github.com/arjanz)
- Provider ayo-connect now allows for interval config (Thanks to https://github.com/jnaviask)
- Cleanup generation for c-like enums (Thanks to https://github.com/monitz87)
- Allow subscription to all storage keys, alignment with Substrate (Thanks to https://github.com/xlc)
- Cater for vote delegations in democracy derives
- Cleanup account derive flags where to allow for optional council modules
- Allow generic types in ApiPromise.combineLatest
- Update to latest substrate metadata
# 1.11.2 Apr 22, 2020
- Small patch to add missing Polkadot master types (will be in next Kusama update)
# 1.11.1 Apr 21, 2020 # 1.11.1 Apr 21, 2020
- **Important** Substrate master has an updated `Weight` (to `u64`), on older chains apply `Weight: 'u32'` (This does affect event decoding if wrongly set) - **Important** Substrate master has an updated `Weight` (to `u64`), on older chains apply `Weight: 'u32'` (This does affect event decoding if wrongly set)
+8 -2
View File
@@ -20,7 +20,8 @@ module.exports = {
}, },
{ text: 'GitHub', link: 'https://github.com/polkadot-js/api' } { text: 'GitHub', link: 'https://github.com/polkadot-js/api' }
], ],
search: false, search: true,
searchMaxSuggestions: 10,
sidebar: [ sidebar: [
{ {
title: 'Getting started', title: 'Getting started',
@@ -97,5 +98,10 @@ module.exports = {
['/types/', '@polkadot/types'], ['/types/', '@polkadot/types'],
'/CONTRIBUTING.md' '/CONTRIBUTING.md'
] ]
} },
plugins: [
['@vuepress/search', {
searchMaxSuggestions: 10
}]
]
}; };
+3
View File
@@ -1,5 +1,8 @@
$accentColor = #fd8824 $accentColor = #fd8824
$textColor = #2c3e50 $textColor = #2c3e50
$borderColor = #eaecef
$codeBgColor = #282c34
$arrowBgColor = #ccc
.home .hero .description, .home .hero .description,
.home .feature h2, .home .feature h2,
+1 -1
View File
@@ -25,7 +25,7 @@ signedBlock.block.extrinsics.forEach((ex, index) => {
## How do I extract the block author? ## How do I extract the block author?
Th block author is encoded inside the consensus logs for the block. To extract, you need to decode the log (which the API does do) and then map the index of the validator to the list of session validators. This extraction is however available on the api derive for new head subscriptions, which returns an extended header with the author populated (assuming that the digest logs are known). The block author is encoded inside the consensus logs for the block. To extract, you need to decode the log (which the API does do) and then map the index of the validator to the list of session validators. This extraction is however available on the api derive for new head subscriptions, which returns an extended header with the author populated (assuming that the digest logs are known).
```js ```js
// subscribe to all new headers (with extended info) // subscribe to all new headers (with extended info)
@@ -1,6 +1,7 @@
/* eslint-disable header/header */ /* eslint-disable header/header */
/* eslint-disable @typescript-eslint/require-await */ /* eslint-disable @typescript-eslint/require-await */
/* eslint-disable @typescript-eslint/unbound-method */ /* eslint-disable @typescript-eslint/unbound-method */
/* eslint-disable @typescript-eslint/no-floating-promises */
// Import the API // Import the API
const { ApiPromise } = require('@polkadot/api'); const { ApiPromise } = require('@polkadot/api');
@@ -1,6 +1,7 @@
/* eslint-disable header/header */ /* eslint-disable header/header */
/* eslint-disable @typescript-eslint/require-await */ /* eslint-disable @typescript-eslint/require-await */
/* eslint-disable @typescript-eslint/unbound-method */ /* eslint-disable @typescript-eslint/unbound-method */
/* eslint-disable @typescript-eslint/no-floating-promises */
// Import the API // Import the API
const { ApiPromise } = require('@polkadot/api'); const { ApiPromise } = require('@polkadot/api');
@@ -1,6 +1,7 @@
/* eslint-disable header/header */ /* eslint-disable header/header */
/* eslint-disable @typescript-eslint/require-await */ /* eslint-disable @typescript-eslint/require-await */
/* eslint-disable @typescript-eslint/unbound-method */ /* eslint-disable @typescript-eslint/unbound-method */
/* eslint-disable @typescript-eslint/no-floating-promises */
// Import the API // Import the API
const { ApiPromise } = require('@polkadot/api'); const { ApiPromise } = require('@polkadot/api');
@@ -1,6 +1,7 @@
/* eslint-disable header/header */ /* eslint-disable header/header */
/* eslint-disable @typescript-eslint/require-await */ /* eslint-disable @typescript-eslint/require-await */
/* eslint-disable @typescript-eslint/no-var-requires */ /* eslint-disable @typescript-eslint/no-var-requires */
/* eslint-disable @typescript-eslint/no-floating-promises */
// Import the API & Provider and some utility functions // Import the API & Provider and some utility functions
const { ApiPromise } = require('@polkadot/api'); const { ApiPromise } = require('@polkadot/api');
@@ -1,6 +1,7 @@
/* eslint-disable header/header */ /* eslint-disable header/header */
/* eslint-disable @typescript-eslint/require-await */ /* eslint-disable @typescript-eslint/require-await */
/* eslint-disable @typescript-eslint/unbound-method */ /* eslint-disable @typescript-eslint/unbound-method */
/* eslint-disable @typescript-eslint/no-floating-promises */
// Import the API & Provider and some utility functions // Import the API & Provider and some utility functions
const { ApiPromise, WsProvider } = require('@polkadot/api'); const { ApiPromise, WsProvider } = require('@polkadot/api');
+13
View File
@@ -63,3 +63,16 @@ Due to these customizations and differences that bleed through to the transactio
Recently Substrate master updated the `Weight` type from `u32` -> `u64`. This type is used in the `DispatchInfo` struct in the `system.ExtrinsicSuccess` events, to return the applied call weights as well as the resulting fees. Since the API master branch tracks Substrate master, this means the change has been applied by default, with the default set to `u64`. Recently Substrate master updated the `Weight` type from `u32` -> `u64`. This type is used in the `DispatchInfo` struct in the `system.ExtrinsicSuccess` events, to return the applied call weights as well as the resulting fees. Since the API master branch tracks Substrate master, this means the change has been applied by default, with the default set to `u64`.
If you are on a chain that has not been upgraded yet, you need to add `Weight: 'u32'` to your types to allow for successful parsing of all events. Without this override, parsing will fail. As soon as one event in the `Vec<EventRecord>` structure from `system.events` fails to parse, all subsequent events are affected and the decoding will return an error. If you are on a chain that has not been upgraded yet, you need to add `Weight: 'u32'` to your types to allow for successful parsing of all events. Without this override, parsing will fail. As soon as one event in the `Vec<EventRecord>` structure from `system.events` fails to parse, all subsequent events are affected and the decoding will return an error.
## When querying older blocks & events, it fails on parsing
Upon initialization, the API is decorated with the [current on-chain metadata](basics.md#metadata) and (if [available](https://github.com/polkadot-js/api/tree/master/packages/types-known/src)) the specific types for the runtime version is added. This allows the API to decode all current (as per the on-chain info) state and extrinsics.
When the chain is upgraded, new metadata (indicating new events, storage and extrinsics) is added on-chain. Additionally this generally goes hand in-hand with changes in types, i.e. fields may be addedd or removed or state that was used could now be migrated to new locations. In most cases, this would mean that the current chain information cannot be used to parse older entries pre-upgrade. A typical consequence of this is that any `.at(...)` or `.range(...)` queries pre-upgrade may fail.
As of the current time, there is no automatic injection of older metadata (based on the runtime version at a specific block) nor decoration of older types if they are available. It can be emulated with what the API will do to handle these cases when it adds a `.historic(...)` query type -
- querying the runtime version at the parent of older block you wish to retrieve
- retrieving and injecting the metadata from the parent block (if the runtime version has changed)
- inject any specific older types for the state at that point
- finally retrieve the actual entry via an `.at(...)` query
+1 -1
View File
@@ -26,7 +26,7 @@ If we had a query with parameters, i.e. where we wish to perform a query for a s
// Subscribe to balance changes for our account // Subscribe to balance changes for our account
const unsub = await api.query.system.account(ADDR, ({ nonce, data: balance }) => { const unsub = await api.query.system.account(ADDR, ({ nonce, data: balance }) => {
console.log(`free balance is ${balance.freee} with ${balance.reserved} reserved and a nonce of ${nonce}`); console.log(`free balance is ${balance.free} with ${balance.reserved} reserved and a nonce of ${nonce}`);
}); });
``` ```
+9 -4
View File
@@ -1,6 +1,6 @@
# Custom RPC # Custom RPC
In previous sections we looked at the injection of types, as in use and defined in modules from the node. Another area that can be customized is RC definitions, and like with the types, the API provides the capability to add user-defined RPCs (in addition to the Polkadot/Substrate base) to allow use of these RPCs via the API. In previous sections we looked at the injection of types, as in use and defined in modules from the node. Another area that can be customized is RPC definitions, and like with the types, the API provides the capability to add user-defined RPCs (in addition to the Polkadot/Substrate base) to allow use of these RPCs via the API.
## Custom definitions ## Custom definitions
@@ -25,9 +25,14 @@ const api = await ApiPromise.create({
} }
], ],
type: 'Balance' type: 'Balance'
} },
} anotherMethod: { ... },
} ...
},
anotherModule: { ... },
...
},
...
}); });
``` ```
+1 -1
View File
@@ -9,5 +9,5 @@
"packages": [ "packages": [
"packages/*" "packages/*"
], ],
"version": "1.11.1" "version": "1.16.1"
} }
+7 -6
View File
@@ -7,7 +7,7 @@
"packages/*" "packages/*"
], ],
"resolutions": { "resolutions": {
"typescript": "^3.8.3" "babel-core": "^7.0.0-bridge.0"
}, },
"scripts": { "scripts": {
"build": "yarn build:interfaces && polkadot-dev-build-ts && (cd packages/typegen && copyfiles scripts/* build)", "build": "yarn build:interfaces && polkadot-dev-build-ts && (cd packages/typegen && copyfiles scripts/* build)",
@@ -24,13 +24,14 @@
"test:watch": "polkadot-dev-run-test --watch" "test:watch": "polkadot-dev-run-test --watch"
}, },
"devDependencies": { "devDependencies": {
"@babel/core": "^7.9.0", "@babel/core": "^7.9.6",
"@babel/register": "^7.9.0", "@babel/register": "^7.9.0",
"@babel/runtime": "^7.9.2", "@babel/runtime": "^7.9.6",
"@polkadot/dev": "^0.52.11", "@polkadot/dev": "^0.54.1",
"@polkadot/ts": "^0.3.18", "@polkadot/ts": "^0.3.23",
"@polkadot/typegen": "workspace:packages/typegen", "@polkadot/typegen": "workspace:packages/typegen",
"@types/jest": "^25.2.1", "@types/jest": "^25.2.3",
"@vuepress/plugin-search": "^1.5.0",
"copyfiles": "^2.2.0" "copyfiles": "^2.2.0"
} }
} }
+7 -7
View File
@@ -1,6 +1,6 @@
{ {
"name": "@polkadot/api-contract", "name": "@polkadot/api-contract",
"version": "1.11.1", "version": "1.16.1",
"description": "Interfaces for interacting with contracts and contract ABIs", "description": "Interfaces for interacting with contracts and contract ABIs",
"main": "index.js", "main": "index.js",
"keywords": [ "keywords": [
@@ -26,12 +26,12 @@
}, },
"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.9.2", "@babel/runtime": "^7.9.6",
"@polkadot/api": "1.11.1", "@polkadot/api": "1.16.1",
"@polkadot/rpc-core": "1.11.1", "@polkadot/rpc-core": "1.16.1",
"@polkadot/types": "1.11.1", "@polkadot/types": "1.16.1",
"@polkadot/util": "^2.8.1", "@polkadot/util": "^2.11.1",
"bn.js": "^5.1.1", "bn.js": "^5.1.2",
"rxjs": "^6.5.5" "rxjs": "^6.5.5"
} }
} }
@@ -19,7 +19,7 @@ function parseSelector (registry: Registry, fnname: string, input: ContractABIMe
return registry.createType('u32', hexToU8a(input)); return registry.createType('u32', hexToU8a(input));
} else if (typeof input === 'string') { } else if (typeof input === 'string') {
try { try {
const array = JSON.parse(input); const array = JSON.parse(input) as unknown[];
assert(array.length === 4, `${fnname}: Invalid selector length`); assert(array.length === 4, `${fnname}: Invalid selector length`);
@@ -108,7 +108,7 @@ export default class ContractRegistry extends MetaRegistry {
public createMessage (name: string, message: Partial<ContractABIMessage> & ContractABIMessageBase): ContractABIFn { public createMessage (name: string, message: Partial<ContractABIMessage> & ContractABIMessageBase): ContractABIFn {
const args = message.args.map(({ name, type }): ContractABIFnArg => { const args = message.args.map(({ name, type }): ContractABIFnArg => {
assert(isObject(type), `Invalid type at index ${type}`); assert(isObject(type), `Invalid type at index ${type.toString()}`);
return { return {
name: stringCamelCase(name), name: stringCamelCase(name),
@@ -183,6 +183,7 @@ export default class ContractRegistry extends MetaRegistry {
public convertMessage ({ args, name, return_type: returnType, ...message }: ContractABIMessagePre): ContractABIMessage { public convertMessage ({ args, name, return_type: returnType, ...message }: ContractABIMessagePre): ContractABIMessage {
return { return {
...message, ...message,
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
args: this.convertArgs(args), args: this.convertArgs(args),
name: this._stringAt(name), name: this._stringAt(name),
returnType: returnType ? this.convertType(returnType) : null returnType: returnType ? this.convertType(returnType) : null
@@ -191,6 +192,7 @@ export default class ContractRegistry extends MetaRegistry {
public convertEvent ({ args }: ContractABIEventPre): ContractABIEvent { public convertEvent ({ args }: ContractABIEventPre): ContractABIEvent {
return { return {
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
args: this.convertArgs(args) args: this.convertArgs(args)
}; };
} }
+20 -20
View File
@@ -7,11 +7,11 @@ import { MetaRegistryItem, MetaRegistryJson, MetaTypeDefClikeEnum, MetaType, Met
import { assert } from '@polkadot/util'; import { assert } from '@polkadot/util';
import { displayType, withTypeString } from '@polkadot/types'; import { displayType, withTypeString } from '@polkadot/types';
const builtinMap: [(id: any) => boolean, MetaTypeInfo][] = [ const builtinMap: [(id: unknown | unknown[] | { 'array.type': unknown } | { 'slice.type': unknown }) => boolean, MetaTypeInfo][] = [
[(id: any): boolean => typeof id === 'string', MetaTypeInfo.BuiltinPlain], [(id: any) => typeof id === 'string', MetaTypeInfo.BuiltinPlain],
[(id: any): boolean => Array.isArray(id), MetaTypeInfo.BuiltinTuple], [(id: any) => Array.isArray(id), MetaTypeInfo.BuiltinTuple],
[(id: any): boolean => !!(id['array.type']), MetaTypeInfo.BuiltinVecFixed], [(id: any) => !!((id as { 'array.type': unknown })['array.type']), MetaTypeInfo.BuiltinVecFixed],
[(id: any): boolean => !!(id['slice.type']), MetaTypeInfo.BuiltinVec] [(id: any) => !!((id as { 'slice.type': unknown })['slice.type']), MetaTypeInfo.BuiltinVec]
]; ];
const typeMap: [string, MetaTypeInfo][] = [ const typeMap: [string, MetaTypeInfo][] = [
@@ -25,8 +25,8 @@ function detectedType ({ def, id }: MetaType): MetaTypeInfo {
assert(!(def as MetaTypeDefUnion)['union.fields'], 'Invalid union type definition found'); assert(!(def as MetaTypeDefUnion)['union.fields'], 'Invalid union type definition found');
const lookup = def === 'builtin' const lookup = def === 'builtin'
? builtinMap.find(([test]): boolean => test(id)) ? builtinMap.find(([test]) => test(id))
: typeMap.find(([test]): boolean => !!(def as any)[test]); : typeMap.find(([test]) => !!(def as unknown as Record<string, unknown>)[test]);
return lookup return lookup
? lookup[1] ? lookup[1]
@@ -59,7 +59,7 @@ class MetadataRegistryLookup {
} }
} }
protected _itemAt (index: number, variant: MetaRegistryItem): any { protected _itemAt (index: number, variant: MetaRegistryItem): string | MetaType | TypeDef {
assert(this._hasItemAt(index, variant), `MetaRegistry: Invalid ${variant} index ${index} found in metadata`); assert(this._hasItemAt(index, variant), `MetaRegistry: Invalid ${variant} index ${index} found in metadata`);
switch (variant) { switch (variant) {
@@ -72,24 +72,24 @@ class MetadataRegistryLookup {
} }
} }
protected _itemsAt (indices: number[], variant: MetaRegistryItem): any[] { protected _itemsAt (indices: number[], variant: MetaRegistryItem): (string | MetaType | TypeDef)[] {
return indices.map((index: number): string => this._itemAt(index, variant)); return indices.map((index: number) => this._itemAt(index, variant));
} }
protected _stringAt (index: StringIndex): string { protected _stringAt (index: StringIndex): string {
return this._itemAt(index, MetaRegistryItem.String); return this._itemAt(index, MetaRegistryItem.String) as string;
} }
public stringsAt (indices: StringIndex[]): string[] { public stringsAt (indices: StringIndex[]): string[] {
return this._itemsAt(indices, MetaRegistryItem.String); return this._itemsAt(indices, MetaRegistryItem.String) as string[];
} }
public typeAt (index: TypeIndex): MetaType { public typeAt (index: TypeIndex): MetaType {
return this._itemAt(index, MetaRegistryItem.Type); return this._itemAt(index, MetaRegistryItem.Type) as MetaType;
} }
public typesAt (indices: TypeIndex[]): MetaType[] { public typesAt (indices: TypeIndex[]): MetaType[] {
return this._itemsAt(indices, MetaRegistryItem.Type); return this._itemsAt(indices, MetaRegistryItem.Type) as MetaType[];
} }
public hasTypeDefAt (index: TypeIndex): boolean { public hasTypeDefAt (index: TypeIndex): boolean {
@@ -98,7 +98,7 @@ class MetadataRegistryLookup {
public typeDefAt (index: TypeIndex, extra: Pick<TypeDef, never> = {}): TypeDef { public typeDefAt (index: TypeIndex, extra: Pick<TypeDef, never> = {}): TypeDef {
return { return {
...this._itemAt(index, MetaRegistryItem.TypeDef), ...this._itemAt(index, MetaRegistryItem.TypeDef) as TypeDef,
...extra ...extra
}; };
} }
@@ -136,7 +136,7 @@ export default class MetaRegistry extends MetadataRegistryLookup {
}; };
} }
private _typeDefDefFields (metaType: MetaType, typeIndex?: TypeIndex): Pick<TypeDef, never> { private _typeDefDefFields (metaType: MetaType, typeIndex: TypeIndex = -1): Pick<TypeDef, never> {
let typeDef; let typeDef;
switch (detectedType(metaType)) { switch (detectedType(metaType)) {
@@ -234,7 +234,7 @@ export default class MetaRegistry extends MetadataRegistryLookup {
}; };
} }
private _typeDefForBuiltinVec (id: MetaTypeIdVec, typeIndex?: TypeIndex): Pick<TypeDef, never> { private _typeDefForBuiltinVec (id: MetaTypeIdVec, typeIndex: TypeIndex = -1): Pick<TypeDef, never> {
const { 'slice.type': vecTypeIndex } = id; const { 'slice.type': vecTypeIndex } = id;
assert(!typeIndex || vecTypeIndex !== typeIndex, `MetaRegistry: self-referencing registry type at index ${typeIndex}`); assert(!typeIndex || vecTypeIndex !== typeIndex, `MetaRegistry: self-referencing registry type at index ${typeIndex}`);
@@ -250,7 +250,7 @@ export default class MetaRegistry extends MetadataRegistryLookup {
}; };
} }
private _typeDefForBuiltinVecFixed (id: MetaTypeIdVecFixed, typeIndex?: TypeIndex): Pick<TypeDef, never> { private _typeDefForBuiltinVecFixed (id: MetaTypeIdVecFixed, typeIndex: TypeIndex = -1): Pick<TypeDef, never> {
const { 'array.len': vecLength, 'array.type': vecTypeIndex } = id; const { 'array.len': vecLength, 'array.type': vecTypeIndex } = id;
assert(!vecLength || vecLength <= 256, 'MetaRegistry: Only support for [Type; <length>], where length <= 256'); assert(!vecLength || vecLength <= 256, 'MetaRegistry: Only support for [Type; <length>], where length <= 256');
@@ -301,7 +301,7 @@ export default class MetaRegistry extends MetadataRegistryLookup {
}; };
} }
public typeDefForOption (id: MetaTypeIdCustom, typeIndex?: TypeIndex): Pick<TypeDef, any> { public typeDefForOption (id: MetaTypeIdCustom, typeIndex: TypeIndex = -1): Pick<TypeDef, any> {
assert(id['custom.params'] && id['custom.params'][0], `Invalid Option type defined at index ${typeIndex}`); assert(id['custom.params'] && id['custom.params'][0], `Invalid Option type defined at index ${typeIndex}`);
return { return {
@@ -310,7 +310,7 @@ export default class MetaRegistry extends MetadataRegistryLookup {
}; };
} }
public typeDefForResult (id: MetaTypeIdCustom, typeIndex?: TypeIndex): Pick<TypeDef, any> { public typeDefForResult (id: MetaTypeIdCustom, typeIndex: TypeIndex = -1): Pick<TypeDef, any> {
assert(id['custom.params'] && id['custom.params'][0] && id['custom.params'][1], `Invalid Result type defined at index ${typeIndex}`); assert(id['custom.params'] && id['custom.params'][0] && id['custom.params'][1], `Invalid Result type defined at index ${typeIndex}`);
return { return {
@@ -47,6 +47,7 @@ export default class Blueprint<ApiType extends ApiTypes> extends BaseWithTx<ApiT
assert(!!this.abi.constructors[constructorIndex], `Specified constructor index ${constructorIndex} does not exist`); assert(!!this.abi.constructors[constructorIndex], `Specified constructor index ${constructorIndex} does not exist`);
return { return {
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
signAndSend: this.decorateMethod( signAndSend: this.decorateMethod(
(account: IKeyringPair | string | AccountId | Address): BlueprintCreateResultSubscription<ApiType> => { (account: IKeyringPair | string | AccountId | Address): BlueprintCreateResultSubscription<ApiType> => {
return this._apiContracts return this._apiContracts
+1 -1
View File
@@ -19,7 +19,6 @@ import { BaseWithTx } from './util';
type CodePutCodeResultSubscription<ApiType extends ApiTypes> = Observable<CodePutCodeResult<ApiType>>; type CodePutCodeResultSubscription<ApiType extends ApiTypes> = Observable<CodePutCodeResult<ApiType>>;
// eslint-disable-next-line @typescript-eslint/interface-name-prefix
export interface CodePutCode<ApiType extends ApiTypes> { export interface CodePutCode<ApiType extends ApiTypes> {
signAndSend (account: IKeyringPair | string | AccountId | Address): CodePutCodeResultSubscription<ApiType>; signAndSend (account: IKeyringPair | string | AccountId | Address): CodePutCodeResultSubscription<ApiType>;
} }
@@ -46,6 +45,7 @@ export default class Code<ApiType extends ApiTypes> extends BaseWithTx<ApiType>
public createBlueprint = (maxGas: number | BN): CodePutCode<ApiType> => { public createBlueprint = (maxGas: number | BN): CodePutCode<ApiType> => {
return { return {
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
signAndSend: this.decorateMethod( signAndSend: this.decorateMethod(
(account: IKeyringPair | string | AccountId | Address): CodePutCodeResultSubscription<ApiType> => (account: IKeyringPair | string | AccountId | Address): CodePutCodeResultSubscription<ApiType> =>
this._apiContracts this._apiContracts
+1 -1
View File
@@ -21,7 +21,6 @@ type ContractCallResultSubscription<ApiType extends ApiTypes, CallType extends C
? Observable<ContractCallResult<CallType>> ? Observable<ContractCallResult<CallType>>
: Promise<ObsInnerType<ContractCallResult<CallType>>>; : Promise<ObsInnerType<ContractCallResult<CallType>>>;
// eslint-disable-next-line @typescript-eslint/interface-name-prefix
export interface ContractCall<ApiType extends ApiTypes, CallType extends ContractCallTypes> { export interface ContractCall<ApiType extends ApiTypes, CallType extends ContractCallTypes> {
send (account: IKeyringPair | string | AccountId | Address): ContractCallResultSubscription<ApiType, CallType>; send (account: IKeyringPair | string | AccountId | Address): ContractCallResultSubscription<ApiType, CallType>;
} }
@@ -45,6 +44,7 @@ export default class Contract<ApiType extends ApiTypes> extends BaseWithTxAndRpc
const { def, fn } = this.getMessage(message); const { def, fn } = this.getMessage(message);
return { return {
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
send: this.decorateMethod( send: this.decorateMethod(
as === 'rpc' && this.hasRpcContractsCall as === 'rpc' && this.hasRpcContractsCall
? (account: IKeyringPair | string | AccountId | Address): ContractCallResult<'rpc'> => ? (account: IKeyringPair | string | AccountId | Address): ContractCallResult<'rpc'> =>
+1 -1
View File
@@ -46,7 +46,7 @@ export abstract class Base<ApiType extends ApiTypes> implements ContractBase<Api
: 0; : 0;
const def = this.abi.abi.contract.messages[index]; const def = this.abi.abi.contract.messages[index];
assert(!!def, `Attempted to access a contract message that does not exist: ${typeof nameOrIndex === 'number' ? `index ${nameOrIndex}` : nameOrIndex}`); assert(!!def, `Attempted to access a contract message that does not exist: ${typeof nameOrIndex === 'number' ? `index ${nameOrIndex}` : (nameOrIndex || 'unknown')}`);
const fn = this.abi.messages[def.name] || this.abi.messages[stringCamelCase(def.name)]; const fn = this.abi.messages[def.name] || this.abi.messages[stringCamelCase(def.name)];
+3
View File
@@ -23,6 +23,7 @@ export interface ContractBase<ApiType extends ApiTypes> {
export interface ContractABITypePre { export interface ContractABITypePre {
ty: TypeIndex; ty: TypeIndex;
// eslint-disable-next-line camelcase
display_name: StringIndex[]; display_name: StringIndex[];
} }
@@ -56,6 +57,7 @@ export interface ContractABIMessageCommon {
export interface ContractABIMessagePre extends ContractABIMessageCommon, ContractABIMessageBasePre { export interface ContractABIMessagePre extends ContractABIMessageCommon, ContractABIMessageBasePre {
name: StringIndex; name: StringIndex;
// eslint-disable-next-line camelcase
return_type: ContractABITypePre | null; return_type: ContractABITypePre | null;
} }
@@ -187,6 +189,7 @@ export interface InterfaceAbi {
} }
export interface InterfaceContractCalls { export interface InterfaceContractCalls {
// eslint-disable-next-line @typescript-eslint/ban-types
[index: string]: Function; [index: string]: Function;
} }
+10 -10
View File
@@ -1,6 +1,6 @@
{ {
"name": "@polkadot/api-derive", "name": "@polkadot/api-derive",
"version": "1.11.1", "version": "1.16.1",
"description": "Common functions used across Polkadot, derived from RPC calls and storage queries.", "description": "Common functions used across Polkadot, derived from RPC calls and storage queries.",
"main": "index.js", "main": "index.js",
"keywords": [ "keywords": [
@@ -27,18 +27,18 @@
}, },
"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.9.2", "@babel/runtime": "^7.9.6",
"@polkadot/api": "1.11.1", "@polkadot/api": "1.16.1",
"@polkadot/rpc-core": "1.11.1", "@polkadot/rpc-core": "1.16.1",
"@polkadot/rpc-provider": "1.11.1", "@polkadot/rpc-provider": "1.16.1",
"@polkadot/types": "1.11.1", "@polkadot/types": "1.16.1",
"@polkadot/util": "^2.8.1", "@polkadot/util": "^2.11.1",
"@polkadot/util-crypto": "^2.8.1", "@polkadot/util-crypto": "^2.11.1",
"bn.js": "^5.1.1", "bn.js": "^5.1.2",
"memoizee": "^0.4.14", "memoizee": "^0.4.14",
"rxjs": "^6.5.5" "rxjs": "^6.5.5"
}, },
"devDependencies": { "devDependencies": {
"@polkadot/keyring": "^2.8.1" "@polkadot/keyring": "^2.11.1"
} }
} }
+1 -1
View File
@@ -40,7 +40,7 @@ export function flags (api: ApiInterfaceRx): (address?: AccountId | Address | st
address && api.query[councilSection]?.members address && api.query[councilSection]?.members
? api.query[councilSection].members() ? api.query[councilSection].members()
: of(undefined), : of(undefined),
address && api.query.council.members address && api.query.council?.members
? api.query.council.members() ? api.query.council.members()
: of([]), : of([]),
address && api.query.technicalCommittee?.members address && api.query.technicalCommittee?.members
@@ -10,6 +10,7 @@ import { map, startWith } from 'rxjs/operators';
import { ApiInterfaceRx } from '@polkadot/api/types'; import { ApiInterfaceRx } from '@polkadot/api/types';
import { ENUMSET_SIZE } from '@polkadot/types/generic/AccountIndex'; import { ENUMSET_SIZE } from '@polkadot/types/generic/AccountIndex';
import { Option, Vec } from '@polkadot/types'; import { Option, Vec } from '@polkadot/types';
import { isFunction } from '@polkadot/util';
import { memo } from '../util'; import { memo } from '../util';
@@ -51,7 +52,7 @@ function query (api: ApiInterfaceRx, accountIndex: AccountIndex | string): Obser
export function indexToId (api: ApiInterfaceRx): (accountIndex: AccountIndex | string) => Observable<AccountId | undefined> { export function indexToId (api: ApiInterfaceRx): (accountIndex: AccountIndex | string) => Observable<AccountId | undefined> {
return memo((accountIndex: AccountIndex | string): Observable<AccountId | undefined> => return memo((accountIndex: AccountIndex | string): Observable<AccountId | undefined> =>
api.query.indices api.query.indices
? api.query.indices.accounts ? isFunction(api.query.indices.accounts)
? query(api, accountIndex) ? query(api, accountIndex)
: queryEnumSet(api, accountIndex) : queryEnumSet(api, accountIndex)
: of(undefined) : of(undefined)
+2 -1
View File
@@ -10,6 +10,7 @@ import { Observable, of } from 'rxjs';
import { map, startWith, switchMap } from 'rxjs/operators'; import { map, startWith, switchMap } from 'rxjs/operators';
import { ENUMSET_SIZE } from '@polkadot/types/generic/AccountIndex'; import { ENUMSET_SIZE } from '@polkadot/types/generic/AccountIndex';
import { Vec } from '@polkadot/types'; import { Vec } from '@polkadot/types';
import { isFunction } from '@polkadot/util';
import { memo } from '../util'; import { memo } from '../util';
@@ -72,7 +73,7 @@ function queryAccounts (api: ApiInterfaceRx): Observable<AccountIndexes> {
export function indexes (api: ApiInterfaceRx): () => Observable<AccountIndexes> { export function indexes (api: ApiInterfaceRx): () => Observable<AccountIndexes> {
return memo((): Observable<AccountIndexes> => return memo((): Observable<AccountIndexes> =>
(api.query.indices (api.query.indices
? api.query.indices.accounts ? isFunction(api.query.indices.accounts)
? queryAccounts(api) ? queryAccounts(api)
: queryEnumSet(api) : queryEnumSet(api)
: of({} as AccountIndexes) : of({} as AccountIndexes)
+3 -2
View File
@@ -9,6 +9,7 @@ import { DeriveBalancesAccount } from '../types';
import { Observable, combineLatest, of } from 'rxjs'; import { Observable, combineLatest, of } from 'rxjs';
import { map, switchMap } from 'rxjs/operators'; import { map, switchMap } from 'rxjs/operators';
import { ApiInterfaceRx } from '@polkadot/api/types'; import { ApiInterfaceRx } from '@polkadot/api/types';
import { isFunction } from '@polkadot/util';
import { memo } from '../util'; import { memo } from '../util';
@@ -86,9 +87,9 @@ export function account (api: ApiInterfaceRx): (address: AccountIndex | AccountI
(accountId (accountId
? combineLatest([ ? combineLatest([
of(accountId), of(accountId),
api.query.system.account isFunction(api.query.system.account)
? queryCurrent(api, accountId) ? queryCurrent(api, accountId)
: api.query.balances.account : isFunction(api.query.balances.account)
? queryBalancesAccount(api, accountId) ? queryBalancesAccount(api, accountId)
: queryBalancesFree(api, accountId) : queryBalancesFree(api, accountId)
]) ])
+2 -2
View File
@@ -10,7 +10,7 @@ import { Observable, combineLatest, of } from 'rxjs';
import { map, switchMap } from 'rxjs/operators'; import { map, switchMap } from 'rxjs/operators';
import { ApiInterfaceRx } from '@polkadot/api/types'; import { ApiInterfaceRx } from '@polkadot/api/types';
import { Option, Vec } from '@polkadot/types'; import { Option, Vec } from '@polkadot/types';
import { bnMax } from '@polkadot/util'; import { bnMax, isFunction } from '@polkadot/util';
import { memo } from '../util'; import { memo } from '../util';
@@ -135,7 +135,7 @@ export function all (api: ApiInterfaceRx): (address: AccountIndex | AccountId |
? combineLatest([ ? combineLatest([
of(account), of(account),
api.derive.chain.bestNumber(), api.derive.chain.bestNumber(),
api.query.balances.account isFunction(api.query.balances.account)
? queryCurrent(api, account.accountId) ? queryCurrent(api, account.accountId)
: queryOld(api, account.accountId) : queryOld(api, account.accountId)
]) ])
+3 -3
View File
@@ -28,12 +28,12 @@ export function fees (api: ApiInterfaceRx): () => Observable<DeriveFees> {
return memo((): Observable<DeriveFees> => return memo((): Observable<DeriveFees> =>
of([ of([
// deprecated - remove // deprecated - remove
(api.consts.balances?.creationFee as Balance) || api.registry.createType('Balance'), (api.consts.balances?.creationFee as unknown as Balance) || api.registry.createType('Balance'),
(api.consts.balances?.transferFee as Balance) || api.registry.createType('Balance'), (api.consts.balances?.transferFee as unknown as Balance) || api.registry.createType('Balance'),
// current // current
(api.consts.balances?.existentialDeposit as Balance) || api.registry.createType('Balance'), (api.consts.balances?.existentialDeposit as Balance) || api.registry.createType('Balance'),
(api.consts.transactionPayment?.transactionBaseFee as Balance) || api.registry.createType('Balance'), (api.consts.transactionPayment?.transactionBaseFee as unknown as Balance) || api.registry.createType('Balance'),
(api.consts.transactionPayment?.transactionByteFee as Balance) || api.registry.createType('Balance') (api.consts.transactionPayment?.transactionByteFee as Balance) || api.registry.createType('Balance')
]).pipe( ]).pipe(
map(([creationFee, transferFee, existentialDeposit, transactionBaseFee, transactionByteFee]): DeriveFees => ({ map(([creationFee, transferFee, existentialDeposit, transactionBaseFee, transactionByteFee]): DeriveFees => ({
@@ -9,6 +9,7 @@ import { DeriveCollectiveProposal } from '../types';
import { Observable, combineLatest, of } from 'rxjs'; import { Observable, combineLatest, of } from 'rxjs';
import { map, switchMap } from 'rxjs/operators'; import { map, switchMap } from 'rxjs/operators';
import { Option } from '@polkadot/types'; import { Option } from '@polkadot/types';
import { isFunction } from '@polkadot/util';
import { memo } from '../util'; import { memo } from '../util';
@@ -30,7 +31,7 @@ function parse ([hashes, proposals, votes]: Result): DeriveCollectiveProposal[]
export function proposals (api: ApiInterfaceRx, section: 'council' | 'technicalCommittee'): () => Observable<DeriveCollectiveProposal[]> { export function proposals (api: ApiInterfaceRx, section: 'council' | 'technicalCommittee'): () => Observable<DeriveCollectiveProposal[]> {
return memo((): Observable<DeriveCollectiveProposal[]> => return memo((): Observable<DeriveCollectiveProposal[]> =>
api.query[section]?.proposals isFunction(api.query[section]?.proposals)
? api.query[section].proposals().pipe( ? api.query[section].proposals().pipe(
switchMap((hashes: Hash[]): Observable<Result> => switchMap((hashes: Hash[]): Observable<Result> =>
hashes.length hashes.length
@@ -10,7 +10,7 @@ import { Observable, combineLatest, of } from 'rxjs';
import { map, switchMap } from 'rxjs/operators'; import { map, switchMap } from 'rxjs/operators';
import { ApiInterfaceRx } from '@polkadot/api/types'; import { ApiInterfaceRx } from '@polkadot/api/types';
import { Option, Vec, u64 } from '@polkadot/types'; import { Option, Vec, u64 } from '@polkadot/types';
import { stringToHex } from '@polkadot/util'; import { isFunction, stringToHex } from '@polkadot/util';
import { memo } from '../util'; import { memo } from '../util';
@@ -96,7 +96,7 @@ function queryScheduler (api: ApiInterfaceRx): Observable<DeriveDispatch[]> {
export function dispatchQueue (api: ApiInterfaceRx): () => Observable<DeriveDispatch[]> { export function dispatchQueue (api: ApiInterfaceRx): () => Observable<DeriveDispatch[]> {
return memo((): Observable<DeriveDispatch[]> => return memo((): Observable<DeriveDispatch[]> =>
api.query.scheduler?.agenda isFunction(api.query.scheduler?.agenda)
? queryScheduler(api) ? queryScheduler(api)
: api.query.democracy.dispatchQueue : api.query.democracy.dispatchQueue
? queryQueue(api) ? queryQueue(api)
@@ -3,6 +3,7 @@
// of the Apache-2.0 license. See the LICENSE file for details. // of the Apache-2.0 license. See the LICENSE file for details.
export * from './dispatchQueue'; export * from './dispatchQueue';
export * from './locks';
export * from './nextExternal'; export * from './nextExternal';
export * from './preimage'; export * from './preimage';
export * from './preimages'; export * from './preimages';
@@ -0,0 +1,66 @@
// Copyright 2017-2020 @polkadot/api-derive authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { AccountId, ReferendumInfo, ReferendumInfoTo239, VotingDirect, VotingDirectVote } from '@polkadot/types/interfaces';
import { ApiInterfaceRx } from '@polkadot/api/types';
import { DeriveDemocracyLock } from '../types';
import BN from 'bn.js';
import { Observable, of } from 'rxjs';
import { map, switchMap } from 'rxjs/operators';
import { Option } from '@polkadot/types';
import { isUndefined } from '@polkadot/util';
import { memo } from '../util';
const LOCKUPS = [0, 1, 2, 4, 8, 16, 32];
const ZERO = new BN(0);
function parseLock (api: ApiInterfaceRx, [referendumId, accountVote]: VotingDirectVote, referendum: ReferendumInfo): DeriveDemocracyLock {
const { balance, vote } = accountVote.asStandard;
let unlockAt = ZERO;
if (referendum.isFinished) {
const { approved, end } = referendum.asFinished;
if ((approved.isTrue && vote.isAye) || (approved.isFalse && vote.isNay)) {
unlockAt = end.add(api.consts.democracy.enactmentPeriod.muln(LOCKUPS[vote.conviction.index]));
}
}
return { balance, isFinished: referendum.isFinished, referendumId, unlockAt, vote };
}
function directLocks (api: ApiInterfaceRx, { votes }: VotingDirect): Observable<DeriveDemocracyLock[]> {
if (!votes.length) {
return of([]);
}
return api.query.democracy.referendumInfoOf.multi<Option<ReferendumInfo | ReferendumInfoTo239>>(votes.map(([referendumId]) => referendumId)).pipe(
map((referendums) =>
votes
.map((vote, index): [VotingDirectVote, ReferendumInfo | ReferendumInfoTo239 | null] =>
[vote, referendums[index].unwrapOr(null)]
)
.filter((item): item is [VotingDirectVote, ReferendumInfo] =>
!!item[1] && isUndefined((item[1] as ReferendumInfoTo239).end) && item[0][1].isStandard
)
.map(([directVote, referendum]) =>
parseLock(api, directVote, referendum)
)
)
);
}
export function locks (api: ApiInterfaceRx): (accountId: string | AccountId) => Observable<DeriveDemocracyLock[]> {
return memo((accountId: string | AccountId): Observable<DeriveDemocracyLock[]> =>
api.query.democracy.votingOf(accountId).pipe(
switchMap((voting): Observable<DeriveDemocracyLock[]> =>
voting.isDirect
? directLocks(api, voting.asDirect)
: of([])
)
)
);
}
+21 -7
View File
@@ -10,27 +10,41 @@ import { Observable, combineLatest, of } from 'rxjs';
import { map, switchMap } from 'rxjs/operators'; import { map, switchMap } from 'rxjs/operators';
import { ApiInterfaceRx } from '@polkadot/api/types'; import { ApiInterfaceRx } from '@polkadot/api/types';
import { Option, Vec } from '@polkadot/types'; import { Option, Vec } from '@polkadot/types';
import { isFunction } from '@polkadot/util';
import { memo } from '../util'; import { memo } from '../util';
type Depositors = Option<ITuple<[Balance, Vec<AccountId>]>>; type DepositorsNew = Option<ITuple<[Vec<AccountId>, Balance]>>;
type DepositorsOld = Option<ITuple<[Balance, Vec<AccountId>]>>;
type Depositors = DepositorsNew | DepositorsOld;
type Proposals = Vec<ITuple<[PropIndex, Hash, AccountId]>>; type Proposals = Vec<ITuple<[PropIndex, Hash, AccountId]>>;
type Result = [Proposals, (DeriveProposalImage | undefined)[], Depositors[]];
function parse ([proposals, images, depositors]: [Proposals, (DeriveProposalImage | undefined)[], Depositors[]]): DeriveProposal[] { // eslint-disable-next-line @typescript-eslint/no-unused-vars
function isNewDepositors (depositors: ITuple<[Vec<AccountId>, Balance]> | ITuple<[Balance, Vec<AccountId>]>): depositors is ITuple<[Vec<AccountId>, Balance]> {
// Detect balance...
// eslint-disable-next-line @typescript-eslint/unbound-method
return isFunction((depositors[1] as Balance).mul);
}
function parse ([proposals, images, optDepositors]: Result): DeriveProposal[] {
return proposals return proposals
.filter(([, , proposer], index): boolean => .filter(([, , proposer], index): boolean =>
!!(depositors[index]?.isSome) && !proposer.isEmpty !!(optDepositors[index]?.isSome) && !proposer.isEmpty
) )
.map(([index, imageHash, proposer], proposalIndex): DeriveProposal => { .map(([index, imageHash, proposer], proposalIndex): DeriveProposal => {
const [balance, seconds] = depositors[proposalIndex].unwrap(); const depositors = optDepositors[proposalIndex].unwrap();
return { return {
balance, ...(
isNewDepositors(depositors)
? { balance: depositors[1], seconds: depositors[0] }
: { balance: depositors[0], seconds: depositors[1] }
),
image: images[proposalIndex], image: images[proposalIndex],
imageHash, imageHash,
index, index,
proposer, proposer
seconds
}; };
}); });
} }
@@ -20,6 +20,7 @@ export function referendumIds (api: ApiInterfaceRx): () => Observable<BN[]> {
]).pipe( ]).pipe(
map(([first, total]): BN[] => map(([first, total]): BN[] =>
total.gt(first) total.gt(first)
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
? [...Array(total.sub(first).toNumber())].map((_, i): BN => first.addn(i)) ? [...Array(total.sub(first).toNumber())].map((_, i): BN => first.addn(i))
: [] : []
) )
@@ -3,13 +3,14 @@
// of the Apache-2.0 license. See the LICENSE file for details. // of the Apache-2.0 license. See the LICENSE file for details.
import { ApiInterfaceRx } from '@polkadot/api/types'; import { ApiInterfaceRx } from '@polkadot/api/types';
import { AccountId, ReferendumInfo, ReferendumInfoTo239, Vote, Voting, VotingDirectVote } from '@polkadot/types/interfaces'; import { AccountId, ReferendumInfo, ReferendumInfoTo239, Vote, Voting, VotingDirectVote, VotingDelegating } from '@polkadot/types/interfaces';
import { DeriveBalancesAccount, DeriveReferendum, DeriveReferendumVote, DeriveReferendumVotes } from '../types'; import { DeriveBalancesAccount, DeriveReferendum, DeriveReferendumVote, DeriveReferendumVotes } from '../types';
import BN from 'bn.js'; import BN from 'bn.js';
import { Observable, of, combineLatest } from 'rxjs'; import { Observable, of, combineLatest } from 'rxjs';
import { map, switchMap } from 'rxjs/operators'; import { map, switchMap } from 'rxjs/operators';
import { Option, Vec } from '@polkadot/types'; import { Option, Vec } from '@polkadot/types';
import { isFunction } from '@polkadot/util';
import { memo } from '../util'; import { memo } from '../util';
import { calcVotes, getStatus, parseImage } from './util'; import { calcVotes, getStatus, parseImage } from './util';
@@ -33,6 +34,7 @@ function votesPrev (api: ApiInterfaceRx, referendumId: BN): Observable<DeriveRef
votersFor.map((accountId, index): DeriveReferendumVote => ({ votersFor.map((accountId, index): DeriveReferendumVote => ({
accountId, accountId,
balance: balances[index].votingBalance || api.registry.createType('Balance'), balance: balances[index].votingBalance || api.registry.createType('Balance'),
isDelegating: false,
vote: votes[index] || api.registry.createType('Vote') vote: votes[index] || api.registry.createType('Vote')
})) }))
) )
@@ -41,10 +43,9 @@ function votesPrev (api: ApiInterfaceRx, referendumId: BN): Observable<DeriveRef
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>().pipe(
map((allVoting): DeriveReferendumVote[] => map((allVoting): DeriveReferendumVote[] => {
allVoting const mapped = allVoting.map(([key, voting]): [AccountId, Voting] => [key.args[0] as AccountId, voting]);
.map(([key, voting]): [AccountId, Voting] => [key.args[0] as AccountId, voting]) const votes = mapped
// FIXME We are ignoring delegated votes
.filter(([, voting]) => voting.isDirect) .filter(([, voting]) => voting.isDirect)
.map(([accountId, voting]): [AccountId, VotingDirectVote[]] => [ .map(([accountId, voting]): [AccountId, VotingDirectVote[]] => [
accountId, accountId,
@@ -57,14 +58,37 @@ function votesCurr (api: ApiInterfaceRx, referendumId: BN): Observable<DeriveRef
if (vote.isStandard) { if (vote.isStandard) {
result.push({ result.push({
accountId, accountId,
isDelegating: false,
...vote.asStandard ...vote.asStandard
}); });
} }
return result; return result;
}, result), [] }, result), []
) );
) const delegations = mapped
.filter(([, voting]) => voting.isDelegating)
.map(([accountId, voting]): [AccountId, VotingDelegating] => [accountId, voting.asDelegating]);
// add delegations
delegations.forEach(([accountId, { balance, conviction, target }]): void => {
// Are we delegating to a delegator
const toDelegator = delegations.find(([accountId]) => accountId.eq(target));
const to = votes.find(({ accountId }) => accountId.eq(toDelegator ? toDelegator[0] : target));
// this delegation has a target
if (to) {
votes.push({
accountId,
balance,
isDelegating: true,
vote: api.registry.createType('Vote', { aye: to.vote.isAye, conviction })
});
}
});
return votes;
})
); );
} }
@@ -72,7 +96,7 @@ export function _referendumVotes (api: ApiInterfaceRx): (referendum: DeriveRefer
return memo((referendum: DeriveReferendum): Observable<DeriveReferendumVotes> => return memo((referendum: DeriveReferendum): Observable<DeriveReferendumVotes> =>
combineLatest([ combineLatest([
api.derive.democracy.sqrtElectorate(), api.derive.democracy.sqrtElectorate(),
api.query.democracy.votingOf isFunction(api.query.democracy.votingOf)
? votesCurr(api, referendum.index) ? votesCurr(api, referendum.index)
: votesPrev(api, referendum.index) : votesPrev(api, referendum.index)
]).pipe( ]).pipe(
+10 -1
View File
@@ -2,11 +2,19 @@
// This software may be modified and distributed under the terms // This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details. // of the Apache-2.0 license. See the LICENSE file for details.
import type BN from 'bn.js';
import { AccountId, Balance, BlockNumber, Hash, Proposal, PropIndex, ReferendumInfoTo239, ReferendumStatus, Vote, ReferendumIndex, VoteThreshold } from '@polkadot/types/interfaces'; import { AccountId, Balance, BlockNumber, Hash, Proposal, PropIndex, ReferendumInfoTo239, ReferendumStatus, Vote, ReferendumIndex, VoteThreshold } from '@polkadot/types/interfaces';
import BN from 'bn.js';
import { Vec } from '@polkadot/types'; import { Vec } from '@polkadot/types';
export interface DeriveDemocracyLock {
balance: Balance;
isFinished: boolean;
referendumId: ReferendumIndex;
unlockAt: BN;
vote: Vote;
}
export interface DeriveDispatch { export interface DeriveDispatch {
at: BlockNumber; at: BlockNumber;
index: ReferendumIndex; index: ReferendumIndex;
@@ -46,6 +54,7 @@ export interface DeriveReferendum {
export interface DeriveReferendumVote { export interface DeriveReferendumVote {
accountId: AccountId; accountId: AccountId;
balance: Balance; balance: Balance;
isDelegating: boolean;
vote: Vote; vote: Vote;
} }
+5 -1
View File
@@ -2,6 +2,10 @@
// This software may be modified and distributed under the terms // This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details. // of the Apache-2.0 license. See the LICENSE file for details.
/* eslint-disable @typescript-eslint/no-unsafe-return */
/* eslint-disable @typescript-eslint/no-unsafe-call */
/* eslint-disable @typescript-eslint/restrict-template-expressions */
import { Observable, from } from 'rxjs'; import { Observable, from } from 'rxjs';
import ApiRx from '@polkadot/api/rx/Api'; import ApiRx from '@polkadot/api/rx/Api';
import MockProvider from '@polkadot/rpc-provider/mock'; import MockProvider from '@polkadot/rpc-provider/mock';
@@ -33,7 +37,7 @@ describe('derive', (): void => {
const api = new ApiRx({ provider: new MockProvider(registry), registry }); const api = new ApiRx({ provider: new MockProvider(registry), registry });
beforeAll((done): void => { beforeAll((done): void => {
api.isReady.subscribe((): void => done()); api.isReady.subscribe(() => done());
}); });
testFunction(api)('accounts', 'idAndIndex', []); testFunction(api)('accounts', 'idAndIndex', []);
+2
View File
@@ -76,9 +76,11 @@ function injectFunctions<AllSections> (api: ApiInterfaceRx, allSections: AllSect
.reduce((sectionAcc, _methodName): DeriveSection<typeof section> => { .reduce((sectionAcc, _methodName): DeriveSection<typeof section> => {
const methodName = _methodName as keyof typeof section; const methodName = _methodName as keyof typeof section;
// Not sure what to do here, casting as any. Though the final types are good // Not sure what to do here, casting as any. Though the final types are good
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment,@typescript-eslint/no-unsafe-call
const method = (section[methodName] as any)(api); const method = (section[methodName] as any)(api);
// idem // idem
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment,@typescript-eslint/no-unsafe-member-access
(sectionAcc as any)[methodName] = method; (sectionAcc as any)[methodName] = method;
return sectionAcc; return sectionAcc;
+2 -1
View File
@@ -9,6 +9,7 @@ import { DeriveSessionIndexes } from '../types';
import { Observable, of } from 'rxjs'; import { Observable, of } from 'rxjs';
import { map } from 'rxjs/operators'; import { map } from 'rxjs/operators';
import { Option, u32 } from '@polkadot/types'; import { Option, u32 } from '@polkadot/types';
import { isFunction } from '@polkadot/util';
import { memo } from '../util'; import { memo } from '../util';
@@ -79,7 +80,7 @@ export function indexes (api: ApiInterfaceRx): () => Observable<DeriveSessionInd
return memo((): Observable<DeriveSessionIndexes> => return memo((): Observable<DeriveSessionIndexes> =>
( (
api.query.session && api.query.staking api.query.session && api.query.staking
? api.query.staking.activeEra ? isFunction(api.query.staking.activeEra)
? query(api) ? query(api)
: queryNoActive(api) : queryNoActive(api)
: empty(api) : empty(api)
+5 -3
View File
@@ -9,6 +9,7 @@ import { Observable, combineLatest, of } from 'rxjs';
import { map, switchMap } from 'rxjs/operators'; import { map, switchMap } from 'rxjs/operators';
import { ApiInterfaceRx } from '@polkadot/api/types'; import { ApiInterfaceRx } from '@polkadot/api/types';
import { Option, u64 } from '@polkadot/types'; import { Option, u64 } from '@polkadot/types';
import { isFunction } from '@polkadot/util';
import { memo } from '../util'; import { memo } from '../util';
@@ -77,9 +78,10 @@ function queryBabeNoHistory (api: ApiInterfaceRx): Observable<[DeriveSessionInfo
export function progress (api: ApiInterfaceRx): () => Observable<DeriveSessionProgress> { export function progress (api: ApiInterfaceRx): () => Observable<DeriveSessionProgress> {
return memo((): Observable<DeriveSessionProgress> => return memo((): Observable<DeriveSessionProgress> =>
api.consts.babe api.consts.babe
? (api.query.staking.erasStartSessionIndex ? (
? queryBabe(api) // 2.x with Babe isFunction(api.query.staking.erasStartSessionIndex)
: queryBabeNoHistory(api) ? queryBabe(api) // 2.x with Babe
: queryBabeNoHistory(api)
).pipe( ).pipe(
map(([info, slots]: [DeriveSessionInfo, ResultSlotsFlat]): DeriveSessionProgress => map(([info, slots]: [DeriveSessionInfo, ResultSlotsFlat]): DeriveSessionProgress =>
createDerive(api, info, slots) createDerive(api, info, slots)
+22 -7
View File
@@ -8,7 +8,7 @@ import { DeriveSessionInfo, DeriveStakingAccount, DeriveStakingQuery, DeriveUnlo
import BN from 'bn.js'; import BN from 'bn.js';
import { Observable, combineLatest } from 'rxjs'; import { Observable, combineLatest } from 'rxjs';
import { map } from 'rxjs/operators'; import { map, switchMap } from 'rxjs/operators';
import { isUndefined } from '@polkadot/util'; import { isUndefined } from '@polkadot/util';
@@ -70,16 +70,31 @@ function parseResult (api: ApiInterfaceRx, sessionInfo: DeriveSessionInfo, query
}; };
} }
export function _account (api: ApiInterfaceRx): (sessionInfo: DeriveSessionInfo, accountId: Uint8Array | string) => Observable<DeriveStakingAccount> {
return memo((sessionInfo: DeriveSessionInfo, accountId: Uint8Array | string): Observable<DeriveStakingAccount> =>
api.derive.staking.query(accountId).pipe(
map((query) => parseResult(api, sessionInfo, query))
));
}
/** /**
* @description From a stash, retrieve the controllerId and fill in all the relevant staking details * @description From a stash, retrieve the controllerId and fill in all the relevant staking details
*/ */
export function account (api: ApiInterfaceRx): (accountId: Uint8Array | string) => Observable<DeriveStakingAccount> { export function account (api: ApiInterfaceRx): (accountId: Uint8Array | string) => Observable<DeriveStakingAccount> {
return memo((accountId: Uint8Array | string): Observable<DeriveStakingAccount> => return memo((accountId: Uint8Array | string): Observable<DeriveStakingAccount> =>
combineLatest([ api.derive.session.info().pipe(
api.derive.session.info(), switchMap((sessionInfo) => api.derive.staking._account(sessionInfo, accountId))
api.derive.staking.query(accountId) ));
]).pipe( }
map(([sessionInfo, query]: [DeriveSessionInfo, DeriveStakingQuery]) =>
parseResult(api, sessionInfo, query)) /**
* @description From a list of stashes, fill in all the relevant staking details
*/
export function accounts (api: ApiInterfaceRx): (accountIds: (Uint8Array | string)[]) => Observable<DeriveStakingAccount[]> {
return memo((accountIds: (Uint8Array | string)[]): Observable<DeriveStakingAccount[]> =>
api.derive.session.info().pipe(
switchMap((sessionInfo) =>
combineLatest(accountIds.map((accountId) => api.derive.staking._account(sessionInfo, accountId)))
)
)); ));
} }
@@ -10,10 +10,12 @@ import { Observable, combineLatest, of } from 'rxjs';
import { map, switchMap } from 'rxjs/operators'; import { map, switchMap } from 'rxjs/operators';
import { StorageKey } from '@polkadot/types'; import { StorageKey } from '@polkadot/types';
import { memo } from '../util'; import { deriveCache, memo } from '../util';
type KeysAndExposures = [StorageKey, Exposure][]; type KeysAndExposures = [StorageKey, Exposure][];
const CACHE_KEY = 'eraExposure';
function mapStakers (era: EraIndex, stakers: KeysAndExposures): DeriveEraExposure { function mapStakers (era: EraIndex, stakers: KeysAndExposures): DeriveEraExposure {
const nominators: DeriveEraNominatorExposure = {}; const nominators: DeriveEraNominatorExposure = {};
const validators: DeriveEraValidatorExposure = {}; const validators: DeriveEraValidatorExposure = {};
@@ -34,26 +36,45 @@ function mapStakers (era: EraIndex, stakers: KeysAndExposures): DeriveEraExposur
return { era, nominators, validators }; return { era, nominators, validators };
} }
export function _eraExposure (api: ApiInterfaceRx): (era: EraIndex, withActive: boolean) => Observable<DeriveEraExposure> {
return memo((era: EraIndex, withActive: boolean): Observable<DeriveEraExposure> => {
const cacheKey = `${CACHE_KEY}-${era.toString()}`;
const cached = withActive
? undefined
: deriveCache.get<DeriveEraExposure>(cacheKey);
return cached
? of(cached)
: api.query.staking.erasStakersClipped.entries(era).pipe(
map((stakers): DeriveEraExposure => {
const value = mapStakers(era, stakers);
!withActive && deriveCache.set(cacheKey, value);
return value;
})
);
});
}
export function eraExposure (api: ApiInterfaceRx): (era: EraIndex) => Observable<DeriveEraExposure> { export function eraExposure (api: ApiInterfaceRx): (era: EraIndex) => Observable<DeriveEraExposure> {
return memo((era: EraIndex): Observable<DeriveEraExposure> => return memo((era: EraIndex): Observable<DeriveEraExposure> =>
api.query.staking.erasStakersClipped.entries(era).pipe( api.derive.staking._eraExposure(era, true)
map((stakers) => mapStakers(era, stakers))
)
); );
} }
export function _erasExposure (api: ApiInterfaceRx): (eras: EraIndex[]) => Observable<DeriveEraExposure[]> { export function _erasExposure (api: ApiInterfaceRx): (eras: EraIndex[], withActive: boolean) => Observable<DeriveEraExposure[]> {
return memo((eras: EraIndex[]): Observable<DeriveEraExposure[]> => return memo((eras: EraIndex[], withActive: boolean): Observable<DeriveEraExposure[]> =>
eras.length eras.length
? combineLatest(eras.map((era) => api.derive.staking.eraExposure(era))) ? combineLatest(eras.map((era) => api.derive.staking._eraExposure(era, withActive)))
: of([]) : of([])
); );
} }
export function erasExposure (api: ApiInterfaceRx): (withActive?: boolean) => Observable<DeriveEraExposure[]> { export function erasExposure (api: ApiInterfaceRx): (withActive?: boolean) => Observable<DeriveEraExposure[]> {
return memo((withActive?: boolean): Observable<DeriveEraExposure[]> => return memo((withActive = false): Observable<DeriveEraExposure[]> =>
api.derive.staking.erasHistoric(withActive).pipe( api.derive.staking.erasHistoric(withActive).pipe(
switchMap((eras) => api.derive.staking._erasExposure(eras)) switchMap((eras) => api.derive.staking._erasExposure(eras, withActive))
) )
); );
} }
+41 -17
View File
@@ -9,7 +9,9 @@ import { DeriveEraPoints, DeriveEraValPoints } from '../types';
import { Observable, of } from 'rxjs'; import { Observable, of } from 'rxjs';
import { map, switchMap } from 'rxjs/operators'; import { map, switchMap } from 'rxjs/operators';
import { memo } from '../util'; import { deriveCache, memo } from '../util';
const CACHE_KEY = 'eraPoints';
function mapValidators ({ individual }: EraRewardPoints): DeriveEraValPoints { function mapValidators ({ individual }: EraRewardPoints): DeriveEraValPoints {
return [...individual.entries()] return [...individual.entries()]
@@ -21,26 +23,48 @@ function mapValidators ({ individual }: EraRewardPoints): DeriveEraValPoints {
}, {}); }, {});
} }
export function _erasPoints (api: ApiInterfaceRx): (eras: EraIndex[]) => Observable<DeriveEraPoints[]> { function mapPoints (eras: EraIndex[], points: EraRewardPoints[]): DeriveEraPoints[] {
return memo((eras: EraIndex[]): Observable<DeriveEraPoints[]> => return eras.map((era, index): DeriveEraPoints => ({
eras.length era,
? api.query.staking.erasRewardPoints.multi<EraRewardPoints>(eras).pipe( eraPoints: points[index].total,
map((points) => validators: mapValidators(points[index])
eras.map((era, index): DeriveEraPoints => ({ }));
era, }
eraPoints: points[index].total,
validators: mapValidators(points[index]) export function _erasPoints (api: ApiInterfaceRx): (eras: EraIndex[], withActive: boolean) => Observable<DeriveEraPoints[]> {
})) return memo((eras: EraIndex[], withActive: boolean): Observable<DeriveEraPoints[]> => {
) if (!eras.length) {
) return of([]);
: of([]) }
);
const cached: DeriveEraPoints[] = withActive
? []
: eras
.map((era) => deriveCache.get<DeriveEraPoints>(`${CACHE_KEY}-${era.toString()}`))
.filter((value): value is DeriveEraPoints => !!value);
const remaining = eras.filter((era) => !cached.some((cached) => era.eq(cached.era)));
return !remaining.length
? of(cached)
: api.query.staking.erasRewardPoints.multi<EraRewardPoints>(remaining).pipe(
map((points): DeriveEraPoints[] => {
const query = mapPoints(remaining, points);
!withActive && query.forEach((q) => deriveCache.set(`${CACHE_KEY}-${q.era.toString()}`, q));
return eras.map((era): DeriveEraPoints =>
cached.find((cached) => era.eq(cached.era)) ||
query.find((query) => era.eq(query.era)) as DeriveEraPoints
);
})
);
});
} }
export function erasPoints (api: ApiInterfaceRx): (withActive?: boolean) => Observable<DeriveEraPoints[]> { export function erasPoints (api: ApiInterfaceRx): (withActive?: boolean) => Observable<DeriveEraPoints[]> {
return memo((withActive?: boolean): Observable<DeriveEraPoints[]> => return memo((withActive = false): Observable<DeriveEraPoints[]> =>
api.derive.staking.erasHistoric(withActive).pipe( api.derive.staking.erasHistoric(withActive).pipe(
switchMap((eras) => api.derive.staking._erasPoints(eras)) switchMap((eras) => api.derive.staking._erasPoints(eras, withActive))
) )
); );
} }
+30 -9
View File
@@ -10,7 +10,9 @@ import { Observable, combineLatest, of } from 'rxjs';
import { map, switchMap } from 'rxjs/operators'; import { map, switchMap } from 'rxjs/operators';
import { StorageKey } from '@polkadot/types'; import { StorageKey } from '@polkadot/types';
import { memo } from '../util'; import { deriveCache, memo } from '../util';
const CACHE_KEY = 'eraPrefs';
function mapPrefs (era: EraIndex, all: [StorageKey, ValidatorPrefs][]): DeriveEraPrefs { function mapPrefs (era: EraIndex, all: [StorageKey, ValidatorPrefs][]): DeriveEraPrefs {
const validators: DeriveEraValPrefs = {}; const validators: DeriveEraValPrefs = {};
@@ -22,26 +24,45 @@ function mapPrefs (era: EraIndex, all: [StorageKey, ValidatorPrefs][]): DeriveEr
return { era, validators }; return { era, validators };
} }
export function _eraPrefs (api: ApiInterfaceRx): (era: EraIndex, withActive: boolean) => Observable<DeriveEraPrefs> {
return memo((era: EraIndex, withActive: boolean): Observable<DeriveEraPrefs> => {
const cacheKey = `${CACHE_KEY}-${era.toString()}`;
const cached = withActive
? undefined
: deriveCache.get<DeriveEraPrefs>(cacheKey);
return cached
? of(cached)
: api.query.staking.erasValidatorPrefs.entries(era).pipe(
map((prefs): DeriveEraPrefs => {
const value = mapPrefs(era, prefs);
!withActive && deriveCache.set(cacheKey, value);
return value;
})
);
});
}
export function eraPrefs (api: ApiInterfaceRx): (era: EraIndex) => Observable<DeriveEraPrefs> { export function eraPrefs (api: ApiInterfaceRx): (era: EraIndex) => Observable<DeriveEraPrefs> {
return memo((era: EraIndex): Observable<DeriveEraPrefs> => return memo((era: EraIndex): Observable<DeriveEraPrefs> =>
api.query.staking.erasValidatorPrefs.entries(era).pipe( api.derive.staking._eraPrefs(era, true)
map((prefs) => mapPrefs(era, prefs))
)
); );
} }
export function _erasPrefs (api: ApiInterfaceRx): (eras: EraIndex[]) => Observable<DeriveEraPrefs[]> { export function _erasPrefs (api: ApiInterfaceRx): (eras: EraIndex[], withActive: boolean) => Observable<DeriveEraPrefs[]> {
return memo((eras: EraIndex[]): Observable<DeriveEraPrefs[]> => return memo((eras: EraIndex[], withActive: boolean): Observable<DeriveEraPrefs[]> =>
eras.length eras.length
? combineLatest(eras.map((era) => api.derive.staking.eraPrefs(era))) ? combineLatest(eras.map((era) => api.derive.staking._eraPrefs(era, withActive)))
: of([]) : of([])
); );
} }
export function erasPrefs (api: ApiInterfaceRx): (withActive?: boolean) => Observable<DeriveEraPrefs[]> { export function erasPrefs (api: ApiInterfaceRx): (withActive?: boolean) => Observable<DeriveEraPrefs[]> {
return memo((withActive?: boolean): Observable<DeriveEraPrefs[]> => return memo((withActive = false): Observable<DeriveEraPrefs[]> =>
api.derive.staking.erasHistoric(withActive).pipe( api.derive.staking.erasHistoric(withActive).pipe(
switchMap((eras) => api.derive.staking._erasPrefs(eras)) switchMap((eras) => api.derive.staking._erasPrefs(eras, withActive))
) )
); );
} }
+42 -14
View File
@@ -10,25 +10,53 @@ import { Observable, of } from 'rxjs';
import { map, switchMap } from 'rxjs/operators'; import { map, switchMap } from 'rxjs/operators';
import { Option } from '@polkadot/types'; import { Option } from '@polkadot/types';
import { memo } from '../util'; import { deriveCache, memo } from '../util';
export function _erasRewards (api: ApiInterfaceRx): (eras: EraIndex[]) => Observable<DeriveEraRewards[]> { const CACHE_KEY = 'eraRewards';
return memo((eras: EraIndex[]): Observable<DeriveEraRewards[]> =>
eras.length function mapRewards (eras: EraIndex[], optRewards: Option<Balance>[]): DeriveEraRewards[] {
? api.query.staking.erasValidatorReward.multi<Option<Balance>>(eras).pipe( return eras.map((era, index): DeriveEraRewards => ({
map((rewards) => eras.map((era, index): DeriveEraRewards => ({ era,
era, eraReward: optRewards[index].unwrapOrDefault()
eraReward: rewards[index].unwrapOrDefault() }));
}))) }
)
: of([]) export function _erasRewards (api: ApiInterfaceRx): (eras: EraIndex[], withActive: boolean) => Observable<DeriveEraRewards[]> {
); return memo((eras: EraIndex[], withActive: boolean): Observable<DeriveEraRewards[]> => {
if (!eras.length) {
return of([]);
}
const cached: DeriveEraRewards[] = withActive
? []
: eras
.map((era) => deriveCache.get<DeriveEraRewards>(`${CACHE_KEY}-${era.toString()}`))
.filter((value): value is DeriveEraRewards => !!value);
const remaining = eras.filter((era) => !cached.some((cached) => era.eq(cached.era)));
if (!remaining.length) {
return of(cached);
}
return api.query.staking.erasValidatorReward.multi<Option<Balance>>(remaining).pipe(
map((optRewards) => {
const query = mapRewards(remaining, optRewards);
!withActive && query.forEach((q) => deriveCache.set(`${CACHE_KEY}-${q.era.toString()}`, q));
return eras.map((era): DeriveEraRewards =>
cached.find((cached) => era.eq(cached.era)) ||
query.find((query) => era.eq(query.era)) as DeriveEraRewards
);
})
);
});
} }
export function erasRewards (api: ApiInterfaceRx): (withActive?: boolean) => Observable<DeriveEraRewards[]> { export function erasRewards (api: ApiInterfaceRx): (withActive?: boolean) => Observable<DeriveEraRewards[]> {
return memo((withActive?: boolean): Observable<DeriveEraRewards[]> => return memo((withActive = false): Observable<DeriveEraRewards[]> =>
api.derive.staking.erasHistoric(withActive).pipe( api.derive.staking.erasHistoric(withActive).pipe(
switchMap((eras) => api.derive.staking._erasRewards(eras)) switchMap((eras) => api.derive.staking._erasRewards(eras, withActive))
) )
); );
} }
+33 -12
View File
@@ -11,7 +11,9 @@ import { Observable, combineLatest, of } from 'rxjs';
import { map, switchMap } from 'rxjs/operators'; import { map, switchMap } from 'rxjs/operators';
import { Option, StorageKey } from '@polkadot/types'; import { Option, StorageKey } from '@polkadot/types';
import { memo } from '../util'; import { deriveCache, memo } from '../util';
const CACHE_KEY = 'eraSlashes';
function mapSlashes (era: EraIndex, noms: [StorageKey, Option<BalanceOf>][], vals: [StorageKey, Option<ITuple<[Perbill, BalanceOf]>>][]): DeriveEraSlashes { function mapSlashes (era: EraIndex, noms: [StorageKey, Option<BalanceOf>][], vals: [StorageKey, Option<ITuple<[Perbill, BalanceOf]>>][]): DeriveEraSlashes {
const nominators: DeriveEraValSlash = {}; const nominators: DeriveEraValSlash = {};
@@ -28,31 +30,50 @@ function mapSlashes (era: EraIndex, noms: [StorageKey, Option<BalanceOf>][], val
return { era, nominators, validators }; return { era, nominators, validators };
} }
export function _eraSlashes (api: ApiInterfaceRx): (era: EraIndex, withActive: boolean) => Observable<DeriveEraSlashes> {
return memo((era: EraIndex, withActive: boolean): Observable<DeriveEraSlashes> => {
const cacheKey = `${CACHE_KEY}-${era.toString()}`;
const cached = withActive
? undefined
: deriveCache.get<DeriveEraSlashes>(cacheKey);
return cached
? of(cached)
: combineLatest([
api.query.staking.nominatorSlashInEra.entries(era),
api.query.staking.validatorSlashInEra.entries(era)
]).pipe(
map(([noms, vals]): DeriveEraSlashes => {
const value = mapSlashes(era, noms, vals);
!withActive && deriveCache.set(cacheKey, value);
return value;
})
);
});
}
export function eraSlashes (api: ApiInterfaceRx): (era: EraIndex) => Observable<DeriveEraSlashes> { export function eraSlashes (api: ApiInterfaceRx): (era: EraIndex) => Observable<DeriveEraSlashes> {
return memo((era: EraIndex): Observable<DeriveEraSlashes> => return memo((era: EraIndex): Observable<DeriveEraSlashes> =>
combineLatest([ api.derive.staking._eraSlashes(era, true)
api.query.staking.nominatorSlashInEra.entries(era),
api.query.staking.validatorSlashInEra.entries(era)
]).pipe(
map(([noms, vals]) => mapSlashes(era, noms, vals))
)
); );
} }
export function _erasSlashes (api: ApiInterfaceRx): (eras: EraIndex[]) => Observable<DeriveEraSlashes[]> { export function _erasSlashes (api: ApiInterfaceRx): (eras: EraIndex[], withActive: boolean) => Observable<DeriveEraSlashes[]> {
return memo((eras: EraIndex[]): Observable<DeriveEraSlashes[]> => return memo((eras: EraIndex[], withActive: boolean): Observable<DeriveEraSlashes[]> =>
eras.length eras.length
? combineLatest( ? combineLatest(
eras.map((era) => api.derive.staking.eraSlashes(era)) eras.map((era) => api.derive.staking._eraSlashes(era, withActive))
) )
: of([]) : of([])
); );
} }
export function erasSlashes (api: ApiInterfaceRx): (withActive?: boolean) => Observable<DeriveEraSlashes[]> { export function erasSlashes (api: ApiInterfaceRx): (withActive?: boolean) => Observable<DeriveEraSlashes[]> {
return memo((withActive?: boolean): Observable<DeriveEraSlashes[]> => return memo((withActive = false): Observable<DeriveEraSlashes[]> =>
api.derive.staking.erasHistoric(withActive).pipe( api.derive.staking.erasHistoric(withActive).pipe(
switchMap((eras) => api.derive.staking._erasSlashes(eras)) switchMap((eras) => api.derive.staking._erasSlashes(eras, withActive))
) )
); );
} }
@@ -11,7 +11,7 @@ import { map, switchMap } from 'rxjs/operators';
import { memo } from '../util'; import { memo } from '../util';
export function ownSlashes (api: ApiInterfaceRx): (accountId: Uint8Array | string, withActive?: boolean) => Observable<DeriveStakerSlashes[]> { export function ownSlashes (api: ApiInterfaceRx): (accountId: Uint8Array | string, withActive?: boolean) => Observable<DeriveStakerSlashes[]> {
return memo((accountId: Uint8Array | string, withActive?: boolean): Observable<DeriveStakerSlashes[]> => { return memo((accountId: Uint8Array | string, withActive = false): Observable<DeriveStakerSlashes[]> => {
return api.derive.staking.erasHistoric(withActive).pipe( return api.derive.staking.erasHistoric(withActive).pipe(
switchMap((eras) => switchMap((eras) =>
eras.length eras.length
+2 -1
View File
@@ -10,6 +10,7 @@ import { DeriveStakingQuery } from '../types';
import { Observable, combineLatest, of } from 'rxjs'; import { Observable, combineLatest, of } from 'rxjs';
import { map, switchMap } from 'rxjs/operators'; import { map, switchMap } from 'rxjs/operators';
import { Option, Vec } from '@polkadot/types'; import { Option, Vec } from '@polkadot/types';
import { isFunction } from '@polkadot/util';
import { memo } from '../util'; import { memo } from '../util';
@@ -87,7 +88,7 @@ export function queryWithQueued (api: ApiInterfaceRx): (accountId: Uint8Array |
const stashId = api.registry.createType('AccountId', accountId); const stashId = api.registry.createType('AccountId', accountId);
return ( return (
api.query.staking.erasStakers isFunction(api.query.staking.erasStakers)
? retrieveCurr(api, stashId) ? retrieveCurr(api, stashId)
: retrievePrev(api, stashId) : retrievePrev(api, stashId)
).pipe( ).pipe(
@@ -11,11 +11,11 @@ import { map, switchMap } from 'rxjs/operators';
import { memo } from '../util'; import { memo } from '../util';
export function _stakerExposure (api: ApiInterfaceRx): (accountId: Uint8Array | string, eras: EraIndex[]) => Observable<DeriveStakerExposure[]> { export function _stakerExposure (api: ApiInterfaceRx): (accountId: Uint8Array | string, eras: EraIndex[], withActive: boolean) => Observable<DeriveStakerExposure[]> {
return memo((accountId: Uint8Array | string, eras: EraIndex[]): Observable<DeriveStakerExposure[]> => { return memo((accountId: Uint8Array | string, eras: EraIndex[], withActive: boolean): Observable<DeriveStakerExposure[]> => {
const stakerId = api.registry.createType('AccountId', accountId).toString(); const stakerId = api.registry.createType('AccountId', accountId).toString();
return api.derive.staking._erasExposure(eras).pipe( return api.derive.staking._erasExposure(eras, withActive).pipe(
map((exposures): DeriveStakerExposure[] => map((exposures): DeriveStakerExposure[] =>
exposures.map(({ era, nominators: allNominators, validators: allValidators }): DeriveStakerExposure => { exposures.map(({ era, nominators: allNominators, validators: allValidators }): DeriveStakerExposure => {
const isValidator = !!allValidators[stakerId]; const isValidator = !!allValidators[stakerId];
@@ -38,9 +38,9 @@ export function _stakerExposure (api: ApiInterfaceRx): (accountId: Uint8Array |
} }
export function stakerExposure (api: ApiInterfaceRx): (accountId: Uint8Array | string, withActive?: boolean) => Observable<DeriveStakerExposure[]> { export function stakerExposure (api: ApiInterfaceRx): (accountId: Uint8Array | string, withActive?: boolean) => Observable<DeriveStakerExposure[]> {
return memo((accountId: Uint8Array | string, withActive?: boolean): Observable<DeriveStakerExposure[]> => return memo((accountId: 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)) switchMap((eras) => api.derive.staking._stakerExposure(accountId, eras, withActive))
) )
); );
} }
@@ -11,11 +11,11 @@ import { map, switchMap } from 'rxjs/operators';
import { memo } from '../util'; import { memo } from '../util';
export function _stakerPoints (api: ApiInterfaceRx): (accountId: Uint8Array | string, eras: EraIndex[]) => Observable<DeriveStakerPoints[]> { export function _stakerPoints (api: ApiInterfaceRx): (accountId: Uint8Array | string, eras: EraIndex[], withActive: boolean) => Observable<DeriveStakerPoints[]> {
return memo((accountId: Uint8Array | string, eras: EraIndex[]): Observable<DeriveStakerPoints[]> => { return memo((accountId: Uint8Array | string, eras: EraIndex[], withActive: boolean): Observable<DeriveStakerPoints[]> => {
const stakerId = api.registry.createType('AccountId', accountId).toString(); const stakerId = api.registry.createType('AccountId', accountId).toString();
return api.derive.staking._erasPoints(eras).pipe( return api.derive.staking._erasPoints(eras, withActive).pipe(
map((points): DeriveStakerPoints[] => map((points): DeriveStakerPoints[] =>
points.map(({ era, eraPoints, validators }): DeriveStakerPoints => ({ points.map(({ era, eraPoints, validators }): DeriveStakerPoints => ({
era, era,
@@ -28,9 +28,9 @@ export function _stakerPoints (api: ApiInterfaceRx): (accountId: Uint8Array | st
} }
export function stakerPoints (api: ApiInterfaceRx): (accountId: Uint8Array | string, withActive?: boolean) => Observable<DeriveStakerPoints[]> { export function stakerPoints (api: ApiInterfaceRx): (accountId: Uint8Array | string, withActive?: boolean) => Observable<DeriveStakerPoints[]> {
return memo((accountId: Uint8Array | string, withActive?: boolean): Observable<DeriveStakerPoints[]> => return memo((accountId: Uint8Array | string, withActive = false): Observable<DeriveStakerPoints[]> =>
api.derive.staking.erasHistoric(withActive).pipe( api.derive.staking.erasHistoric(withActive).pipe(
switchMap((eras) => api.derive.staking._stakerPoints(accountId, eras)) switchMap((eras) => api.derive.staking._stakerPoints(accountId, eras, withActive))
) )
); );
} }
@@ -10,17 +10,18 @@ import BN from 'bn.js';
import { Observable, combineLatest, of } from 'rxjs'; import { Observable, combineLatest, of } from 'rxjs';
import { map, switchMap } from 'rxjs/operators'; import { map, switchMap } from 'rxjs/operators';
import { Option } from '@polkadot/types'; import { Option } from '@polkadot/types';
import { isFunction } from '@polkadot/util';
import { memo } from '../util'; import { memo } from '../util';
type Result = [DeriveEraPoints[], DeriveEraPrefs[], DeriveEraRewards[], DeriveStakerExposure[]]; type ErasResult = [{ unwrapOr: (value: BN) => BN }, DeriveEraPoints[], DeriveEraPrefs[], DeriveEraRewards[]];
const ZERO = new BN(0); const ZERO = new BN(0);
const MIN_ONE = new BN(-1); const MIN_ONE = new BN(-1);
const COMM_DIV = new BN(1_000_000_000); const COMM_DIV = new BN(1_000_000_000);
const MAX_ERAS = new BN(1_000_000_000); const MAX_ERAS = new BN(1_000_000_000);
function parseRewards (api: ApiInterfaceRx, stashId: AccountId, [erasPoints, erasPrefs, erasRewards, exposures]: Result): DeriveStakerReward[] { 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: 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') };
@@ -97,28 +98,29 @@ function filterEras (eras: EraIndex[], stakingLedger: StakingLedger): EraIndex[]
return eras.filter((era) => filterEra(era, stakingLedger)); return eras.filter((era) => filterEra(era, stakingLedger));
} }
function filterRewards (api: ApiInterfaceRx, rewards: DeriveStakerReward[], stakingLedger: StakingLedger, withActive?: boolean): Observable<DeriveStakerReward[]> { function filterRewards (api: ApiInterfaceRx, eras: EraIndex[], migrateEra: BN, rewards: DeriveStakerReward[], stakingLedger: StakingLedger, withActive: boolean): Observable<DeriveStakerReward[]> {
if (withActive) { if (withActive) {
return of(rewards); return of(rewards);
} }
const validators = uniqValidators(rewards); const validators = uniqValidators(rewards);
return combineLatest([ return (
api.query.staking.migrateEra isFunction(api.tx.staking.payoutStakers)
? api.query.staking.migrateEra<Option<EraIndex>>()
: of({ unwrapOr: () => api.tx.staking.payoutStakers ? MIN_ONE : MAX_ERAS }),
api.tx.staking.payoutStakers
? api.derive.staking.queryMulti(validators) ? api.derive.staking.queryMulti(validators)
: of([]) : of([])
]).pipe( ).pipe(
map(([optMigrate, queryValidators]): DeriveStakerReward[] => { map((queryValidators): DeriveStakerReward[] => {
const migrateEra: BN = optMigrate.unwrapOr(MIN_ONE); const filter = withActive
? eras
: filterEras(eras, stakingLedger);
return rewards return rewards
.filter(({ isEmpty }) => !isEmpty) .filter(({ isEmpty }) => !isEmpty)
.filter((reward): boolean => { .filter((reward): boolean => {
if (reward.era.lte(migrateEra)) { if (!filter.some((filter) => reward.era.eq(filter))) {
return false;
} else if (reward.era.lt(migrateEra)) {
// we filter again here, the actual ledger may have changed, e.g. something has been claimed // we filter again here, the actual ledger may have changed, e.g. something has been claimed
return filterEra(reward.era, stakingLedger); return filterEra(reward.era, stakingLedger);
} }
@@ -154,35 +156,41 @@ function filterRewards (api: ApiInterfaceRx, rewards: DeriveStakerReward[], stak
); );
} }
export function _stakerRewards (api: ApiInterfaceRx): (accountId: Uint8Array | string, eras: EraIndex[], withActive?: boolean) => Observable<DeriveStakerReward[]> { export function _stakerRewardsEras (api: ApiInterfaceRx): (eras: EraIndex[], withActive: boolean) => Observable<ErasResult> {
return memo((accountId: Uint8Array | string, _eras: EraIndex[], withActive?: boolean): Observable<DeriveStakerReward[]> => return memo((eras: EraIndex[], withActive: boolean): Observable<ErasResult> =>
api.derive.staking.query(accountId).pipe( combineLatest([
switchMap(({ stakingLedger, stashId }): Observable<DeriveStakerReward[]> => { isFunction(api.query.staking.migrateEra)
? api.query.staking.migrateEra<Option<EraIndex>>()
: of({ unwrapOr: () => isFunction(api.tx.staking.payoutStakers) ? ZERO : MAX_ERAS }),
api.derive.staking._erasPoints(eras, withActive),
api.derive.staking._erasPrefs(eras, withActive),
api.derive.staking._erasRewards(eras, withActive)
])
);
}
export function _stakerRewards (api: ApiInterfaceRx): (accountId: Uint8Array | string, eras: EraIndex[], withActive: boolean) => Observable<DeriveStakerReward[]> {
return memo((accountId: Uint8Array | string, eras: EraIndex[], withActive: boolean): Observable<DeriveStakerReward[]> =>
combineLatest([
api.derive.staking.query(accountId),
api.derive.staking._stakerExposure(accountId, eras, withActive),
api.derive.staking._stakerRewardsEras(eras, withActive)
]).pipe(
switchMap(([{ stakingLedger, stashId }, exposures, erasResult]): Observable<DeriveStakerReward[]> => {
const migrateEra: BN = erasResult[0].unwrapOr(ZERO);
if (!stashId || !stakingLedger) { if (!stashId || !stakingLedger) {
return of([]); return of([]);
} }
const eras = withActive return filterRewards(api, eras, migrateEra, parseRewards(api, stashId, erasResult, exposures), stakingLedger, withActive);
? _eras
: filterEras(_eras, stakingLedger);
return combineLatest([
api.derive.staking._erasPoints(eras),
api.derive.staking._erasPrefs(eras),
api.derive.staking._erasRewards(eras),
api.derive.staking._stakerExposure(stashId, eras)
]).pipe(
switchMap((result): Observable<DeriveStakerReward[]> =>
filterRewards(api, parseRewards(api, stashId, result), stakingLedger, withActive)
)
);
}) })
) )
); );
} }
export function stakerRewards (api: ApiInterfaceRx): (accountId: Uint8Array | string, withActive?: boolean) => Observable<DeriveStakerReward[]> { export function stakerRewards (api: ApiInterfaceRx): (accountId: Uint8Array | string, withActive?: boolean) => Observable<DeriveStakerReward[]> {
return memo((accountId: Uint8Array | string, withActive?: boolean): Observable<DeriveStakerReward[]> => return memo((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))
) )
@@ -190,7 +198,7 @@ export function stakerRewards (api: ApiInterfaceRx): (accountId: Uint8Array | st
} }
export function stakerRewardsMulti (api: ApiInterfaceRx): (accountIds: (Uint8Array | string)[], withActive?: boolean) => Observable<DeriveStakerReward[][]> { export function stakerRewardsMulti (api: ApiInterfaceRx): (accountIds: (Uint8Array | string)[], withActive?: boolean) => Observable<DeriveStakerReward[][]> {
return memo((accountIds: (Uint8Array | string)[], withActive?: boolean): Observable<DeriveStakerReward[][]> => return memo((accountIds: (Uint8Array | string)[], withActive = false): Observable<DeriveStakerReward[][]> =>
accountIds.length accountIds.length
? api.derive.staking.erasHistoric(withActive).pipe( ? api.derive.staking.erasHistoric(withActive).pipe(
switchMap((eras) => switchMap((eras) =>
@@ -11,11 +11,11 @@ import { map, switchMap } from 'rxjs/operators';
import { memo } from '../util'; import { memo } from '../util';
export function _stakerSlashes (api: ApiInterfaceRx): (accountId: Uint8Array | string, eras: EraIndex[]) => Observable<DeriveStakerSlashes[]> { export function _stakerSlashes (api: ApiInterfaceRx): (accountId: Uint8Array | string, eras: EraIndex[], withActive: boolean) => Observable<DeriveStakerSlashes[]> {
return memo((accountId: Uint8Array | string, eras: EraIndex[]): Observable<DeriveStakerSlashes[]> => { return memo((accountId: Uint8Array | string, eras: EraIndex[], withActive: boolean): Observable<DeriveStakerSlashes[]> => {
const stakerId = api.registry.createType('AccountId', accountId).toString(); const stakerId = api.registry.createType('AccountId', accountId).toString();
return api.derive.staking._erasSlashes(eras).pipe( return api.derive.staking._erasSlashes(eras, withActive).pipe(
map((slashes): DeriveStakerSlashes[] => map((slashes): DeriveStakerSlashes[] =>
slashes.map(({ era, nominators, validators }): DeriveStakerSlashes => ({ slashes.map(({ era, nominators, validators }): DeriveStakerSlashes => ({
era, era,
@@ -27,9 +27,9 @@ export function _stakerSlashes (api: ApiInterfaceRx): (accountId: Uint8Array | s
} }
export function stakerSlashes (api: ApiInterfaceRx): (accountId: Uint8Array | string, withActive?: boolean) => Observable<DeriveStakerSlashes[]> { export function stakerSlashes (api: ApiInterfaceRx): (accountId: Uint8Array | string, withActive?: boolean) => Observable<DeriveStakerSlashes[]> {
return memo((accountId: Uint8Array | string, withActive?: boolean): Observable<DeriveStakerSlashes[]> => return memo((accountId: Uint8Array | string, withActive = false): Observable<DeriveStakerSlashes[]> =>
api.derive.staking.erasHistoric(withActive).pipe( api.derive.staking.erasHistoric(withActive).pipe(
switchMap((eras) => api.derive.staking._stakerSlashes(accountId, eras)) switchMap((eras) => api.derive.staking._stakerSlashes(accountId, eras, withActive))
) )
); );
} }
+1 -2
View File
@@ -2,11 +2,10 @@
// This software may be modified and distributed under the terms // This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details. // of the Apache-2.0 license. See the LICENSE file for details.
import type BN from 'bn.js';
import { AccountId, Balance, EraIndex, Exposure, Keys, RewardDestination, RewardPoint, StakingLedger, ValidatorPrefs } from '@polkadot/types/interfaces'; import { AccountId, Balance, EraIndex, Exposure, Keys, RewardDestination, RewardPoint, StakingLedger, ValidatorPrefs } from '@polkadot/types/interfaces';
import { DeriveSessionIndexes } from '../session/types'; import { DeriveSessionIndexes } from '../session/types';
import BN from 'bn.js';
export type DeriveEraValPoints = Record<string, RewardPoint>; export type DeriveEraValPoints = Record<string, RewardPoint>;
export type DeriveEraValPrefs = Record<string, ValidatorPrefs>; export type DeriveEraValPrefs = Record<string, ValidatorPrefs>;
+7
View File
@@ -4,4 +4,11 @@
import BN from 'bn.js'; import BN from 'bn.js';
export const FALLBACK_MAX_HASH_COUNT = 250;
// default here to 5 min eras, adjusted based on the actual blocktime
export const FALLBACK_PERIOD = new BN(6 * 1000);
export const MAX_FINALITY_LAG = new BN(5); export const MAX_FINALITY_LAG = new BN(5);
export const MORTAL_PERIOD = new BN(5 * 60 * 1000);
+2 -6
View File
@@ -5,23 +5,19 @@
import { Header, Index } from '@polkadot/types/interfaces'; import { Header, Index } from '@polkadot/types/interfaces';
import { AnyNumber, Codec, IExtrinsicEra } from '@polkadot/types/types'; import { AnyNumber, Codec, IExtrinsicEra } from '@polkadot/types/types';
import BN from 'bn.js';
import { Observable, combineLatest, of } from 'rxjs'; import { Observable, combineLatest, of } from 'rxjs';
import { map, switchMap } from 'rxjs/operators'; import { map, switchMap } from 'rxjs/operators';
import { ApiInterfaceRx } from '@polkadot/api/types'; import { ApiInterfaceRx } from '@polkadot/api/types';
import { isNumber, isUndefined } from '@polkadot/util'; import { isNumber, isUndefined } from '@polkadot/util';
import { FALLBACK_PERIOD, MAX_FINALITY_LAG, MORTAL_PERIOD } from './constants';
interface Result { interface Result {
header: Header | null; header: Header | null;
mortalLength: number; mortalLength: number;
nonce: Index; nonce: Index;
} }
// default here to 5 min eras, adjusted based on the actual blocktime
const FALLBACK_PERIOD = new BN(6 * 1000);
const MAX_FINALITY_LAG = new BN(5);
const MORTAL_PERIOD = new BN(5 * 60 * 1000);
function latestNonce (api: ApiInterfaceRx, address: string): Observable<Index> { function latestNonce (api: ApiInterfaceRx, address: string): Observable<Index> {
return api.derive.balances.account(address).pipe( return api.derive.balances.account(address).pipe(
map(({ accountNonce }): Index => accountNonce) map(({ accountNonce }): Index => accountNonce)
@@ -9,7 +9,7 @@ import runtimeTypes from '@polkadot/types/interfaces/runtime/definitions';
import { Struct } from '@polkadot/types'; import { Struct } from '@polkadot/types';
// We can ignore the properties, added via Struct.with // We can ignore the properties, added via Struct.with
const _Header: Constructor<Header> = Struct.with(runtimeTypes.types.Header as any) as any; const _Header = Struct.with(runtimeTypes.types.Header as any) as Constructor<Header>;
/** /**
* @name HeaderExtended * @name HeaderExtended
+1 -1
View File
@@ -2,9 +2,9 @@
// This software may be modified and distributed under the terms // This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details. // of the Apache-2.0 license. See the LICENSE file for details.
import type BN from 'bn.js';
import { AccountId, Balance, BalanceLock, BalanceLockTo212, BalanceOf, Bid, BidKind, BlockNumber, Hash, Index, Proposal, ProposalIndex, SetIndex, SocietyVote, StrikeCount, TreasuryProposal, Votes, VoteIndex, VouchingStatus } from '@polkadot/types/interfaces'; import { AccountId, Balance, BalanceLock, BalanceLockTo212, BalanceOf, Bid, BidKind, BlockNumber, Hash, Index, Proposal, ProposalIndex, SetIndex, SocietyVote, StrikeCount, TreasuryProposal, Votes, VoteIndex, VouchingStatus } from '@polkadot/types/interfaces';
import BN from 'bn.js';
import { u32 } from '@polkadot/types'; import { u32 } from '@polkadot/types';
export * from './accounts/types'; export * from './accounts/types';
+66
View File
@@ -0,0 +1,66 @@
// Copyright 2017-2020 @polkadot/api-derive authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { DeriveCache } from './types';
import { deriveNoopCache } from './cacheImpl';
interface CacheValue<T> {
v: T;
x: number;
}
const CHACHE_EXPIRY = 7 * (24 * 60) * (60 * 1000);
let deriveCache: DeriveCache;
function wrapCache (keyStart: string, cache: DeriveCache): DeriveCache {
return {
del: (partial: string): void => cache.del(`${keyStart}${partial}`),
forEach: cache.forEach,
get: <T = any> (partial: string): T | undefined => {
const key = `${keyStart}${partial}`;
const cached = cache.get<CacheValue<T>>(key);
if (cached) {
cached.x = Date.now();
cache.set(key, cached);
return cached.v;
}
return undefined;
},
set: (partial: string, v: unknown): void => {
cache.set(`${keyStart}${partial}`, { v, x: Date.now() });
}
};
}
function clearCache (cache: DeriveCache): void {
// clear all expired values
const now = Date.now();
const all: any[] = [];
cache.forEach((key: string, { x }: CacheValue<any>): void => {
((now - x) > CHACHE_EXPIRY) && all.push(key);
});
// don't do delete inside loop, just in-case
all.forEach((key) => cache.del(key));
}
export function setDeriveCache (prefix = '', cache?: DeriveCache): void {
deriveCache = cache
? wrapCache(`derive:${prefix}:`, cache)
: deriveNoopCache;
if (cache) {
clearCache(cache);
}
}
setDeriveCache();
export { deriveCache };
+35
View File
@@ -0,0 +1,35 @@
// Copyright 2017-2020 @polkadot/api-derive authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { DeriveCache } from './types';
const mapCache = new Map<string, any>();
const deriveMapCache: DeriveCache = {
del: (key: string): void => {
mapCache.delete(key);
},
forEach: (cb: (key: string, value: any) => void): void => {
const entries = mapCache.entries();
for (const entry in entries) {
cb(entry[0], entry[1]);
}
},
get: <T = any> (key: string): T | undefined => {
return mapCache.get(key) as T;
},
set: (key: string, value: any): void => {
mapCache.set(key, value);
}
};
const deriveNoopCache: DeriveCache = {
del: (): void => undefined,
forEach: () => undefined,
get: (): undefined => undefined,
set: (_: string, value: unknown): unknown => value
};
export { deriveMapCache, deriveNoopCache };
+2
View File
@@ -5,6 +5,8 @@
import { drr } from '@polkadot/rpc-core/rxjs'; import { drr } from '@polkadot/rpc-core/rxjs';
export * from './approvalFlagsToBools'; export * from './approvalFlagsToBools';
export * from './cache';
export * from './cacheImpl';
export * from './memo'; export * from './memo';
export { drr }; export { drr };
+10
View File
@@ -0,0 +1,10 @@
// Copyright 2017-2020 @polkadot/api-derive authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
export interface DeriveCache {
del: (key: string) => void;
forEach: (cb: (key: string, value: any) => void) => void;
get: <T = any> (key: string) => T | undefined;
set: (key: string, value: any) => void;
}
+1
View File
@@ -92,6 +92,7 @@ const api = await ApiPromise.create({
Some of the users of the API (let us know if you are missing from the list), include - Some of the users of the API (let us know if you are missing from the list), include -
- [Polkadot-JS UI](https://github.com/polkadot-js/apps) A user-interface that allows you to make transactions, query the network or participate in actions on the network such as referendums and staking - [Polkadot-JS UI](https://github.com/polkadot-js/apps) A user-interface that allows you to make transactions, query the network or participate in actions on the network such as referendums and staking
- [KodaDot](https://github.com/vue-polkadot/apps) ([twitter](https://twitter.com/KodaDot)) - Vue.js web wallet, governance dashboard and aspiring performance (lightweight) alternative to original apps, mobile-first.
- [Polkabot](https://gitlab.com/Polkabot) Polkabot is a Matrix chatbot that keeps an eye on the Polkadot network. You can see Polkabot in action in https://matrix.to/#/#polkadot-network-status:matrix.org - [Polkabot](https://gitlab.com/Polkabot) Polkabot is a Matrix chatbot that keeps an eye on the Polkadot network. You can see Polkabot in action in https://matrix.to/#/#polkadot-network-status:matrix.org
- [Polkawallet.io](https://polkawallet.io) and [Polkawallet (Github)](https://github.com/polkawallet-io/polkawallet-RN/) A mobile wallet for the Polkadot network to manage funds and make transactions, available on both Androind and iOS - [Polkawallet.io](https://polkawallet.io) and [Polkawallet (Github)](https://github.com/polkawallet-io/polkawallet-RN/) A mobile wallet for the Polkadot network to manage funds and make transactions, available on both Androind and iOS
- [PolkaStats.io](https://polkastats.io), [PolkaStats frontend GitHub repository](https://github.com/Colm3na/polkastats-v2) and [PolkaStats backend GitHub repository](https://github.com/Colm3na/polkastats-backend-v2) Polkadot network statistics (currently Kusama and Alexander). Shows network information and staking details from validators and intentions. - [PolkaStats.io](https://polkastats.io), [PolkaStats frontend GitHub repository](https://github.com/Colm3na/polkastats-v2) and [PolkaStats backend GitHub repository](https://github.com/Colm3na/polkastats-backend-v2) Polkadot network statistics (currently Kusama and Alexander). Shows network information and staking details from validators and intentions.
+14 -14
View File
@@ -1,6 +1,6 @@
{ {
"name": "@polkadot/api", "name": "@polkadot/api",
"version": "1.11.1", "version": "1.16.1",
"description": "Promise and RxJS wrappers around the Polkadot JS RPC", "description": "Promise and RxJS wrappers around the Polkadot JS RPC",
"main": "index.js", "main": "index.js",
"keywords": [ "keywords": [
@@ -26,21 +26,21 @@
}, },
"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.9.2", "@babel/runtime": "^7.9.6",
"@polkadot/api-derive": "1.11.1", "@polkadot/api-derive": "1.16.1",
"@polkadot/keyring": "^2.8.1", "@polkadot/keyring": "^2.11.1",
"@polkadot/metadata": "1.11.1", "@polkadot/metadata": "1.16.1",
"@polkadot/rpc-core": "1.11.1", "@polkadot/rpc-core": "1.16.1",
"@polkadot/rpc-provider": "1.11.1", "@polkadot/rpc-provider": "1.16.1",
"@polkadot/types": "1.11.1", "@polkadot/types": "1.16.1",
"@polkadot/types-known": "1.11.1", "@polkadot/types-known": "1.16.1",
"@polkadot/util": "^2.8.1", "@polkadot/util": "^2.11.1",
"@polkadot/util-crypto": "^2.8.1", "@polkadot/util-crypto": "^2.11.1",
"bn.js": "^5.1.1", "bn.js": "^5.1.2",
"eventemitter3": "^4.0.0", "eventemitter3": "^4.0.4",
"rxjs": "^6.5.5" "rxjs": "^6.5.5"
}, },
"devDependencies": { "devDependencies": {
"@polkadot/keyring": "^2.8.1" "@polkadot/keyring": "^2.11.1"
} }
} }
+81 -34
View File
@@ -2,11 +2,12 @@
/* eslint-disable */ /* eslint-disable */
import { Codec } from '@polkadot/types/types'; import { Codec } from '@polkadot/types/types';
import { Vec } from '@polkadot/types/codec';
import { u32, u64 } from '@polkadot/types/primitive'; import { u32, u64 } from '@polkadot/types/primitive';
import { Gas } from '@polkadot/types/interfaces/contracts'; import { Balance, BalanceOf, BlockNumber, LockIdentifier, ModuleId, Moment, Percent, Permill, RuntimeDbWeight, Weight } from '@polkadot/types/interfaces/runtime';
import { Balance, BalanceOf, BlockNumber, Moment, Percent, Permill } from '@polkadot/types/interfaces/runtime';
import { SessionIndex } from '@polkadot/types/interfaces/session'; import { SessionIndex } from '@polkadot/types/interfaces/session';
import { EraIndex } from '@polkadot/types/interfaces/staking'; import { EraIndex } from '@polkadot/types/interfaces/staking';
import { WeightToFeeCoefficient } from '@polkadot/types/interfaces/support';
declare module '@polkadot/metadata/Decorated/consts/types' { declare module '@polkadot/metadata/Decorated/consts/types' {
export interface Constants { export interface Constants {
@@ -36,26 +37,6 @@ declare module '@polkadot/metadata/Decorated/consts/types' {
}; };
contracts: { contracts: {
[index: string]: AugmentedConst<object & Codec>; [index: string]: AugmentedConst<object & Codec>;
/**
* The maximum amount of gas that could be expended per block. A reasonable
* default value is 10_000_000.
**/
blockGasLimit: AugmentedConst<Gas>;
/**
* The base fee charged for calling into a contract. A reasonable default
* value is 135.
**/
callBaseFee: AugmentedConst<Gas>;
/**
* The fee required to instantiate a contract instance. A reasonable default value
* is 21.
**/
contractFee: AugmentedConst<BalanceOf>;
/**
* The base fee charged for instantiating a contract. A reasonable default value
* is 175.
**/
instantiateBaseFee: AugmentedConst<Gas>;
/** /**
* The maximum nesting level of a call/instantiate stack. A reasonable default * The maximum nesting level of a call/instantiate stack. A reasonable default
* value is 100. * value is 100.
@@ -72,6 +53,7 @@ declare module '@polkadot/metadata/Decorated/consts/types' {
/** /**
* The amount of funds a contract should deposit in order to offset * The amount of funds a contract should deposit in order to offset
* the cost of one byte. * the cost of one byte.
*
* Let's suppose the deposit is 1,000 BU (balance units)/byte and the rent is 1 BU/byte/day, * Let's suppose the deposit is 1,000 BU (balance units)/byte and the rent is 1 BU/byte/day,
* then a contract with 1,000,000 BU that uses 1,000 bytes of storage would pay no rent. * then a contract with 1,000,000 BU that uses 1,000 bytes of storage would pay no rent.
* But if the balance reduced to 500,000 BU and the storage stayed the same at 1,000, * But if the balance reduced to 500,000 BU and the storage stayed the same at 1,000,
@@ -80,6 +62,7 @@ declare module '@polkadot/metadata/Decorated/consts/types' {
rentDepositOffset: AugmentedConst<BalanceOf>; rentDepositOffset: AugmentedConst<BalanceOf>;
/** /**
* Number of block delay an extrinsic claim surcharge has. * Number of block delay an extrinsic claim surcharge has.
*
* When claim surcharge is called by an extrinsic the rent is checked * When claim surcharge is called by an extrinsic the rent is checked
* for current_block - delay * for current_block - delay
**/ **/
@@ -98,14 +81,6 @@ declare module '@polkadot/metadata/Decorated/consts/types' {
* The minimum amount required to generate a tombstone. * The minimum amount required to generate a tombstone.
**/ **/
tombstoneDeposit: AugmentedConst<BalanceOf>; tombstoneDeposit: AugmentedConst<BalanceOf>;
/**
* The fee to be paid for making a transaction; the base.
**/
transactionBaseFee: AugmentedConst<BalanceOf>;
/**
* The fee to be paid for making a transaction; the per-byte portion.
**/
transactionByteFee: AugmentedConst<BalanceOf>;
}; };
democracy: { democracy: {
[index: string]: AugmentedConst<object & Codec>; [index: string]: AugmentedConst<object & Codec>;
@@ -115,6 +90,7 @@ declare module '@polkadot/metadata/Decorated/consts/types' {
cooloffPeriod: AugmentedConst<BlockNumber>; cooloffPeriod: AugmentedConst<BlockNumber>;
/** /**
* The minimum period of locking and the period between a proposal being approved and enacted. * The minimum period of locking and the period between a proposal being approved and enacted.
*
* It should generally be a little more than the unstake period to ensure that * It should generally be a little more than the unstake period to ensure that
* voting stakers have an opportunity to remove themselves from the system in the case where * voting stakers have an opportunity to remove themselves from the system in the case where
* they are on the losing side of a vote. * they are on the losing side of a vote.
@@ -128,6 +104,10 @@ declare module '@polkadot/metadata/Decorated/consts/types' {
* How often (in blocks) new public referenda are launched. * How often (in blocks) new public referenda are launched.
**/ **/
launchPeriod: AugmentedConst<BlockNumber>; launchPeriod: AugmentedConst<BlockNumber>;
/**
* The maximum number of votes for an account.
**/
maxVotes: AugmentedConst<u32>;
/** /**
* The minimum amount to be used as a deposit for a public referendum proposal. * The minimum amount to be used as a deposit for a public referendum proposal.
**/ **/
@@ -146,6 +126,7 @@ declare module '@polkadot/metadata/Decorated/consts/types' {
candidacyBond: AugmentedConst<BalanceOf>; candidacyBond: AugmentedConst<BalanceOf>;
desiredMembers: AugmentedConst<u32>; desiredMembers: AugmentedConst<u32>;
desiredRunnersUp: AugmentedConst<u32>; desiredRunnersUp: AugmentedConst<u32>;
moduleId: AugmentedConst<LockIdentifier>;
termDuration: AugmentedConst<BlockNumber>; termDuration: AugmentedConst<BlockNumber>;
votingBond: AugmentedConst<BalanceOf>; votingBond: AugmentedConst<BalanceOf>;
}; };
@@ -160,6 +141,37 @@ declare module '@polkadot/metadata/Decorated/consts/types' {
**/ **/
windowSize: AugmentedConst<BlockNumber>; windowSize: AugmentedConst<BlockNumber>;
}; };
identity: {
[index: string]: AugmentedConst<object & Codec>;
/**
* The amount held on deposit for a registered identity.
**/
basicDeposit: AugmentedConst<BalanceOf>;
/**
* The amount held on deposit per additional field for a registered identity.
**/
fieldDeposit: AugmentedConst<BalanceOf>;
/**
* Maximum number of additional fields that may be stored in an ID. Needed to bound the I/O
* required to access an identity, but can be pretty high.
**/
maxAdditionalFields: AugmentedConst<u32>;
/**
* Maxmimum number of registrars allowed in the system. Needed to bound the complexity
* of, e.g., updating judgements.
**/
maxRegistrars: AugmentedConst<u32>;
/**
* The maximum number of sub-accounts allowed per identified account.
**/
maxSubAccounts: AugmentedConst<u32>;
/**
* The amount held on deposit for a registered subaccount. This should account for the fact
* that one storage item's value will increase by the size of an account ID, and there will be
* another trie item whose value is the size of an account ID plus 32 bytes.
**/
subAccountDeposit: AugmentedConst<BalanceOf>;
};
society: { society: {
[index: string]: AugmentedConst<object & Codec>; [index: string]: AugmentedConst<object & Codec>;
/** /**
@@ -175,6 +187,10 @@ declare module '@polkadot/metadata/Decorated/consts/types' {
* before they become suspended. * before they become suspended.
**/ **/
maxStrikes: AugmentedConst<u32>; maxStrikes: AugmentedConst<u32>;
/**
* The societies's module id
**/
moduleId: AugmentedConst<ModuleId>;
/** /**
* The amount of incentive paid within each period. Doesn't include VoterTip. * The amount of incentive paid within each period. Doesn't include VoterTip.
**/ **/
@@ -200,6 +216,33 @@ declare module '@polkadot/metadata/Decorated/consts/types' {
**/ **/
sessionsPerEra: AugmentedConst<SessionIndex>; sessionsPerEra: AugmentedConst<SessionIndex>;
}; };
system: {
[index: string]: AugmentedConst<object & Codec>;
/**
* The base weight of executing a block, independent of the transactions in the block.
**/
blockExecutionWeight: AugmentedConst<Weight>;
/**
* The maximum number of blocks to allow in mortal eras.
**/
blockHashCount: AugmentedConst<BlockNumber>;
/**
* The weight of runtime database operations the runtime can invoke.
**/
dbWeight: AugmentedConst<RuntimeDbWeight>;
/**
* The base weight of an Extrinsic in the block, independent of the of extrinsic being executed.
**/
extrinsicBaseWeight: AugmentedConst<Weight>;
/**
* The maximum length of a block (in bytes).
**/
maximumBlockLength: AugmentedConst<u32>;
/**
* The maximum weight of a block.
**/
maximumBlockWeight: AugmentedConst<Weight>;
};
timestamp: { timestamp: {
[index: string]: AugmentedConst<object & Codec>; [index: string]: AugmentedConst<object & Codec>;
/** /**
@@ -212,14 +255,14 @@ declare module '@polkadot/metadata/Decorated/consts/types' {
}; };
transactionPayment: { transactionPayment: {
[index: string]: AugmentedConst<object & Codec>; [index: string]: AugmentedConst<object & Codec>;
/**
* The fee to be paid for making a transaction; the base.
**/
transactionBaseFee: AugmentedConst<BalanceOf>;
/** /**
* The fee to be paid for making a transaction; the per-byte portion. * The fee to be paid for making a transaction; the per-byte portion.
**/ **/
transactionByteFee: AugmentedConst<BalanceOf>; transactionByteFee: AugmentedConst<BalanceOf>;
/**
* The polynomial that is applied in order to derive fee from weight.
**/
weightToFee: AugmentedConst<Vec<WeightToFeeCoefficient>>;
}; };
treasury: { treasury: {
[index: string]: AugmentedConst<object & Codec>; [index: string]: AugmentedConst<object & Codec>;
@@ -227,6 +270,10 @@ declare module '@polkadot/metadata/Decorated/consts/types' {
* Percentage of spare funds (if any) that are burnt per spend period. * Percentage of spare funds (if any) that are burnt per spend period.
**/ **/
burn: AugmentedConst<Permill>; burn: AugmentedConst<Permill>;
/**
* The treasury's module id, used for deriving its sovereign account ID.
**/
moduleId: AugmentedConst<ModuleId>;
/** /**
* Fraction of a proposal's value that should be bonded in order to place the proposal. * Fraction of a proposal's value that should be bonded in order to place the proposal.
* An accepted proposal gets these back. A rejected proposal does not. * An accepted proposal gets these back. A rejected proposal does not.
+78 -20
View File
@@ -5,19 +5,19 @@ import { AnyNumber, ITuple, Observable } from '@polkadot/types/types';
import { Option, U8aFixed, Vec } from '@polkadot/types/codec'; import { Option, U8aFixed, Vec } from '@polkadot/types/codec';
import { Bytes, Data, bool, u32, u64 } from '@polkadot/types/primitive'; import { Bytes, Data, bool, u32, u64 } from '@polkadot/types/primitive';
import { UncleEntryItem } from '@polkadot/types/interfaces/authorship'; import { UncleEntryItem } from '@polkadot/types/interfaces/authorship';
import { BabeAuthorityWeight, MaybeVrf, Randomness } from '@polkadot/types/interfaces/babe'; import { BabeAuthorityWeight, MaybeRandomness, NextConfigDescriptor, Randomness } from '@polkadot/types/interfaces/babe';
import { AccountData, BalanceLock, ReleasesBalances } from '@polkadot/types/interfaces/balances'; import { AccountData, BalanceLock, ReleasesBalances } from '@polkadot/types/interfaces/balances';
import { ProposalIndex, Votes } from '@polkadot/types/interfaces/collective'; import { ProposalIndex, Votes } from '@polkadot/types/interfaces/collective';
import { AuthorityId, RawVRFOutput } from '@polkadot/types/interfaces/consensus'; import { AuthorityId } from '@polkadot/types/interfaces/consensus';
import { CodeHash, ContractInfo, Gas, PrefabWasmModule, Schedule } from '@polkadot/types/interfaces/contracts'; import { CodeHash, ContractInfo, PrefabWasmModule, Schedule } from '@polkadot/types/interfaces/contracts';
import { PreimageStatus, PropIndex, Proposal, ProxyState, ReferendumIndex, ReferendumInfo, Voting } from '@polkadot/types/interfaces/democracy'; import { PreimageStatus, PropIndex, Proposal, ProxyState, ReferendumIndex, ReferendumInfo, ReleasesDemocracy, Voting } from '@polkadot/types/interfaces/democracy';
import { VoteThreshold } from '@polkadot/types/interfaces/elections'; import { VoteThreshold } from '@polkadot/types/interfaces/elections';
import { SetId, StoredPendingChange, StoredState } from '@polkadot/types/interfaces/grandpa'; import { SetId, StoredPendingChange, StoredState } from '@polkadot/types/interfaces/grandpa';
import { RegistrarInfo, Registration } from '@polkadot/types/interfaces/identity'; import { RegistrarInfo, Registration } from '@polkadot/types/interfaces/identity';
import { AuthIndex } from '@polkadot/types/interfaces/imOnline'; import { AuthIndex } from '@polkadot/types/interfaces/imOnline';
import { DeferredOffenceOf, Kind, OffenceDetails, OpaqueTimeSlot, ReportIdOf } from '@polkadot/types/interfaces/offences'; import { DeferredOffenceOf, Kind, OffenceDetails, OpaqueTimeSlot, ReportIdOf } from '@polkadot/types/interfaces/offences';
import { ActiveRecovery, RecoveryConfig } from '@polkadot/types/interfaces/recovery'; import { ActiveRecovery, RecoveryConfig } from '@polkadot/types/interfaces/recovery';
import { AccountId, AccountIndex, Balance, BalanceOf, BlockNumber, Hash, KeyTypeId, Moment, Perbill, ValidatorId, Weight } from '@polkadot/types/interfaces/runtime'; import { AccountId, AccountIndex, Balance, BalanceOf, BlockNumber, ExtrinsicsWeight, Hash, KeyTypeId, Moment, Perbill, ValidatorId } from '@polkadot/types/interfaces/runtime';
import { Scheduled, TaskAddress } from '@polkadot/types/interfaces/scheduler'; import { Scheduled, TaskAddress } from '@polkadot/types/interfaces/scheduler';
import { Keys, SessionIndex } from '@polkadot/types/interfaces/session'; import { Keys, SessionIndex } from '@polkadot/types/interfaces/session';
import { Bid, BidKind, SocietyVote, StrikeCount, VouchingStatus } from '@polkadot/types/interfaces/society'; import { Bid, BidKind, SocietyVote, StrikeCount, VouchingStatus } from '@polkadot/types/interfaces/society';
@@ -69,21 +69,28 @@ declare module '@polkadot/api/types/storage' {
* 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.
**/ **/
initialized: AugmentedQuery<ApiType, () => Observable<Option<MaybeVrf>>> & QueryableStorageEntry<ApiType>; initialized: AugmentedQuery<ApiType, () => Observable<Option<MaybeRandomness>>> & QueryableStorageEntry<ApiType>;
/** /**
* How late the current block is compared to its parent. * How late the current block is compared to its parent.
*
* This entry is populated as part of block execution and is cleaned up * This entry is populated as part of block execution and is cleaned up
* on block finalization. Querying this storage entry outside of block * on block finalization. Querying this storage entry outside of block
* execution context should always yield zero. * execution context should always yield zero.
**/ **/
lateness: AugmentedQuery<ApiType, () => Observable<BlockNumber>> & QueryableStorageEntry<ApiType>; lateness: AugmentedQuery<ApiType, () => Observable<BlockNumber>> & QueryableStorageEntry<ApiType>;
/**
* Next epoch configuration, if changed.
**/
nextEpochConfig: AugmentedQuery<ApiType, () => Observable<Option<NextConfigDescriptor>>> & QueryableStorageEntry<ApiType>;
/** /**
* Next epoch randomness. * Next epoch randomness.
**/ **/
nextRandomness: AugmentedQuery<ApiType, () => Observable<Randomness>> & QueryableStorageEntry<ApiType>; nextRandomness: AugmentedQuery<ApiType, () => Observable<Randomness>> & QueryableStorageEntry<ApiType>;
/** /**
* The epoch randomness for the *current* epoch. * The epoch randomness for the *current* epoch.
*
* # Security * # Security
*
* This MUST NOT be used for gambling, as it can be influenced by a * This MUST NOT be used for gambling, as it can be influenced by a
* malicious validator in the short term. It MAY be used in many * malicious validator in the short term. It MAY be used in many
* cryptographic protocols, however, so long as one remembers that this * cryptographic protocols, however, so long as one remembers that this
@@ -94,22 +101,29 @@ declare module '@polkadot/api/types/storage' {
randomness: AugmentedQuery<ApiType, () => Observable<Randomness>> & QueryableStorageEntry<ApiType>; randomness: AugmentedQuery<ApiType, () => Observable<Randomness>> & QueryableStorageEntry<ApiType>;
/** /**
* Randomness under construction. * Randomness under construction.
*
* We make a tradeoff between storage accesses and list length. * We make a tradeoff between storage accesses and list length.
* We store the under-construction randomness in segments of up to * We store the under-construction randomness in segments of up to
* `UNDER_CONSTRUCTION_SEGMENT_LENGTH`. * `UNDER_CONSTRUCTION_SEGMENT_LENGTH`.
*
* Once a segment reaches this length, we begin the next one. * Once a segment reaches this length, we begin the next one.
* We reset all segments and return to `0` at the beginning of every * We reset all segments and return to `0` at the beginning of every
* epoch. * epoch.
**/ **/
segmentIndex: AugmentedQuery<ApiType, () => Observable<u32>> & QueryableStorageEntry<ApiType>; segmentIndex: AugmentedQuery<ApiType, () => Observable<u32>> & QueryableStorageEntry<ApiType>;
underConstruction: AugmentedQuery<ApiType, (arg: u32 | AnyNumber | Uint8Array) => Observable<Vec<RawVRFOutput>>> & QueryableStorageEntry<ApiType>; /**
* TWOX-NOTE: `SegmentIndex` is an increasing integer, so this is okay.
**/
underConstruction: AugmentedQuery<ApiType, (arg: u32 | AnyNumber | Uint8Array) => Observable<Vec<Randomness>>> & QueryableStorageEntry<ApiType>;
}; };
balances: { balances: {
[index: string]: QueryableStorageEntry<ApiType>; [index: string]: QueryableStorageEntry<ApiType>;
/** /**
* The balance of an account. * The balance of an account.
*
* NOTE: THIS MAY NEVER BE IN EXISTENCE AND YET HAVE A `total().is_zero()`. If the total * NOTE: THIS MAY NEVER BE IN EXISTENCE AND YET HAVE A `total().is_zero()`. If the total
* is ever zero, then the entry *MUST* be removed. * is ever zero, then the entry *MUST* be removed.
*
* 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 module is used to store balances.
**/ **/
account: AugmentedQuery<ApiType, (arg: AccountId | string | Uint8Array) => Observable<AccountData>> & QueryableStorageEntry<ApiType>; account: AugmentedQuery<ApiType, (arg: AccountId | string | Uint8Array) => Observable<AccountData>> & QueryableStorageEntry<ApiType>;
@@ -120,6 +134,7 @@ declare module '@polkadot/api/types/storage' {
locks: AugmentedQuery<ApiType, (arg: AccountId | string | Uint8Array) => Observable<Vec<BalanceLock>>> & QueryableStorageEntry<ApiType>; locks: AugmentedQuery<ApiType, (arg: AccountId | string | Uint8Array) => Observable<Vec<BalanceLock>>> & QueryableStorageEntry<ApiType>;
/** /**
* Storage version of the pallet. * Storage version of the pallet.
*
* This is set to v2.0.0 for new networks. * This is set to v2.0.0 for new networks.
**/ **/
storageVersion: AugmentedQuery<ApiType, () => Observable<ReleasesBalances>> & QueryableStorageEntry<ApiType>; storageVersion: AugmentedQuery<ApiType, () => Observable<ReleasesBalances>> & QueryableStorageEntry<ApiType>;
@@ -140,20 +155,14 @@ declare module '@polkadot/api/types/storage' {
codeStorage: AugmentedQuery<ApiType, (arg: CodeHash | string | Uint8Array) => Observable<Option<PrefabWasmModule>>> & QueryableStorageEntry<ApiType>; codeStorage: AugmentedQuery<ApiType, (arg: CodeHash | string | Uint8Array) => Observable<Option<PrefabWasmModule>>> & QueryableStorageEntry<ApiType>;
/** /**
* The code associated with a given account. * The code associated with a given account.
*
* TWOX-NOTE: SAFE since `AccountId` is a secure hash.
**/ **/
contractInfoOf: AugmentedQuery<ApiType, (arg: AccountId | string | Uint8Array) => Observable<Option<ContractInfo>>> & QueryableStorageEntry<ApiType>; contractInfoOf: AugmentedQuery<ApiType, (arg: AccountId | string | Uint8Array) => Observable<Option<ContractInfo>>> & QueryableStorageEntry<ApiType>;
/** /**
* Current cost schedule for contracts. * Current cost schedule for contracts.
**/ **/
currentSchedule: AugmentedQuery<ApiType, () => Observable<Schedule>> & QueryableStorageEntry<ApiType>; currentSchedule: AugmentedQuery<ApiType, () => Observable<Schedule>> & QueryableStorageEntry<ApiType>;
/**
* The price of one unit of gas.
**/
gasPrice: AugmentedQuery<ApiType, () => Observable<BalanceOf>> & QueryableStorageEntry<ApiType>;
/**
* Gas spent so far in this block.
**/
gasSpent: AugmentedQuery<ApiType, () => Observable<Gas>> & QueryableStorageEntry<ApiType>;
/** /**
* A mapping from an original code hash to the original code, untouched by instrumentation. * A mapping from an original code hash to the original code, untouched by instrumentation.
**/ **/
@@ -200,8 +209,10 @@ declare module '@polkadot/api/types/storage' {
cancellations: AugmentedQuery<ApiType, (arg: Hash | string | Uint8Array) => Observable<bool>> & QueryableStorageEntry<ApiType>; cancellations: AugmentedQuery<ApiType, (arg: Hash | string | Uint8Array) => Observable<bool>> & QueryableStorageEntry<ApiType>;
/** /**
* Those who have locked a deposit. * Those who have locked a deposit.
*
* TWOX-NOTE: Safe, as increasing integer keys are safe.
**/ **/
depositOf: AugmentedQuery<ApiType, (arg: PropIndex | AnyNumber | Uint8Array) => Observable<Option<ITuple<[BalanceOf, Vec<AccountId>]>>>> & QueryableStorageEntry<ApiType>; depositOf: AugmentedQuery<ApiType, (arg: PropIndex | AnyNumber | Uint8Array) => Observable<Option<ITuple<[Vec<AccountId>, BalanceOf]>>>> & QueryableStorageEntry<ApiType>;
/** /**
* True if the last referendum tabled was submitted externally. False if it was a public * True if the last referendum tabled was submitted externally. False if it was a public
* proposal. * proposal.
@@ -210,6 +221,8 @@ declare module '@polkadot/api/types/storage' {
/** /**
* Accounts for which there are locks in action which may be removed at some point in the * Accounts for which there are locks in action which may be removed at some point in the
* future. The value is the block number at which the lock expires and may be removed. * future. The value is the block number at which the lock expires and may be removed.
*
* TWOX-NOTE: OK ― `AccountId` is a secure hash.
**/ **/
locks: AugmentedQuery<ApiType, (arg: AccountId | string | Uint8Array) => Observable<Option<BlockNumber>>> & QueryableStorageEntry<ApiType>; locks: AugmentedQuery<ApiType, (arg: AccountId | string | Uint8Array) => Observable<Option<BlockNumber>>> & QueryableStorageEntry<ApiType>;
/** /**
@@ -232,6 +245,8 @@ declare module '@polkadot/api/types/storage' {
/** /**
* Who is able to vote for whom. Value is the fund-holding account, key is the * Who is able to vote for whom. Value is the fund-holding account, key is the
* vote-transaction-sending account. * vote-transaction-sending account.
*
* TWOX-NOTE: OK ― `AccountId` is a secure hash.
**/ **/
proxy: AugmentedQuery<ApiType, (arg: AccountId | string | Uint8Array) => Observable<Option<ProxyState>>> & QueryableStorageEntry<ApiType>; proxy: AugmentedQuery<ApiType, (arg: AccountId | string | Uint8Array) => Observable<Option<ProxyState>>> & QueryableStorageEntry<ApiType>;
/** /**
@@ -248,11 +263,21 @@ declare module '@polkadot/api/types/storage' {
referendumCount: AugmentedQuery<ApiType, () => Observable<ReferendumIndex>> & QueryableStorageEntry<ApiType>; referendumCount: AugmentedQuery<ApiType, () => Observable<ReferendumIndex>> & QueryableStorageEntry<ApiType>;
/** /**
* Information concerning any given referendum. * Information concerning any given referendum.
*
* TWOX-NOTE: SAFE as indexes are not under an attacker’s control.
**/ **/
referendumInfoOf: AugmentedQuery<ApiType, (arg: ReferendumIndex | AnyNumber | Uint8Array) => Observable<Option<ReferendumInfo>>> & QueryableStorageEntry<ApiType>; referendumInfoOf: AugmentedQuery<ApiType, (arg: ReferendumIndex | AnyNumber | Uint8Array) => Observable<Option<ReferendumInfo>>> & QueryableStorageEntry<ApiType>;
/**
* Storage version of the pallet.
*
* New networks start with last version.
**/
storageVersion: AugmentedQuery<ApiType, () => Observable<Option<ReleasesDemocracy>>> & QueryableStorageEntry<ApiType>;
/** /**
* All votes for a particular voter. We store the balance for the number of votes that we * All votes for a particular voter. We store the balance for the number of votes that we
* have recorded. The second item is the total amount of delegations, that will be added. * have recorded. The second item is the total amount of delegations, that will be added.
*
* TWOX-NOTE: SAFE as `AccountId`s are crypto hashes anyway.
**/ **/
votingOf: AugmentedQuery<ApiType, (arg: AccountId | string | Uint8Array) => Observable<Voting>> & QueryableStorageEntry<ApiType>; votingOf: AugmentedQuery<ApiType, (arg: AccountId | string | Uint8Array) => Observable<Voting>> & QueryableStorageEntry<ApiType>;
}; };
@@ -277,6 +302,8 @@ declare module '@polkadot/api/types/storage' {
runnersUp: AugmentedQuery<ApiType, () => Observable<Vec<ITuple<[AccountId, BalanceOf]>>>> & QueryableStorageEntry<ApiType>; runnersUp: AugmentedQuery<ApiType, () => Observable<Vec<ITuple<[AccountId, BalanceOf]>>>> & QueryableStorageEntry<ApiType>;
/** /**
* Votes and locked stake of a particular voter. * Votes and locked stake of a particular voter.
*
* TWOX-NOTE: SAFE as `AccountId` is a crypto hash
**/ **/
voting: AugmentedQuery<ApiType, (arg: AccountId | string | Uint8Array) => Observable<ITuple<[BalanceOf, Vec<AccountId>]>>> & QueryableStorageEntry<ApiType>; voting: AugmentedQuery<ApiType, (arg: AccountId | string | Uint8Array) => Observable<ITuple<[BalanceOf, Vec<AccountId>]>>> & QueryableStorageEntry<ApiType>;
}; };
@@ -298,6 +325,8 @@ declare module '@polkadot/api/types/storage' {
/** /**
* A mapping from grandpa set ID to the index of the *most recent* session for which its * A mapping from grandpa set ID to the index of the *most recent* session for which its
* members were responsible. * members were responsible.
*
* TWOX-NOTE: `SetId` is not under user control.
**/ **/
setIdSession: AugmentedQuery<ApiType, (arg: SetId | AnyNumber | Uint8Array) => Observable<Option<SessionIndex>>> & QueryableStorageEntry<ApiType>; setIdSession: AugmentedQuery<ApiType, (arg: SetId | AnyNumber | Uint8Array) => Observable<Option<SessionIndex>>> & QueryableStorageEntry<ApiType>;
/** /**
@@ -313,17 +342,23 @@ declare module '@polkadot/api/types/storage' {
[index: string]: QueryableStorageEntry<ApiType>; [index: string]: QueryableStorageEntry<ApiType>;
/** /**
* Information that is pertinent to identify the entity behind an account. * Information that is pertinent to identify the entity behind an account.
*
* TWOX-NOTE: OK ― `AccountId` is a secure hash.
**/ **/
identityOf: AugmentedQuery<ApiType, (arg: AccountId | string | Uint8Array) => Observable<Option<Registration>>> & QueryableStorageEntry<ApiType>; identityOf: AugmentedQuery<ApiType, (arg: AccountId | string | Uint8Array) => Observable<Option<Registration>>> & QueryableStorageEntry<ApiType>;
/** /**
* The set of registrars. Not expected to get very big as can only be added through a * The set of registrars. Not expected to get very big as can only be added through a
* special origin (likely a council motion). * special origin (likely a council motion).
*
* The index into this can be cast to `RegistrarIndex` to get a valid value. * The index into this can be cast to `RegistrarIndex` to get a valid value.
**/ **/
registrars: AugmentedQuery<ApiType, () => Observable<Vec<Option<RegistrarInfo>>>> & QueryableStorageEntry<ApiType>; registrars: AugmentedQuery<ApiType, () => Observable<Vec<Option<RegistrarInfo>>>> & QueryableStorageEntry<ApiType>;
/** /**
* Alternative "sub" identities of this account. * Alternative "sub" identities of this account.
*
* The first item is the deposit, the second is a vector of the accounts. * The first item is the deposit, the second is a vector of the accounts.
*
* TWOX-NOTE: OK ― `AccountId` is a secure hash.
**/ **/
subsOf: AugmentedQuery<ApiType, (arg: AccountId | string | Uint8Array) => Observable<ITuple<[BalanceOf, Vec<AccountId>]>>> & QueryableStorageEntry<ApiType>; subsOf: AugmentedQuery<ApiType, (arg: AccountId | string | Uint8Array) => Observable<ITuple<[BalanceOf, Vec<AccountId>]>>> & QueryableStorageEntry<ApiType>;
/** /**
@@ -341,6 +376,7 @@ declare module '@polkadot/api/types/storage' {
authoredBlocks: AugmentedQueryDoubleMap<ApiType, (key1: SessionIndex | AnyNumber | Uint8Array, key2: ValidatorId | string | Uint8Array) => Observable<u32>> & QueryableStorageEntry<ApiType>; authoredBlocks: AugmentedQueryDoubleMap<ApiType, (key1: SessionIndex | AnyNumber | Uint8Array, key2: ValidatorId | string | Uint8Array) => Observable<u32>> & QueryableStorageEntry<ApiType>;
/** /**
* The block number after which it's ok to send heartbeats in current session. * The block number after which it's ok to send heartbeats in current session.
*
* At the beginning of each session we set this to a value that should * At the beginning of each session we set this to a value that should
* fall roughly in the middle of the session duration. * fall roughly in the middle of the session duration.
* The idea is to first wait for the validators to produce a block * The idea is to first wait for the validators to produce a block
@@ -381,7 +417,9 @@ declare module '@polkadot/api/types/storage' {
reports: AugmentedQuery<ApiType, (arg: ReportIdOf | string | Uint8Array) => Observable<Option<OffenceDetails>>> & QueryableStorageEntry<ApiType>; reports: AugmentedQuery<ApiType, (arg: ReportIdOf | string | Uint8Array) => Observable<Option<OffenceDetails>>> & QueryableStorageEntry<ApiType>;
/** /**
* Enumerates all reports of a kind along with the time they happened. * Enumerates all reports of a kind along with the time they happened.
*
* All reports are sorted by the time of offence. * All reports are sorted by the time of offence.
*
* Note that the actual type of this mapping is `Vec<u8>`, this is because values of * Note that the actual type of this mapping is `Vec<u8>`, this is because values of
* different types are not supported at the moment so we are doing the manual serialization. * different types are not supported at the moment so we are doing the manual serialization.
**/ **/
@@ -400,12 +438,14 @@ declare module '@polkadot/api/types/storage' {
[index: string]: QueryableStorageEntry<ApiType>; [index: string]: QueryableStorageEntry<ApiType>;
/** /**
* Active recovery attempts. * Active recovery attempts.
*
* First account is the account to be recovered, and the second account * First account is the account to be recovered, and the second account
* is the user trying to recover the account. * is the user trying to recover the account.
**/ **/
activeRecoveries: AugmentedQueryDoubleMap<ApiType, (key1: AccountId | string | Uint8Array, key2: AccountId | string | Uint8Array) => Observable<Option<ActiveRecovery>>> & QueryableStorageEntry<ApiType>; activeRecoveries: AugmentedQueryDoubleMap<ApiType, (key1: AccountId | string | Uint8Array, key2: AccountId | string | Uint8Array) => Observable<Option<ActiveRecovery>>> & QueryableStorageEntry<ApiType>;
/** /**
* The list of allowed proxy accounts. * The list of allowed proxy accounts.
*
* Map from the user who can access it to the recovered account. * Map from the user who can access it to the recovered account.
**/ **/
proxy: AugmentedQuery<ApiType, (arg: AccountId | string | Uint8Array) => Observable<Option<AccountId>>> & QueryableStorageEntry<ApiType>; proxy: AugmentedQuery<ApiType, (arg: AccountId | string | Uint8Array) => Observable<Option<AccountId>>> & QueryableStorageEntry<ApiType>;
@@ -433,6 +473,7 @@ declare module '@polkadot/api/types/storage' {
currentIndex: AugmentedQuery<ApiType, () => Observable<SessionIndex>> & QueryableStorageEntry<ApiType>; currentIndex: AugmentedQuery<ApiType, () => Observable<SessionIndex>> & QueryableStorageEntry<ApiType>;
/** /**
* Indices of disabled validators. * Indices of disabled validators.
*
* The set is cleared when `on_session_ending` returns a new set of identities. * The set is cleared when `on_session_ending` returns a new set of identities.
**/ **/
disabledValidators: AugmentedQuery<ApiType, () => Observable<Vec<u32>>> & QueryableStorageEntry<ApiType>; disabledValidators: AugmentedQuery<ApiType, () => Observable<Vec<u32>>> & QueryableStorageEntry<ApiType>;
@@ -531,6 +572,7 @@ declare module '@polkadot/api/types/storage' {
[index: string]: QueryableStorageEntry<ApiType>; [index: string]: QueryableStorageEntry<ApiType>;
/** /**
* The active era information, it holds index and start. * The active era information, it holds index and start.
*
* The active era is the era currently rewarded. * The active era is the era currently rewarded.
* Validator set of this era must be equal to `SessionInterface::validators`. * Validator set of this era must be equal to `SessionInterface::validators`.
**/ **/
@@ -541,6 +583,7 @@ declare module '@polkadot/api/types/storage' {
bonded: AugmentedQuery<ApiType, (arg: AccountId | string | Uint8Array) => Observable<Option<AccountId>>> & QueryableStorageEntry<ApiType>; bonded: AugmentedQuery<ApiType, (arg: AccountId | string | Uint8Array) => Observable<Option<AccountId>>> & QueryableStorageEntry<ApiType>;
/** /**
* A mapping from still-bonded eras to the first session index of that era. * A mapping from still-bonded eras to the first session index of that era.
*
* Must contains information for eras for the range: * Must contains information for eras for the range:
* `[active_era - bounding_duration; active_era]` * `[active_era - bounding_duration; active_era]`
**/ **/
@@ -552,6 +595,7 @@ declare module '@polkadot/api/types/storage' {
canceledSlashPayout: AugmentedQuery<ApiType, () => Observable<BalanceOf>> & QueryableStorageEntry<ApiType>; canceledSlashPayout: AugmentedQuery<ApiType, () => Observable<BalanceOf>> & QueryableStorageEntry<ApiType>;
/** /**
* The current era index. * The current era index.
*
* This is the latest planned era, depending on how the Session pallet queues the validator * This is the latest planned era, depending on how the Session pallet queues the validator
* set, it might be active or not. * set, it might be active or not.
**/ **/
@@ -572,18 +616,23 @@ declare module '@polkadot/api/types/storage' {
erasRewardPoints: AugmentedQuery<ApiType, (arg: EraIndex | AnyNumber | Uint8Array) => Observable<EraRewardPoints>> & QueryableStorageEntry<ApiType>; erasRewardPoints: AugmentedQuery<ApiType, (arg: EraIndex | AnyNumber | Uint8Array) => Observable<EraRewardPoints>> & QueryableStorageEntry<ApiType>;
/** /**
* Exposure of validator at era. * Exposure of validator at era.
*
* This is keyed first by the era index to allow bulk deletion and then the stash account. * This is keyed first by the era index to allow bulk deletion and then the stash account.
*
* Is it removed after `HISTORY_DEPTH` eras. * Is it removed after `HISTORY_DEPTH` eras.
* If stakers hasn't been set or has been removed then empty exposure is returned. * If stakers hasn't been set or has been removed then empty exposure is returned.
**/ **/
erasStakers: AugmentedQueryDoubleMap<ApiType, (key1: EraIndex | AnyNumber | Uint8Array, key2: AccountId | string | Uint8Array) => Observable<Exposure>> & QueryableStorageEntry<ApiType>; erasStakers: AugmentedQueryDoubleMap<ApiType, (key1: EraIndex | AnyNumber | Uint8Array, key2: AccountId | string | Uint8Array) => Observable<Exposure>> & QueryableStorageEntry<ApiType>;
/** /**
* Clipped Exposure of validator at era. * Clipped Exposure of validator at era.
*
* This is similar to [`ErasStakers`] but number of nominators exposed is reduced to the * This is similar to [`ErasStakers`] but number of nominators exposed is reduced to the
* `T::MaxNominatorRewardedPerValidator` biggest stakers. * `T::MaxNominatorRewardedPerValidator` biggest stakers.
* (Note: the field `total` and `own` of the exposure remains unchanged). * (Note: the field `total` and `own` of the exposure remains unchanged).
* This is used to limit the i/o cost for the nominator payout. * This is used to limit the i/o cost for the nominator payout.
*
* This is keyed fist by the era index to allow bulk deletion and then the stash account. * This is keyed fist by the era index to allow bulk deletion and then the stash account.
*
* Is it removed after `HISTORY_DEPTH` eras. * Is it removed after `HISTORY_DEPTH` eras.
* If stakers hasn't been set or has been removed then empty exposure is returned. * If stakers hasn't been set or has been removed then empty exposure is returned.
**/ **/
@@ -599,12 +648,15 @@ declare module '@polkadot/api/types/storage' {
erasTotalStake: AugmentedQuery<ApiType, (arg: EraIndex | AnyNumber | Uint8Array) => Observable<BalanceOf>> & QueryableStorageEntry<ApiType>; erasTotalStake: AugmentedQuery<ApiType, (arg: EraIndex | AnyNumber | Uint8Array) => Observable<BalanceOf>> & QueryableStorageEntry<ApiType>;
/** /**
* Similar to `ErasStakers`, this holds the preferences of validators. * Similar to `ErasStakers`, this holds the preferences of validators.
*
* This is keyed first by the era index to allow bulk deletion and then the stash account. * This is keyed first by the era index to allow bulk deletion and then the stash account.
*
* Is it removed after `HISTORY_DEPTH` eras. * Is it removed after `HISTORY_DEPTH` eras.
**/ **/
erasValidatorPrefs: AugmentedQueryDoubleMap<ApiType, (key1: EraIndex | AnyNumber | Uint8Array, key2: AccountId | string | Uint8Array) => Observable<ValidatorPrefs>> & QueryableStorageEntry<ApiType>; erasValidatorPrefs: AugmentedQueryDoubleMap<ApiType, (key1: EraIndex | AnyNumber | Uint8Array, key2: AccountId | string | Uint8Array) => Observable<ValidatorPrefs>> & QueryableStorageEntry<ApiType>;
/** /**
* The total validator era payout for the last `HISTORY_DEPTH` eras. * The total validator era payout for the last `HISTORY_DEPTH` eras.
*
* Eras that haven't finished yet or has been removed doesn't have reward. * Eras that haven't finished yet or has been removed doesn't have reward.
**/ **/
erasValidatorReward: AugmentedQuery<ApiType, (arg: EraIndex | AnyNumber | Uint8Array) => Observable<Option<BalanceOf>>> & QueryableStorageEntry<ApiType>; erasValidatorReward: AugmentedQuery<ApiType, (arg: EraIndex | AnyNumber | Uint8Array) => Observable<Option<BalanceOf>>> & QueryableStorageEntry<ApiType>;
@@ -614,7 +666,9 @@ declare module '@polkadot/api/types/storage' {
forceEra: AugmentedQuery<ApiType, () => Observable<Forcing>> & QueryableStorageEntry<ApiType>; forceEra: AugmentedQuery<ApiType, () => Observable<Forcing>> & QueryableStorageEntry<ApiType>;
/** /**
* Number of eras to keep in history. * Number of eras to keep in history.
*
* Information is kept for eras in `[current_era - history_depth; current_era]`. * Information is kept for eras in `[current_era - history_depth; current_era]`.
*
* Must be more than the number of eras delayed by session otherwise. * Must be more than the number of eras delayed by session otherwise.
* I.e. active era must always be in history. * I.e. active era must always be in history.
* I.e. `active_era > current_era - history_depth` must be guaranteed. * I.e. `active_era > current_era - history_depth` must be guaranteed.
@@ -671,6 +725,7 @@ declare module '@polkadot/api/types/storage' {
slashingSpans: AugmentedQuery<ApiType, (arg: AccountId | string | Uint8Array) => Observable<Option<SlashingSpans>>> & QueryableStorageEntry<ApiType>; slashingSpans: AugmentedQuery<ApiType, (arg: AccountId | string | Uint8Array) => Observable<Option<SlashingSpans>>> & QueryableStorageEntry<ApiType>;
/** /**
* The percentage of the slash that is distributed to reporters. * The percentage of the slash that is distributed to reporters.
*
* The rest of the slashed value is handled by the `Slash`. * The rest of the slashed value is handled by the `Slash`.
**/ **/
slashRewardFraction: AugmentedQuery<ApiType, () => Observable<Perbill>> & QueryableStorageEntry<ApiType>; slashRewardFraction: AugmentedQuery<ApiType, () => Observable<Perbill>> & QueryableStorageEntry<ApiType>;
@@ -692,6 +747,7 @@ declare module '@polkadot/api/types/storage' {
/** /**
* True if network has been upgraded to this version. * True if network has been upgraded to this version.
* Storage version of the pallet. * Storage version of the pallet.
*
* This is set to v3.0.0 for new networks. * This is set to v3.0.0 for new networks.
**/ **/
storageVersion: AugmentedQuery<ApiType, () => Observable<ReleasesStaking>> & QueryableStorageEntry<ApiType>; storageVersion: AugmentedQuery<ApiType, () => Observable<ReleasesStaking>> & QueryableStorageEntry<ApiType>;
@@ -730,14 +786,14 @@ declare module '@polkadot/api/types/storage' {
* Total length (in bytes) for all extrinsics put together, for the current block. * Total length (in bytes) for all extrinsics put together, for the current block.
**/ **/
allExtrinsicsLen: AugmentedQuery<ApiType, () => Observable<Option<u32>>> & QueryableStorageEntry<ApiType>; allExtrinsicsLen: AugmentedQuery<ApiType, () => Observable<Option<u32>>> & QueryableStorageEntry<ApiType>;
/**
* Total weight for all extrinsics put together, for the current block.
**/
allExtrinsicsWeight: AugmentedQuery<ApiType, () => Observable<Option<Weight>>> & QueryableStorageEntry<ApiType>;
/** /**
* Map of block numbers to block hashes. * Map of block numbers to block hashes.
**/ **/
blockHash: AugmentedQuery<ApiType, (arg: BlockNumber | AnyNumber | Uint8Array) => Observable<Hash>> & QueryableStorageEntry<ApiType>; blockHash: AugmentedQuery<ApiType, (arg: BlockNumber | AnyNumber | Uint8Array) => Observable<Hash>> & QueryableStorageEntry<ApiType>;
/**
* The current weight for the block.
**/
blockWeight: AugmentedQuery<ApiType, () => Observable<ExtrinsicsWeight>> & QueryableStorageEntry<ApiType>;
/** /**
* Digest of the current block, also part of the block header. * Digest of the current block, also part of the block header.
**/ **/
@@ -753,9 +809,11 @@ declare module '@polkadot/api/types/storage' {
/** /**
* Mapping between a topic (represented by T::Hash) and a vector of indexes * Mapping between a topic (represented by T::Hash) and a vector of indexes
* of events in the `<Events<T>>` list. * of events in the `<Events<T>>` list.
*
* All topic vectors have deterministic storage locations depending on the topic. This * All topic vectors have deterministic storage locations depending on the topic. This
* allows light-clients to leverage the changes trie storage tracking mechanism and * allows light-clients to leverage the changes trie storage tracking mechanism and
* in case of changes fetch the list of events of interest. * in case of changes fetch the list of events of interest.
*
* The value has the type `(T::BlockNumber, EventIndex)` because if we used only just * The value has the type `(T::BlockNumber, EventIndex)` because if we used only just
* the `EventIndex` then in case if the topic has the same contents on the next block * the `EventIndex` then in case if the topic has the same contents on the next block
* no notification will be triggered thus the event might be lost. * no notification will be triggered thus the event might be lost.
+10 -3
View File
@@ -13,6 +13,7 @@ import { AuthorityId } from '@polkadot/types/interfaces/consensus';
import { ContractCallRequest, ContractExecResult } from '@polkadot/types/interfaces/contracts'; import { ContractCallRequest, ContractExecResult } from '@polkadot/types/interfaces/contracts';
import { CreatedBlock } from '@polkadot/types/interfaces/engine'; import { CreatedBlock } from '@polkadot/types/interfaces/engine';
import { Extrinsic } from '@polkadot/types/interfaces/extrinsics'; import { Extrinsic } from '@polkadot/types/interfaces/extrinsics';
import { ReportedRoundStates } from '@polkadot/types/interfaces/grandpa';
import { StorageKind } from '@polkadot/types/interfaces/offchain'; import { StorageKind } from '@polkadot/types/interfaces/offchain';
import { RuntimeDispatchInfo } from '@polkadot/types/interfaces/payment'; import { RuntimeDispatchInfo } from '@polkadot/types/interfaces/payment';
import { RpcMethods } from '@polkadot/types/interfaces/rpc'; import { RpcMethods } from '@polkadot/types/interfaces/rpc';
@@ -140,15 +141,21 @@ declare module '@polkadot/rpc-core/types.jsonrpc' {
**/ **/
finalizeBlock: AugmentedRpc<(hash: BlockHash | string | Uint8Array, justification?: Justification | string | Uint8Array) => Observable<bool>>; finalizeBlock: AugmentedRpc<(hash: BlockHash | string | Uint8Array, justification?: Justification | string | Uint8Array) => Observable<bool>>;
}; };
grandpa: {
/**
* Returns the state of the current best round state as well as the ongoing background rounds
**/
roundState: AugmentedRpc<() => Observable<ReportedRoundStates>>;
};
offchain: { offchain: {
/** /**
* 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 | '__UNUSED' | '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 | '__UNUSED' | 'PERSISTENT' | 'LOCAL' | number | Uint8Array, key: Bytes | string | Uint8Array, value: Bytes | string | Uint8Array) => Observable<Null>>;
}; };
payment: { payment: {
/** /**
@@ -234,7 +241,7 @@ declare module '@polkadot/rpc-core/types.jsonrpc' {
/** /**
* Subscribes to storage changes for the provided keys * Subscribes to storage changes for the provided keys
**/ **/
subscribeStorage: AugmentedRpc<<T = Codec[]>(keys: Vec<StorageKey> | (StorageKey | string | Uint8Array | any)[]) => Observable<T>>; subscribeStorage: AugmentedRpc<<T = Codec[]>(keys?: Vec<StorageKey> | (StorageKey | string | Uint8Array | any)[]) => Observable<T>>;
}; };
system: { system: {
/** /**
File diff suppressed because it is too large Load Diff
+35 -23
View File
@@ -15,14 +15,13 @@ import { map, switchMap, take, tap, toArray } from 'rxjs/operators';
import decorateDerive, { ExactDerive } from '@polkadot/api-derive'; import decorateDerive, { ExactDerive } from '@polkadot/api-derive';
import { memo } from '@polkadot/api-derive/util'; import { memo } from '@polkadot/api-derive/util';
import DecoratedMeta from '@polkadot/metadata/Decorated'; import DecoratedMeta from '@polkadot/metadata/Decorated';
import getHasher from '@polkadot/metadata/Decorated/storage/fromMetadata/getHasher';
import RpcCore from '@polkadot/rpc-core'; import RpcCore from '@polkadot/rpc-core';
import { WsProvider } from '@polkadot/rpc-provider'; import { WsProvider } from '@polkadot/rpc-provider';
import { Metadata, Null, Option, Raw, Text, TypeRegistry, u64 } from '@polkadot/types'; import { Metadata, Null, Option, Raw, Text, TypeRegistry, u64 } from '@polkadot/types';
import Linkage, { LinkageResult } from '@polkadot/types/codec/Linkage'; import Linkage, { LinkageResult } from '@polkadot/types/codec/Linkage';
import { DEFAULT_VERSION as EXTRINSIC_DEFAULT_VERSION } from '@polkadot/types/extrinsic/constants'; import { DEFAULT_VERSION as EXTRINSIC_DEFAULT_VERSION } from '@polkadot/types/extrinsic/constants';
import StorageKey, { StorageEntry, unwrapStorageType } from '@polkadot/types/primitive/StorageKey'; import StorageKey, { StorageEntry, unwrapStorageType } from '@polkadot/types/primitive/StorageKey';
import { assert, compactStripLength, isNull, isUndefined, logger, u8aConcat, u8aToHex } from '@polkadot/util'; import { assert, compactStripLength, logger, u8aToHex } from '@polkadot/util';
import { createSubmittable } from '../submittable'; import { createSubmittable } from '../submittable';
import augmentObject from '../util/augmentObject'; import augmentObject from '../util/augmentObject';
@@ -32,7 +31,7 @@ import Events from './Events';
interface MetaDecoration { interface MetaDecoration {
callIndex?: Uint8Array; callIndex?: Uint8Array;
meta: any; meta: Record<string, unknown>;
method: string; method: string;
section: string; section: string;
toJSON: () => any; toJSON: () => any;
@@ -247,9 +246,9 @@ export default abstract class Decorate<ApiType extends ApiTypes> extends Events
) )
// eslint-disable-next-line @typescript-eslint/no-unused-vars // eslint-disable-next-line @typescript-eslint/no-unused-vars
.forEach(([_, { method, section }]): void => { .forEach(([_, { method, section }]): void => {
delete (this._rpc as any)[section][method]; delete (this._rpc as Record<string, Record<string, unknown>>)[section][method];
delete (this._rpcCore as any)[section][method]; delete (this._rpcCore as unknown as Record<string, Record<string, unknown>>)[section][method];
delete (this._rx.rpc as any)[section][method]; delete (this._rx.rpc as Record<string, Record<string, unknown>>)[section][method];
}); });
} }
@@ -258,11 +257,12 @@ export default abstract class Decorate<ApiType extends ApiTypes> extends Events
const sectionName = _sectionName as keyof DecoratedRpc<ApiType, RpcInterface>; const sectionName = _sectionName as keyof DecoratedRpc<ApiType, RpcInterface>;
// out and section here are horrors to get right from a typing perspective :( // out and section here are horrors to get right from a typing perspective :(
(out as any)[sectionName] = Object.entries(rpc[sectionName]).reduce((section, [methodName, method]): DecoratedRpcSection<ApiType, RpcInterface[typeof sectionName]> => { (out as Record<string, unknown>)[sectionName] = Object.entries(rpc[sectionName]).reduce((section, [methodName, method]): DecoratedRpcSection<ApiType, RpcInterface[typeof sectionName]> => {
// skip subscriptions where we have a non-subscribe interface // skip subscriptions where we have a non-subscribe interface
if (this.hasSubscriptions || !(methodName.startsWith('subscribe') || methodName.startsWith('unsubscribe'))) { if (this.hasSubscriptions || !(methodName.startsWith('subscribe') || methodName.startsWith('unsubscribe'))) {
(section as any)[methodName] = decorateMethod(method, { methodName }); (section as Record<string, unknown>)[methodName] = decorateMethod(method, { methodName }) as unknown;
(section as any)[methodName].raw = decorateMethod(method.raw, { methodName }); // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
(section as Record<string, { raw: unknown }>)[methodName].raw = decorateMethod(method.raw, { methodName }) as unknown;
} }
return section; return section;
@@ -273,10 +273,12 @@ export default abstract class Decorate<ApiType extends ApiTypes> extends Events
} }
protected _decorateMulti<ApiType extends ApiTypes> (decorateMethod: DecorateMethod<ApiType>): QueryableStorageMulti<ApiType> { protected _decorateMulti<ApiType extends ApiTypes> (decorateMethod: DecorateMethod<ApiType>): QueryableStorageMulti<ApiType> {
// eslint-disable-next-line @typescript-eslint/no-unsafe-return
return decorateMethod((calls: QueryableStorageMultiArg<ApiType>[]): Observable<Codec[]> => return decorateMethod((calls: QueryableStorageMultiArg<ApiType>[]): Observable<Codec[]> =>
this._rpcCore.state.subscribeStorage( this._rpcCore.state.subscribeStorage(
calls.map((arg: QueryableStorageMultiArg<ApiType>): [QueryableStorageEntry<ApiType>, ...Arg[]] => calls.map((arg: QueryableStorageMultiArg<ApiType>): [QueryableStorageEntry<ApiType>, ...Arg[]] =>
// the input is a QueryableStorageEntry, convert to StorageEntry // the input is a QueryableStorageEntry, convert to StorageEntry
// eslint-disable-next-line @typescript-eslint/no-unsafe-return
Array.isArray(arg) Array.isArray(arg)
? [arg[0].creator, ...arg.slice(1)] ? [arg[0].creator, ...arg.slice(1)]
: [arg.creator] as any))); : [arg.creator] as any)));
@@ -300,7 +302,8 @@ export default abstract class Decorate<ApiType extends ApiTypes> extends Events
const decorated = (...params: Arg[]): SubmittableExtrinsic<ApiType> => const decorated = (...params: Arg[]): SubmittableExtrinsic<ApiType> =>
creator(method(...params)); creator(method(...params));
return this._decorateFunctionMeta(method, decorated as any) as SubmittableExtrinsicFunction<ApiType>; // eslint-disable-next-line @typescript-eslint/no-unsafe-return
return this._decorateFunctionMeta(method as any, decorated as any) as unknown as SubmittableExtrinsicFunction<ApiType>;
} }
protected _decorateStorage<ApiType extends ApiTypes> (storage: Storage, decorateMethod: DecorateMethod<ApiType>): QueryableStorage<ApiType> { protected _decorateStorage<ApiType extends ApiTypes> (storage: Storage, decorateMethod: DecorateMethod<ApiType>): QueryableStorage<ApiType> {
@@ -320,6 +323,7 @@ export default abstract class Decorate<ApiType extends ApiTypes> extends Events
const getArgs = (...args: any[]): any[] => extractStorageArgs(creator, args); const getArgs = (...args: any[]): any[] => extractStorageArgs(creator, args);
// FIXME We probably want to be able to query the full list with non-subs as well // FIXME We probably want to be able to query the full list with non-subs as well
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
const decorated = this.hasSubscriptions && creator.iterKey && creator.meta.type.isMap && creator.meta.type.asMap.linked.isTrue const decorated = this.hasSubscriptions && creator.iterKey && creator.meta.type.isMap && creator.meta.type.asMap.linked.isTrue
? this._decorateStorageLinked(creator, decorateMethod) ? this._decorateStorageLinked(creator, decorateMethod)
: decorateMethod((...args: any[]): Observable<Codec> => ( : decorateMethod((...args: any[]): Observable<Codec> => (
@@ -333,32 +337,41 @@ export default abstract class Decorate<ApiType extends ApiTypes> extends Events
: this._rpcCore.state.getStorage(getArgs(...args)) : this._rpcCore.state.getStorage(getArgs(...args))
), { methodName: creator.method }); ), { methodName: creator.method });
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
decorated.creator = creator; decorated.creator = creator;
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access,@typescript-eslint/no-unsafe-assignment
decorated.at = decorateMethod((hash: Hash, arg1?: Arg, arg2?: Arg): Observable<Codec> => decorated.at = decorateMethod((hash: Hash, arg1?: Arg, arg2?: Arg): Observable<Codec> =>
this._rpcCore.state.getStorage(getArgs(arg1, arg2), hash)); this._rpcCore.state.getStorage(getArgs(arg1, arg2), hash));
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access,@typescript-eslint/no-unsafe-assignment
decorated.hash = decorateMethod((arg1?: Arg, arg2?: Arg): Observable<Hash> => decorated.hash = decorateMethod((arg1?: Arg, arg2?: Arg): Observable<Hash> =>
this._rpcCore.state.getStorageHash(getArgs(arg1, arg2))); this._rpcCore.state.getStorageHash(getArgs(arg1, arg2)));
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
decorated.key = (arg1?: Arg, arg2?: Arg): string => decorated.key = (arg1?: Arg, arg2?: Arg): string =>
u8aToHex(compactStripLength(creator(creator.meta.type.isDoubleMap ? [arg1, arg2] : arg1))[1]); u8aToHex(compactStripLength(creator(creator.meta.type.isDoubleMap ? [arg1, arg2] : arg1))[1]);
decorated.keyPrefix = (): string => // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
u8aToHex(creator.keyPrefix); decorated.keyPrefix = (key1?: Arg): string =>
u8aToHex(creator.keyPrefix(key1));
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access,@typescript-eslint/no-unsafe-assignment
decorated.range = decorateMethod((range: [Hash, Hash?], arg1?: Arg, arg2?: Arg): Observable<[Hash, Codec][]> => decorated.range = decorateMethod((range: [Hash, Hash?], arg1?: Arg, arg2?: Arg): Observable<[Hash, Codec][]> =>
this._decorateStorageRange(decorated, [arg1, arg2], range)); this._decorateStorageRange(decorated, [arg1, arg2], range));
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access,@typescript-eslint/no-unsafe-assignment
decorated.size = decorateMethod((arg1?: Arg, arg2?: Arg): Observable<u64> => decorated.size = decorateMethod((arg1?: Arg, arg2?: Arg): Observable<u64> =>
this._rpcCore.state.getStorageSize(getArgs(arg1, arg2))); this._rpcCore.state.getStorageSize(getArgs(arg1, arg2)));
// .keys() & .entries() only available on map types // .keys() & .entries() only available on map types
if (creator.iterKey && (creator.meta.type.isMap || creator.meta.type.isDoubleMap)) { if (creator.iterKey && (creator.meta.type.isMap || creator.meta.type.isDoubleMap)) {
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access,@typescript-eslint/no-unsafe-assignment
decorated.entries = decorateMethod( decorated.entries = decorateMethod(
memo((doubleMapArg?: Arg): Observable<[StorageKey, Codec][]> => memo((doubleMapArg?: Arg): Observable<[StorageKey, Codec][]> =>
this._retrieveMapEntries(creator, doubleMapArg))); this._retrieveMapEntries(creator, doubleMapArg)));
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access,@typescript-eslint/no-unsafe-assignment
decorated.keys = decorateMethod( decorated.keys = decorateMethod(
memo((doubleMapArg?: Arg): Observable<StorageKey[]> => memo((doubleMapArg?: Arg): Observable<StorageKey[]> =>
this._retrieveMapKeys(creator, doubleMapArg))); this._retrieveMapKeys(creator, doubleMapArg)));
@@ -367,12 +380,13 @@ export default abstract class Decorate<ApiType extends ApiTypes> extends Events
// only support multi where subs are available // only support multi where subs are available
if (this.hasSubscriptions) { if (this.hasSubscriptions) {
// When using double map storage function, user need to pass double map key as an array // When using double map storage function, user need to pass double map key as an array
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access,@typescript-eslint/no-unsafe-assignment
decorated.multi = decorateMethod((args: (Arg | Arg[])[]): Observable<Codec[]> => decorated.multi = decorateMethod((args: (Arg | Arg[])[]): Observable<Codec[]> =>
this._rpcCore.state.subscribeStorage( this._rpcCore.state.subscribeStorage(
args.map((arg: Arg[] | Arg): [StorageEntry, Arg | Arg[]] => [creator, arg]))); args.map((arg: Arg[] | Arg): [StorageEntry, Arg | Arg[]] => [creator, arg])));
} }
return this._decorateFunctionMeta(creator, decorated) as unknown as QueryableStorageEntry<ApiType>; return this._decorateFunctionMeta(creator as any, decorated) as unknown as QueryableStorageEntry<ApiType>;
} }
private _decorateStorageRange<ApiType extends ApiTypes> (decorated: QueryableStorageEntry<ApiType>, args: [Arg?, Arg?], range: [Hash, Hash?]): Observable<[Hash, Codec][]> { private _decorateStorageRange<ApiType extends ApiTypes> (decorated: QueryableStorageEntry<ApiType>, args: [Arg?, Arg?], range: [Hash, Hash?]): Observable<[Hash, Codec][]> {
@@ -389,9 +403,12 @@ export default abstract class Decorate<ApiType extends ApiTypes> extends Events
} }
private _decorateStorageLinked<ApiType extends ApiTypes> (creator: StorageEntry, decorateMethod: DecorateMethod<ApiType>): ReturnType<DecorateMethod<ApiType>> { private _decorateStorageLinked<ApiType extends ApiTypes> (creator: StorageEntry, decorateMethod: DecorateMethod<ApiType>): ReturnType<DecorateMethod<ApiType>> {
const result: Map<Codec, ITuple<[Codec, Linkage<Codec>]> | null> = new Map(); const result = new Map<Codec, ITuple<[Codec, Linkage<Codec>]> | null>();
let subject: BehaviorSubject<LinkageResult>; let subject: BehaviorSubject<LinkageResult>;
let head: Codec | null = null; let head: Codec | null = null;
const iterKey = creator.iterKey;
assert(iterKey, 'iterKey field is missing');
// retrieve a value based on the key, iterating if it has a next entry. Since // retrieve a value based on the key, iterating if it has a next entry. Since
// entries can be re-linked in the middle of a list, we subscribe here to make // entries can be re-linked in the middle of a list, we subscribe here to make
@@ -449,13 +466,15 @@ export default abstract class Decorate<ApiType extends ApiTypes> extends Events
// this handles the case where the head changes effectively, i.e. a new entry // this handles the case where the head changes effectively, i.e. a new entry
// appears at the top of the list, the new getNext gets kicked off // appears at the top of the list, the new getNext gets kicked off
// eslint-disable-next-line @typescript-eslint/no-unsafe-return
return decorateMethod((...args: any[]): Observable<LinkageResult | [Codec, Linkage<Codec>]> => return decorateMethod((...args: any[]): Observable<LinkageResult | [Codec, Linkage<Codec>]> =>
args.length args.length
? this._rpcCore.state ? this._rpcCore.state
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
.subscribeStorage<[[Codec, Linkage<Codec>]]>([[creator, ...args]]) .subscribeStorage<[[Codec, Linkage<Codec>]]>([[creator, ...args]])
.pipe(map(([data]): [Codec, Linkage<Codec>] => data)) .pipe(map(([data]): [Codec, Linkage<Codec>] => data))
: this._rpcCore.state : this._rpcCore.state
.subscribeStorage<[LinkageResult]>([creator.iterKey]) .subscribeStorage<[LinkageResult]>([iterKey()])
.pipe(switchMap(([key]): Observable<LinkageResult> => getNext(head = key))) .pipe(switchMap(([key]): Observable<LinkageResult> => getNext(head = key)))
); );
} }
@@ -463,14 +482,7 @@ export default abstract class Decorate<ApiType extends ApiTypes> extends Events
private _retrieveMapKeys ({ iterKey, meta }: StorageEntry, arg?: Arg): Observable<StorageKey[]> { private _retrieveMapKeys ({ iterKey, meta }: StorageEntry, arg?: Arg): Observable<StorageKey[]> {
assert(iterKey && (meta.type.isMap || meta.type.isDoubleMap), 'keys can only be retrieved on maps, linked maps and double maps'); assert(iterKey && (meta.type.isMap || meta.type.isDoubleMap), 'keys can only be retrieved on maps, linked maps and double maps');
const headKey = this.createType('Raw', u8aConcat( const headKey = iterKey(arg).toHex();
iterKey,
meta.type.isDoubleMap && !isUndefined(arg) && !isNull(arg)
? getHasher(meta.type.asDoubleMap.hasher)(
this.createType(meta.type.asDoubleMap.key1.toString() as 'Raw', arg).toU8a()
)
: new Uint8Array([])
)).toHex();
const startSubject = new BehaviorSubject<string>(headKey); const startSubject = new BehaviorSubject<string>(headKey);
return this._rpcCore.state.getKeysPaged return this._rpcCore.state.getKeysPaged
+22 -23
View File
@@ -5,7 +5,7 @@
import { SignedBlock, RuntimeVersion } from '@polkadot/types/interfaces'; import { SignedBlock, RuntimeVersion } from '@polkadot/types/interfaces';
import { ApiBase, ApiOptions, ApiTypes, DecorateMethod } from '../types'; import { ApiBase, ApiOptions, ApiTypes, DecorateMethod } from '../types';
import { Subscription, combineLatest, of } from 'rxjs'; import { Observable, Subscription, of } from 'rxjs';
import { map, switchMap } from 'rxjs/operators'; import { map, switchMap } from 'rxjs/operators';
import { Metadata, Text } from '@polkadot/types'; import { Metadata, Text } from '@polkadot/types';
import { LATEST_EXTRINSIC_VERSION } from '@polkadot/types/extrinsic/Extrinsic'; import { LATEST_EXTRINSIC_VERSION } from '@polkadot/types/extrinsic/Extrinsic';
@@ -62,6 +62,7 @@ export default abstract class Init<ApiType extends ApiTypes> extends Decorate<Ap
// 'connected' event, then the `on('connected')` won't fire anymore. To // 'connected' event, then the `on('connected')` won't fire anymore. To
// cater for this case, we call manually `this._onProviderConnect`. // cater for this case, we call manually `this._onProviderConnect`.
if (this._rpcCore.provider.isConnected()) { if (this._rpcCore.provider.isConnected()) {
// eslint-disable-next-line @typescript-eslint/no-floating-promises
this.#onProviderConnect(); this.#onProviderConnect();
} }
} }
@@ -107,7 +108,7 @@ export default abstract class Init<ApiType extends ApiTypes> extends Decorate<Ap
// manually build a list of all available methods in this RPC, we are // manually build a list of all available methods in this RPC, we are
// going to filter on it to align the cloned RPC without making a call // going to filter on it to align the cloned RPC without making a call
Object.keys(source.rpc).forEach((section): void => { Object.keys(source.rpc).forEach((section): void => {
Object.keys((source.rpc as any)[section]).forEach((method): void => { Object.keys((source.rpc as Record<string, Record<string, unknown>>)[section]).forEach((method): void => {
methods.push(`${section}_${method}`); methods.push(`${section}_${method}`);
}); });
}); });
@@ -124,28 +125,25 @@ export default abstract class Init<ApiType extends ApiTypes> extends Decorate<Ap
} }
this.#updateSub = this._rpcCore.state.subscribeRuntimeVersion().pipe( this.#updateSub = this._rpcCore.state.subscribeRuntimeVersion().pipe(
switchMap((version: RuntimeVersion) => switchMap((version: RuntimeVersion): Observable<boolean> =>
combineLatest( // only retrieve the metadata when the on-chain version has been changed
of(version), this._runtimeVersion?.specVersion.eq(version.specVersion)
this._rpcCore.state.getMetadata() ? of(false)
) : this._rpcCore.state.getMetadata().pipe(
), map((metadata: Metadata): boolean => {
map(([version, metadata]: [RuntimeVersion, Metadata]): boolean => { l.log(`Runtime version updated to spec=${version.specVersion.toString()}, tx=${version.transactionVersion.toString()}`);
if (this._runtimeVersion?.specVersion.eq(version.specVersion)) {
return false;
}
l.log(`Runtime version updated to ${version.specVersion}`); this._runtimeMetadata = metadata;
this._runtimeVersion = version;
this._rx.runtimeVersion = version;
this._runtimeMetadata = metadata; this.registerTypes(getSpecTypes(this.registry, this._runtimeChain as Text, version.specName, version.specVersion));
this._runtimeVersion = version; this.injectMetadata(metadata, false);
this._rx.runtimeVersion = version;
this.registerTypes(getSpecTypes(this.registry, this._runtimeChain as Text, version.specName, version.specVersion)); return true;
this.injectMetadata(metadata, false); })
)
return true; )
})
).subscribe(); ).subscribe();
} }
@@ -159,6 +157,7 @@ export default abstract class Init<ApiType extends ApiTypes> extends Decorate<Ap
// set our chain version & genesisHash as returned // set our chain version & genesisHash as returned
this._runtimeChain = chain; this._runtimeChain = chain;
this._runtimeVersion = runtimeVersion; this._runtimeVersion = runtimeVersion;
this._rx.runtimeVersion = runtimeVersion;
// do the setup for the specific chain // do the setup for the specific chain
this.registry.setChainProperties(chainProps); this.registry.setChainProperties(chainProps);
@@ -169,7 +168,7 @@ export default abstract class Init<ApiType extends ApiTypes> extends Decorate<Ap
await this._filterRpc(); await this._filterRpc();
// retrieve metadata, either from chain or as pass-in via options // retrieve metadata, either from chain or as pass-in via options
const metadataKey = `${this._genesisHash}-${runtimeVersion.specVersion}`; const metadataKey = `${this._genesisHash?.toHex() || '0x'}-${runtimeVersion.specVersion.toString()}`;
const metadata = metadataKey in optMetadata const metadata = metadataKey in optMetadata
? new Metadata(this.registry, optMetadata[metadataKey]) ? new Metadata(this.registry, optMetadata[metadataKey])
: await this._rpcCore.state.getMetadata().toPromise(); : await this._rpcCore.state.getMetadata().toPromise();
@@ -234,7 +233,7 @@ export default abstract class Init<ApiType extends ApiTypes> extends Decorate<Ap
}); });
}, KEEPALIVE_INTERVAL); }, KEEPALIVE_INTERVAL);
} catch (_error) { } catch (_error) {
const error = new Error(`FATAL: Unable to initialize the API: ${_error.message}`); const error = new Error(`FATAL: Unable to initialize the API: ${(_error as Error).message}`);
l.error(error); l.error(error);
+2 -2
View File
@@ -29,8 +29,8 @@ interface PkgJson {
let pkgJson: PkgJson = { name: '@polkadot/api', version: '-' }; let pkgJson: PkgJson = { name: '@polkadot/api', version: '-' };
import('../package.json') import('../package.json')
.then((_pkgJson: any): void => { .then((_pkgJson: unknown): void => {
pkgJson = _pkgJson; pkgJson = _pkgJson as PkgJson;
}) })
.catch((): void => { .catch((): void => {
// ignore // ignore
+14 -9
View File
@@ -87,7 +87,7 @@ async function query (api: ApiPromise, keyring: TestKeyringMap): Promise<void> {
// check range types // check range types
const entries = await api.query.system.events.range(['0x12345', '0x7890']); const entries = await api.query.system.events.range(['0x12345', '0x7890']);
console.log(`Received ${entries.length} entries, ${entries.map(([hash, events]) => `${hash.toHex()}: ${events.length} events`)}`); console.log(`Received ${entries.length} entries, ${entries.map(([hash, events]) => `${hash.toHex()}: ${events.length} events`).join(', ')}`);
} }
async function rpc (api: ApiPromise): Promise<void> { async function rpc (api: ApiPromise): Promise<void> {
@@ -105,6 +105,7 @@ async function rpc (api: ApiPromise): Promise<void> {
await api.rpc.chain.getBlock.raw('0x123456'); await api.rpc.chain.getBlock.raw('0x123456');
// using raw subs // using raw subs
// eslint-disable-next-line @typescript-eslint/no-floating-promises
api.rpc.chain.subscribeNewHeads.raw((result: Uint8Array): void => { api.rpc.chain.subscribeNewHeads.raw((result: Uint8Array): void => {
console.log(result); console.log(result);
}); });
@@ -125,7 +126,7 @@ function types (api: ApiPromise): void {
async function tx (api: ApiPromise, keyring: TestKeyringMap): Promise<void> { async function tx (api: ApiPromise, keyring: TestKeyringMap): Promise<void> {
// transfer, also allows for BigInt inputs here // transfer, also allows for BigInt inputs here
const transfer = api.tx.balances.transfer(keyring.bob.address, 123_456_789n); const transfer = api.tx.balances.transfer(keyring.bob.address, 123456789n);
console.log('transfer as Call', transfer as IMethod); console.log('transfer as Call', transfer as IMethod);
console.log('transfer as Extrinsic', transfer as IExtrinsic); console.log('transfer as Extrinsic', transfer as IExtrinsic);
@@ -159,8 +160,9 @@ async function tx (api: ApiPromise, keyring: TestKeyringMap): Promise<void> {
}); });
// it allows for query & then using the submittable // it allows for query & then using the submittable
const second = api.tx.democracy.second(123); const second = api.tx.democracy.second(123, 5);
// eslint-disable-next-line @typescript-eslint/no-floating-promises
second.signAndSend('123', (result): void => { second.signAndSend('123', (result): void => {
console.log(result); console.log(result);
}); });
@@ -173,12 +175,15 @@ async function main (): Promise<void> {
const api = await ApiPromise.create(); const api = await ApiPromise.create();
const keyring = testKeyring(); const keyring = testKeyring();
consts(api); // eslint-disable-next-line @typescript-eslint/no-floating-promises
derive(api); Promise.all([
query(api, keyring); consts(api),
rpc(api); derive(api),
types(api); query(api, keyring),
tx(api, keyring); rpc(api),
types(api),
tx(api, keyring)
]);
} }
// eslint-disable-next-line @typescript-eslint/unbound-method // eslint-disable-next-line @typescript-eslint/unbound-method
+4 -2
View File
@@ -13,7 +13,7 @@ import { hexToU8a } from '@polkadot/util';
import { SingleAccountSigner } from '../../test/util'; import { SingleAccountSigner } from '../../test/util';
import ApiPromise from './Api'; import ApiPromise from './Api';
const TRANSFER_SIG = '0xa1d493ab6b74550da434fbc153a739429be68c9d30e59e631fb5d08f348504deefb5577f4824e138741ad102f479109827e8fa9552812a3e5f505a24d10e820f'; const TRANSFER_SIG = '0x7a10e5ed9a14284eca7bea53f81631981dddda5a3d2dee973b136475947264801465726e4829ae3994d9058df638d959d4e043c7f1924299546790dda1dea20a';
describe('ApiPromise', (): void => { describe('ApiPromise', (): void => {
const registry = new TypeRegistry(); const registry = new TypeRegistry();
@@ -39,7 +39,7 @@ describe('ApiPromise', (): void => {
const signer = new SingleAccountSigner(registry, aliceEd); const signer = new SingleAccountSigner(registry, aliceEd);
const api = await ApiPromise.create({ provider, registry, signer }); const api = await ApiPromise.create({ provider, registry, signer });
const transfer = api.tx.balances.transfer(keyring.getPair('0xe659a7a1628cdd93febc04a4e0646ea20e9f5f0ce097d9a05290d4a9e054df4e').address, 321_564_789_876_512_345n); const transfer = api.tx.balances.transfer(keyring.getPair('0xe659a7a1628cdd93febc04a4e0646ea20e9f5f0ce097d9a05290d4a9e054df4e').address, 321564789876512345n);
return { api, transfer: await transfer.signAsync(aliceEd.address, {}) }; return { api, transfer: await transfer.signAsync(aliceEd.address, {}) };
} }
@@ -57,8 +57,10 @@ describe('ApiPromise', (): void => {
const metadata: any = {}; const metadata: any = {};
const key = `${genesisHash}-${specVersion}`; const key = `${genesisHash}-${specVersion}`;
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
metadata[key] = rpcData; metadata[key] = rpcData;
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
const api = await ApiPromise.create({ metadata, provider, registry } as ApiOptions); const api = await ApiPromise.create({ metadata, provider, registry } as ApiOptions);
expect(api.genesisHash).toBeDefined(); expect(api.genesisHash).toBeDefined();
+14 -14
View File
@@ -25,6 +25,7 @@ function extractArgs (args: any[], needsCallback: boolean): [any[], Callback<Cod
// If the last arg is a function, we pop it, put it into callback. // If the last arg is a function, we pop it, put it into callback.
// actualArgs will then hold the actual arguments to be passed to `method` // actualArgs will then hold the actual arguments to be passed to `method`
if (args.length && isFunction(args[args.length - 1])) { if (args.length && isFunction(args[args.length - 1])) {
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
callback = actualArgs.pop(); callback = actualArgs.pop();
} }
@@ -38,6 +39,7 @@ function extractArgs (args: any[], needsCallback: boolean): [any[], Callback<Cod
function promiseTracker (resolve: (value: () => void) => void, reject: (value: Error) => void): Tracker { function promiseTracker (resolve: (value: () => void) => void, reject: (value: Error) => void): Tracker {
let isCompleted = false; let isCompleted = false;
// eslint-disable-next-line @typescript-eslint/ban-types
const complete = (fn: Function, value: any): void => { const complete = (fn: Function, value: any): void => {
if (!isCompleted) { if (!isCompleted) {
isCompleted = true; isCompleted = true;
@@ -68,24 +70,22 @@ export function decorateMethod<Method extends AnyFunction> (method: Method, opti
const [actualArgs, callback] = extractArgs(args, !!needsCallback); const [actualArgs, callback] = extractArgs(args, !!needsCallback);
if (!callback) { if (!callback) {
// eslint-disable-next-line @typescript-eslint/no-unsafe-call,@typescript-eslint/no-unsafe-member-access
return method(...actualArgs).pipe(first()).toPromise() as Promise<ObsInnerType<ReturnType<Method>>>; return method(...actualArgs).pipe(first()).toPromise() as Promise<ObsInnerType<ReturnType<Method>>>;
} }
return new Promise((resolve, reject): void => { return new Promise((resolve, reject): void => {
const tracker = promiseTracker(resolve, reject); const tracker = promiseTracker(resolve, reject);
const subscription = method(...actualArgs)
.pipe( // eslint-disable-next-line @typescript-eslint/no-unsafe-call,@typescript-eslint/no-unsafe-member-access,@typescript-eslint/no-unsafe-assignment
// if we find an error (invalid params, etc), reject the promise const subscription: { unsubscribe: () => void } = method(...actualArgs).pipe(
catchError((error): Observable<never> => // if we find an error (invalid params, etc), reject the promise
tracker.reject(error) catchError((error): Observable<never> => tracker.reject(error)),
), // upon the first result, resolve with the unsub function
// upon the first result, resolve with the unsub function // eslint-disable-next-line @typescript-eslint/no-unsafe-call,@typescript-eslint/no-unsafe-member-access,@typescript-eslint/no-unsafe-return
tap((): void => tap(() => tracker.resolve(() => subscription.unsubscribe()))
tracker.resolve((): void => subscription.unsubscribe()) ).subscribe(callback);
) }) as UnsubscribePromise;
)
.subscribe(callback);
}) as any; // ???
} as StorageEntryPromiseOverloads; } as StorageEntryPromiseOverloads;
} }
@@ -264,7 +264,7 @@ export default class ApiPromise extends ApiBase<'promise'> {
* ``` * ```
*/ */
// eslint-disable-next-line @typescript-eslint/require-await // eslint-disable-next-line @typescript-eslint/require-await
public async combineLatest (fns: (CombinatorFunction | [CombinatorFunction, ...any[]])[], callback: CombinatorCallback): UnsubscribePromise { public async combineLatest <T extends any[] = any[]> (fns: (CombinatorFunction | [CombinatorFunction, ...any[]])[], callback: CombinatorCallback<T>): UnsubscribePromise {
const combinator = new Combinator(fns, callback); const combinator = new Combinator(fns, callback);
return (): void => { return (): void => {
+9 -6
View File
@@ -7,15 +7,16 @@ import { UnsubscribePromise } from '../types';
import { isFunction } from '@polkadot/util'; import { isFunction } from '@polkadot/util';
export type CombinatorCallback = Callback<any[]>; export type CombinatorCallback <T extends any[]> = Callback<T>;
export interface CombinatorFunction { export interface CombinatorFunction {
(cb: Callback<any>): UnsubscribePromise; (cb: Callback<any>): UnsubscribePromise;
} }
export default class Combinator { export default class Combinator<T extends any[] = any[]> {
#allHasFired = false; #allHasFired = false;
#callback: CombinatorCallback; #callback: CombinatorCallback<T>;
#fired: boolean[] = []; #fired: boolean[] = [];
@@ -27,7 +28,7 @@ export default class Combinator {
#subscriptions: UnsubscribePromise[] = []; #subscriptions: UnsubscribePromise[] = [];
constructor (fns: (CombinatorFunction | [CombinatorFunction, ...any[]])[], callback: CombinatorCallback) { constructor (fns: (CombinatorFunction | [CombinatorFunction, ...any[]])[], callback: CombinatorCallback<T>) {
this.#callback = callback; this.#callback = callback;
// eslint-disable-next-line @typescript-eslint/require-await // eslint-disable-next-line @typescript-eslint/require-await
@@ -40,6 +41,7 @@ export default class Combinator {
this.#fns.push(fn); this.#fns.push(fn);
// Not quite 100% how to have a variable number at the front here // Not quite 100% how to have a variable number at the front here
// eslint-disable-next-line @typescript-eslint/no-unsafe-return,@typescript-eslint/ban-types
return (fn as Function)(...args, this._createCallback(index)); return (fn as Function)(...args, this._createCallback(index));
}); });
} }
@@ -53,7 +55,7 @@ export default class Combinator {
} }
protected _createCallback (index: number): (value: any) => void { protected _createCallback (index: number): (value: any) => void {
return (value: any): void => { return (value: unknown): void => {
this.#fired[index] = true; this.#fired[index] = true;
this.#results[index] = value; this.#results[index] = value;
@@ -67,7 +69,8 @@ export default class Combinator {
} }
try { try {
this.#callback(this.#results); // eslint-disable-next-line @typescript-eslint/no-floating-promises
this.#callback(this.#results as T);
} catch (error) { } catch (error) {
// swallow, we don't want the handler to trip us up // swallow, we don't want the handler to trip us up
} }
+17
View File
@@ -49,5 +49,22 @@ describe('ApiRx', (): void => {
}) })
); );
}); });
it('allows the second argument to signAsync to be omitted', () => {
const signer = new SingleAccountSigner(registry, keyring.alice_session);
ApiRx.create({ provider, registry, signer }).pipe(
switchMap((api: ApiRx): Observable<SubmittableExtrinsic<'rxjs'>> =>
api.tx.balances
.transfer(keyring.eve.address, 12345)
.signAsync(keyring.alice_session)
),
map((tx: SubmittableExtrinsic<'rxjs'>): void => {
expect(tx.signature.toHex()).toEqual(
'0x97f3cfe5088fcd575313e983f45d02b0f630e7b94ff9a3ac50e20cd096a8f554fda73d42ead891b5a1d3ce5607d83f20b0c6570b555e949cfb5763d0abcd590b'
);
})
);
});
}); });
}); });
+14 -7
View File
@@ -41,6 +41,7 @@ export default function createClass <ApiType extends ApiTypes> ({ api, apiType,
const [allOptions] = this.#makeSignAndSendOptions(options); const [allOptions] = this.#makeSignAndSendOptions(options);
const address = isKeyringPair(account) ? account.address : account.toString(); const address = isKeyringPair(account) ? account.address : account.toString();
// eslint-disable-next-line @typescript-eslint/no-unsafe-return,@typescript-eslint/no-unsafe-call
return decorateMethod( return decorateMethod(
(): Observable<RuntimeDispatchInfo> => (): Observable<RuntimeDispatchInfo> =>
api.derive.tx.signingInfo(address, allOptions.nonce, allOptions.era).pipe( api.derive.tx.signingInfo(address, allOptions.nonce, allOptions.era).pipe(
@@ -60,7 +61,7 @@ export default function createClass <ApiType extends ApiTypes> ({ api, apiType,
} }
// sign a transaction, returning the this to allow chaining, i.e. .sign(...).send() // sign a transaction, returning the this to allow chaining, i.e. .sign(...).send()
public sign (account: IKeyringPair, optionsOrNonce: Partial<SignerOptions>): this { public sign (account: IKeyringPair, optionsOrNonce?: Partial<SignerOptions>): this {
super.sign(account, this.#makeSignOptions(this.#optionsOrNonce(optionsOrNonce), {})); super.sign(account, this.#makeSignOptions(this.#optionsOrNonce(optionsOrNonce), {}));
return this; return this;
@@ -69,7 +70,8 @@ export default function createClass <ApiType extends ApiTypes> ({ api, apiType,
// signs a transaction, returning `this` to allow chaining. E.g.: `sign(...).send()` // signs a transaction, returning `this` to allow chaining. E.g.: `sign(...).send()`
// //
// also supports signing through external signers // also supports signing through external signers
public signAsync (account: AddressOrPair, optionsOrNonce: Partial<SignerOptions>): SubmittableThis<ApiType, this> { public signAsync (account: AddressOrPair, optionsOrNonce?: Partial<SignerOptions>): SubmittableThis<ApiType, this> {
// eslint-disable-next-line @typescript-eslint/no-unsafe-return,@typescript-eslint/no-unsafe-call
return decorateMethod( return decorateMethod(
(): Observable<this> => (): Observable<this> =>
this.#observeSign(account, optionsOrNonce).pipe(mapTo(this)) this.#observeSign(account, optionsOrNonce).pipe(mapTo(this))
@@ -90,6 +92,7 @@ export default function createClass <ApiType extends ApiTypes> ({ api, apiType,
const [options, statusCb] = this.#makeSignAndSendOptions(optionsOrStatus, optionalStatusCb); const [options, statusCb] = this.#makeSignAndSendOptions(optionsOrStatus, optionalStatusCb);
const isSubscription = api.hasSubscriptions && (this.#ignoreStatusCb || !!statusCb); const isSubscription = api.hasSubscriptions && (this.#ignoreStatusCb || !!statusCb);
// eslint-disable-next-line @typescript-eslint/no-unsafe-return,@typescript-eslint/no-unsafe-call
return decorateMethod( return decorateMethod(
(): Observable<Codec> => ( (): Observable<Codec> => (
this.#observeSign(account, options).pipe( this.#observeSign(account, options).pipe(
@@ -112,6 +115,7 @@ export default function createClass <ApiType extends ApiTypes> ({ api, apiType,
public send (statusCb?: Callback<ISubmittableResult>): SubmittableResultResult<ApiType> | SubmittableResultSubscription<ApiType> { public send (statusCb?: Callback<ISubmittableResult>): SubmittableResultResult<ApiType> | SubmittableResultSubscription<ApiType> {
const isSubscription = api.hasSubscriptions && (this.#ignoreStatusCb || !!statusCb); const isSubscription = api.hasSubscriptions && (this.#ignoreStatusCb || !!statusCb);
// eslint-disable-next-line @typescript-eslint/no-unsafe-return,@typescript-eslint/no-unsafe-call
return decorateMethod( return decorateMethod(
isSubscription isSubscription
? this.#observeSubscribe ? this.#observeSubscribe
@@ -148,6 +152,7 @@ export default function createClass <ApiType extends ApiTypes> ({ api, apiType,
...options, ...options,
...extras, ...extras,
runtimeVersion: api.runtimeVersion, runtimeVersion: api.runtimeVersion,
signedExtensions: api.registry.signedExtensions,
version: api.extrinsicType version: api.extrinsicType
} as SignatureOptions; } as SignatureOptions;
} }
@@ -164,7 +169,7 @@ export default function createClass <ApiType extends ApiTypes> ({ api, apiType,
return [options, statusCb]; return [options, statusCb];
} }
#observeSign = (account: AddressOrPair, optionsOrNonce: Partial<SignerOptions>): Observable<number | undefined> => { #observeSign = (account: AddressOrPair, optionsOrNonce?: Partial<SignerOptions>): Observable<number | undefined> => {
const address = isKeyringPair(account) ? account.address : account.toString(); const address = isKeyringPair(account) ? account.address : account.toString();
const options = this.#optionsOrNonce(optionsOrNonce); const options = this.#optionsOrNonce(optionsOrNonce);
let updateId: number | undefined; let updateId: number | undefined;
@@ -184,7 +189,7 @@ export default function createClass <ApiType extends ApiTypes> ({ api, apiType,
); );
} }
#observeStatus = (status: ExtrinsicStatus): Observable<ISubmittableResult> => { #observeStatus = (hash: Hash, status: ExtrinsicStatus): Observable<ISubmittableResult> => {
if (!status.isFinalized && !status.isInBlock) { if (!status.isFinalized && !status.isInBlock) {
return of(new SubmittableResult({ status })); return of(new SubmittableResult({ status }));
} }
@@ -196,7 +201,7 @@ export default function createClass <ApiType extends ApiTypes> ({ api, apiType,
return api.derive.tx.events(blockHash).pipe( return api.derive.tx.events(blockHash).pipe(
map(({ block, events }): ISubmittableResult => map(({ block, events }): ISubmittableResult =>
new SubmittableResult({ new SubmittableResult({
events: filterEvents(this.hash, block, events, status), events: filterEvents(hash, block, events, status),
status status
}) })
) )
@@ -212,9 +217,11 @@ export default function createClass <ApiType extends ApiTypes> ({ api, apiType,
} }
#observeSubscribe = (updateId = -1): Observable<ISubmittableResult> => { #observeSubscribe = (updateId = -1): Observable<ISubmittableResult> => {
const hash = this.hash;
return api.rpc.author.submitAndWatchExtrinsic(this).pipe( return api.rpc.author.submitAndWatchExtrinsic(this).pipe(
switchMap((status): Observable<ISubmittableResult> => switchMap((status): Observable<ISubmittableResult> =>
this.#observeStatus(status) this.#observeStatus(hash, status)
), ),
tap((status): void => { tap((status): void => {
this.#updateSigner(updateId, status); this.#updateSigner(updateId, status);
@@ -224,7 +231,7 @@ export default function createClass <ApiType extends ApiTypes> ({ api, apiType,
// NOTE here we actually override nonce if it was specified (backwards compat for // NOTE here we actually override nonce if it was specified (backwards compat for
// the previous signature - don't let userspace break, but allow then time to upgrade) // the previous signature - don't let userspace break, but allow then time to upgrade)
#optionsOrNonce = (optionsOrNonce: Partial<SignerOptions>): Partial<SignerOptions> => { #optionsOrNonce = (optionsOrNonce: Partial<SignerOptions> = {}): Partial<SignerOptions> => {
return isBn(optionsOrNonce) || isNumber(optionsOrNonce) return isBn(optionsOrNonce) || isNumber(optionsOrNonce)
? { nonce: optionsOrNonce } ? { nonce: optionsOrNonce }
: optionsOrNonce; : optionsOrNonce;
@@ -22,6 +22,6 @@ export default function createSubmittable<ApiType extends ApiTypes> (apiType: Ap
Submittable = createClass<ApiType>({ api, apiType, decorateMethod }); Submittable = createClass<ApiType>({ api, apiType, decorateMethod });
} }
return new Submittable(api.registry, extrinsic); return new Submittable(api.registry, extrinsic) as SubmittableExtrinsic<ApiType>;
}; };
} }
+3 -3
View File
@@ -3,7 +3,7 @@
// of the Apache-2.0 license. See the LICENSE file for details. // of the Apache-2.0 license. See the LICENSE file for details.
import { AccountId, Address, Extrinsic, ExtrinsicStatus, EventRecord, Hash, RuntimeDispatchInfo } from '@polkadot/types/interfaces'; import { AccountId, Address, Extrinsic, ExtrinsicStatus, EventRecord, Hash, RuntimeDispatchInfo } from '@polkadot/types/interfaces';
import { AnyNumber, AnyU8a, Callback, Codec, IExtrinsicEra, IKeyringPair, SignatureOptions, Signer, ISubmittableResult } from '@polkadot/types/types'; import { AnyNumber, AnyU8a, Callback, Codec, IExtrinsicEra, IKeyringPair, Signer, ISubmittableResult } from '@polkadot/types/types';
import { ApiTypes } from '../types'; import { ApiTypes } from '../types';
import { Observable } from 'rxjs'; import { Observable } from 'rxjs';
@@ -50,9 +50,9 @@ export interface SubmittableExtrinsic<ApiType extends ApiTypes> extends Extrinsi
send(statusCb: Callback<ISubmittableResult>): SubmittableResultSubscription<ApiType>; send(statusCb: Callback<ISubmittableResult>): SubmittableResultSubscription<ApiType>;
sign(account: IKeyringPair, _options: Partial<SignatureOptions>): this; sign(account: IKeyringPair, _options?: Partial<SignerOptions>): this;
signAsync(account: AddressOrPair, _options: Partial<SignatureOptions>): SubmittableThis<ApiType, this>; signAsync(account: AddressOrPair, _options?: Partial<SignerOptions>): SubmittableThis<ApiType, this>;
signAndSend(account: AddressOrPair, options?: Partial<SignerOptions>): SubmittableResultResult<ApiType>; signAndSend(account: AddressOrPair, options?: Partial<SignerOptions>): SubmittableResultResult<ApiType>;
+1
View File
@@ -40,6 +40,7 @@ export interface StorageEntryBase<ApiType extends ApiTypes, F extends AnyFunctio
export interface StorageEntryDoubleMap<ApiType extends ApiTypes, F extends AnyFunction> extends StorageEntryBase<ApiType, F> { export interface StorageEntryDoubleMap<ApiType extends ApiTypes, F extends AnyFunction> extends StorageEntryBase<ApiType, F> {
entries: <T extends Codec | any = ObsInnerType<ReturnType<F>>>(arg?: Parameters<F>[0]) => PromiseOrObs<ApiType, [StorageKey, T][]>; entries: <T extends Codec | any = ObsInnerType<ReturnType<F>>>(arg?: Parameters<F>[0]) => PromiseOrObs<ApiType, [StorageKey, T][]>;
keyPrefix: (key1?: Parameters<F>[0]) => string;
} }
interface StorageEntryObservableMulti { interface StorageEntryObservableMulti {
@@ -12,6 +12,7 @@ describe('augmentObject', (): void => {
}); });
afterEach((): void => { afterEach((): void => {
// eslint-disable-next-line @typescript-eslint/no-unsafe-call,@typescript-eslint/no-unsafe-member-access
spy.mockClear(); spy.mockClear();
}); });
+3 -3
View File
@@ -74,7 +74,7 @@ function extractMethods (src: Record<string, Record<string, any>>, dst: Record<s
* already available, but rather just adds new missing ites into the result object. * already available, but rather just adds new missing ites into the result object.
* @internal * @internal
*/ */
export default function augmentObject (prefix: string, src: Record<string, Record<string, any>>, dst: Record<string, Record<string, any>>, fromEmpty = false): Record<string, Record<string, any>> { export default function augmentObject (prefix: string, src: Record<string, Record<string, unknown>>, dst: Record<string, Record<string, unknown>>, fromEmpty = false): Record<string, Record<string, any>> {
if (fromEmpty) { if (fromEmpty) {
Object.keys(dst).forEach((key): void => { Object.keys(dst).forEach((key): void => {
delete dst[key]; delete dst[key];
@@ -88,12 +88,12 @@ export default function augmentObject (prefix: string, src: Record<string, Recor
return Object return Object
.keys(src) .keys(src)
.reduce((newSection, sectionName): Record<string, Record<string, any>> => { .reduce((newSection, sectionName): Record<string, Record<string, unknown>> => {
const section = src[sectionName]; const section = src[sectionName];
newSection[sectionName] = Object newSection[sectionName] = Object
.keys(section) .keys(section)
.reduce((result, methodName): Record<string, any> => { .reduce((result, methodName): Record<string, unknown> => {
// TODO When it does match, check the actual details and warn when there are differences // TODO When it does match, check the actual details and warn when there are differences
if (!result[methodName]) { if (!result[methodName]) {
result[methodName] = section[methodName]; result[methodName] = section[methodName];
+5 -7
View File
@@ -14,17 +14,14 @@ export type DeriveAllSections<ApiType extends ApiTypes, AllSections extends AnyD
// A technically unsafe version of Object.keys(obj) that assumes that // A technically unsafe version of Object.keys(obj) that assumes that
// obj only has known properties of T // obj only has known properties of T
function keys<T extends object> (obj: T): (keyof T)[] { function keys<T extends Record<string, unknown>> (obj: T): (keyof T)[] {
return Object.keys(obj) as (keyof T)[]; return Object.keys(obj);
} }
/** /**
* This is a methods decorator which keeps all type information. * This is a methods decorator which keeps all type information.
*/ */
function decorateMethods<ApiType extends ApiTypes, Section extends Record<string, AnyFunction>> ( function decorateMethods<ApiType extends ApiTypes, Section extends Record<string, AnyFunction>> (section: Section, decorateMethod: DecorateMethod<ApiType>): DeriveSection<ApiType, Section> {
section: Section,
decorateMethod: DecorateMethod<ApiType>
): DeriveSection<ApiType, Section> {
return keys(section).reduce( return keys(section).reduce(
<MethodName extends keyof Section>( <MethodName extends keyof Section>(
acc: DeriveSection<ApiType, Section>, acc: DeriveSection<ApiType, Section>,
@@ -32,7 +29,8 @@ function decorateMethods<ApiType extends ApiTypes, Section extends Record<string
): DeriveSection<ApiType, Section> => { ): DeriveSection<ApiType, Section> => {
const method = section[methodName]; const method = section[methodName];
acc[methodName] = decorateMethod(method); // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
acc[methodName] = decorateMethod(method) as MethodResult<ApiType, Section[MethodName]>;
return acc; return acc;
}, },
+1 -1
View File
@@ -18,7 +18,7 @@ export default function filterEvents (extHash: H256, { block: { extrinsics, head
if (index === -1) { if (index === -1) {
// only warn on filtering with isInBlock (finalization finalizes after) // only warn on filtering with isInBlock (finalization finalizes after)
if (status.isInBlock) { if (status.isInBlock) {
l.warn(`block ${header.hash}: Unable to find extrinsic ${myHash} inside ${allHashes}`); l.warn(`block ${header.hash.toHex()}: Unable to find extrinsic ${myHash} inside ${allHashes.join(', ')}`);
} }
return; return;
+1 -2
View File
@@ -35,8 +35,7 @@ describe('extractStorageArgs', (): void => {
it('validates no-arg plain (failing when there are args)', (): void => { it('validates no-arg plain (failing when there are args)', (): void => {
expect( expect(
(): any[] => (): unknown => extractStorageArgs(storage.timestamp.now, [123, 456])
extractStorageArgs(storage.timestamp.now, [123, 456])
).toThrow('timestamp.now() does not take any arguments, 2 found'); ).toThrow('timestamp.now() does not take any arguments, 2 found');
}); });
+1 -1
View File
@@ -35,7 +35,7 @@ function doMap (creator: StorageEntry, args: any[]): [StorageEntry] | [StorageEn
// sets up the arguments in the form of [creator, args] ready to be used in a storage // sets up the arguments in the form of [creator, args] ready to be used in a storage
// call. Additionally, it verifies that the correct number of arguments have been passed // call. Additionally, it verifies that the correct number of arguments have been passed
export function extractStorageArgs (creator: StorageEntry, _args: any[]): any[] { export function extractStorageArgs (creator: StorageEntry, _args: any[]): [StorageEntry, [any, any]] | [StorageEntry] | [StorageEntry, any] {
const args = _args.filter((arg) => !isUndefined(arg)); const args = _args.filter((arg) => !isUndefined(arg));
if (creator.meta.type.isDoubleMap) { if (creator.meta.type.isDoubleMap) {
+2
View File
@@ -9,6 +9,8 @@ function createApi (): Promise<ApiPromise> {
process.env.NODE_ENV = 'test'; process.env.NODE_ENV = 'test';
const provider = new WsProvider('wss://kusama-rpc.polkadot.io'); const provider = new WsProvider('wss://kusama-rpc.polkadot.io');
// const provider = new WsProvider('wss://westend-rpc.polkadot.io/');
// const provider = new WsProvider('ws://127.0.0.1:9944/');
return new ApiPromise({ provider }).isReady; return new ApiPromise({ provider }).isReady;
} }
+1 -1
View File
@@ -7,7 +7,7 @@ import { EventRecord } from '@polkadot/types/interfaces';
import { SubmittableResult } from '../../src'; import { SubmittableResult } from '../../src';
// log all events for the transfers, calling done() when finalized // log all events for the transfers, calling done() when finalized
export const logEvents = (done: () => {}): (r: SubmittableResult) => void => export const logEvents = (done: () => Record<string, unknown>): (r: SubmittableResult) => void =>
({ events, status }: SubmittableResult): void => { ({ events, status }: SubmittableResult): void => {
console.log('Transaction status:', status.type); console.log('Transaction status:', status.type);
+8 -8
View File
@@ -1,6 +1,6 @@
{ {
"name": "@polkadot/metadata", "name": "@polkadot/metadata",
"version": "1.11.1", "version": "1.16.1",
"description": "Helpers to extract information from runtime metadata", "description": "Helpers to extract information from runtime metadata",
"main": "index.js", "main": "index.js",
"publishConfig": { "publishConfig": {
@@ -26,14 +26,14 @@
}, },
"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.9.2", "@babel/runtime": "^7.9.6",
"@polkadot/types": "1.11.1", "@polkadot/types": "1.16.1",
"@polkadot/types-known": "1.11.1", "@polkadot/types-known": "1.16.1",
"@polkadot/util": "^2.8.1", "@polkadot/util": "^2.11.1",
"@polkadot/util-crypto": "^2.8.1", "@polkadot/util-crypto": "^2.11.1",
"bn.js": "^5.1.1" "bn.js": "^5.1.2"
}, },
"devDependencies": { "devDependencies": {
"@polkadot/keyring": "^2.8.1" "@polkadot/keyring": "^2.11.1"
} }
} }
@@ -29,7 +29,8 @@ describe('extrinsics', (): void => {
implName: 'test', implName: 'test',
implVersion: new BN(123), implVersion: new BN(123),
specName: 'test', specName: 'test',
specVersion: new BN(123) specVersion: new BN(123),
transactionVersion: new BN(123)
} }
}).toHex() }).toHex()
).toEqual( ).toEqual(
@@ -4,7 +4,7 @@
import { Text, TypeRegistry } from '@polkadot/types'; import { Text, TypeRegistry } from '@polkadot/types';
import { StorageEntry } from '@polkadot/types/primitive/StorageKey'; import { StorageEntry } from '@polkadot/types/primitive/StorageKey';
import { stringToU8a, u8aConcat, u8aToHex } from '@polkadot/util'; import { assert, stringToU8a, u8aConcat, u8aToHex } from '@polkadot/util';
import createFunction from './createFunction'; import createFunction from './createFunction';
@@ -14,6 +14,7 @@ describe('createFunction', (): void => {
it('should create timestamp.now correctly', (): void => { it('should create timestamp.now correctly', (): void => {
expect( expect(
createFunction(registry, { createFunction(registry, {
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
meta: { type: {} } as any, meta: { type: {} } as any,
method: 'Now', method: 'Now',
prefix: 'Timestamp', prefix: 'Timestamp',
@@ -29,6 +30,7 @@ describe('createFunction', (): void => {
createFunction( createFunction(
registry, registry,
{ {
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
meta: { type: {} } as any, meta: { type: {} } as any,
method: 'authorityCount', method: 'authorityCount',
prefix: 'Substrate', prefix: 'Substrate',
@@ -50,6 +52,7 @@ describe('createFunction', (): void => {
createFunction( createFunction(
registry, registry,
{ {
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
meta: { type: {} } as any, meta: { type: {} } as any,
method: 'authorityCount', method: 'authorityCount',
prefix: 'Substrate', prefix: 'Substrate',
@@ -74,6 +77,7 @@ describe('createFunction', (): void => {
beforeAll((): void => { beforeAll((): void => {
storageFn = createFunction(registry, { storageFn = createFunction(registry, {
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
meta: { meta: {
name: 'metaName', name: 'metaName',
type: { type: {
@@ -104,10 +108,22 @@ describe('createFunction', (): void => {
(): Uint8Array => storageFn(['5DXUeE5N5LtkW97F2PzqYPyqNkxqSWESdGSPTX6AvkUAhwKP']) (): Uint8Array => storageFn(['5DXUeE5N5LtkW97F2PzqYPyqNkxqSWESdGSPTX6AvkUAhwKP'])
).toThrow(/requires two arguments/); ).toThrow(/requires two arguments/);
}); });
it('accepts an optional parameter for key construction', (): void => {
const iterKey = storageFn.iterKey;
assert(iterKey, 'storageFn.iterKey is undefined');
const result = iterKey('5DXUeE5N5LtkW97F2PzqYPyqNkxqSWESdGSPTX6AvkUAhwKP');
expect(u8aToHex(result)).toEqual('0x223416315e3dddca3b5a47fd0ac8e4916482b9ade7bc6657aaca787ba1add3b4c4303117deb55aad9858c8a873273280f78d172b398d5e77e43a2db5e42163e9');
expect(u8aToHex(iterKey())).toEqual('0x223416315e3dddca3b5a47fd0ac8e4916482b9ade7bc6657aaca787ba1add3b4');
});
}); });
it('allows creates double map function with a Null type key', (): void => { it('allows creates double map function with a Null type key', (): void => {
const storageFn = createFunction(registry, { const storageFn = createFunction(registry, {
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
meta: { meta: {
type: { type: {
asDoubleMap: { asDoubleMap: {
@@ -133,6 +149,7 @@ describe('createFunction', (): void => {
it('allows creating of known DoubleMap keys (with Bytes)', (): void => { it('allows creating of known DoubleMap keys (with Bytes)', (): void => {
const storageFn = createFunction(registry, { const storageFn = createFunction(registry, {
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
meta: { meta: {
type: { type: {
asDoubleMap: { asDoubleMap: {
@@ -73,10 +73,7 @@ function createKeyDoubleMap (registry: Registry, itemFn: CreateItemFn, stringKey
const { meta: { name, type } } = itemFn; const { meta: { name, type } } = itemFn;
// since we are passing an almost-unknown through, trust, but verify // since we are passing an almost-unknown through, trust, but verify
assert( assert(Array.isArray(args) && !isUndefined(args[0]) && !isNull(args[0]) && !isUndefined(args[1]) && !isNull(args[1]), `${(name || 'unknown').toString()} is a DoubleMap and requires two arguments`);
Array.isArray(args) && !isUndefined(args[0]) && !isNull(args[0]) && !isUndefined(args[1]) && !isNull(args[1]),
`${name} is a DoubleMap and requires two arguments`
);
// if this fails, we have bigger issues // if this fails, we have bigger issues
assert(!isUndefined(hasher2), '2 hashing functions should be defined for DoubleMaps'); assert(!isUndefined(hasher2), '2 hashing functions should be defined for DoubleMaps');
@@ -110,7 +107,7 @@ function createKey (registry: Registry, itemFn: CreateItemFn, stringKey: string,
if (type.isMap) { if (type.isMap) {
const map = type.asMap; const map = type.asMap;
assert(!isUndefined(arg) && !isNull(arg), `${name} is a Map and requires one argument`); assert(!isUndefined(arg) && !isNull(arg), `${name.toString()} is a Map and requires one argument`);
param = createTypeUnsafe(registry, map.key.toString(), [arg]).toU8a(); param = createTypeUnsafe(registry, map.key.toString(), [arg]).toU8a();
} }
@@ -134,7 +131,7 @@ function expandWithMeta ({ meta, method, prefix, section }: CreateItemFn, storag
// explicitly add the actual method in the toJSON, this gets used to determine caching and without it // explicitly add the actual method in the toJSON, this gets used to determine caching and without it
// instances (e.g. collective) will not work since it is only matched on param meta // instances (e.g. collective) will not work since it is only matched on param meta
storageFn.toJSON = (): any => ({ storageFn.toJSON = (): any => ({
...(meta.toJSON() as any), ...(meta.toJSON() as Record<string, unknown>),
storage: { method, prefix, section } storage: { method, prefix, section }
}); });
@@ -142,7 +139,7 @@ function expandWithMeta ({ meta, method, prefix, section }: CreateItemFn, storag
} }
/** @internal */ /** @internal */
function extendHeadMeta (registry: Registry, { meta: { documentation, name, type }, section }: CreateItemFn, { method }: StorageEntry, iterFn: (arg?: any) => Raw): StorageKey { function extendHeadMeta (registry: Registry, { meta: { documentation, name, type }, section }: CreateItemFn, { method }: StorageEntry, iterFn: (arg?: any) => Raw): (arg?: any) => StorageKey {
const outputType = type.isMap const outputType = type.isMap
? type.asMap.key.toString() ? type.asMap.key.toString()
: type.asDoubleMap.key1.toString(); : type.asDoubleMap.key1.toString();
@@ -157,7 +154,12 @@ function extendHeadMeta (registry: Registry, { meta: { documentation, name, type
type: registry.createType('StorageEntryTypeLatest', registry.createType('PlainTypeLatest', type.isMap ? type.asMap.key : type.asDoubleMap.key1), 0) type: registry.createType('StorageEntryTypeLatest', registry.createType('PlainTypeLatest', type.isMap ? type.asMap.key : type.asDoubleMap.key1), 0)
}); });
return registry.createType('StorageKey', iterFn, { method, section }); const prefixKey = registry.createType('StorageKey', iterFn, { method, section });
return (arg?: any): StorageKey =>
!isUndefined(arg) && !isNull(arg)
? registry.createType('StorageKey', iterFn(arg), { method, section })
: prefixKey;
} }
// attach the head key hashing for linked maps // attach the head key hashing for linked maps
@@ -177,8 +179,12 @@ function extendLinkedMap (registry: Registry, itemFn: CreateItemFn, storageFn: S
// attach the full list hashing for prefixed maps // attach the full list hashing for prefixed maps
/** @internal */ /** @internal */
function extendPrefixedMap (registry: Registry, itemFn: CreateItemFn, storageFn: StorageEntry): StorageEntry { function extendPrefixedMap (registry: Registry, itemFn: CreateItemFn, storageFn: StorageEntry): StorageEntry {
storageFn.iterKey = extendHeadMeta(registry, itemFn, storageFn, (): Raw => const { meta: { type } } = itemFn;
new Raw(registry, createPrefixedKey(itemFn))
storageFn.iterKey = extendHeadMeta(registry, itemFn, storageFn, (arg?: any): Raw =>
type.isDoubleMap && !isUndefined(arg) && !isNull(arg)
? new Raw(registry, u8aConcat(createPrefixedKey(itemFn), getHasher(type.asDoubleMap.hasher)(registry.createType(type.asDoubleMap.key1.toString() as 'Raw', arg).toU8a())))
: new Raw(registry, createPrefixedKey(itemFn))
); );
return storageFn; return storageFn;
@@ -219,7 +225,8 @@ export default function createFunction (registry: Registry, itemFn: CreateItemFn
extendDoubleMap(registry, itemFn, storageFn); extendDoubleMap(registry, itemFn, storageFn);
} }
storageFn.keyPrefix = storageFn.iterKey || compactStripLength(storageFn())[1]; storageFn.keyPrefix = (arg?: any): Uint8Array =>
(storageFn.iterKey && storageFn.iterKey(arg)) || compactStripLength(storageFn())[1];
return storageFn; return storageFn;
} }
@@ -14,11 +14,11 @@ export type HasherFunction = (data: HasherInput) => Uint8Array;
const DEFAULT_FN = (data: HasherInput): Uint8Array => xxhashAsU8a(data, 128); const DEFAULT_FN = (data: HasherInput): Uint8Array => xxhashAsU8a(data, 128);
const HASHERS: Record<keyof typeof AllHashers, HasherFunction> = { const HASHERS: Record<keyof typeof AllHashers, HasherFunction> = {
Blake2_128: (data: HasherInput): Uint8Array => // eslint-disable-line @typescript-eslint/camelcase Blake2_128: (data: HasherInput): Uint8Array => // eslint-disable-line camelcase
blake2AsU8a(data, 128), blake2AsU8a(data, 128),
Blake2_128Concat: (data: HasherInput): Uint8Array => // eslint-disable-line @typescript-eslint/camelcase Blake2_128Concat: (data: HasherInput): Uint8Array => // eslint-disable-line camelcase
u8aConcat(blake2AsU8a(data, 128), u8aToU8a(data)), u8aConcat(blake2AsU8a(data, 128), u8aToU8a(data)),
Blake2_256: (data: HasherInput): Uint8Array => // eslint-disable-line @typescript-eslint/camelcase Blake2_256: (data: HasherInput): Uint8Array => // eslint-disable-line camelcase
blake2AsU8a(data, 256), blake2AsU8a(data, 256),
Identity: (data: HasherInput): Uint8Array => Identity: (data: HasherInput): Uint8Array =>
u8aToU8a(data), u8aToU8a(data),
@@ -14,7 +14,7 @@ export default function getStorage (registry: Registry, metaVersion: number): St
substrate: Object substrate: Object
.entries(substrate) .entries(substrate)
.reduce((storage: Record<string, StorageEntry>, [key, fn]): Record<string, StorageEntry> => { .reduce((storage: Record<string, StorageEntry>, [key, fn]): Record<string, StorageEntry> => {
(storage as any)[key] = fn(registry, metaVersion); (storage as Record<string, unknown>)[key] = fn(registry, metaVersion);
return storage; return storage;
}, {}) }, {})
@@ -2,7 +2,7 @@
// This software may be modified and distributed under the terms // This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details. // of the Apache-2.0 license. See the LICENSE file for details.
import { Registry } from '@polkadot/types/types'; import { AnyNumber, Registry } from '@polkadot/types/types';
import { assert } from '@polkadot/util'; import { assert } from '@polkadot/util';
@@ -11,7 +11,7 @@ import U32 from '@polkadot/types/primitive/U32';
export const MAGIC_NUMBER = 0x6174656d; // `meta`, reversed for Little Endian encoding export const MAGIC_NUMBER = 0x6174656d; // `meta`, reversed for Little Endian encoding
export default class MagicNumber extends U32 { export default class MagicNumber extends U32 {
constructor (registry: Registry, value?: any) { constructor (registry: Registry, value?: AnyNumber) {
super(registry, value); super(registry, value);
if (!this.isEmpty) { if (!this.isEmpty) {
@@ -33,13 +33,13 @@ type MetaAsX = 'asV0' | 'asV1' | 'asV2' | 'asV3' | 'asV4' | 'asV5' | 'asV6' | 'a
* The versioned runtime metadata as a decoded structure * The versioned runtime metadata as a decoded structure
*/ */
export default class MetadataVersioned extends Struct { export default class MetadataVersioned extends Struct {
readonly #converted: Map<number, MetaMapped> = new Map(); readonly #converted = new Map<number, MetaMapped>();
constructor (registry: Registry, value?: any) { constructor (registry: Registry, value?: unknown) {
super(registry, { super(registry, {
magicNumber: MagicNumber, magicNumber: MagicNumber,
metadata: 'MetadataAll' metadata: 'MetadataAll'
}, value); }, value as Map<unknown, unknown>);
registry.setMetadata(this); registry.setMetadata(this);
} }
@@ -2,9 +2,11 @@
// This software may be modified and distributed under the terms // This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details. // of the Apache-2.0 license. See the LICENSE file for details.
type Types = string | Types[];
/** @internal */ /** @internal */
export default function flattenUniq (list: any[]): any[] { export default function flattenUniq (list: Types[]): string[] {
const flat = list.reduce((result, entry): any[] => { const flat = list.reduce((result: string[], entry): string[] => {
return result.concat( return result.concat(
Array.isArray(entry) Array.isArray(entry)
? flattenUniq(entry) ? flattenUniq(entry)
@@ -13,6 +15,6 @@ export default function flattenUniq (list: any[]): any[] {
}, []); }, []);
return [...new Set(flat)] return [...new Set(flat)]
.filter((value: any): any => value) .filter((value: string) => value)
.sort(); .sort();
} }

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