Compare commits

..
374 Commits
Author SHA1 Message Date
Github Actions 8c73cd7d6e [CI Skip] release/stable 1.24.1
skip-checks: true
2020-07-13 09:49:07 +00:00
Jaco Greeff 36232c0289 1.24 (#2421) 2020-07-13 11:38:47 +02:00
Github Actions 50d4e0397f [CI Skip] release/beta 1.24.0-beta.2
skip-checks: true
2020-07-10 13:28:14 +00:00
Jaco Greeff 539a8c4cb5 Types for poll module (#2418) 2020-07-10 15:17:03 +02:00
Github Actions b849976b3b [CI Skip] release/beta 1.24.0-beta.1
skip-checks: true
2020-07-08 14:35:48 +00:00
Jaco Greeff 2395401a2b Raw/Bytes isUtf8 & assert in toUtf8 (#2414) 2020-07-08 16:24:13 +02:00
Github Actions 0e1bbd5cac [CI Skip] release/beta 1.24.0-beta.0
skip-checks: true
2020-07-08 12:57:36 +00:00
Jaco Greeff e9489d41cb Raw isAscii & toUtf8 (#2413)
* Raw isAscii & toUtf8

* Tests for isAscii & toUtf8

* Cleanup return types
2020-07-08 14:46:12 +02:00
Github Actions 63483b9db7 [CI Skip] release/stable 1.23.1
skip-checks: true
2020-07-06 05:45:32 +00:00
Jaco Greeff b26c7f9f0a 1.23.1 (ith version bump) 2020-07-06 07:31:36 +02:00
Github Actions a165c9375c [CI Skip] release/beta 1.23.0-beta.7
skip-checks: true
2020-07-06 05:27:04 +00:00
Jaco Greeff 28631f7180 1.23 (#2411) 2020-07-06 07:15:07 +02:00
Github Actions 6489251b47 [CI Skip] release/beta 1.23.0-beta.6
skip-checks: true
2020-07-03 15:34:13 +00:00
Jaco Greeff 66884febea Add OpaqueCall type (#2408) 2020-07-03 17:22:02 +02:00
Github Actions 8058dc350f [CI Skip] release/beta 1.23.0-beta.5
skip-checks: true
2020-07-03 10:05:48 +00:00
Jaco Greeff 63096cc238 Remove unneeded base extends (#2407)
* Remove unneeded base extends

* CHANGELOG

* Result with value on enum
2020-07-03 11:55:39 +02:00
Github Actions 05600c0cd0 [CI Skip] release/beta 1.23.0-beta.4
skip-checks: true
2020-07-03 09:46:07 +00:00
Jaco Greeff eed5e23e65 Validate number sign in AbstractInt (#2406) 2020-07-03 11:33:30 +02:00
Github Actions cdf5b15673 [CI Skip] release/beta 1.23.0-beta.3
skip-checks: true
2020-07-02 05:27:15 +00:00
Jaco Greeff 1922676bd7 Bump deps (#2404) 2020-07-02 07:14:08 +02:00
Github Actions b6c427e985 [CI Skip] release/beta 1.23.0-beta.2
skip-checks: true
2020-07-01 15:55:54 +00:00
Jaco Greeff 0327aedf8e Update ProxyType for Kusama, Polkadot & Westend (#2403)
* Update ProxyType fro Kusama, Polkadot & Westend

* CHANGELOG
2020-07-01 17:42:22 +02:00
Github Actions d7035cebb1 [CI Skip] release/beta 1.23.0-beta.1
skip-checks: true
2020-07-01 11:51:42 +00:00
Daniel Maricic 8b492021af Fixed typo in README (#2402) 2020-07-01 13:39:07 +02:00
Github Actions 6a01fc7c8c [CI Skip] release/beta 1.23.0-beta.0
skip-checks: true
2020-07-01 05:58:34 +00:00
Jaco Greeff bbc30ec9dc Cross-referencing type failure (#2400)
* Cross-referencing type failure

* typo

* Adjust toRawType() with name from registry

* Rewrite yarn.lock

* Adjustments

* Test adjustments
2020-07-01 07:47:21 +02:00
Github Actions f07c0628bc [CI Skip] release/stable 1.22.1
skip-checks: true
2020-06-30 08:04:08 +00:00
Jaco Greeff 023c7588e5 1.22 (#2399)
* 1.22

* CHANGELOG for OpenTip
2020-06-30 09:52:42 +02:00
Jaco Greeff 7dfc8625cc New OpenTip structure (#2394)
* New OpenTip structure

* Kusama update
2020-06-29 16:20:43 +02:00
Github Actions 8643b5da87 [CI Skip] release/beta 1.22.0-beta.5
skip-checks: true
2020-06-29 07:03:10 +00:00
Jaco Greeff afa0e63ae8 CHANGELOG & Bumps (#2397)
* CHANGELOG & Bumps

* Rewrite yarn.lock
2020-06-29 08:52:12 +02:00
Github Actions 534303ff45 [CI Skip] release/beta 1.22.0-beta.4
skip-checks: true
2020-06-28 14:18:29 +00:00
Jaco Greeff f1ebcddec6 Adjust for vesting via locks (#2396) 2020-06-28 16:08:02 +02:00
Github Actions 657a2006dd [CI Skip] release/beta 1.22.0-beta.3
skip-checks: true
2020-06-24 19:02:00 +00:00
Jaco Greeff 219e928c01 Retried staker rewards for specified eras (#2392) 2020-06-24 20:52:21 +02:00
Github Actions 43183118d5 [CI Skip] release/beta 1.22.0-beta.2
skip-checks: true
2020-06-24 10:43:10 +00:00
Alexander Krupenkin 76e15d465d Add [u8; 33] type width for U8aFixed type (#2391)
ECDSA compressed public key has 33-byte length, this is required for encoding public key as a parameter.
2020-06-24 12:31:55 +02:00
Github Actions 4c0387e1a3 [CI Skip] release/beta 1.22.0-beta.1
skip-checks: true
2020-06-23 20:31:15 +00:00
Jaco Greeff bbbd82eb4a Move indices cache to indices list (#2390) 2020-06-23 22:19:13 +02:00
Github Actions a34a7450aa [CI Skip] release/beta 1.22.0-beta.0
skip-checks: true
2020-06-23 18:38:54 +00:00
Jaco Greeff bf472fdcf4 Optimize accountId -> accountIndex lookups (#2389) 2020-06-23 20:25:58 +02:00
Github Actions f428a58006 [CI Skip] release/stable 1.21.1
skip-checks: true
2020-06-23 16:12:18 +00:00
Jaco Greeff fcce2ab340 1.21 (#2384)
* 1.21

* CHANGELOG

* Babe EquivocationProof

* Update CHANGELOG.md
2020-06-23 18:01:47 +02:00
Jaco Greeff 877eb11717 Swap releases type to shared enum (#2388)
* Swap releases type to u8

* Shared enum for releases

* Update metadata for new names
2020-06-23 17:40:15 +02:00
Jaco Greeff 4b55f1be93 Babe Equivocation (#2374)
* Babe Equivocation

* metadata field rename to GrandpaEquivocationProof
2020-06-23 16:46:26 +02:00
Github Actions f2a677634e [CI Skip] release/beta 1.21.0-beta.4
skip-checks: true
2020-06-23 13:18:12 +00:00
Jaco Greeff eea4c8775e Use setImmediate for unsubscribe (allow outer resolve) (#2385) 2020-06-23 15:06:08 +02:00
Github Actions 792bf0ec36 [CI Skip] release/beta 1.21.0-beta.3
skip-checks: true
2020-06-23 12:20:27 +00:00
Jaco Greeff e3d13107a9 Add support for CheckMortality extension (#2383) 2020-06-23 14:08:40 +02:00
Jaco Greeff e5c2c6a228 Use BN in-place operators as appropriate (#2381)
* Use BN in-place operators as appropriate

* CHANGELOG
2020-06-23 14:02:54 +02:00
Github Actions d2be79132c [CI Skip] release/beta 1.21.0-beta.2
skip-checks: true
2020-06-23 11:59:30 +00:00
Jaco Greeff 76da2638c1 Ensure subscriptions always unsubscribe as required (#2380)
* Ensure single-shot calls always unsubscribe

* memo/refCount cleanups

* Fix unsubscriptions

* Cleanup linting types

* CHANGELOG
2020-06-23 13:47:28 +02:00
Github Actions daf3912920 [CI Skip] release/beta 1.21.0-beta.1
skip-checks: true
2020-06-23 09:17:57 +00:00
Jaco Greeff 6dfebbb9fe Fixup subscriptions for promise (w/ callback) (#2379)
* Fixup subscriptions for promise (w/ callback)

* Update packages/api/src/base/Decorate.ts
2020-06-23 11:05:51 +02:00
Github Actions e55c5f77f7 [CI Skip] release/beta 1.21.0-beta.0
skip-checks: true
2020-06-23 07:41:54 +00:00
Jaco Greeff c7315ffb74 Do not use subscriptions on single subs (#2378)
* Do not use subscriptions on single subs

* Apply suggestions from code review
2020-06-23 09:29:49 +02:00
Github Actions 84eb806f07 [CI Skip] release/stable 1.20.1
skip-checks: true
2020-06-22 14:20:44 +00:00
Jaco Greeff 2493442a2e 1.20 (#2377)
* 1.20

* Indicate @polkadot/util bump
2020-06-22 16:08:22 +02:00
Github Actions 77df7907c7 [CI Skip] release/beta 1.20.0-beta.9
skip-checks: true
2020-06-22 13:42:01 +00:00
Jaco Greeff f1b6268784 Bump metadata (#2376) 2020-06-22 15:31:27 +02:00
Github Actions 9aa9380251 [CI Skip] release/beta 1.20.0-beta.8
skip-checks: true
2020-06-22 08:22:33 +00:00
Jaco Greeff b4306cb60a Bump metadata (#2373) 2020-06-22 10:12:01 +02:00
Github Actions 1e83daf797 [CI Skip] release/beta 1.20.0-beta.7
skip-checks: true
2020-06-21 11:26:27 +00:00
Jaco Greeff d46d32d9bc Optimize query/queryMulti retrievals (#2371)
* Optimize query/queryMulti retrievals

* Current retrieval on a batch basis

* Dedup staking.account/accounts internally
2020-06-21 13:13:38 +02:00
Github Actions 032a0a595c [CI Skip] release/beta 1.20.0-beta.6
skip-checks: true
2020-06-21 08:09:28 +00:00
Jaco Greeff 34101ec12b Adjust with queryMulti as applicable (#2370) 2020-06-21 09:56:02 +02:00
Github Actions 4e02b982d3 [CI Skip] release/beta 1.20.0-beta.5
skip-checks: true
2020-06-20 18:12:10 +00:00
Jaco Greeff 5b96d52fa6 Adjust for zero-length combines (#2369) 2020-06-20 20:00:01 +02:00
Github Actions 735f2b835e [CI Skip] release/beta 1.20.0-beta.4
skip-checks: true
2020-06-20 13:42:40 +00:00
Jaco Greeff 646e64c286 Add derive.staking.waitingInfo (#2367)
* Add derive.staking.waitingInfo

* Small optimizations

* Updated
2020-06-20 15:30:48 +02:00
Github Actions fc9060caa8 [CI Skip] release/beta 1.20.0-beta.3
skip-checks: true
2020-06-19 12:04:34 +00:00
Jaco Greeff 503c2b3c63 Add transactionPayment release type (#2366) 2020-06-19 13:51:40 +02:00
Github Actions 168abc130f [CI Skip] release/beta 1.20.0-beta.2
skip-checks: true
2020-06-18 08:28:13 +00:00
Jaco Greeff 5c5db2709b Add system_dryRun RPCs (#2363)
* Add system_dryRun RPCs

* CHANGELOG
2020-06-18 10:15:41 +02:00
Github Actions 5a4ff5420f [CI Skip] release/beta 1.20.0-beta.1
skip-checks: true
2020-06-18 08:04:22 +00:00
Jaco Greeff a1655508ba Cleanups in API typing (& overrides) (#2362)
* Cleanups in API typing (& overrides)

* Less magic "as" overrides
2020-06-18 09:52:39 +02:00
Github Actions 64827a6114 [CI Skip] release/beta 1.20.0-beta.0
skip-checks: true
2020-06-17 22:18:49 +00:00
Jaco Greeff 2eb09374bc Map entries/keys cleanups (#2360) 2020-06-18 00:06:19 +02:00
Github Actions ddf67d5564 [CI Skip] release/stable 1.19.1
skip-checks: true
2020-06-16 06:47:45 +00:00
Jaco Greeff ad6b8280a2 1.19 (#2354)
* Bump deps

* 1.19

* Update CHANGELOG.md

* Freshen Substrate metadata
2020-06-16 08:34:19 +02:00
Github Actions 682c6b6fb2 [CI Skip] release/beta 1.19.0-beta.3
skip-checks: true
2020-06-12 21:28:49 +00:00
Jaco Greeff 6a281211b4 Bump metadata, allow type alias on events (#2351)
* Bump metadata, allow type alias on events

* Update packages/api/src/submittable/createClass.ts

* Update packages/metadata/src/Metadata/v11/static-substrate.json

* Fresh, no config changes
2020-06-12 23:15:50 +02:00
Github Actions 6ef94b3c3b [CI Skip] release/beta 1.19.0-beta.2
skip-checks: true
2020-06-12 16:31:41 +00:00
Jeremías Díaz e900d1d657 impovement: better typing of entries related funcs (#2346)
* impovement: better typing of entries related funcs

* refactor: remove duplicate definition
2020-06-12 18:19:55 +02:00
Github Actions 7f1a3fa636 [CI Skip] release/beta 1.19.0-beta.1
skip-checks: true
2020-06-11 07:00:42 +00:00
Jaco Greeff 21802664b8 Metadata bump (#2348) 2020-06-11 08:48:52 +02:00
Github Actions 1492df11a7 [CI Skip] release/beta 1.19.0-beta.0
skip-checks: true
2020-06-10 11:13:46 +00:00
Jaco Greeff 00fed90da2 Update parachain types (#2344) 2020-06-10 13:00:10 +02:00
Github Actions e6beb6554d [CI Skip] release/stable 1.18.1
skip-checks: true
2020-06-08 15:53:39 +00:00
Jaco Greeff 099cf5a351 1.18 (#2340)
* 1.18

* Polkadot ProxyType
2020-06-08 17:39:12 +02:00
Github Actions 55e762a348 [CI Skip] release/beta 1.18.0-beta.10
skip-checks: true
2020-06-08 13:43:22 +00:00
Jaco Greeff 0ad146c607 Adjust ProxyType for Westend (#2339) 2020-06-08 15:30:51 +02:00
Github Actions 4e7f3f5268 [CI Skip] release/beta 1.18.0-beta.9
skip-checks: true
2020-06-08 08:02:24 +00:00
Jeremías DíazandJaco Greeff 6a9e3d80f1 feat: add external pagination support (#2325)
* feat: add external pagination support

* Ordering, no functionality changes

* fix: use correct assertion condition

Also moved the PaginationOptions type to the base types file

* Apply suggestions from code review

Co-authored-by: Jaco Greeff <jacogr@gmail.com>
2020-06-08 09:49:53 +02:00
Github Actions dee98fae55 [CI Skip] release/beta 1.18.0-beta.8
skip-checks: true
2020-06-08 05:59:44 +00:00
Xiliang Chen ff52876920 allow Option in enum & Result type (#2336) 2020-06-08 07:45:22 +02:00
Github Actions 4d01a09c54 [CI Skip] release/beta 1.18.0-beta.7
skip-checks: true
2020-06-07 17:27:50 +00:00
Jaco Greeff 7310ea825e Allow for string subids (#2335) 2020-06-07 19:16:16 +02:00
Github Actions 15b80a47c3 [CI Skip] release/beta 1.18.0-beta.6
skip-checks: true
2020-06-07 13:02:15 +00:00
Jaco Greeff 622682b4ef npos-election ElectionScore type (#2334) 2020-06-07 14:50:25 +02:00
Github Actions 56415df4ab [CI Skip] release/beta 1.18.0-beta.5
skip-checks: true
2020-06-06 06:53:17 +00:00
Jaco Greeff 8bea5e5a3b Align Call section/method field names (#2332) 2020-06-06 08:40:41 +02:00
Github Actions d6372ade44 [CI Skip] release/beta 1.18.0-beta.4
skip-checks: true
2020-06-05 20:32:29 +00:00
Jaco Greeff f501994df8 Bump deps (#2333) 2020-06-05 22:20:32 +02:00
Github Actions b787a7d5a0 [CI Skip] release/beta 1.18.0-beta.3
skip-checks: true
2020-06-03 20:20:42 +00:00
Gerben van de Wiel 11d162a10d Adding some extra notes on changes in the specname (#2329) 2020-06-03 22:08:06 +02:00
Github Actions e2564dea17 [CI Skip] release/beta 1.18.0-beta.2
skip-checks: true
2020-06-03 13:40:22 +00:00
Jaco Greeff 2b9152871e Add ProxyType (#2327) 2020-06-03 15:27:11 +02:00
Github Actions 70ecb03d14 [CI Skip] release/beta 1.18.0-beta.1
skip-checks: true
2020-06-03 05:46:05 +00:00
djuanito.eth a2f179acb1 Update fees to current constants (#2320)
* Update fees to current constants

* Reorder args on map()

* Fixed incorrect order of args on map()
2020-06-03 07:34:03 +02:00
Jaco Greeff c8cb97edef beta 0 reset 2020-06-03 07:33:27 +02:00
Github Actions 69d344c6c3 [CI Skip] release/stable 1.17.2
skip-checks: true
2020-06-02 15:26:46 +00:00
Jaco Greeff 44cdf49b2c Resolve first result after unsub promise (via setImmediate) (#2324) 2020-06-02 17:14:29 +02:00
Github Actions daaf4654a1 [CI Skip] release/stable 1.17.1
skip-checks: true
2020-06-02 12:26:21 +00:00
Jaco Greeff f8d4fcaf04 1.17 (#2323) 2020-06-02 14:15:27 +02:00
Github Actions eb19a39d82 [CI Skip] release/beta 1.17.0-beta.8
skip-checks: true
2020-06-02 10:50:47 +00:00
Jaco Greeff 7ed958fb2d Metadata bump (#2322)
* Metadata bump

* yarn.lock

* var requires
2020-06-02 12:39:48 +02:00
Github Actions bbe9b94f26 [CI Skip] release/beta 1.17.0-beta.7
skip-checks: true
2020-06-02 09:17:06 +00:00
Jaco Greeff 6e83e6aaef Adjust call-only metadata output (#2321) 2020-06-02 11:03:34 +02:00
Github Actions 1545bbf7c5 [CI Skip] release/beta 1.17.0-beta.6
skip-checks: true
2020-05-31 11:18:45 +00:00
Jaco Greeff 5bfc2cd534 Protect against div-by-zero (#2319)
* Protect against div-by-zero

* Rewrite
2020-05-31 13:07:42 +02:00
Github Actions b22d0a196f [CI Skip] 1.17.0-beta.5
skip-checks: true
2020-05-28 11:23:47 +00:00
Jaco Greeff b174864804 Adjust own cache key (per accountId) (#2317) 2020-05-28 13:12:27 +02:00
Github Actions e6834d60c5 [CI Skip] 1.17.0-beta.4
skip-checks: true
2020-05-28 10:54:39 +00:00
Jaco Greeff 97438bb2e8 Small combineLatest -> queryMulti opts (#2316)
* Small combineLatest -> queryMulti opts

* Update packages/api-derive/src/staking/ownSlashes.ts
2020-05-28 12:43:02 +02:00
Github Actions f630d43a25 [CI Skip] 1.17.0-beta.3
skip-checks: true
2020-05-28 10:19:44 +00:00
Jaco Greeff 0187f1ff19 Extend deriveCache around ownExposure/ownSlash (#2315) 2020-05-28 12:07:02 +02:00
Github Actions d8db866316 [CI Skip] 1.17.0-beta.2
skip-checks: true
2020-05-28 09:55:46 +00:00
Jaco Greeff 28aa9e18a7 Bump deps (#2314) 2020-05-28 11:43:45 +02:00
Github Actions 3eaea97b8f [CI Skip] 1.17.0-beta.1
skip-checks: true
2020-05-28 08:55:06 +00:00
Jaco Greeff ea0e5e4547 BTreeSet decoding from Array (#2313) 2020-05-28 10:42:46 +02:00
Github Actions 1256317b65 [CI Skip] 1.17.0-beta.0
skip-checks: true
2020-05-27 17:42:13 +00:00
Jaco Greeff e0c3ed1b96 Fix ElectionSize type (#2312) 2020-05-27 19:29:13 +02:00
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
Github Actions dd6e6ddfc1 [CI Skip] 1.11.1
skip-checks: true
2020-04-21 07:47:25 +00:00
Jaco Greeff 9975f58cfb 1.11 (#2198)
* 1.11

* isOptional is custom RPC sample

* Names is one-liner for custom RPCs
2020-04-21 09:38:09 +02:00
Github Actions 536369261f [CI Skip] 1.11.0-beta.35
skip-checks: true
2020-04-21 07:10:16 +00:00
Jaco Greeff 33165e93dc Add state_getReadProof (#2196) 2020-04-21 09:00:03 +02:00
Github Actions 39a38a6c44 [CI Skip] 1.11.0-beta.34
skip-checks: true
2020-04-21 05:41:16 +00:00
Keith Ingram b18bdc37f9 Add api.derive.accounts.flags (#2195)
* account flags in new call

* Fix
2020-04-21 07:31:00 +02:00
Github Actions 79847aabf7 [CI Skip] 1.11.0-beta.33
skip-checks: true
2020-04-20 09:22:55 +00:00
Jaco Greeff ab75863d94 Fix derive.democracy.preimage signature (#2194) 2020-04-20 11:12:03 +02:00
Github Actions c908a27b7d [CI Skip] 1.11.0-beta.32
skip-checks: true
2020-04-18 07:31:19 +00:00
Jaco Greeff 98c7e5d5ea Optimize entries retrieval (#2193) 2020-04-18 09:21:06 +02:00
Github Actions fd4587a0bc [CI Skip] 1.11.0-beta.31
skip-checks: true
2020-04-17 13:41:21 +00:00
Jaco Greeff e211ae1667 Added types for DoubleVoteReport (parachains) (#2192) 2020-04-17 15:32:51 +02:00
Github Actions af735176fe [CI Skip] 1.11.0-beta.30
skip-checks: true
2020-04-17 10:34:48 +00:00
Jaco Greeff 9eb44d6e89 console warnings on the use of node-template (#2191)
* console warnings on the use of node-template

* Message formatting
2020-04-17 12:23:44 +02:00
Github Actions 379e841808 [CI Skip] 1.11.0-beta.29
skip-checks: true
2020-04-17 06:07:08 +00:00
Jaco Greeff 5c16b8e8a1 Adjust spec types (starting versions) (#2189) 2020-04-17 07:55:53 +02:00
Github Actions 96d7d9ff5a [CI Skip] 1.11.0-beta.28
skip-checks: true
2020-04-16 19:55:16 +00:00
Jaco Greeff e9fbbbbd42 Typos 2020-04-16 21:44:04 +02:00
Github Actions 73750ddb7d [CI Skip] 1.11.0-beta.27
skip-checks: true
2020-04-16 19:39:17 +00:00
Jaco Greeff 4e1145c66f FAQ entry for Weight adjustment (#2188)
* FAQ entry for Weight adjustment

* CHANGELOG entry for rxjs Observable exposure

* Event decoding
2020-04-16 21:29:22 +02:00
Github Actions 7f35fa22d5 [CI Skip] 1.11.0-beta.26
skip-checks: true
2020-04-16 17:14:23 +00:00
Jeremías Díaz da1daf5bd9 fix: ensure consistent Observable version (#2187) 2020-04-16 19:03:00 +02:00
Github Actions 5afc87ce47 [CI Skip] 1.11.0-beta.25
skip-checks: true
2020-04-16 16:21:36 +00:00
Jaco Greeff a2269cd999 Explain where args come from and their types (#2186)
* Explain where args come from and their types

* Update api.query.other.md
2020-04-16 18:11:12 +02:00
Github Actions 201308c259 [CI Skip] 1.11.0-beta.24
skip-checks: true
2020-04-16 14:32:15 +00:00
Jaco Greeff 00490116dd Add system_{localPeerId, localListenAddresses} RPCs (#2185)
* Add system_{localPeerId, localListenAddresses} RPCs

* CHANGELOG
2020-04-16 16:21:40 +02:00
Github Actions 1968c878f5 [CI Skip] 1.11.0-beta.23
skip-checks: true
2020-04-16 13:52:16 +00:00
Jaco Greeff 52ccb9fbbf Linkage fixes (#2184)
* Fix linkage decoding

* Actually fix linkage

* CHANGELOG
2020-04-16 15:41:42 +02:00
Github Actions 03e21ea64b [CI Skip] 1.11.0-beta.22
skip-checks: true
2020-04-16 13:39:19 +00:00
Jaco Greeff 8c949bb3df StorageKey toHuman returns decoded key (#2183) 2020-04-16 15:28:15 +02:00
Github Actions e484e7cf35 [CI Skip] 1.11.0-beta.21
skip-checks: true
2020-04-16 11:32:18 +00:00
Jaco Greeff 7aac4c7936 Add missing cookbook .keys 2020-04-16 13:21:04 +02:00
Github Actions 933c8d48e2 [CI Skip] 1.11.0-beta.20
skip-checks: true
2020-04-16 11:18:25 +00:00
Jaco Greeff d3d3bb9b5a Adjust Weight to u64 (#2181)
* Adjust Weight to u64

* Adjust copy (really should be reading folders...)

* build:interfaces

* EventRecord test expectation update
2020-04-16 13:08:46 +02:00
Github Actions f4d976c337 [CI Skip] 1.11.0-beta.19
skip-checks: true
2020-04-16 10:17:47 +00:00
Jaco Greeff 07c4037fcf On subscriptions, ensure rx.runtimeVersion is set (#2180) 2020-04-16 12:05:35 +02:00
Github Actions 52d73d8698 [CI Skip] 1.11.0-beta.18
skip-checks: true
2020-04-16 09:02:05 +00:00
Jeremías Díaz ccfab75f41 fix: use camelCase for storage module names (#2176) 2020-04-16 10:51:19 +02:00
Github Actions b8204b138d [CI Skip] 1.11.0-beta.17
skip-checks: true
2020-04-16 08:46:32 +00:00
Jaco Greeff a97cb6e25d Return all identity hashes (not just as subset) (#2179) 2020-04-16 10:36:37 +02:00
Github Actions 11534a1153 [CI Skip] 1.11.0-beta.16
skip-checks: true
2020-04-16 07:21:00 +00:00
Jaco Greeff dd1fab5366 Adjust set bitfileds to LE (#2178) 2020-04-16 09:09:17 +02:00
Github Actions dbb3a5ccc2 [CI Skip] 1.11.0-beta.15
skip-checks: true
2020-04-15 16:26:29 +00:00
Jaco Greeff fb08215e0d Add Fixed128 type (#2175) 2020-04-15 18:15:11 +02:00
Github Actions d7d7ab2f89 [CI Skip] 1.11.0-beta.14
skip-checks: true
2020-04-15 08:54:43 +00:00
Jaco Greeff 25393cd982 Add note on field ordering (#2173)
* Add note on field ordering

* Field ordering additional links
2020-04-15 10:43:15 +02:00
Github Actions d6a6089e2d [CI Skip] 1.11.0-beta.13
skip-checks: true
2020-04-15 06:55:53 +00:00
Jaco Greeff a3eaca0270 Small doc cleanups (#2172) 2020-04-15 08:44:15 +02:00
Github Actions f9d1b4d653 [CI Skip] 1.11.0-beta.12
skip-checks: true
2020-04-14 20:22:21 +00:00
Jaco Greeff f81712343a Transaction batching (#2171) 2020-04-14 22:10:25 +02:00
Github Actions 33e414be12 [CI Skip] 1.11.0-beta.11
skip-checks: true
2020-04-14 16:27:55 +00:00
Jaco Greeff 9387103558 cookbook link 2020-04-14 18:15:28 +02:00
Github Actions 3b7c1afa95 [CI Skip] 1.11.0-beta.10
skip-checks: true
2020-04-14 15:28:01 +00:00
Jaco Greeff 7e1fa8954b Extend storage cookbook (#2169)
* Extend storage cookbook

* Update storage.md

* Update storage.md
2020-04-14 17:16:46 +02:00
Github Actions 53c62f1542 [CI Skip] 1.11.0-beta.9
skip-checks: true
2020-04-14 14:56:23 +00:00
Jaco Greeff 5ed94a50e1 Update .123trigger 2020-04-14 16:45:30 +02:00
Github Actions b1c047149b [CI Skip] 1.11.0-beta.8
skip-checks: true
2020-04-14 14:35:37 +00:00
Jaco Greeff 7a0efaf58c Kusama 1057 known types (#2168) 2020-04-14 16:24:19 +02:00
Github Actions 5acce98346 [CI Skip] 1.11.0-beta.7
skip-checks: true
2020-04-14 11:52:00 +00:00
Jaco Greeff 165179ebf2 Remove flags on derive.accounts.info (#2167)
* Remove flags from derive.account.info

* adjust types
2020-04-14 13:40:12 +02:00
Github Actions def60dce9e [CI Skip] 1.11.0-beta.6
skip-checks: true
2020-04-14 10:49:12 +00:00
Jaco Greeff c8f91fcf7a Parameterize DoNotConstruct (#2165)
* Parameterize DoNotConstruct

* Update DoNotConstruct list

* typo fix
2020-04-14 12:37:30 +02:00
Github Actions 70a160cca0 [CI Skip] 1.11.0-beta.5
skip-checks: true
2020-04-14 10:31:23 +00:00
Jaco Greeff 9691fd5ba7 don't subscribe to runtime updates with no subs (#2166) 2020-04-14 12:20:07 +02:00
Jaco Greeff 475cb4fa69 Move Digest to interfaces (#2164)
* Move Digest to interfaces

* Unconstructable typos
2020-04-14 12:09:36 +02:00
Github Actions 5c54b3cc92 [CI Skip] 1.11.0-beta.4
skip-checks: true
2020-04-14 10:05:31 +00:00
Jaco Greeff 55d8c58d95 Add transactionVerions to RuntimeVersion struct (#2163) 2020-04-14 11:54:42 +02:00
Github Actions edf8adaa88 [CI Skip] 1.11.0-beta.3
skip-checks: true
2020-04-14 08:49:43 +00:00
Jaco Greeff 1f8f6e54bd Add unsigned sending to cookbook (#2162)
* Add unsigned sending to cookbook

* Block author extraction example
2020-04-14 10:36:15 +02:00
Github Actions f6ca7b9a9d [CI Skip] 1.11.0-beta.2
skip-checks: true
2020-04-14 07:52:33 +00:00
Jaco Greeff 7732339fc0 Line lengths 2020-04-14 09:41:04 +02:00
Jaco Greeff 5a8a8c7ecb Fix cookbook links 2020-04-14 09:34:39 +02:00
Github Actions 05df087e73 [CI Skip] 1.11.0-beta.1
skip-checks: true
2020-04-14 06:58:37 +00:00
Jaco Greeff 5b71abfe80 Make a start at a cookbook... still loads to go (#2160) 2020-04-14 08:48:14 +02:00
Github Actions 1d6c33060a [CI Skip] 1.11.0-beta.0
skip-checks: true
2020-04-13 10:45:21 +00:00
Jaco Greeff eae573e6a2 Simplify entries() decoding (#2159) 2020-04-13 12:33:24 +02:00
366 changed files with 15392 additions and 15216 deletions
+4 -2
View File
@@ -1,3 +1,5 @@
21
1.4.2
24
1.4.2
1.6.2
1.11.2
1.12.21.17.2
+1
View File
@@ -1,3 +1,4 @@
.eslintrc.js
**/build/*
**/coverage/*
**/node_modules/*
+2 -5
View File
@@ -10,7 +10,7 @@ jobs:
matrix:
step: ['build:release', 'docs:release']
name: ${{ matrix.step }}
if: "! contains(github.event.head_commit.message, '[CI Skip]') && github.repository == 'polkadot-js/api'"
if: "! startsWith(github.event.head_commit.message, '[CI Skip]') && github.repository == 'polkadot-js/api'"
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v1
@@ -21,16 +21,13 @@ jobs:
CC_TEST_REPORTER_ID: ${{ secrets.CC_TEST_REPORTER_ID }}
GH_PAGES_SRC: build-docs
GH_PAT: ${{ secrets.GH_PAT }}
GH_TOKEN: ${{ secrets.GH_PAT }}
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
GH_RELEASE_GITHUB_API_TOKEN: ${{ secrets.GH_PAT }}
NPM_TOKEN: ${{ secrets.NPM_TOKEN }}
run: |
yarn install --immutable | grep -v 'YN0013'
yarn ${{ matrix.step }}
dummy:
name: Dummy
if: "contains(github.event.head_commit.message, '[CI Skip]')"
runs-on: ubuntu-latest
steps:
- name: dummy
+14 -8
View File
File diff suppressed because one or more lines are too long
+242 -73
View File
@@ -1,4 +1,173 @@
# 1.10.1 Apr 13, 2020
# CHANGELOG
## 1.24.1 Jul 13, 2020
- Added `isAscii` & `isUtf8` getters to `Bytes` & `Raw` types
- Added `toUtf8()` helper to `Bytes` & `Raw` types
- `@polkadot/util` 2.18
## 1.23.1 Jul 6, 2020
- Small README typo fix (Thanks to https://github.com/woss)
- Add latest Substrate master types
- Adjust `<Codec>.toRawType()` to use registry name as available
- Update `ProxyType` for Kusama, Polkadot & Westend with `IdentityJudgement`
- Validate number format (signed/unsigned) for number types
- Remove core codec dependencies on Base class (with proper TS encapsulation)
- `@polkadot/util` 2.17
## 1.22.1 Jun 30, 2020
- **Important** Substrate changed the treasury tip structure, on older chains supply `OpenTip: 'OpenTipTo225'`
- Allow for `[u8; 33]` in U8aFixed (Thanks to https://github.com/akru)
- Improve derive accountId -> accountIndex lookups (optimize entries queries)
- Vesting balance calculations via `derive.balances.all` has been updated for locks
- Add derive for multi staking rewards with specified eras
- `@polkadot/util` 2.16
## 1.21.1 Jun 23, 2020
- Fix subscriptions never unsubscribing after the id swap in 1.18.1 (Thanks to https://github.com/dillu24 for testing iterations)
- Add support for `CheckMortality` signed extension (old `CheckEra` is now an alias)
- Promise API will default to using `getStorage` on non-subscription calls, reducing RPC overhead
- Optimize derive BN allocations, using in-place operators as applicable
- Add new Substrate types for Babe `EquivocationProof`
- Adjust `Releases` enum to use a shared instance
## 1.20.1 Jun 22, 2020
- **Important** RPC for `account_nextIndex` has been moved to `system_accountNextIndex` (Aligning with Substrate as a primary alias)
- Cleanup map entries support with only Substrate 2.0-era RPCs (when introduced)
- Add `system_dryRun` RPC
- Optimize `derive.staking.queryMulti` retrievals with additional per-type batching
- Add `derive.staking.waitingInfo` (same as `electedInfo` for waiting validators)
- Adjust types & metadata for latest Substrate
- `@polkadot/util` 2.15
## 1.19.1 Jun 16, 2020
- Improve typing on `.entries()` queries (Thanks to https://github.com/monitz87)
- Align metadata and types with latest Substrate
- Update Polkadot types for current evolution of parachains
- Allow for type aliasing on events (aligning with calls & queries)
- `@polkadot/util` 2.14
## 1.18.1 Jun 8, 2020
- Expand docs on node-template types (Thanks to https://github.com/g2udevelopment)
- Update contract fees to current impl. (Thanks to https://github.com/djuanit0x)
- Allow `Option` types in enum/Result type generation (Thanks to http://github.com/xlc)
- Add `.entriesPaged` and `.keysPaged` methods for state maps (https://github.com/monitz87)
- Add types for new Substrate proxy module
- Adjust types for new Substrate (renamed) npos-elections module
- `Call` now exposes `method` & `section` fields (aligned with `toHuman()` representation)
- Cater for new Substrate string subscription ids (with backwards compatibility)
- `@polkadot/util` 2.13
## 1.17.2 Jun 2, 2020
- Ensure subscription promise resolves before first result
## 1.17.1 Jun 2, 2020
- Fix `ElectionSize` type (Thanks to https://github.com/arjanz)
- Allow `BTreeSet` decoding from Array/JSON inputs
- Adjust Call-only metadata output to trim documentation to first full line
- Safeguard against divide-by-zero for total era points (expired reward eras)
- Internal derive optimizations with combining calls
- Support for latest Substrate types & metadata
- `@polkadot/util` 2.12
## 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
- **Important** Substrate master has an updated `Weight` (to `u64`), on older chains apply `Weight: 'u32'` (This does affect event decoding if wrongly set)
- Allow user type augmentation to work with different versions of rxjs (Thanks to https://github.com/monitz87)
- Align augmented generation with camelCase (Thanks to https://github.com/monitz87)
- Fix bitfield endian encoding (Thanks to investigation by https://github.com/xlc)
- Add account flag derives via `accounts.flags(accountId)` (Thanks to https://github.com/kwingram25)
- Fix entries decoding for `Option<Number>` (& simplify, decoding correctly on rpc layer)
- Add `system.{localPeerId, localListenAddresses}` & `state.getReadProof` RPCs
- Ensure proper propagation of `api.runtimeVersion` (used for signing) after upgrade
- Field ordering fix for deprecated `Linkage` (used in linked maps)
- `derive.account.info` now returns all field enum types decoded (not only raw)
- Add banner with FAQ entries for node-template to aid with common issues
- `Digest` has been moved to definitions, removal of `GenericDigest` type
- Support `Fixed128` type
- Add `transactionVersion` to `RuntimeVersion` struct
- Enhance API support for non-subscription providers (skip subscription to runtimeVersion)
- Adjust types for Kusama 1057 (notably the new `StakingLedger`)
## 1.10.1 Apr 13, 2020
- **Important** Substrate master has updated staking, on older chains apply `StakingLedger: 'StakingLedgerTo240'`
- Add `rpc.system.chainType` to retrieve the chain type (Development. Local, Live & Custom)
@@ -11,7 +180,7 @@
- Internally all private/protected methods/variables are now `_` prefixed (Aligning with the `private/protected` indicators in the TS definitions)
- Update metadata/docs-from-metadata to the latest Substrate
# 1.9.1 Apr 1, 2020
## 1.9.1 Apr 1, 2020
- **Breaking change** (TypeScript with derives only) The return type names for `api.derive.*` have been adjusted for consistency, all starting with `Derive*` (previously a mixture of `Derived*` and `Derive*`)
- **Breaking change** (derives only) Additional cleanups of democracy proposal & referenda derives, including support for new Polkadot/Substrate vote retrievals
@@ -26,7 +195,7 @@
- Fix encoding for `Vec<u8>`-related types as part of constants
- Internal adjustment of interface type locations (no impact on imports via `@polkadot/types/interfaces`)
# 1.8.1 Mar 22, 2020
## 1.8.1 Mar 22, 2020
- **Breaking change** The format for any custom RPCs have been changed (alongside API-internal changes) to allow for better RPC management. If you are currently using custom RPCs (or planning to do so), look at the [updated documentation](https://polkadot.js.org/api/start/rpc.custom.html)
- **Breaking change** Alongside API RPC changes, the `@polkadot/jsonrpc` package has been removed. Since it was never documented and only used internally, this should not have adverse impacts. All RPC definitions itself has now been moved to the relevant modules inside `@polkadot/types/interfaces`
@@ -38,7 +207,7 @@
- Adjusted referendum derives to cater for bot new/old democracy. Derived `referendumInfo` now includes `status` field, not `info`
- Add `initWasm` flag to API options. When set to `false` does not init the WASM portion (leaving it to the user elsewhere)
# 1.7.1 Mar 17, 2020
## 1.7.1 Mar 17, 2020
- **Important** Current versions of Polkadot/Substrate have dropped support for linked maps on storage entries. If you are using these queries to retrieve all entries, for instance `staking.{nominators,validators}()` and using an upgraded chain, you need to swap to retrieving entries via `.entries()` or `.keys()` for the keys.
- Pull in support and types for latest Polkadot/Substrate
@@ -48,11 +217,11 @@
- Expanded `derive.staking.*` derives, including addition of `derive.staking.own*`
- Re-add fixed (with tests) checks for query args, previously disabled in 1.6.2
# 1.6.2 Mar 12, 2020
## 1.6.2 Mar 12, 2020
- Revert checks for query args, not working on `.at()` queries (proper fix in next version)
# 1.6.1 Mar 12, 2020
## 1.6.1 Mar 12, 2020
- **Breaking change** `api.rpc.state.queryStorage(...)` now fully decodes the `Vec<StorageChangeSet>` and returns a decoded `[Hash, Codec[]][]` when using this RPC.
- `StorageKey` now has an `.args` property, decoded from meta where `twox64_concat` or `blake128_concat` are used on maps
@@ -66,7 +235,7 @@
- Add runtime validation for map arguments to `api.query.*`
- TypeScript interfaces for linked maps now correctly generates as `[Type, Linkage<Next>]`
# 1.5.1 Mar 06, 2020
## 1.5.1 Mar 06, 2020
- **Important** Substrate master has updated staking, on older chains supply `StakingLedger: 'StakingLedgerTo223'`
- **Important** Substrate master has updated collective, on older chains supply `Votes: 'VotesTo230'`
@@ -86,11 +255,11 @@
- Add additional derives to `api.derive.staking` to handle lazy-payout retrievals
- Update `@polkadot/{util, util-crypto, keyring}` to 1.6.1 & `@polkadot/wasm` to 1.2.1
# 1.4.2 Feb 27, 2020
## 1.4.2 Feb 27, 2020
- Fix `api.tx(<extrinsic>): Submittable` decoration (non-working in 1.4.1, now with proper test)
# 1.4.1 Feb 26, 2020
## 1.4.1 Feb 26, 2020
- **Breaking change** (TypeScript only) The `*.d.ts` files now contain TypeScript 3.8 features (specifically `#private`), which is not usable in TS versions < 3.8
- **Breaking change** - `api.derive.staking.*` has updated result types and detects support for lazy payouts queries
@@ -116,7 +285,7 @@
- Cleanup augmentation and generation scripts for type definitions, aligning with api augmentation
- Bump to `@polkadot/{util, util-crypto, keyring}` 2.5.1
# 1.3.1 Feb 18, 2020
## 1.3.1 Feb 18, 2020
- Add `@types/bn.js` as a normal dependency, exposed in `*.d.ts` (Thanks to https://github.com/monitz87)
- Type generation scripts (including `polkadot-types-from-{chain,defs}`) has been moved to the `@polkadot/typegen` package
@@ -124,7 +293,7 @@
- Expose chain properties on registry (and use for API type formatting)
- Add `toHuman(isExtended?: boolean)` to all codec types, formatting into a human-readable structure
# 1.2.1 Feb 16, 2020
## 1.2.1 Feb 16, 2020
- **Important** Update RPC status codes (latest Substrate 2), with the `isInBlock` (`isFinalized` now indicates finality)
- Storage `.entries(arg?: any)` now has the correct argument type for DoubleMap (Thanks to https://github.com/monitz87)
@@ -142,7 +311,7 @@
- Cleanup `codec/Date` tests to make it run properly on all timezones
- Add explicit dependencies to all packages and move TypeScript `@types/*` to dev deps
# 1.1.1 Feb 06, 2020
## 1.1.1 Feb 06, 2020
- **Important** Chains without `balances.account` or `system.account` should supply `"BalanceLock": "BalanceLockTo212"` to their types to use the previous-generation `BalanceLock` (when querying locks)
- Add support for `balances.account` in all applicable derives (incl. `vesting` module)
@@ -156,7 +325,7 @@
- Adjust balances fees derivation with optional transfer and creation fees (removed in Substrate)
- Adjust enum `.toJSON()` to return type name as specified
# 1.0.1 Jan 30, 2020
## 1.0.1 Jan 30, 2020
- **Breaking change** Drop support for Substrate v1 chain in all derives
- Return unsub functions from provider .on emitters (Thanks to https://github.com/jak-pan)
@@ -175,7 +344,7 @@
- Remove support for un-deployed metadata
- Remove old known types for Substrate V1
# 0.100.1 Jan 13, 2020
## 0.100.1 Jan 13, 2020
- **Important** This will the the last API version with Substrate 1.x support. Although you will still be able to use subsequent versions with older chains, dependent libraries such as sr25519 may not be compatible.
- Add support for the Substrate identity module
@@ -186,7 +355,7 @@
- Add support for latest Polkadot/Substrate types
- Add `paymentInfo` to submittables to calculate fees
# 0.99.1 Dec 13, 2019
## 0.99.1 Dec 13, 2019
- **Breaking change** The `Data` and `U8a` type has been renamed and just replaced with the `Raw` type
- **Breaking change** The `api.derive.staking.info` has been split into 2 - `staking.query` for non-balance related information (more effective) and `staking.account` that enhances query for all the information previously found `.info`
@@ -195,7 +364,7 @@
- Add additional derives for both council & treasury
- Alignment with latest Polkadot/Substrate master branch types
# 0.98.1 Dec 04, 2019
## 0.98.1 Dec 04, 2019
- Make the TypeScript generation script mor re-usable (Thanks to https://github.com/xlc)
- Add `.entries()` for all map-types, returning storage keys and values
@@ -204,7 +373,7 @@
- Support for new Substrate democracy with preimages in derive
- Alignment of types with Substrate/Polkadot master branches
# 0.97.1 Nov 29, 2019
## 0.97.1 Nov 29, 2019
- **Breaking change** Add the passing on an explicit `Registry` to all calls to `createType` as well as all codec classes. If you are upgrading form an older version, use the [migration guide](UPGRADING.md) to walk through the changes required.
- **Breaking change** The metadata classes have been moved from `@polkadot/types` into `@polkadot/metadata`. If you explicitly create `Metadata` classes, you now would need to do so with the `import Metadata from '@polkadot/metadata';` This is a decorated class, where the previous metadata is now available on `Metadata.metadata`, alongside decorated `consts.*`', `tx.*` and `query.*`.
@@ -216,7 +385,7 @@
- Support for Metadata V9, which adjusts the hashing methods of storage entries
- Support for Metadata V10 (still un-released), which includes prefixed map support
# 0.96.1 Nov 09, 2019
## 0.96.1 Nov 09, 2019
- Updated types for latest Kusama
- Add `filterRecords` (in addition to `findRecord`) on submittable results
@@ -226,11 +395,11 @@
- Update council derives for the latest Substrate master support (with constants)
- Derive cleanups, including sharing of instances between the API and internal to derives
# 0.95.2 Oct 25, 2019
## 0.95.2 Oct 25, 2019
- Temporary removal of `account_nextIndex` use, will be re-added in a future release
# 0.95.1 Oct 25, 2019
## 0.95.1 Oct 25, 2019
- Support Extrinsic V4 with additional signature indicator (Latest Polkadot/Substrate/Kusama)
- Adjust subscription update checks to avoid duplicated data updates
@@ -240,7 +409,7 @@
- All latest Polkadot & Substrate types (as per master branches)
- **Breaking change** `Call.injectMethods` is moved to `Call.injectMetadata` to align with `Events` (This _should_ not be used externally, however mentioned as breaking here)
# 0.94.1 Oct 07, 2019
## 0.94.1 Oct 07, 2019
- Add handling of `Result<Ok, Error>` definitions
- Adjust API cloning now takes RPC filters from source into account
@@ -252,7 +421,7 @@
- Add documentation for custom extrinsic formats (advanced chains)
- Update to latest substrate master metadata
# 0.93.1 Sep 26, 2019
## 0.93.1 Sep 26, 2019
- Support for Kusama CC2
- In extrinsic submission, use `rpc.account.nextIndex` to retrieve the nonce when available
@@ -262,7 +431,7 @@
- Support recursive type registration (self-referencing via `Box`) in addition to better sanitation of user-defined-types
- Documentation and example updates (thanks mostly to contributions)
# 0.92.1 Sep 12, 2019
## 0.92.1 Sep 12, 2019
- The API now correctly sets the ss58 prefix as retrieved from the chain properties via `ss58Format`
- Bump to `@polkadot/util` 1.4.1, removing use of `ExtError`
@@ -270,7 +439,7 @@
- Support the latest Polkadot & Substrate master branches (incl. metadata updates)
- Getting started documentation has been made available
# 0.91.1 Sep 09, 2019
## 0.91.1 Sep 09, 2019
- This release was focussed on stability, with a number of cleanups and bug-fixes
- Adjustments for Substrate 1.x chain detection (with auto-types) and Substrate 2.x support has been extended with all latest types
@@ -284,7 +453,7 @@
- **Breaking change** `SignerPayload` is renamed to `SignerPayloadJSON`
- **Breaking change** `SignerPayloadJSON`, `SignerPayloadRawBase` and `SignerPayloadRaw` are all moved to `@polkadot/types`
# 0.90.1 Aug 24, 2019
## 0.90.1 Aug 24, 2019
If you are upgrading form an older version, use the CHANGELOG hand-in-hand with the [migration guide](UPGRADING.md).
@@ -302,7 +471,7 @@ If you are upgrading form an older version, use the CHANGELOG hand-in-hand with
- The `types/codec/createType` has been moved to `types/codec/create` with the same exports. If you explicitly imported from here (and not doing the suggested `import { createType } from '@polkadot/types`), the reference needs to be updated
# 0.82.0-beta.x Jul 28, 2019
## 0.82.0-beta.x Jul 28, 2019
- Support for substrate 2.x (master) has been extended,
- Additional types have been addedd for the modules
@@ -321,7 +490,7 @@ If you are upgrading form an older version, use the CHANGELOG hand-in-hand with
- The `ContractsAbi` type has been moved from `@polkadot/types` to `import { Abi } from '@polkadot/api-contract`. This paves the way for an enhanced contracts interface, instead of dealing with low-level API calls.
# 0.81.1 Jun 14, 2019
## 0.81.1 Jun 14, 2019
- The dependency on `@polkadot/keyring` has been removed - if you relied on the API to provide this, you would now need to manually add it
- `createType` allows for the creation of `[u8; <length>]` types (opening the door for contract support)
@@ -341,7 +510,7 @@ If you are upgrading form an older version, use the CHANGELOG hand-in-hand with
- Add `off` method to `Api` (Base, for both `ApiPromise` & `ApiRx`) to remove an event listener
# 0.80.1 Jun 04, 2019
## 0.80.1 Jun 04, 2019
- Support for mortal transactions
- Better DoubleMap storage support
@@ -351,7 +520,7 @@ If you are upgrading form an older version, use the CHANGELOG hand-in-hand with
- Misc. cleanups and fixes
# 0.79.1 May 22, 2019
## 0.79.1 May 22, 2019
- DoubleMap query support
- Support latest EventRecord metadata (substrate master)
@@ -363,7 +532,7 @@ If you are upgrading form an older version, use the CHANGELOG hand-in-hand with
- Add `toRawType` on all type classes (breakdown into primitive types)
# 0.78.1 May 08, 2019
## 0.78.1 May 08, 2019
- Fix linked-maps (not working since 0.77.1)
- Convert Usize to U32 (as found in WASM environments)
@@ -374,13 +543,13 @@ If you are upgrading form an older version, use the CHANGELOG hand-in-hand with
- Metadata updates for substrate (WithdrawReasons, ContractInfo)
# 0.77.1 Apr 25, 2019
## 0.77.1 Apr 25, 2019
- Support Metadata v4, which introduces the use of a custom hasher to hash storage map keys.
- Add TreasuryProposal (not the same as democracy, type aliased)
# 0.76.1 Apr 03, 2019
## 0.76.1 Apr 03, 2019
- Caching improvements (duplicate queries, no duplicate subscriptions)
- Experimental contract API
@@ -388,12 +557,12 @@ If you are upgrading form an older version, use the CHANGELOG hand-in-hand with
- Update @polkadot/util-crypto with smaller footprint
# 0.75.1 Mar 29, 2019
## 0.75.1 Mar 29, 2019
- Start journey to 1.0
# 0.53.1 Mar 29, 2019
## 0.53.1 Mar 29, 2019
- Change spelling to US English as per substrate master (1.0-rc1). Breaking changes as a result:
- For extrinsic status results, if you have checked the type returns, i.e. `result.type === 'Finalised'` now check on the status for `result.status.isFinalized` or `result.status.isBroadcast`, ... (the `type` property is now accessible only on `result.status.type`)
@@ -404,7 +573,7 @@ If you are upgrading form an older version, use the CHANGELOG hand-in-hand with
- All examples have been updated with sr25519 addresses (with the new checksums)
# 0.52.1 Mar 28, 2019
## 0.52.1 Mar 28, 2019
- Support queries to linked mapped storage (found in new staking interfaces)
- Add `derive.staking.controllers` to retrieve all active staking controllers
@@ -414,42 +583,42 @@ If you are upgrading form an older version, use the CHANGELOG hand-in-hand with
- Check for single instances for api and types as they are loaded (assertSingletonPackage)
# 0.51.1 Mar 25, 2019
## 0.51.1 Mar 25, 2019
- Support metadata V2 as per latest substrate master
- Update metadata with new types as per latest substrate master
# 0.50.1 Mar 23, 2019
## 0.50.1 Mar 23, 2019
- Latest util-crypto (usage of WASM with JS fallbacks if not available)
- Update upstream @polkadot dependencies (for new crypto)
# 0.49.1 Mar 20, 2019
## 0.49.1 Mar 20, 2019
- Fix large message signing on non-known nodes (default is now hashing, there has been enough time between upgrades)
# 0.48.1 Mar 18, 2019
## 0.48.1 Mar 18, 2019
- Pull in new sr25519 capable keyring for dev nodes
- When using dev mode, it assumes that the node is the latest with derived sr25519 keys
# 0.47.1 Mar 14, 2019
## 0.47.1 Mar 14, 2019
- Swap to publishing -beta.x on merge (non-breaking testing)
# 0.46.1 Mar 01, 2019
## 0.46.1 Mar 01, 2019
- Extended type registration to now handle internal types as well. Additionally the built-in Extrinsic type can now we overridden with a custom version.
- Where `Extrinsic` and `Method` is used as types, consider importing `{ IMethod, IExtrinsic }` from `@polkadot/types/types`, especially in the cases where this is used from a `SubmittableExtrinsic`
- The `typeRegistry` constant is now `getTypeRegistry()` as a function
# 0.45.1 Feb 19, 2019
## 0.45.1 Feb 19, 2019
- Storage with option values now correctly return `Option<Type>` and is indicated as such in the documentation
@@ -466,7 +635,7 @@ console.log('llo', llo.unwrapOr('not set') /* Option<BlockNumber> */)
```
# 0.44.1 Feb 19, 2019
## 0.44.1 Feb 19, 2019
- Split primitives and types into separate folders. This should not affect external use since the exports remain the same, however does have an impact where classes are referenced directly. e.g.
@@ -484,45 +653,45 @@ import { Method, Signature } from '@polkadot/types';
```
# 0.43.1 Feb 14, 2019
## 0.43.1 Feb 14, 2019
- Introduces support for the new keyring with sr25519 support in addition to ed25519. While this does not change the exposed API, it is considered breaking since @polkadot/keyring has interface changes. (Unless needed, don't rush the upgrade)
# 0.42.1 Jan 31, 2019
## 0.42.1 Jan 31, 2019
- Support for substrate hash signing with implVersion >= 18
- Changed signatures for Extrinsic signing, this should not have (much) of an impact since it is generally not used directly. SubmittableExtrinsic (as exposed by the API), supports the old-style use.
# 0.41.1 Jan 26, 2019
## 0.41.1 Jan 26, 2019
- Support the V1 metadata specification from Substrate in addition to the currently testnet active V0 version
# 0.40.1 Jan 16, 2019
## 0.40.1 Jan 16, 2019
- The API interfaces now require a WS-compatible provider, e.g. subscription support is a must. Previously the HTTPProvider could be use (although it was very limited in the interactions).
# 0.39.1 Jan 11, 2019
## 0.39.1 Jan 11, 2019
- The Promise API now returns a `Promise<UnsubFunction>` instead of `UnsubFunction` when making subscriptions.
# 0.38.1 Jan 08, 2019
## 0.38.1 Jan 08, 2019
Substrate has been updated with a breaking new transaction format where the Index/Nonce is now encoded as a Compact. This change is being rolled out to both Alexander (Polkadot testnet) as well as Charred Cherry (Substrate testnet) - transactions between old and new are not compatible.
# 0.37.1 Jan 04, 2019
## 0.37.1 Jan 04, 2019
api-observable has been removed. This was only used in /apps and inconsistent with the api/rx and api/promise APIs. Future work will include derives like was included in api-observable into the base.
Tuples now return single types when only one type is available, i.e. `(AccountId)` would now resolve as `AccountId`. The extra type wrapper adds no benefit to users here.
# 0.36.1 Jan 03, 2019
## 0.36.1 Jan 03, 2019
Api Promise has been updated in the way we deal with subscriptions. Previously a subscription returned `Promise<number>` where the caller was to keep track of the id and use it in subsequent unsubscribes. Now any subscriptions return an unsubscribe/destroy function `(): void`, that is use for removing the subscriptions, e.g.
@@ -533,51 +702,51 @@ unsubscribe(); // here we destroy the subscription
```
# 0.35.1 Dec 20, 2018
## 0.35.1 Dec 20, 2018
Swapped to new metadata structures from Substrate. If the API is not working with your node, update Substrate to latest master branch. (Or 0.9.1 for Charred Cherry). Dropped support for old metadata as found as far back as BBQ Birch.
# 0.34.1 Dec 18, 2018
## 0.34.1 Dec 18, 2018
Changed the send signature (for future expansion of eg. events) to return `result: { status: ExtrinsicStatus }` instead of `status: ExtrinsicStatus`. For most cases where only status `type` checks are used, i.e. `status.type === 'Finalised'` this should not be a breaking change. Deep inspection of the status object however will need to adapt.
# 0.33.1 Dec 06, 2018
## 0.33.1 Dec 06, 2018
# 0.32.1 Nov 21, 2018
## 0.32.1 Nov 21, 2018
# 0.31.1 Oct 10, 2018
## 0.31.1 Oct 10, 2018
# 0.30.1 Sep 27, 2018
## 0.30.1 Sep 27, 2018
# 0.29.1 Sep 14, 2018
## 0.29.1 Sep 14, 2018
# 0.28.1 Aug 11, 2018
## 0.28.1 Aug 11, 2018
# 0.15.1 Aug 07, 2018
## 0.15.1 Aug 07, 2018
# 0.14.1 Jun 23, 2018
## 0.14.1 Jun 23, 2018
# 0.13.1 May 29, 2018
## 0.13.1 May 29, 2018
# 0.12.1 May 18, 2018
## 0.12.1 May 18, 2018
# 0.11.1 May 16, 2018
## 0.11.1 May 16, 2018
# 0.10.1 May 07, 2018
## 0.10.1 May 07, 2018
# 0.9.1 Apr 24, 2018
## 0.9.1 Apr 24, 2018
# 0.8.1 Mar 15, 2018
## 0.8.1 Mar 15, 2018
# 0.7.1 Jan 25, 2018
## 0.7.1 Jan 25, 2018
# 0.6.1 Dec 03, 2017
## 0.6.1 Dec 03, 2017
# 0.5.1 Nov 28, 2017
## 0.5.1 Nov 28, 2017
# 0.4.1 Nov 19, 2017
## 0.4.1 Nov 19, 2017
# 0.3.1 Nov 19, 2017
## 0.3.1 Nov 19, 2017
# 0.2.1 Nov 18, 2017
## 0.2.1 Nov 18, 2017
+1 -1
View File
@@ -7,7 +7,7 @@
# @polkadot/api
This library provides a clean wrapper around all the methods exposed by a Polkadot/Subtrate network client and defines all the types exposed by a node. For complete documentation around the classes, interfaces and their use, visit the [documentation portal](https://polkadot.js.org/api/).
This library provides a clean wrapper around all the methods exposed by a Polkadot/Substrate network client and defines all the types exposed by a node. For complete documentation around the classes, interfaces and their use, visit the [documentation portal](https://polkadot.js.org/api/).
If you are an existing user, please be sure to track the [CHANGELOG](CHANGELOG.md) and [UPGRADING](UPGRADING.md) guides when changing versions.
+1
View File
@@ -19,4 +19,5 @@ copy_folder "metadata"
copy_folder "rpc-core"
copy_folder "rpc-provider"
copy_folder "types"
copy_folder "types-known"
copy_folder "typegen"
+19 -2
View File
@@ -20,7 +20,8 @@ module.exports = {
},
{ text: 'GitHub', link: 'https://github.com/polkadot-js/api' }
],
search: false,
search: true,
searchMaxSuggestions: 10,
sidebar: [
{
title: 'Getting started',
@@ -50,6 +51,17 @@ module.exports = {
['start/FAQ.md', 'FAQ']
]
},
{
title: 'Cookbook',
path: '/cookbook/',
collapsable: false,
sidebarDepth: 0,
children: [
['cookbook/blocks.md', 'Blocks'],
['cookbook/storage.md', 'Storage'],
['cookbook/tx.md', 'Transactions']
]
},
{
title: 'Examples (Promise API)',
path: '/examples/promise/',
@@ -86,5 +98,10 @@ module.exports = {
['/types/', '@polkadot/types'],
'/CONTRIBUTING.md'
]
}
},
plugins: [
['@vuepress/search', {
searchMaxSuggestions: 10
}]
]
};
+3
View File
@@ -1,5 +1,8 @@
$accentColor = #fd8824
$textColor = #2c3e50
$borderColor = #eaecef
$codeBgColor = #282c34
$arrowBgColor = #ccc
.home .hero .description,
.home .feature h2,
+2 -9
View File
@@ -13,7 +13,7 @@ features:
- title: Types
details: Various type interfaces to make using returned values from API calls transparent in your code.
footer: Apache-2 Licensed | Copyright © 2017-2019 polkadot-js authors and contributors
footer: Apache-2 Licensed | Copyright © 2017-2020 polkadot-js authors and contributors
---
## Welcome
@@ -21,16 +21,9 @@ footer: Apache-2 Licensed | Copyright © 2017-2019 polkadot-js authors and contr
The API provides application developers the ability to query a node and interact with the Polkadot or Substrate chains using Javascript. Here you will find documentation and examples to get you started.
::: tip Getting started & Examples
[Jump right in](/start/) and get an overview on using the API in your projects, from installation all the way through to making it do magic. Already understand how things work and just want the examples? [The ApiPromise examples](/examples/promise/) provide some basic recipies.
[Jump right in](/start/) and get an overview on using the API in your projects, from installation all the way through to making it do magic. Have things working and want tips? The [cookbook](/cookbook/) provides some tips and tricks. Getting started and want some full examples? [The ApiPromise examples](/examples/promise/) provide some basic examples.
:::
## Available packages
This repository split up into a number of internal packages, namely -
- [api](api/README.md) Promise and RxJS-based APIs
- [types](types/README.md) Type encoding and decoding wrappers
## The Polkadot Project
You can read more about the Polkadot Network at [https://polkadot.network/](https://polkadot.network/) and more about the polkadot-js projects at [https://polkadot.js.org](https://polkadot.js.org)
+19
View File
@@ -0,0 +1,19 @@
# Cookbook
The cookbook hosts small code snippets in a question-answer format. It does not walk you through the whole setup, like the [basic examples](../examples/), but rather aims to answer some questions around specific uses. It also does not replace the [getting started FAQ](../start/FAQ.md), rather this is focussed explicitly on code samples, instead of general trouble-shooting for common mishaps.
These questions are added as they do come up and the hope is that the snippets here is will be useful to others, instead of just the original person who asked on a specific use-case. As of today, it is only making a start and not fully comprehensive yet - check back early, check back often.
## Sections
The following cookbook sections are available -
- [Blocks](blocks.md) - Snippets around working with blocks and headers
- [Storage](storage.md) - Snippets for working with storage
- [Transactions](tx.md) - Snippets for working with transactions
... more to come.
## Contribute
And as always, if you have an addition to make, or a question to ask any [any PRs](https://github.com/polkadot-js/api/tree/master/docs) or [issues](https://github.com/polkadot-js/api/issues) are appreciated. The initial content was generate from exactly such questions, either in Riot chat or as submitted as issues.
+44
View File
@@ -0,0 +1,44 @@
# Blocks
The building blocks for each blockchain. As such there are a number of examples for working with blocks and headers, that could be useful.
## How do I retrieve the header/extrinsic hash from blocks?
A block hash refers to the hash over the header, the extrinsic hash refers to the hash of the encoded extrinsic. Since all objects returned by the API implements the `.hash => Hash` getter, we can simply use this to view the actual hash.
```js
// returns Hash
const blockHash = await this.api.rpc.chain.getBlockHash(blockNumber);
// returns SignedBlock
const signedBlock = await this.api.rpc.chain.getBlock(blockHash);
// the hash for the block, always via header (Hash -> toHex()) - will be
// the same as blockHash above (also available on any header retrieved,
// subscription or once-off)
console.log(signedBlock.header.hash.toHex());
// the hash for each extrinsic in the block
signedBlock.block.extrinsics.forEach((ex, index) => {
console.log(index, ex.hash.toHex());
});
```
## How do I extract the block author?
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
// subscribe to all new headers (with extended info)
api.derive.chain.subscribeNewHeads((header) => {
console.log(`#${header.number}: ${header.author}`);
});
```
For a single header only, the derives also contain a `getHeader`, which once again returns a header extended with the author -
```js
// retrieve the last header (hash optional)
const header = await api.derive.chain.getHeader();
console.log(`#${header.number}: ${header.author}`);
```
+55
View File
@@ -0,0 +1,55 @@
# Storage
Here you will find snippets for working with storage.
## How do I check for storage existence?
In the metadata, for each storage item a fallback is provided. This means that when an entry does not exist, the fallback (which is the default value for the type) will be provided. This means, that querying for a non-existent key (unless an option), will yield a value -
```js
// retrieve Option<StakingLedger>
const ledger = await api.query.staking.ledger('EoukLS2Rzh6dZvMQSkqFy4zGvqeo14ron28Ue3yopVc8e3Q');
// retrieve ValidatorPrefs (will yield the default value)
const prefs = await api.query.staking.validators('EoukLS2Rzh6dZvMQSkqFy4zGvqeo14ron28Ue3yopVc8e3Q');
console.log(ledger.isNone, ledger.isSome); // true, false
console.log(JSON.stringify(prefs.toHuman())); // {"commission":"0"}
```
In the second case, the non-existent prefs returns the default/fallback value for the storage item. So in this case we don't know if the value is set to 0 or unset. Existence can be checked by using the storage size, which would be zero if nothing is stored.
```js
// exists
const sizeY = await api.query.staking.validators.size('DB2mp5nNhbFN86J9hxoAog8JALMhDXgwvWMxrRMLNUFMEY4');
// non existent
const sizeN = await api.query.staking.validators.size('EoukLS2Rzh6dZvMQSkqFy4zGvqeo14ron28Ue3yopVc8e3Q');
console.log(sizeY.isZero(), sizeY.toNumber()); // false 4
console.log(sizeN.isZero(), sizeY.toNumber()); // true 0
```
## How do I use .entries()/.keys() on double maps?
As [explained elsewhere](../start/api.query.other.md#map-keys-entries) each map-type storage entry exposes the entries/keys helpers to retrieve the whole list. In the case of double maps, with the addition of a single argument, you can retrieve either all entries or a subset based on the first map key.
In both these cases, entries/keys operate the same way, `.entries()` retrieving `(StorageKey, Codec)[]` and `.keys()` retrieving `StorageKey[]`
```js
// Retrieves the entries for all slashes, in all eras (no arg)
const allEntries = await api.query.staking.nominatorSlashInEra.entries();
// nominatorSlashInEra(EraIndex, AccountId) for the types of the key args
allEntries.forEach(([{ args: [era, nominatorId] }, value]) => {
console.log(`${era}: ${nominatorId} slashed ${value.toHuman()}`);
});
```
While we can retrieve only the keys for a specific era, using a argument for the first part of the doublemap (as defined here, an `EraIndex`) -
```js
// Retrieves the keys for the slashed validators in era 652
const slashedKeys = await api.query.staking.nominatorSlashInEra.keys(652);
// key args still contains [EraIndex, AccountId] decoded
console.log(`slashed: ${slashedKeys.map(({ args: [era, nominatorId] }) => nominatorId)`);
```
+112
View File
@@ -0,0 +1,112 @@
# Transactions
A blockchain is no fun if you are not submitting transactions. Or at least if somebody is not submitting any. Here you will find some snippets for dealing with some common issues.
## How do I estimate the transaction fees?
In addition to the `signAndSend` helper on transactions, `.paymentInfo` (with the exact same parameters) are also exposed. Using the same sender, it applies a dummy signature to the transaction and then gets the fee estimation via RPC.
```js
// estimate the fees as RuntimeDispatchInfo, using the signer (either
// address or locked/unlocked keypair) (When overrides are applied, e.g
// nonce, the format would be `paymentInfo(sender, { nonce })`)
const info = await api.tx.balances
.transfer(recipient, 123)
.paymentInfo(sender);
// log relevant info, partialFee is Balance, estimated for current
console.log(`
class=${class.toString()},
weight=${weight.toString()},
partialFee=${partialFee.toHuman()}
`);
```
## How do I get the decoded enum for an ExtrinsicFailed event?
Assuming you are sending a tx via `.signAndSend`, the callback yields information around the tx pool status as well as any events when `isInBlock` or `isFinalized`. If an extrinsic fails via `system.ExtrinsicFailed` event, you can retrieve the error, if defined as an enum on a module.
```js
api.tx.balances
.transfer(recipient, 123)
.signAndSend(sender, ({ status, events }) => {
if (status.isInBlock || status.isFinalized) {
events
// find/filter for failed events
.filter(({ section, method }) =>
section === 'system' &&
method === 'ExtrinsicFailed'
)
// we know that data for system.ExtrinsicFailed is
// (DispatchError, DispatchInfo)
.forEach(({ data: [error, info] }) => {
if (error.isModule) {
// for module errors, we have the section indexed, lookup
const decoded = api.registry.findMetaError(error.asModule);
const { documentation, method, section } = decoded;
console.log(`${section}.${method}: ${documentation.join(' ')}`);
} else {
// Other, CannotLookup, BadOrigin, no extra info
console.log(error.toString());
}
});
}
});
```
## How do I send an unsigned extrinsic?
For most runtime modules, transactions need to be signed and validation for this happens node-side. There are however modules that accepts unsigned extrinsics, an example would be the Polkadot/Kusama token claims (which is here used as an example).
```js
// construct the transaction, exactly as per normal
const utx = api.tx.claims.claim(beneficiary, ethSignature);
// send it without calling sign, pass callback with status/events
tx.send(({ status }) => {
if (status.isInBlock) {
console.log(`included in ${status.asInBlock}`);
}
});
```
The signing is indicated by the first byte in the transaction, so in this case we have called `.send` on it (no `.sign` or `.signAndSend`), so it will be sent using the unsigned state, without signature attached.
## How can I batch transactions?
Polkadot/Substrate provides a `utility.batch` method that can be used to send a number of transactions at once. These are then executed from a single sender (single nonce specified) in sequence. This is very useful in a number of cases, for instance if you wish to create a payout for a validator for multiple eras, you can use this method. Likewise, you can send a number of transfers at once. Or even batch different types of transactions.
```js
// construct a list of transactions we want to batch
const txs = [
api.tx.balances.transfer(addrBob, 12345),
api.tx.balances.transfer(addrEve, 12345),
api.tx.staking.unbond(12345)
];
// construct the batch and send the transactions
api.tx.utility
.batch(txs)
.signAndSend(sender, ({ status }) => {
if (status.isInBlock) {
console.log(`included in ${status.asInBlock}`);
}
});
```
## How do I take the pending tx pool into account in my nonce?
The `system.account` query will always contain the current state, i.e. it will reflect the nonce for the last known block. As such when sending multiple transactions in quick succession (see batching above), there may be transactions in the pool that has the same nonce that `signAndSend` would apply - this call doesn't do any magic, it simply reads the state for the nonce. Since we can specify options to the `signandSend` operation, we can override the nonce, either by manually incrementing it o querying it via `nextNonce`.
```js
for (let i = 0; i < 10; i++) {
// retrieve the nextNonce, taking txs in the pool into account
const nonce = await api.rpc.account.nextNonce(sender);
// send, just retrieving the hash, not waiting on status
const txhash = await api.tx.balances
.transfer(recipient, 123)
.signAndSend(sender, { nonce });
}
```
@@ -1,6 +1,7 @@
/* eslint-disable header/header */
/* eslint-disable @typescript-eslint/require-await */
/* eslint-disable @typescript-eslint/unbound-method */
/* eslint-disable @typescript-eslint/no-floating-promises */
// Import the API
const { ApiPromise } = require('@polkadot/api');
@@ -1,6 +1,7 @@
/* eslint-disable header/header */
/* eslint-disable @typescript-eslint/require-await */
/* eslint-disable @typescript-eslint/unbound-method */
/* eslint-disable @typescript-eslint/no-floating-promises */
// Import the API
const { ApiPromise } = require('@polkadot/api');
@@ -1,6 +1,7 @@
/* eslint-disable header/header */
/* eslint-disable @typescript-eslint/require-await */
/* eslint-disable @typescript-eslint/unbound-method */
/* eslint-disable @typescript-eslint/no-floating-promises */
// Import the API
const { ApiPromise } = require('@polkadot/api');
@@ -1,6 +1,7 @@
/* eslint-disable header/header */
/* eslint-disable @typescript-eslint/require-await */
/* eslint-disable @typescript-eslint/no-var-requires */
/* eslint-disable @typescript-eslint/no-floating-promises */
// Import the API & Provider and some utility functions
const { ApiPromise } = require('@polkadot/api');
@@ -1,6 +1,7 @@
/* eslint-disable header/header */
/* eslint-disable @typescript-eslint/require-await */
/* eslint-disable @typescript-eslint/unbound-method */
/* eslint-disable @typescript-eslint/no-floating-promises */
// Import the API & Provider and some utility functions
const { ApiPromise, WsProvider } = require('@polkadot/api');
+22
View File
@@ -20,6 +20,9 @@ All data transferred between the API and the Node is in a SCALE-encoded binary f
To fix this, you should look at the specific `api.tx.*` params and adjust the type definitions for those param types to match what is found on the node side. In some rare cases the cause could be extrinsic formatting related, to track these make an `api.tx.system.remark(data: Bytes)` call, if it fails, the API and node cannot agree on [an extrinsic format and adjustments are required](types.extend.md#impact-on-extrinsics).
If you are using a node-template based version of substrate and you changed the specName you need to add these typings(In addition to other custom types) `{"Address": "AccountId","LookupSource": "AccountId"}`. This is also the case when you use [polkadot-js/apps](https://github.com/polkadot-js/apps) to connect to your node. When the specName stays node-template the API is smart enough to add the custom typings.
## I would like to sign transactions offline
The API itself is independent on where the signature comes from and how it is injected. Additionally it implements a signer interface, that can be used for external signing - an example of this is the [polkadot-js/apps](https://github.com/polkadot-js/apps) support for signing via extensions and even the [polkadot-js/extension](https://github.com/polkadot-js/extension) support for tools such as the [Parity Signer](https://github.com/paritytech/parity-signer).
@@ -57,3 +60,22 @@ The API always injects the default type definitions as specified by the Substrat
The Substrate node-template has added customizations for some types in the default template, specifically around the `Address` and `Lookup` types, removing any lookups based on indices. This means that the transaction payload saves 2 bytes for a transfer and is an approach followed by other chains as well, notably Polkadot & Kusama.
Due to these customizations and differences that bleed through to the transaction formats, out-of-the-box chains based on the node-template will have issues when sending transactions. To fix this, you would need to add [the customized Address types into your API](types.extend.md#impact-on-extrinsics) instances (or UIs), allowing the API to have the information required to adjust the encoding.
## Using a non-current-master node, I have issues parsing events
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.
## 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
@@ -23,7 +23,7 @@ A couple of items to note in the example above: we don't call `account` directly
...
// Retrieve a snapshot of the validators
const validators = await api.query.session.validators();
const validatorKeys = await api.query.session.validators.keys();
// Subscribe to the balances for these accounts
const unsub = await api.query.balances.account.multi(validators, (balances) => {
+10 -5
View File
@@ -71,18 +71,23 @@ exposures.forEach(([key, exposure]) => {
});
```
Here we are querying a double-map, so we supply 1 argument. No arguments on double-maps will be very costly, retrieving all the eras and associated entries. Additionally when `twox64_concat` & `blake2_concat` is used, the key `.args` will contain decoded values of the params, in this case it will contain the actual `AccountId` of the staker. (Since that was not supplied)
To understand the usage of the `key.args`, you need to understand that map/doublemap keys are stored alongside their lookups. This means that the raw key has hashed parts as well as the raw data. The API will decode the keys and provide the raw key arguments in args. This would mean -
In the same way as above we can simply do `.keys(activeEra.index): StorageKey[]` to retrieve all the keys here, including the individual keys args (available on maps with decodable hashing functions) -
- if we are querying `api.query.staking.validators(validatorId: AccountId)` via `entries`, the `key.args` would be `[AccountId]`
- if we are querying `api.query.staking.erasStakers(era: EraIndex, validatorId: AccountId)` via `entries`, the `key.args` would be `[EraIndex, AccountId]`
the same applies to `.keys()` - here the list of keys also have the decoded args, as specified. You can think of `.args` as a tuple with the same types as the types required to retrieve a single entry in the map.
In the first example we are querying a double-map, so we supply 1 argument. No arguments on double-maps will be very costly, retrieving all the eras and associated entries. In the same way as above we can simply do `.keys(activeEra.index): StorageKey[]` to retrieve all the keys here, including the individual keys args (available on maps with decodable hashing functions) -
```js
// retrieve all the nominator keys
const keys = await api.query.staking.nominators.keys();
// extract the first key argument (AccountId) as string
const nominatorIds = keys.map((key) => key.args[0].toString());
// extract the first key argument [AccountId] as string
const nominatorIds = keys.map(({ args: [nominatorId] }) => nominatorId);
console.log('all nominators:', nminatorIds.join(', '));
console.log('all nominators:', nominatorIds.join(', '));
```
## State entries
+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
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}`);
});
```
+17 -5
View File
@@ -1,6 +1,6 @@
# 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
@@ -17,16 +17,28 @@ const api = await ApiPromise.create({
{
name: 'index',
type: 'u64'
},
{
name: 'at',
type: 'Hash',
isOptional: true
}
],
type: 'Balance'
}
}
}
},
anotherMethod: { ... },
...
},
anotherModule: { ... },
...
},
...
});
```
In the above example we have defined a new method, which is now available on the RPCs as `api.rpc.firstModule.testMethod(u64) => Promise<Balance>`. Do be aware that while defined, the method will only appear if it is in the list as returned by `api.rpc.rpc.methods()`, which is the list of known RPCs the node exposes. When making changes to the node, always ensure that it does expose the RPC method correctly, otherwise it will not be decorated.
In the above example we have defined a new method, which is now available on the RPCs as `api.rpc.firstModule.testMethod(index: u64, at?: Hash) => Promise<Balance>`. In the case of optional params, we have added the `isOptional: true` flag alongside the `name` & `type` in the param definition.
Be aware that while defined, the method will only appear on the API if it is in the list as returned by `api.rpc.rpc.methods()`, which is the list of known RPCs the node exposes. When making changes to the node, always ensure that it does expose the RPC method correctly, otherwise it will not be decorated.
## Definition breakdown
+9
View File
@@ -26,6 +26,15 @@ const api = await ApiPromise.create({
The above introduces the `types` registry, effectively allowing overrides and the definition of new types. The override above would mean that immediately the API will treat all occurrences of `Balance` not as the default, but rather as the defined size.
## Field ordering
When defining any custom structures or types, it is critical that the following rules are applied -
- Map exactly to what is defined in the Rust code, i.e. defining a `SaleType` cannot be `u16` on the one end and `u32` on the other end. If mismatches occur, the serialization will fail.
- Ensure that the field order is maintained in all definitions. The SCALE serialization is binary and contains no field names in the serialization, only the encoded values. Any decoding is therefore done based on the size of the type and the order thereof in the definitions.
These rules apply everywhere. Always ensure that the types match exactly between the environments and that the ordering is maintained, be it for structs, tuples or enums.
## User-defined structs
Registration also applies to any type that can be found on a specific chain, i.e. we can add any types that is available on a specific node -
+1 -1
View File
@@ -4,7 +4,7 @@ In the previous section we looked at the TypeScript definitions that are availab
## Definitions
A large part of the type definitions are defined not as classes, but rather as structures from which type definitions are extracted and that can be used as-is to let the API know how to decode a type. By now you should be familiar with [type extensions](types.extend.md), but effectively the [types library does exactly the same](https://github.com/polkadot-js/api/tree/master/packages/types/src/interfaces).
A large part of the type definitions are defined not as classes, but rather as structures from which type definitions are extracted and that can be used as-is to let the API know how to decode a type. By now you should be familiar with [type extensions](types.extend.md) and the [rules around fields](types.extend.md#field-ordering), but effectively the [types library does exactly the same](https://github.com/polkadot-js/api/tree/master/packages/types/src/interfaces).
To create TypeScript-aware definitions and keep your files in a single place, you can follow the same approach. Assuming you have a package named `@MeInc/stuff` where you have the definitions in an `stuff/interfaces` folder. Each sub-folder would indicate a runtime module, e.g.
+1 -1
View File
@@ -9,5 +9,5 @@
"packages": [
"packages/*"
],
"version": "1.10.1"
"version": "1.24.1"
}
+11 -9
View File
@@ -7,7 +7,7 @@
"packages/*"
],
"resolutions": {
"typescript": "^3.8.3"
"babel-core": "^7.0.0-bridge.0"
},
"scripts": {
"build": "yarn build:interfaces && polkadot-dev-build-ts && (cd packages/typegen && copyfiles scripts/* build)",
@@ -24,13 +24,15 @@
"test:watch": "polkadot-dev-run-test --watch"
},
"devDependencies": {
"@babel/core": "^7.9.0",
"@babel/register": "^7.9.0",
"@babel/runtime": "^7.9.2",
"@polkadot/dev": "^0.52.9",
"@polkadot/ts": "^0.3.18",
"@babel/core": "^7.10.4",
"@babel/register": "^7.10.4",
"@babel/runtime": "^7.10.4",
"@polkadot/dev": "^0.55.21",
"@polkadot/ts": "^0.3.27",
"@polkadot/typegen": "workspace:packages/typegen",
"@types/jest": "^25.2.1",
"copyfiles": "^2.2.0"
}
"@types/jest": "^26.0.4",
"@vuepress/plugin-search": "^1.5.2",
"copyfiles": "^2.3.0"
},
"version": "1.24.1"
}
+8 -8
View File
@@ -1,6 +1,6 @@
{
"name": "@polkadot/api-contract",
"version": "1.10.1",
"version": "1.24.1",
"description": "Interfaces for interacting with contracts and contract ABIs",
"main": "index.js",
"keywords": [
@@ -26,12 +26,12 @@
},
"homepage": "https://github.com/polkadot-js/api/tree/master/packages/api-contract#readme",
"dependencies": {
"@babel/runtime": "^7.9.2",
"@polkadot/api": "1.10.1",
"@polkadot/rpc-core": "1.10.1",
"@polkadot/types": "1.10.1",
"@polkadot/util": "^2.8.1",
"bn.js": "^5.1.1",
"rxjs": "^6.5.5"
"@babel/runtime": "^7.10.4",
"@polkadot/api": "1.24.1",
"@polkadot/rpc-core": "1.24.1",
"@polkadot/types": "1.24.1",
"@polkadot/util": "^2.18.1",
"bn.js": "^5.1.2",
"rxjs": "^6.6.0"
}
}
@@ -19,7 +19,7 @@ function parseSelector (registry: Registry, fnname: string, input: ContractABIMe
return registry.createType('u32', hexToU8a(input));
} else if (typeof input === 'string') {
try {
const array = JSON.parse(input);
const array = JSON.parse(input) as unknown[];
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 {
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 {
name: stringCamelCase(name),
@@ -183,6 +183,7 @@ export default class ContractRegistry extends MetaRegistry {
public convertMessage ({ args, name, return_type: returnType, ...message }: ContractABIMessagePre): ContractABIMessage {
return {
...message,
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
args: this.convertArgs(args),
name: this._stringAt(name),
returnType: returnType ? this.convertType(returnType) : null
@@ -191,6 +192,7 @@ export default class ContractRegistry extends MetaRegistry {
public convertEvent ({ args }: ContractABIEventPre): ContractABIEvent {
return {
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
args: this.convertArgs(args)
};
}
+20 -20
View File
@@ -7,11 +7,11 @@ import { MetaRegistryItem, MetaRegistryJson, MetaTypeDefClikeEnum, MetaType, Met
import { assert } from '@polkadot/util';
import { displayType, withTypeString } from '@polkadot/types';
const builtinMap: [(id: any) => boolean, MetaTypeInfo][] = [
[(id: any): boolean => typeof id === 'string', MetaTypeInfo.BuiltinPlain],
[(id: any): boolean => Array.isArray(id), MetaTypeInfo.BuiltinTuple],
[(id: any): boolean => !!(id['array.type']), MetaTypeInfo.BuiltinVecFixed],
[(id: any): boolean => !!(id['slice.type']), MetaTypeInfo.BuiltinVec]
const builtinMap: [(id: unknown | unknown[] | { 'array.type': unknown } | { 'slice.type': unknown }) => boolean, MetaTypeInfo][] = [
[(id: any) => typeof id === 'string', MetaTypeInfo.BuiltinPlain],
[(id: any) => Array.isArray(id), MetaTypeInfo.BuiltinTuple],
[(id: any) => !!((id as { 'array.type': unknown })['array.type']), MetaTypeInfo.BuiltinVecFixed],
[(id: any) => !!((id as { 'slice.type': unknown })['slice.type']), MetaTypeInfo.BuiltinVec]
];
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');
const lookup = def === 'builtin'
? builtinMap.find(([test]): boolean => test(id))
: typeMap.find(([test]): boolean => !!(def as any)[test]);
? builtinMap.find(([test]) => test(id))
: typeMap.find(([test]) => !!(def as unknown as Record<string, unknown>)[test]);
return lookup
? 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`);
switch (variant) {
@@ -72,24 +72,24 @@ class MetadataRegistryLookup {
}
}
protected _itemsAt (indices: number[], variant: MetaRegistryItem): any[] {
return indices.map((index: number): string => this._itemAt(index, variant));
protected _itemsAt (indices: number[], variant: MetaRegistryItem): (string | MetaType | TypeDef)[] {
return indices.map((index: number) => this._itemAt(index, variant));
}
protected _stringAt (index: StringIndex): string {
return this._itemAt(index, MetaRegistryItem.String);
return this._itemAt(index, MetaRegistryItem.String) as 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 {
return this._itemAt(index, MetaRegistryItem.Type);
return this._itemAt(index, MetaRegistryItem.Type) as 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 {
@@ -98,7 +98,7 @@ class MetadataRegistryLookup {
public typeDefAt (index: TypeIndex, extra: Pick<TypeDef, never> = {}): TypeDef {
return {
...this._itemAt(index, MetaRegistryItem.TypeDef),
...this._itemAt(index, MetaRegistryItem.TypeDef) as TypeDef,
...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;
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;
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;
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}`);
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}`);
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`);
return {
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
signAndSend: this.decorateMethod(
(account: IKeyringPair | string | AccountId | Address): BlueprintCreateResultSubscription<ApiType> => {
return this._apiContracts
+1 -1
View File
@@ -19,7 +19,6 @@ import { BaseWithTx } from './util';
type CodePutCodeResultSubscription<ApiType extends ApiTypes> = Observable<CodePutCodeResult<ApiType>>;
// eslint-disable-next-line @typescript-eslint/interface-name-prefix
export interface CodePutCode<ApiType extends ApiTypes> {
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> => {
return {
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
signAndSend: this.decorateMethod(
(account: IKeyringPair | string | AccountId | Address): CodePutCodeResultSubscription<ApiType> =>
this._apiContracts
+1 -1
View File
@@ -21,7 +21,6 @@ type ContractCallResultSubscription<ApiType extends ApiTypes, CallType extends C
? Observable<ContractCallResult<CallType>>
: Promise<ObsInnerType<ContractCallResult<CallType>>>;
// eslint-disable-next-line @typescript-eslint/interface-name-prefix
export interface ContractCall<ApiType extends ApiTypes, CallType extends ContractCallTypes> {
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);
return {
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
send: this.decorateMethod(
as === 'rpc' && this.hasRpcContractsCall
? (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;
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)];
+3
View File
@@ -23,6 +23,7 @@ export interface ContractBase<ApiType extends ApiTypes> {
export interface ContractABITypePre {
ty: TypeIndex;
// eslint-disable-next-line camelcase
display_name: StringIndex[];
}
@@ -56,6 +57,7 @@ export interface ContractABIMessageCommon {
export interface ContractABIMessagePre extends ContractABIMessageCommon, ContractABIMessageBasePre {
name: StringIndex;
// eslint-disable-next-line camelcase
return_type: ContractABITypePre | null;
}
@@ -187,6 +189,7 @@ export interface InterfaceAbi {
}
export interface InterfaceContractCalls {
// eslint-disable-next-line @typescript-eslint/ban-types
[index: string]: Function;
}
+11 -11
View File
@@ -1,6 +1,6 @@
{
"name": "@polkadot/api-derive",
"version": "1.10.1",
"version": "1.24.1",
"description": "Common functions used across Polkadot, derived from RPC calls and storage queries.",
"main": "index.js",
"keywords": [
@@ -27,18 +27,18 @@
},
"homepage": "https://github.com/polkadot-js/api/tree/master/packages/api-derive#readme",
"dependencies": {
"@babel/runtime": "^7.9.2",
"@polkadot/api": "1.10.1",
"@polkadot/rpc-core": "1.10.1",
"@polkadot/rpc-provider": "1.10.1",
"@polkadot/types": "1.10.1",
"@polkadot/util": "^2.8.1",
"@polkadot/util-crypto": "^2.8.1",
"bn.js": "^5.1.1",
"@babel/runtime": "^7.10.4",
"@polkadot/api": "1.24.1",
"@polkadot/rpc-core": "1.24.1",
"@polkadot/rpc-provider": "1.24.1",
"@polkadot/types": "1.24.1",
"@polkadot/util": "^2.18.1",
"@polkadot/util-crypto": "^2.18.1",
"bn.js": "^5.1.2",
"memoizee": "^0.4.14",
"rxjs": "^6.5.5"
"rxjs": "^6.6.0"
},
"devDependencies": {
"@polkadot/keyring": "^2.8.1"
"@polkadot/keyring": "^2.18.1"
}
}
+69
View File
@@ -0,0 +1,69 @@
// 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 { ApiInterfaceRx } from '@polkadot/api/types';
import { AccountId, Address, Balance } from '@polkadot/types/interfaces';
import { ITuple } from '@polkadot/types/types';
import { DeriveAccountFlags } from '../types';
import { Observable, combineLatest, of } from 'rxjs';
import { map } from 'rxjs/operators';
import { Vec } from '@polkadot/types';
import { memo } from '../util';
type FlagsIntermediate = [
Vec<ITuple<[AccountId, Balance]>> | undefined,
AccountId[],
AccountId[],
AccountId[],
AccountId | undefined
];
function isIncludedFn (accountId: AccountId | Address | string): (_: AccountId | Address |string) => boolean {
return function (id: AccountId | Address | string): boolean {
return id.toString() === accountId.toString();
};
}
/**
* @name info
* @description Returns account membership flags
*/
export function flags (api: ApiInterfaceRx): (address?: AccountId | Address | string | null) => Observable<DeriveAccountFlags> {
return memo((address?: AccountId | Address | string | null): Observable<DeriveAccountFlags> => {
const councilSection = api.query.electionsPhragmen ? 'electionsPhragmen' : 'elections';
return (
combineLatest([
address && api.query[councilSection]?.members
? api.query[councilSection].members()
: of(undefined),
address && api.query.council?.members
? api.query.council.members()
: of([]),
address && api.query.technicalCommittee?.members
? api.query.technicalCommittee.members()
: of([]),
address && api.query.society?.members
? api.query.society.members()
: of([]),
address && api.query.sudo?.key
? api.query.sudo.key()
: of(undefined)
]) as Observable<FlagsIntermediate>
).pipe(
map(([electionsMembers, councilMembers, technicalCommitteeMembers, societyMembers, sudoKey]): DeriveAccountFlags => {
const isIncluded = address ? isIncludedFn(address) : (): boolean => false;
return {
isCouncil: (electionsMembers?.map(([id]: ITuple<[AccountId, Balance]>) => id) || councilMembers || []).some(isIncluded),
isSociety: (societyMembers || []).some(isIncluded),
isSudo: sudoKey?.toString() === address?.toString(),
isTechCommittee: (technicalCommitteeMembers || []).some(isIncluded)
};
})
);
});
}
@@ -3,6 +3,7 @@
// of the Apache-2.0 license. See the LICENSE file for details.
import { AccountId, AccountIndex, Address } from '@polkadot/types/interfaces';
import { AccountIdAndIndex } from '../types';
import { Observable, of } from 'rxjs';
import { map } from 'rxjs/operators';
@@ -12,8 +13,6 @@ import { decodeAddress } from '@polkadot/util-crypto';
import { memo } from '../util';
export type AccountIdAndIndex = [AccountId?, AccountIndex?];
function retrieve (api: ApiInterfaceRx, address: Address | AccountId | AccountIndex | string | null | undefined): Observable<AccountIdAndIndex> {
try {
// yes, this can fail, don't care too much, catch will catch it
@@ -2,6 +2,7 @@
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
export * from './flags';
export * from './idAndIndex';
export * from './idToIndex';
export * from './indexToId';
@@ -10,6 +10,7 @@ import { map, startWith } from 'rxjs/operators';
import { ApiInterfaceRx } from '@polkadot/api/types';
import { ENUMSET_SIZE } from '@polkadot/types/generic/AccountIndex';
import { Option, Vec } from '@polkadot/types';
import { isFunction } from '@polkadot/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> {
return memo((accountIndex: AccountIndex | string): Observable<AccountId | undefined> =>
api.query.indices
? api.query.indices.accounts
? isFunction(api.query.indices.accounts)
? query(api, accountIndex)
: queryEnumSet(api, accountIndex)
: of(undefined)
+18 -6
View File
@@ -10,11 +10,14 @@ import { Observable, of } from 'rxjs';
import { map, startWith, switchMap } from 'rxjs/operators';
import { ENUMSET_SIZE } from '@polkadot/types/generic/AccountIndex';
import { Vec } from '@polkadot/types';
import { isFunction } from '@polkadot/util';
import { memo } from '../util';
const enumsetSize = ENUMSET_SIZE.toNumber();
let indicesCache: AccountIndexes | null = null;
function queryEnumSet (api: ApiInterfaceRx): Observable<AccountIndexes> {
return api.query.indices.nextEnumSet<AccountIndex>().pipe(
// use the nextEnumSet (which is a counter of the number of sets) to construct
@@ -71,11 +74,20 @@ function queryAccounts (api: ApiInterfaceRx): Observable<AccountIndexes> {
*/
export function indexes (api: ApiInterfaceRx): () => Observable<AccountIndexes> {
return memo((): Observable<AccountIndexes> =>
(api.query.indices
? api.query.indices.accounts
? queryAccounts(api)
: queryEnumSet(api)
: of({} as AccountIndexes)
).pipe(startWith({}))
indicesCache
? of(indicesCache)
: (
api.query.indices
? isFunction(api.query.indices.accounts)
? queryAccounts(api).pipe(startWith({}))
: queryEnumSet(api).pipe(startWith({}))
: of({} as AccountIndexes)
).pipe(
map((indices): AccountIndexes => {
indicesCache = indices;
return indices;
})
)
);
}
+8 -48
View File
@@ -5,11 +5,11 @@
import { ApiInterfaceRx } from '@polkadot/api/types';
import { AccountId, AccountIndex, Address, Balance, Registration } from '@polkadot/types/interfaces';
import { ITuple } from '@polkadot/types/types';
import { DeriveAccountFlags, DeriveAccountInfo, DeriveAccountRegistration } from '../types';
import { DeriveAccountInfo, DeriveAccountRegistration } from '../types';
import { Observable, combineLatest, of } from 'rxjs';
import { map, switchMap } from 'rxjs/operators';
import { Bytes, Data, Option, u32, Vec } from '@polkadot/types';
import { Bytes, Data, Option, u32 } from '@polkadot/types';
import { u8aToString } from '@polkadot/util';
import { memo } from '../util';
@@ -17,15 +17,9 @@ import { memo } from '../util';
function dataAsString (data: Data): string | undefined {
return data.isRaw
? u8aToString(data.asRaw.toU8a(true))
: data.isSha256
? data.asSha256.toHex()
: undefined;
}
function includedWrapper (accountId?: AccountId): (_: AccountId) => boolean {
return function (id: AccountId): boolean {
return id.eq(accountId);
};
: data.isNone
? undefined
: data.toHex();
}
function retrieveNick (api: ApiInterfaceRx, accountId?: AccountId): Observable<string | undefined> {
@@ -115,39 +109,6 @@ function retrieveIdentity (api: ApiInterfaceRx, accountId?: AccountId): Observab
);
}
function retrieveFlags (api: ApiInterfaceRx, accountId?: AccountId): Observable<DeriveAccountFlags> {
const councilSection = api.query.electionsPhragmen ? 'electionsPhragmen' : 'elections';
return combineLatest([
api.query[councilSection]?.members
? api.query[councilSection].members<Vec<ITuple<[AccountId, Balance]>>>()
: of(undefined),
api.query.council?.members
? api.query.council.members()
: of([]),
api.query.technicalCommittee?.members
? api.query.technicalCommittee.members()
: of([]),
api.query.society?.members
? api.query.society.members()
: of([]),
api.query.sudo?.key
? api.query.sudo.key()
: of(undefined)
]).pipe(
map(([electionsMembers, councilMembers, technicalCommitteeMembers, societyMembers, sudoKey]): DeriveAccountFlags => {
const checkIncluded = includedWrapper(accountId);
return {
isCouncil: (electionsMembers?.map(([id]) => id) || councilMembers || []).some(checkIncluded),
isSociety: societyMembers.some(checkIncluded),
isSudo: !!sudoKey && sudoKey.eq(accountId),
isTechCommittee: technicalCommitteeMembers.some(checkIncluded)
};
})
);
}
/**
* @name info
* @description Returns aux. info with regards to an account, current that includes the accountId, accountIndex and nickname
@@ -155,16 +116,15 @@ function retrieveFlags (api: ApiInterfaceRx, accountId?: AccountId): Observable<
export function info (api: ApiInterfaceRx): (address?: AccountIndex | AccountId | Address | string | null) => Observable<DeriveAccountInfo> {
return memo((address?: AccountIndex | AccountId | Address | string | null): Observable<DeriveAccountInfo> =>
api.derive.accounts.idAndIndex(address).pipe(
switchMap(([accountId, accountIndex]): Observable<[Partial<DeriveAccountInfo>, DeriveAccountFlags, DeriveAccountRegistration, string?]> =>
switchMap(([accountId, accountIndex]): Observable<[Partial<DeriveAccountInfo>, DeriveAccountRegistration, string?]> =>
combineLatest([
of({ accountId, accountIndex }),
retrieveFlags(api, accountId),
retrieveIdentity(api, accountId),
retrieveNick(api, accountId)
])
),
map(([{ accountId, accountIndex }, flags, identity, nickname]): DeriveAccountInfo => ({
accountId, accountIndex, ...flags, identity, nickname
map(([{ accountId, accountIndex }, identity, nickname]): DeriveAccountInfo => ({
accountId, accountIndex, identity, nickname
}))
));
}
+38
View File
@@ -0,0 +1,38 @@
// 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, AccountIndex, RegistrationJudgement } from '@polkadot/types/interfaces';
export type AccountIdAndIndex = [AccountId?, AccountIndex?];
export type AccountIndexes = Record<string, AccountIndex>;
export interface DeriveAccountRegistration {
display?: string;
displayParent?: string;
email?: string;
image?: string;
legal?: string;
other?: Record<string, string>;
parent?: AccountId;
pgp?: string;
riot?: string;
twitter?: string;
web?: string;
judgements: RegistrationJudgement[];
}
export interface DeriveAccountFlags {
isCouncil: boolean;
isSociety: boolean;
isSudo: boolean;
isTechCommittee: boolean;
}
export interface DeriveAccountInfo {
accountId?: AccountId;
accountIndex?: AccountIndex;
identity: DeriveAccountRegistration;
nickname?: string;
}
+3 -2
View File
@@ -9,6 +9,7 @@ import { DeriveBalancesAccount } from '../types';
import { Observable, combineLatest, of } from 'rxjs';
import { map, switchMap } from 'rxjs/operators';
import { ApiInterfaceRx } from '@polkadot/api/types';
import { isFunction } from '@polkadot/util';
import { memo } from '../util';
@@ -86,9 +87,9 @@ export function account (api: ApiInterfaceRx): (address: AccountIndex | AccountI
(accountId
? combineLatest([
of(accountId),
api.query.system.account
isFunction(api.query.system.account)
? queryCurrent(api, accountId)
: api.query.balances.account
: isFunction(api.query.balances.account)
? queryBalancesAccount(api, accountId)
: queryBalancesFree(api, accountId)
])
+13 -17
View File
@@ -10,7 +10,7 @@ import { Observable, combineLatest, of } from 'rxjs';
import { map, switchMap } from 'rxjs/operators';
import { ApiInterfaceRx } from '@polkadot/api/types';
import { Option, Vec } from '@polkadot/types';
import { bnMax } from '@polkadot/util';
import { bnMax, isFunction } from '@polkadot/util';
import { memo } from '../util';
@@ -20,15 +20,17 @@ type Result = [DeriveBalancesAccount, BlockNumber, ResultBalance];
function calcBalances (api: ApiInterfaceRx, [{ accountId, accountNonce, freeBalance, frozenFee, frozenMisc, reservedBalance, votingBalance }, bestNumber, [vesting, locks]]: Result): DeriveBalancesAll {
let lockedBalance = api.registry.createType('Balance');
let lockedBreakdown: (BalanceLock | BalanceLockTo212)[] = [];
let vestingLocked = api.registry.createType('Balance');
let allLocked = false;
if (Array.isArray(locks)) {
// only get the locks that are valid until passed the current block
lockedBreakdown = (locks as BalanceLockTo212[]).filter(({ until }): boolean => !until || (bestNumber && until.gt(bestNumber)));
const notAll = lockedBreakdown.filter(({ amount }): boolean => !amount.isMax());
const notAll = lockedBreakdown.filter(({ amount }) => !amount.isMax());
allLocked = lockedBreakdown.some(({ amount }): boolean => amount.isMax());
allLocked = lockedBreakdown.some(({ amount }) => amount.isMax());
vestingLocked = api.registry.createType('Balance', lockedBreakdown.filter(({ id }) => id.eq('0x76657374696e6720')).reduce((result: BN, { amount }) => result.iadd(amount), new BN(0)));
// get the maximum of the locks according to https://github.com/paritytech/substrate/blob/master/srml/balances/src/lib.rs#L699
if (notAll.length) {
@@ -41,19 +43,11 @@ function calcBalances (api: ApiInterfaceRx, [{ accountId, accountNonce, freeBala
// - perBlock is the unlock amount
const { locked: vestingTotal, perBlock, startingBlock } = vesting || api.registry.createType('VestingInfo');
const isStarted = bestNumber.gt(startingBlock);
const vestedBalance = api.registry.createType('Balance', isStarted ? perBlock.mul(bestNumber.sub(startingBlock)) : 0);
const isVesting = isStarted && vestedBalance.lt(vestingTotal);
// The available balance & vested has an interplay here
// "
// vesting is a guarantee that the account's balance will never go below a certain amount. so it functions in the opposite way, a bit like a lock that is monotonically decreasing rather than a liquid amount that is monotonically increasing.
// locks function as the same guarantee - that a balance will not be lower than a particular amount.
// because of this you can see that if there is a "vesting lock" that guarantees the balance cannot go below 200, and a "staking lock" that guarantees the balance cannot drop below 300, then we just have two guarantees of which the first is irrelevant.
// i.e. (balance >= 200 && balance >= 300) == (balance >= 300)
// ""
const floating = freeBalance.sub(lockedBalance);
const extraReceived = isVesting ? freeBalance.sub(vestingTotal) : new BN(0);
const availableBalance = api.registry.createType('Balance', allLocked ? 0 : bnMax(new BN(0), isVesting && floating.gt(vestedBalance) ? vestedBalance.add(extraReceived) : floating));
const vestedNow = isStarted ? perBlock.mul(bestNumber.sub(startingBlock)) : new BN(0);
const vestedBalance = vestedNow.gt(vestingTotal) ? vestingTotal : api.registry.createType('Balance', vestedNow);
const isVesting = isStarted && !vestingLocked.isZero();
const vestedClaimable = api.registry.createType('Balance', isVesting ? vestingLocked.sub(vestingTotal.sub(vestedBalance)) : 0);
const availableBalance = api.registry.createType('Balance', allLocked ? 0 : bnMax(new BN(0), freeBalance.sub(lockedBalance)));
return {
accountId,
@@ -67,6 +61,8 @@ function calcBalances (api: ApiInterfaceRx, [{ accountId, accountNonce, freeBala
lockedBreakdown,
reservedBalance,
vestedBalance,
vestedClaimable,
vestingLocked,
vestingTotal,
votingBalance
};
@@ -135,7 +131,7 @@ export function all (api: ApiInterfaceRx): (address: AccountIndex | AccountId |
? combineLatest([
of(account),
api.derive.chain.bestNumber(),
api.query.balances.account
isFunction(api.query.balances.account)
? queryCurrent(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> =>
of([
// deprecated - remove
(api.consts.balances?.creationFee as Balance) || api.registry.createType('Balance'),
(api.consts.balances?.transferFee as Balance) || api.registry.createType('Balance'),
(api.consts.balances?.creationFee as unknown as Balance) || api.registry.createType('Balance'),
(api.consts.balances?.transferFee as unknown as Balance) || api.registry.createType('Balance'),
// current
(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')
]).pipe(
map(([creationFee, transferFee, existentialDeposit, transactionBaseFee, transactionByteFee]): DeriveFees => ({
@@ -9,6 +9,7 @@ import { DeriveCollectiveProposal } from '../types';
import { Observable, combineLatest, of } from 'rxjs';
import { map, switchMap } from 'rxjs/operators';
import { Option } from '@polkadot/types';
import { isFunction } from '@polkadot/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[]> {
return memo((): Observable<DeriveCollectiveProposal[]> =>
api.query[section]?.proposals
isFunction(api.query[section]?.proposals)
? api.query[section].proposals().pipe(
switchMap((hashes: Hash[]): Observable<Result> =>
hashes.length
+9 -7
View File
@@ -11,23 +11,24 @@ import { map } from 'rxjs/operators';
import { memo } from '../util';
type ResultV2 = [BN, BN, BN, BN, BN, BN, BN, BN, BN];
type ResultV2 = [BN, BN, BN, BN, BN, BN, BN, BN, BN, BN];
// query via constants (current applicable path)
function queryConstants (api: ApiInterfaceRx): Observable<ResultV2> {
return of([
// deprecated
api.consts.contracts.callBaseFee || api.registry.createType('Balance'),
api.consts.contracts.contractFee || api.registry.createType('Balance'),
api.consts.contracts.creationFee || api.registry.createType('Balance'),
api.consts.contracts.transactionBaseFee || api.registry.createType('Balance'),
api.consts.contracts.transactionByteFee || api.registry.createType('Balance'),
api.consts.contracts.transferFee || api.registry.createType('Balance'),
// current
api.consts.contracts.callBaseFee,
api.consts.contracts.contractFee,
api.consts.contracts.rentByteFee,
api.consts.contracts.rentDepositOffset,
api.consts.contracts.tombstoneDeposit,
api.consts.contracts.transactionBaseFee,
api.consts.contracts.transactionByteFee
api.consts.contracts.surchargeReward,
api.consts.contracts.tombstoneDeposit
]) as unknown as Observable<ResultV2>;
}
@@ -47,12 +48,13 @@ function queryConstants (api: ApiInterfaceRx): Observable<ResultV2> {
export function fees (api: ApiInterfaceRx): () => Observable<DeriveContractFees> {
return memo((): Observable<DeriveContractFees> => {
return queryConstants(api).pipe(
map(([creationFee, transferFee, callBaseFee, contractFee, rentByteFee, rentDepositOffset, tombstoneDeposit, transactionBaseFee, transactionByteFee]): DeriveContractFees => ({
map(([callBaseFee, contractFee, creationFee, transactionBaseFee, transactionByteFee, transferFee, rentByteFee, rentDepositOffset, surchargeReward, tombstoneDeposit]): DeriveContractFees => ({
callBaseFee,
contractFee,
creationFee,
rentByteFee,
rentDepositOffset,
surchargeReward,
tombstoneDeposit,
transactionBaseFee,
transactionByteFee,
@@ -10,7 +10,7 @@ import { Observable, combineLatest, of } from 'rxjs';
import { map, switchMap } from 'rxjs/operators';
import { ApiInterfaceRx } from '@polkadot/api/types';
import { Option, Vec, u64 } from '@polkadot/types';
import { stringToHex } from '@polkadot/util';
import { isFunction, stringToHex } from '@polkadot/util';
import { memo } from '../util';
@@ -96,7 +96,7 @@ function queryScheduler (api: ApiInterfaceRx): Observable<DeriveDispatch[]> {
export function dispatchQueue (api: ApiInterfaceRx): () => Observable<DeriveDispatch[]> {
return memo((): Observable<DeriveDispatch[]> =>
api.query.scheduler?.agenda
isFunction(api.query.scheduler?.agenda)
? queryScheduler(api)
: api.query.democracy.dispatchQueue
? queryQueue(api)
@@ -3,6 +3,7 @@
// of the Apache-2.0 license. See the LICENSE file for details.
export * from './dispatchQueue';
export * from './locks';
export * from './nextExternal';
export * from './preimage';
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([])
)
)
);
}
@@ -17,8 +17,8 @@ import { parseImage } from './util';
type PreImage = Option<ITuple<[Bytes, AccountId, Balance, BlockNumber]>>;
export function preimage (api: ApiInterfaceRx): (hash: Hash) => Observable<DeriveProposalImage | undefined> {
return memo((hashes: Hash[]): Observable<DeriveProposalImage | undefined> =>
api.query.democracy.preimages<PreImage>(hashes).pipe(
return memo((hash: Hash): Observable<DeriveProposalImage | undefined> =>
api.query.democracy.preimages<PreImage>(hash).pipe(
map((imageOpt) => parseImage(api, imageOpt))
)
);
@@ -20,9 +20,7 @@ export function preimages (api: ApiInterfaceRx): (hashes: Hash[]) => Observable<
return memo((hashes: Hash[]): Observable<(DeriveProposalImage | undefined)[]> =>
api.query.democracy.preimages.multi<PreImage>(hashes).pipe(
map((images): (DeriveProposalImage | undefined)[] =>
images.map((imageOpt) =>
parseImage(api, imageOpt)
)
images.map((imageOpt) => parseImage(api, imageOpt))
)
)
);
+21 -7
View File
@@ -10,27 +10,41 @@ import { Observable, combineLatest, of } from 'rxjs';
import { map, switchMap } from 'rxjs/operators';
import { ApiInterfaceRx } from '@polkadot/api/types';
import { Option, Vec } from '@polkadot/types';
import { isFunction } from '@polkadot/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 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
.filter(([, , proposer], index): boolean =>
!!(depositors[index]?.isSome) && !proposer.isEmpty
!!(optDepositors[index]?.isSome) && !proposer.isEmpty
)
.map(([index, imageHash, proposer], proposalIndex): DeriveProposal => {
const [balance, seconds] = depositors[proposalIndex].unwrap();
const depositors = optDepositors[proposalIndex].unwrap();
return {
balance,
...(
isNewDepositors(depositors)
? { balance: depositors[1], seconds: depositors[0] }
: { balance: depositors[0], seconds: depositors[1] }
),
image: images[proposalIndex],
imageHash,
index,
proposer,
seconds
proposer
};
});
}
@@ -20,6 +20,7 @@ export function referendumIds (api: ApiInterfaceRx): () => Observable<BN[]> {
]).pipe(
map(([first, total]): BN[] =>
total.gt(first)
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
? [...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.
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 BN from 'bn.js';
import { Observable, of, combineLatest } from 'rxjs';
import { map, switchMap } from 'rxjs/operators';
import { Option, Vec } from '@polkadot/types';
import { isFunction } from '@polkadot/util';
import { memo } 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 => ({
accountId,
balance: balances[index].votingBalance || api.registry.createType('Balance'),
isDelegating: false,
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[]> {
return api.query.democracy.votingOf.entries<Voting>().pipe(
map((allVoting): DeriveReferendumVote[] =>
allVoting
.map(([key, voting]): [AccountId, Voting] => [key.args[0] as AccountId, voting])
// FIXME We are ignoring delegated votes
map((allVoting): DeriveReferendumVote[] => {
const mapped = allVoting.map(([key, voting]): [AccountId, Voting] => [key.args[0] as AccountId, voting]);
const votes = mapped
.filter(([, voting]) => voting.isDirect)
.map(([accountId, voting]): [AccountId, VotingDirectVote[]] => [
accountId,
@@ -57,14 +58,37 @@ function votesCurr (api: ApiInterfaceRx, referendumId: BN): Observable<DeriveRef
if (vote.isStandard) {
result.push({
accountId,
isDelegating: false,
...vote.asStandard
});
}
return 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> =>
combineLatest([
api.derive.democracy.sqrtElectorate(),
api.query.democracy.votingOf
isFunction(api.query.democracy.votingOf)
? votesCurr(api, referendum.index)
: votesPrev(api, referendum.index)
]).pipe(
+10 -1
View File
@@ -2,11 +2,19 @@
// This software may be modified and distributed under the terms
// 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 BN from 'bn.js';
import { Vec } from '@polkadot/types';
export interface DeriveDemocracyLock {
balance: Balance;
isFinished: boolean;
referendumId: ReferendumIndex;
unlockAt: BN;
vote: Vote;
}
export interface DeriveDispatch {
at: BlockNumber;
index: ReferendumIndex;
@@ -46,6 +54,7 @@ export interface DeriveReferendum {
export interface DeriveReferendumVote {
accountId: AccountId;
balance: Balance;
isDelegating: boolean;
vote: Vote;
}
+3 -3
View File
@@ -82,15 +82,15 @@ function calcVotesPrev (votesFor: DeriveReferendumVote[]): DeriveReferendumVoteS
if (vote.isAye) {
state.allAye.push(derived);
state.voteCountAye++;
state.votedAye = state.votedAye.add(counted);
state.votedAye.iadd(counted);
} else {
state.allNay.push(derived);
state.voteCountNay++;
state.votedNay = state.votedNay.add(counted);
state.votedNay.iadd(counted);
}
state.voteCount++;
state.votedTotal = state.votedTotal.add(counted);
state.votedTotal.iadd(counted);
return state;
}, {
+5 -1
View File
@@ -2,6 +2,10 @@
// This software may be modified and distributed under the terms
// 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 ApiRx from '@polkadot/api/rx/Api';
import MockProvider from '@polkadot/rpc-provider/mock';
@@ -33,7 +37,7 @@ describe('derive', (): void => {
const api = new ApiRx({ provider: new MockProvider(registry), registry });
beforeAll((done): void => {
api.isReady.subscribe((): void => done());
api.isReady.subscribe(() => done());
});
testFunction(api)('accounts', 'idAndIndex', []);
+2
View File
@@ -76,9 +76,11 @@ function injectFunctions<AllSections> (api: ApiInterfaceRx, allSections: AllSect
.reduce((sectionAcc, _methodName): DeriveSection<typeof section> => {
const methodName = _methodName as keyof typeof section;
// 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);
// idem
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment,@typescript-eslint/no-unsafe-member-access
(sectionAcc as any)[methodName] = method;
return sectionAcc;
+2 -1
View File
@@ -9,6 +9,7 @@ import { DeriveSessionIndexes } from '../types';
import { Observable, of } from 'rxjs';
import { map } from 'rxjs/operators';
import { Option, u32 } from '@polkadot/types';
import { isFunction } from '@polkadot/util';
import { memo } from '../util';
@@ -79,7 +80,7 @@ export function indexes (api: ApiInterfaceRx): () => Observable<DeriveSessionInd
return memo((): Observable<DeriveSessionIndexes> =>
(
api.query.session && api.query.staking
? api.query.staking.activeEra
? isFunction(api.query.staking.activeEra)
? query(api)
: queryNoActive(api)
: empty(api)
+7 -5
View File
@@ -9,6 +9,7 @@ import { Observable, combineLatest, of } from 'rxjs';
import { map, switchMap } from 'rxjs/operators';
import { ApiInterfaceRx } from '@polkadot/api/types';
import { Option, u64 } from '@polkadot/types';
import { isFunction } from '@polkadot/util';
import { memo } from '../util';
@@ -16,9 +17,9 @@ type ResultSlots = [u64, u64, u64, Option<SessionIndex>];
type ResultSlotsFlat = [u64, u64, u64, SessionIndex];
function createDerive (api: ApiInterfaceRx, info: DeriveSessionInfo, [currentSlot, epochIndex, epochOrGenesisStartSlot, activeEraStartSessionIndex]: ResultSlotsFlat): DeriveSessionProgress {
const epochStartSlot = epochIndex.mul(info.sessionLength).add(epochOrGenesisStartSlot);
const epochStartSlot = epochIndex.mul(info.sessionLength).iadd(epochOrGenesisStartSlot);
const sessionProgress = currentSlot.sub(epochStartSlot);
const eraProgress = info.currentIndex.sub(activeEraStartSessionIndex).mul(info.sessionLength).add(sessionProgress);
const eraProgress = info.currentIndex.sub(activeEraStartSessionIndex).imul(info.sessionLength).iadd(sessionProgress);
return {
...info,
@@ -77,9 +78,10 @@ function queryBabeNoHistory (api: ApiInterfaceRx): Observable<[DeriveSessionInfo
export function progress (api: ApiInterfaceRx): () => Observable<DeriveSessionProgress> {
return memo((): Observable<DeriveSessionProgress> =>
api.consts.babe
? (api.query.staking.erasStartSessionIndex
? queryBabe(api) // 2.x with Babe
: queryBabeNoHistory(api)
? (
isFunction(api.query.staking.erasStartSessionIndex)
? queryBabe(api) // 2.x with Babe
: queryBabeNoHistory(api)
).pipe(
map(([info, slots]: [DeriveSessionInfo, ResultSlotsFlat]): DeriveSessionProgress =>
createDerive(api, info, slots)
+29 -15
View File
@@ -7,8 +7,8 @@ import { Balance, StakingLedger, UnlockChunk } from '@polkadot/types/interfaces'
import { DeriveSessionInfo, DeriveStakingAccount, DeriveStakingQuery, DeriveUnlocking } from '../types';
import BN from 'bn.js';
import { Observable, combineLatest } from 'rxjs';
import { map } from 'rxjs/operators';
import { Observable } from 'rxjs';
import { map, switchMap } from 'rxjs/operators';
import { isUndefined } from '@polkadot/util';
@@ -21,7 +21,7 @@ function groupByEra (list: UnlockChunk[]): Record<string, BN> {
map[key] = !map[key]
? value.unwrap()
: map[key].add(value.unwrap());
: map[key].iadd(value.unwrap());
return map;
}, {});
@@ -32,8 +32,8 @@ function calculateUnlocking (api: ApiInterfaceRx, stakingLedger: StakingLedger |
return undefined;
}
const unlockingChunks = stakingLedger.unlocking.filter(({ era }): boolean =>
era.unwrap().sub(sessionInfo.activeEra).gtn(0)
const unlockingChunks = stakingLedger.unlocking.filter(({ era }) =>
era.unwrap().gt(sessionInfo.activeEra)
);
if (!unlockingChunks.length) {
@@ -43,11 +43,13 @@ function calculateUnlocking (api: ApiInterfaceRx, stakingLedger: StakingLedger |
// group the unlock chunks that have the same era and sum their values
const groupedResult = groupByEra(unlockingChunks);
const results = Object.entries(groupedResult).map(([eraString, value]): DeriveUnlocking => ({
remainingEras: new BN(eraString).sub(sessionInfo.activeEra),
remainingEras: new BN(eraString).isub(sessionInfo.activeEra),
value: api.registry.createType('Balance', value)
}));
return results.length ? results : undefined;
return results.length
? results
: undefined;
}
function redeemableSum (api: ApiInterfaceRx, stakingLedger: StakingLedger | undefined, sessionInfo: DeriveSessionInfo): Balance {
@@ -57,7 +59,7 @@ function redeemableSum (api: ApiInterfaceRx, stakingLedger: StakingLedger | unde
return api.registry.createType('Balance', stakingLedger.unlocking.reduce((total, { era, value }): BN => {
return sessionInfo.activeEra.gte(era.unwrap())
? total.add(value.unwrap())
? total.iadd(value.unwrap())
: total;
}, new BN(0)));
}
@@ -70,16 +72,28 @@ function parseResult (api: ApiInterfaceRx, sessionInfo: DeriveSessionInfo, 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) =>
api.derive.staking.queryMulti(accountIds).pipe(
map((queries) => queries.map((query) => parseResult(api, sessionInfo, query)))
)
)
)
);
}
/**
* @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> {
return memo((accountId: Uint8Array | string): Observable<DeriveStakingAccount> =>
combineLatest([
api.derive.session.info(),
api.derive.staking.query(accountId)
]).pipe(
map(([sessionInfo, query]: [DeriveSessionInfo, DeriveStakingQuery]) =>
parseResult(api, sessionInfo, query))
));
api.derive.staking.accounts([accountId]).pipe(
map(([first]) => first)
)
);
}
+10 -15
View File
@@ -3,10 +3,9 @@
// of the Apache-2.0 license. See the LICENSE file for details.
import { ApiInterfaceRx } from '@polkadot/api/types';
import { AccountId } from '@polkadot/types/interfaces';
import { DeriveStakingQuery, DeriveStakingElected } from '../types';
import { DeriveStakingElected } from '../types';
import { Observable, combineLatest, of } from 'rxjs';
import { Observable } from 'rxjs';
import { map, switchMap } from 'rxjs/operators';
import { memo } from '../util';
@@ -14,18 +13,14 @@ import { memo } from '../util';
export function electedInfo (api: ApiInterfaceRx): () => Observable<DeriveStakingElected> {
return memo((): Observable<DeriveStakingElected> =>
api.derive.staking.validators().pipe(
switchMap(({ nextElected }): Observable<[AccountId[], DeriveStakingQuery[]]> =>
combineLatest([
of(nextElected),
combineLatest(
nextElected.map((accountId) => api.derive.staking.query(accountId))
)
])
),
map(([nextElected, info]): DeriveStakingElected => ({
info,
nextElected
}))
switchMap(({ nextElected }): Observable<DeriveStakingElected> =>
api.derive.staking.queryMulti(nextElected).pipe(
map((info): DeriveStakingElected => ({
info,
nextElected
}))
)
)
)
);
}
@@ -10,10 +10,12 @@ import { Observable, combineLatest, of } from 'rxjs';
import { map, switchMap } from 'rxjs/operators';
import { StorageKey } from '@polkadot/types';
import { memo } from '../util';
import { deriveCache, memo } from '../util';
type KeysAndExposures = [StorageKey, Exposure][];
const CACHE_KEY = 'eraExposure';
function mapStakers (era: EraIndex, stakers: KeysAndExposures): DeriveEraExposure {
const nominators: DeriveEraNominatorExposure = {};
const validators: DeriveEraValidatorExposure = {};
@@ -34,26 +36,45 @@ function mapStakers (era: EraIndex, stakers: KeysAndExposures): DeriveEraExposur
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> {
return memo((era: EraIndex): Observable<DeriveEraExposure> =>
api.query.staking.erasStakersClipped.entries(era).pipe(
map((stakers) => mapStakers(era, stakers))
)
api.derive.staking._eraExposure(era, true)
);
}
export function _erasExposure (api: ApiInterfaceRx): (eras: EraIndex[]) => Observable<DeriveEraExposure[]> {
return memo((eras: EraIndex[]): Observable<DeriveEraExposure[]> =>
export function _erasExposure (api: ApiInterfaceRx): (eras: EraIndex[], withActive: boolean) => Observable<DeriveEraExposure[]> {
return memo((eras: EraIndex[], withActive: boolean): Observable<DeriveEraExposure[]> =>
eras.length
? combineLatest(eras.map((era) => api.derive.staking.eraExposure(era)))
? combineLatest(eras.map((era) => api.derive.staking._eraExposure(era, withActive)))
: of([])
);
}
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(
switchMap((eras) => api.derive.staking._erasExposure(eras))
switchMap((eras) => api.derive.staking._erasExposure(eras, withActive))
)
);
}
@@ -12,8 +12,8 @@ import { Option, u32 } from '@polkadot/types';
import { memo } from '../util';
export function erasHistoric (api: ApiInterfaceRx): (withActive?: boolean) => Observable<EraIndex[]> {
return memo((withActive?: boolean): Observable<EraIndex[]> =>
export function erasHistoric (api: ApiInterfaceRx): (withActive: boolean) => Observable<EraIndex[]> {
return memo((withActive: boolean): Observable<EraIndex[]> =>
api.query.staking?.activeEra
? api.queryMulti<[Option<ActiveEraInfo>, u32]>([
api.query.staking.activeEra,
+41 -17
View File
@@ -9,7 +9,9 @@ import { DeriveEraPoints, DeriveEraValPoints } from '../types';
import { Observable, of } from 'rxjs';
import { map, switchMap } from 'rxjs/operators';
import { memo } from '../util';
import { deriveCache, memo } from '../util';
const CACHE_KEY = 'eraPoints';
function mapValidators ({ individual }: EraRewardPoints): DeriveEraValPoints {
return [...individual.entries()]
@@ -21,26 +23,48 @@ function mapValidators ({ individual }: EraRewardPoints): DeriveEraValPoints {
}, {});
}
export function _erasPoints (api: ApiInterfaceRx): (eras: EraIndex[]) => Observable<DeriveEraPoints[]> {
return memo((eras: EraIndex[]): Observable<DeriveEraPoints[]> =>
eras.length
? api.query.staking.erasRewardPoints.multi<EraRewardPoints>(eras).pipe(
map((points) =>
eras.map((era, index): DeriveEraPoints => ({
era,
eraPoints: points[index].total,
validators: mapValidators(points[index])
}))
)
)
: of([])
);
function mapPoints (eras: EraIndex[], points: EraRewardPoints[]): DeriveEraPoints[] {
return 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([]);
}
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[]> {
return memo((withActive?: boolean): Observable<DeriveEraPoints[]> =>
return memo((withActive = false): Observable<DeriveEraPoints[]> =>
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 { 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 {
const validators: DeriveEraValPrefs = {};
@@ -22,26 +24,45 @@ function mapPrefs (era: EraIndex, all: [StorageKey, ValidatorPrefs][]): DeriveEr
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> {
return memo((era: EraIndex): Observable<DeriveEraPrefs> =>
api.query.staking.erasValidatorPrefs.entries(era).pipe(
map((prefs) => mapPrefs(era, prefs))
)
api.derive.staking._eraPrefs(era, true)
);
}
export function _erasPrefs (api: ApiInterfaceRx): (eras: EraIndex[]) => Observable<DeriveEraPrefs[]> {
return memo((eras: EraIndex[]): Observable<DeriveEraPrefs[]> =>
export function _erasPrefs (api: ApiInterfaceRx): (eras: EraIndex[], withActive: boolean) => Observable<DeriveEraPrefs[]> {
return memo((eras: EraIndex[], withActive: boolean): Observable<DeriveEraPrefs[]> =>
eras.length
? combineLatest(eras.map((era) => api.derive.staking.eraPrefs(era)))
? combineLatest(eras.map((era) => api.derive.staking._eraPrefs(era, withActive)))
: of([])
);
}
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(
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 { Option } from '@polkadot/types';
import { memo } from '../util';
import { deriveCache, memo } from '../util';
export function _erasRewards (api: ApiInterfaceRx): (eras: EraIndex[]) => Observable<DeriveEraRewards[]> {
return memo((eras: EraIndex[]): Observable<DeriveEraRewards[]> =>
eras.length
? api.query.staking.erasValidatorReward.multi<Option<Balance>>(eras).pipe(
map((rewards) => eras.map((era, index): DeriveEraRewards => ({
era,
eraReward: rewards[index].unwrapOrDefault()
})))
)
: of([])
);
const CACHE_KEY = 'eraRewards';
function mapRewards (eras: EraIndex[], optRewards: Option<Balance>[]): DeriveEraRewards[] {
return eras.map((era, index): DeriveEraRewards => ({
era,
eraReward: optRewards[index].unwrapOrDefault()
}));
}
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[]> {
return memo((withActive?: boolean): Observable<DeriveEraRewards[]> =>
return memo((withActive = false): Observable<DeriveEraRewards[]> =>
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 { 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 {
const nominators: DeriveEraValSlash = {};
@@ -28,31 +30,50 @@ function mapSlashes (era: EraIndex, noms: [StorageKey, Option<BalanceOf>][], val
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> {
return memo((era: EraIndex): Observable<DeriveEraSlashes> =>
combineLatest([
api.query.staking.nominatorSlashInEra.entries(era),
api.query.staking.validatorSlashInEra.entries(era)
]).pipe(
map(([noms, vals]) => mapSlashes(era, noms, vals))
)
api.derive.staking._eraSlashes(era, true)
);
}
export function _erasSlashes (api: ApiInterfaceRx): (eras: EraIndex[]) => Observable<DeriveEraSlashes[]> {
return memo((eras: EraIndex[]): Observable<DeriveEraSlashes[]> =>
export function _erasSlashes (api: ApiInterfaceRx): (eras: EraIndex[], withActive: boolean) => Observable<DeriveEraSlashes[]> {
return memo((eras: EraIndex[], withActive: boolean): Observable<DeriveEraSlashes[]> =>
eras.length
? combineLatest(
eras.map((era) => api.derive.staking.eraSlashes(era))
eras.map((era) => api.derive.staking._eraSlashes(era, withActive))
)
: of([])
);
}
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(
switchMap((eras) => api.derive.staking._erasSlashes(eras))
switchMap((eras) => api.derive.staking._erasSlashes(eras, withActive))
)
);
}
+1
View File
@@ -21,3 +21,4 @@ export * from './stakerRewards';
export * from './stakerSlashes';
export * from './stashes';
export * from './validators';
export * from './waitingInfo';
+47 -19
View File
@@ -2,34 +2,62 @@
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { EraIndex, Exposure } from '@polkadot/types/interfaces';
import { ApiInterfaceRx } from '@polkadot/api/types';
import { DeriveOwnExposure } from '../types';
import { Observable, combineLatest, of } from 'rxjs';
import { map, switchMap } from 'rxjs/operators';
import { memo } from '../util';
import { deriveCache, memo } from '../util';
export function ownExposure (api: ApiInterfaceRx): (accountId: Uint8Array | string, withActive?: boolean) => Observable<DeriveOwnExposure[]> {
return memo((accountId: Uint8Array | string, withActive?: boolean): Observable<DeriveOwnExposure[]> => {
const CACHE_KEY = 'ownExposure';
export function _ownExposure (api: ApiInterfaceRx): (accountId: Uint8Array | string, era: EraIndex, withActive: boolean) => Observable<DeriveOwnExposure> {
return memo((accountId: Uint8Array | string, era: EraIndex, withActive: boolean): Observable<DeriveOwnExposure> => {
const cacheKey = `${CACHE_KEY}-${era.toString()}-${accountId.toString()}`;
const cached = withActive
? undefined
: deriveCache.get<DeriveOwnExposure>(cacheKey);
return cached
? of(cached)
: api.queryMulti<[Exposure, Exposure]>([
[api.query.staking.erasStakersClipped, [era, accountId]],
[api.query.staking.erasStakers, [era, accountId]]
]).pipe(
map(([clipped, exposure]): DeriveOwnExposure => {
const value = { clipped, era, exposure };
!withActive && deriveCache.set(cacheKey, value);
return value;
})
);
});
}
export function ownExposure (api: ApiInterfaceRx): (accountId: Uint8Array | string, era: EraIndex) => Observable<DeriveOwnExposure> {
return memo((accountId: Uint8Array | string, era: EraIndex): Observable<DeriveOwnExposure> =>
api.derive.staking._ownExposure(accountId, era, true)
);
}
export function _ownExposures (api: ApiInterfaceRx): (accountId: Uint8Array | string, eras: EraIndex[], withActive: boolean) => Observable<DeriveOwnExposure[]> {
return memo((accountId: Uint8Array | string, eras: EraIndex[], withActive: boolean): Observable<DeriveOwnExposure[]> =>
eras.length
? combineLatest(
eras.map((era) => api.derive.staking._ownExposure(accountId, era, withActive))
)
: of([])
);
}
export function ownExposures (api: ApiInterfaceRx): (accountId: Uint8Array | string, withActive?: boolean) => Observable<DeriveOwnExposure[]> {
return memo((accountId: Uint8Array | string, withActive = false): Observable<DeriveOwnExposure[]> => {
return api.derive.staking.erasHistoric(withActive).pipe(
switchMap((eras) =>
eras.length
? combineLatest(
eras.map((era) => combineLatest([
of(era),
api.query.staking.erasStakersClipped(era, accountId),
api.query.staking.erasStakers(era, accountId)
]))
)
: of([])
),
map((result): DeriveOwnExposure[] =>
result.map(([era, clipped, exposure]): DeriveOwnExposure => ({
clipped,
era,
exposure
}))
api.derive.staking._ownExposures(accountId, eras, withActive)
)
);
});
+53 -19
View File
@@ -3,34 +3,68 @@
// of the Apache-2.0 license. See the LICENSE file for details.
import { ApiInterfaceRx } from '@polkadot/api/types';
import { BalanceOf, EraIndex, Perbill } from '@polkadot/types/interfaces';
import { ITuple } from '@polkadot/types/types';
import { DeriveStakerSlashes } from '../types';
import { Observable, combineLatest, of } from 'rxjs';
import { map, switchMap } from 'rxjs/operators';
import { Option } from '@polkadot/types';
import { memo } from '../util';
import { deriveCache, memo } from '../util';
const CACHE_KEY = 'ownSlash';
export function _ownSlash (api: ApiInterfaceRx): (accountId: Uint8Array | string, era: EraIndex, withActive: boolean) => Observable<DeriveStakerSlashes> {
return memo((accountId: Uint8Array | string, era: EraIndex, withActive: boolean): Observable<DeriveStakerSlashes> => {
const cacheKey = `${CACHE_KEY}-${era.toString()}-${accountId.toString()}`;
const cached = withActive
? undefined
: deriveCache.get<DeriveStakerSlashes>(cacheKey);
return cached
? of(cached)
: api.queryMulti<[Option<BalanceOf>, Option<ITuple<[Perbill, BalanceOf]>>]>([
[api.query.staking.nominatorSlashInEra, [era, accountId]],
[api.query.staking.validatorSlashInEra, [era, accountId]]
]).pipe(
map(([optNom, optVal]): DeriveStakerSlashes => {
const value = {
era,
total: optVal.isSome
? optVal.unwrap()[1]
: optNom.unwrapOrDefault()
};
!withActive && deriveCache.set(cacheKey, value);
return value;
})
);
});
}
export function ownSlash (api: ApiInterfaceRx): (accountId: Uint8Array | string, era: EraIndex) => Observable<DeriveStakerSlashes> {
return memo((accountId: Uint8Array | string, era: EraIndex): Observable<DeriveStakerSlashes> =>
api.derive.staking._ownSlash(accountId, era, true)
);
}
export function _ownSlashes (api: ApiInterfaceRx): (accountId: Uint8Array | string, eras: EraIndex[], withActive: boolean) => Observable<DeriveStakerSlashes[]> {
return memo((accountId: Uint8Array | string, eras: EraIndex[], withActive: boolean): Observable<DeriveStakerSlashes[]> =>
eras.length
? combineLatest(
eras.map((era) => api.derive.staking._ownSlash(accountId, era, withActive))
)
: of([])
);
}
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(
switchMap((eras) =>
eras.length
? combineLatest(
eras.map((era) => combineLatest([
of(era),
api.query.staking.nominatorSlashInEra(era, accountId),
api.query.staking.validatorSlashInEra(era, accountId)
]))
)
: of([])
),
map((result): DeriveStakerSlashes[] =>
result.map(([era, optNom, optVal]): DeriveStakerSlashes => ({
era,
total: optVal.isSome
? optVal.unwrap()[1]
: optNom.unwrapOrDefault()
}))
api.derive.staking._ownSlashes(accountId, eras, withActive)
)
);
});
+81 -59
View File
@@ -3,19 +3,20 @@
// of the Apache-2.0 license. See the LICENSE file for details.
import { ApiInterfaceRx } from '@polkadot/api/types';
import { AccountId, Exposure, Keys, Nominations, RewardDestination, ValidatorPrefs } from '@polkadot/types/interfaces';
import { AccountId, EraIndex, Exposure, Keys, Nominations, RewardDestination, StakingLedger, ValidatorPrefs } from '@polkadot/types/interfaces';
import { ITuple } from '@polkadot/types/types';
import { DeriveStakingQuery } from '../types';
import { Observable, combineLatest, of } from 'rxjs';
import { map, switchMap } from 'rxjs/operators';
import { Option, Vec } from '@polkadot/types';
import { isFunction } from '@polkadot/util';
import { memo } from '../util';
type MultiResult = [Option<AccountId>, Option<ITuple<[Nominations]> | Nominations>, RewardDestination, ITuple<[ValidatorPrefs]> | ValidatorPrefs, Option<Keys>, Exposure];
function unwrapSessionIds (stashId: AccountId, queuedKeys: [AccountId, Keys][], nextKeys: Option<Keys>): { nextSessionIds: AccountId[]; sessionIds: AccountId[] } {
function parseSessionIds (stashId: AccountId, queuedKeys: [AccountId, Keys][], nextKeys: Option<Keys>): { nextSessionIds: AccountId[]; sessionIds: AccountId[] } {
const sessionIds = (queuedKeys.find(([currentId]): boolean =>
currentId.eq(stashId)
) || [undefined, [] as AccountId[]])[1];
@@ -27,6 +28,31 @@ function unwrapSessionIds (stashId: AccountId, queuedKeys: [AccountId, Keys][],
};
}
function parseController (stashId: AccountId, queuedKeys: Vec<ITuple<[AccountId, Keys]>>, [controllerIdOpt, nominatorsOpt, rewardDestination, validatorPrefs, nextKeys, exposure]: MultiResult, stakingLedgerOpt: Option<StakingLedger>): DeriveStakingQuery {
const controllerId = controllerIdOpt.unwrapOr(null);
const nominators = nominatorsOpt.unwrapOr(null);
return controllerId && stakingLedgerOpt.isSome
? {
accountId: stashId,
controllerId,
exposure,
nominators: nominators
? Array.isArray(nominators)
? nominators[0].targets
: nominators.targets
: [],
rewardDestination,
stakingLedger: stakingLedgerOpt.unwrapOr(undefined),
stashId,
validatorPrefs: Array.isArray(validatorPrefs)
? validatorPrefs[0]
: validatorPrefs,
...parseSessionIds(stashId, queuedKeys, nextKeys)
}
: { accountId: stashId, nextSessionIds: [], sessionIds: [] };
}
function retrievePrev (api: ApiInterfaceRx, stashId: AccountId): Observable<MultiResult> {
return api.queryMulti<MultiResult>([
[api.query.staking.bonded, stashId],
@@ -38,64 +64,43 @@ function retrievePrev (api: ApiInterfaceRx, stashId: AccountId): Observable<Mult
]);
}
function retrieveCurr (api: ApiInterfaceRx, stashId: AccountId): Observable<MultiResult> {
return api.derive.session.indexes().pipe(
switchMap(({ activeEra }) =>
api.queryMulti<MultiResult>([
[api.query.staking.bonded, stashId],
[api.query.staking.nominators, stashId],
[api.query.staking.payee, stashId],
[api.query.staking.validators, stashId],
api.consts.session?.dedupKeyPrefix
? [api.query.session.nextKeys, [api.consts.session.dedupKeyPrefix, stashId]]
: [api.query.session.nextKeys, stashId],
[api.query.staking.erasStakers, [activeEra, stashId]]
])
function retrieveCurr (api: ApiInterfaceRx, stashIds: AccountId[], activeEra: EraIndex): Observable<MultiResult[]> {
return combineLatest([
api.query.staking.bonded.multi<Option<AccountId>>(stashIds),
api.query.staking.nominators.multi<Option<Nominations>>(stashIds),
api.query.staking.payee.multi<RewardDestination>(stashIds),
api.query.staking.validators.multi<ValidatorPrefs>(stashIds),
api.consts.session?.dedupKeyPrefix
? api.query.session.nextKeys.multi<Option<Keys>>(stashIds.map((stashId) => [api.consts.session.dedupKeyPrefix, stashId]))
: api.query.session.nextKeys.multi<Option<Keys>>(stashIds),
api.query.staking.erasStakers.multi<Exposure>(stashIds.map((stashId) => [activeEra, stashId]))
]).pipe(
map(([controllerIdOpt, nominatorsOpt, rewardDestination, validatorPrefs, nextKeys, exposure]): MultiResult[] =>
controllerIdOpt.map((controllerIdOpt, index): MultiResult =>
[controllerIdOpt, nominatorsOpt[index], rewardDestination[index], validatorPrefs[index], nextKeys[index], exposure[index]]
)
)
);
}
function retrieveController (api: ApiInterfaceRx, stashId: AccountId, queuedKeys: Vec<ITuple<[AccountId, Keys]>>, [controllerIdOpt, nominatorsOpt, rewardDestination, validatorPrefs, nextKeys, exposure]: MultiResult): Observable<DeriveStakingQuery> {
const controllerId = controllerIdOpt.unwrapOr(null);
const nominators = nominatorsOpt.unwrapOr(null);
function retrieveControllers (api: ApiInterfaceRx, optControllerIds: Option<AccountId>[]): Observable<Option<StakingLedger>[]> {
const ids = optControllerIds.filter((opt) => opt.isSome).map((opt) => opt.unwrap());
return controllerId
? api.query.staking.ledger(controllerId).pipe(
map((stakingLedgerOpt): DeriveStakingQuery => ({
accountId: stashId,
controllerId,
exposure,
nominators: nominators
? Array.isArray(nominators)
? nominators[0].targets
: nominators.targets
: [],
rewardDestination,
stakingLedger: stakingLedgerOpt.unwrapOr(undefined),
stashId,
validatorPrefs: Array.isArray(validatorPrefs)
? validatorPrefs[0]
: validatorPrefs,
...unwrapSessionIds(stashId, queuedKeys, nextKeys)
}))
)
: of({ accountId: stashId, nextSessionIds: [], sessionIds: [] });
}
if (!ids.length) {
return of(optControllerIds.map(() => api.registry.createType('Option<StakingLedger>')));
}
export function queryWithQueued (api: ApiInterfaceRx): (accountId: Uint8Array | string, queuedKeys: Vec<ITuple<[AccountId, Keys]>>) => Observable<DeriveStakingQuery> {
return memo((accountId: Uint8Array | string, queuedKeys: Vec<ITuple<[AccountId, Keys]>>): Observable<DeriveStakingQuery> => {
const stashId = api.registry.createType('AccountId', accountId);
return api.query.staking.ledger.multi<Option<StakingLedger>>(ids).pipe(
map((optLedgers): Option<StakingLedger>[] => {
let offset = -1;
return (
api.query.staking.erasStakers
? retrieveCurr(api, stashId)
: retrievePrev(api, stashId)
).pipe(
switchMap((result): Observable<DeriveStakingQuery> =>
retrieveController(api, stashId, queuedKeys, result)
)
);
});
return optControllerIds.map((opt): Option<StakingLedger> =>
opt.isSome
? optLedgers[++offset]
: api.registry.createType('Option<StakingLedger>')
);
})
);
}
/**
@@ -103,8 +108,8 @@ export function queryWithQueued (api: ApiInterfaceRx): (accountId: Uint8Array |
*/
export function query (api: ApiInterfaceRx): (accountId: Uint8Array | string) => Observable<DeriveStakingQuery> {
return memo((accountId: Uint8Array | string): Observable<DeriveStakingQuery> =>
api.query.session.queuedKeys<Vec<ITuple<[AccountId, Keys]>>>().pipe(
switchMap((queuedKeys) => api.derive.staking.queryWithQueued(accountId, queuedKeys))
api.derive.staking.queryMulti([accountId]).pipe(
map(([first]) => first)
)
);
}
@@ -112,10 +117,27 @@ export function query (api: ApiInterfaceRx): (accountId: Uint8Array | string) =>
export function queryMulti (api: ApiInterfaceRx): (accountIds: (Uint8Array | string)[]) => Observable<DeriveStakingQuery[]> {
return memo((accountIds: (Uint8Array | string)[]): Observable<DeriveStakingQuery[]> =>
accountIds.length
? api.query.session.queuedKeys<Vec<ITuple<[AccountId, Keys]>>>().pipe(
switchMap((queuedKeys) => combineLatest(
accountIds.map((acc) => api.derive.staking.queryWithQueued(acc, queuedKeys))
))
? combineLatest([
api.query.session.queuedKeys<Vec<ITuple<[AccountId, Keys]>>>(),
api.derive.session.indexes()
]).pipe(
switchMap(([queuedKeys, { activeEra }]): Observable<DeriveStakingQuery[]> => {
const stashIds = accountIds.map((accountId) => api.registry.createType('AccountId', accountId));
return (
isFunction(api.query.staking.erasStakers)
? retrieveCurr(api, stashIds, activeEra)
: combineLatest(stashIds.map((stashId) => retrievePrev(api, stashId)))
).pipe(
switchMap((results): Observable<DeriveStakingQuery[]> =>
retrieveControllers(api, results.map(([optController]) => optController)).pipe(
map((stakingLedgerOpts) =>
stashIds.map((stashId, index) => parseController(stashId, queuedKeys, results[index], stakingLedgerOpts[index]))
)
)
)
);
})
)
: of([])
);
@@ -11,11 +11,11 @@ import { map, switchMap } from 'rxjs/operators';
import { memo } from '../util';
export function _stakerExposure (api: ApiInterfaceRx): (accountId: Uint8Array | string, eras: EraIndex[]) => Observable<DeriveStakerExposure[]> {
return memo((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[], withActive: boolean): Observable<DeriveStakerExposure[]> => {
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[] =>
exposures.map(({ era, nominators: allNominators, validators: allValidators }): DeriveStakerExposure => {
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[]> {
return memo((accountId: Uint8Array | string, withActive?: boolean): Observable<DeriveStakerExposure[]> =>
return memo((accountId: Uint8Array | string, withActive = false): Observable<DeriveStakerExposure[]> =>
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';
export function _stakerPoints (api: ApiInterfaceRx): (accountId: Uint8Array | string, eras: EraIndex[]) => Observable<DeriveStakerPoints[]> {
return memo((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[], withActive: boolean): Observable<DeriveStakerPoints[]> => {
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[] =>
points.map(({ era, eraPoints, validators }): DeriveStakerPoints => ({
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[]> {
return memo((accountId: Uint8Array | string, withActive?: boolean): Observable<DeriveStakerPoints[]> =>
return memo((accountId: Uint8Array | string, withActive = false): Observable<DeriveStakerPoints[]> =>
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 { map, switchMap } from 'rxjs/operators';
import { Option } from '@polkadot/types';
import { isFunction } from '@polkadot/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 MIN_ONE = new BN(-1);
const COMM_DIV = 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 => {
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') };
@@ -31,25 +32,27 @@ function parseRewards (api: ApiInterfaceRx, stashId: AccountId, [erasPoints, era
Object.entries(eraValidators).forEach(([validatorId, exposure]): void => {
const valPoints = allValPoints[validatorId] || ZERO;
const valComm = allValPrefs[validatorId]?.commission.unwrap() || ZERO;
const avail = eraReward.mul(valPoints).div(eraPoints);
const valCut = valComm.mul(avail).div(COMM_DIV);
const expTotal = exposure.total.unwrap();
let avail = ZERO;
let value: BN | undefined;
if (!expTotal.isZero() && !valPoints.isZero()) {
if (!(expTotal.isZero() || valPoints.isZero() || eraPoints.isZero())) {
avail = eraReward.mul(valPoints).div(eraPoints);
const valCut = valComm.mul(avail).div(COMM_DIV);
let staked: BN;
if (validatorId === stakerId) {
staked = exposure.own.unwrap();
} else {
const stakerExp = exposure.others.find(({ who }): boolean => who.eq(stakerId));
const stakerExp = exposure.others.find(({ who }) => who.eq(stakerId));
staked = stakerExp
? stakerExp.value.unwrap()
: ZERO;
}
value = avail.sub(valCut).mul(staked).div(expTotal).add(validatorId === stakerId ? valCut : ZERO);
value = avail.sub(valCut).imul(staked).div(expTotal).iadd(validatorId === stakerId ? valCut : ZERO);
}
validators[validatorId] = {
@@ -97,28 +100,29 @@ function filterEras (eras: EraIndex[], stakingLedger: StakingLedger): EraIndex[]
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) {
return of(rewards);
}
const validators = uniqValidators(rewards);
return combineLatest([
api.query.staking.migrateEra
? api.query.staking.migrateEra<Option<EraIndex>>()
: of({ unwrapOr: () => api.tx.staking.payoutStakers ? MIN_ONE : MAX_ERAS }),
api.tx.staking.payoutStakers
return (
isFunction(api.tx.staking.payoutStakers)
? api.derive.staking.queryMulti(validators)
: of([])
]).pipe(
map(([optMigrate, queryValidators]): DeriveStakerReward[] => {
const migrateEra: BN = optMigrate.unwrapOr(MIN_ONE);
).pipe(
map((queryValidators): DeriveStakerReward[] => {
const filter = withActive
? eras
: filterEras(eras, stakingLedger);
return rewards
.filter(({ isEmpty }) => !isEmpty)
.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
return filterEra(reward.era, stakingLedger);
}
@@ -154,49 +158,59 @@ function filterRewards (api: ApiInterfaceRx, rewards: DeriveStakerReward[], stak
);
}
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[]> =>
api.derive.staking.query(accountId).pipe(
switchMap(({ stakingLedger, stashId }): Observable<DeriveStakerReward[]> => {
export function _stakerRewardsEras (api: ApiInterfaceRx): (eras: EraIndex[], withActive: boolean) => Observable<ErasResult> {
return memo((eras: EraIndex[], withActive: boolean): Observable<ErasResult> =>
combineLatest([
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) {
return of([]);
}
const eras = 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)
)
);
return filterRewards(api, eras, migrateEra, parseRewards(api, stashId, erasResult, exposures), stakingLedger, withActive);
})
)
);
}
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(
switchMap((eras) => api.derive.staking._stakerRewards(accountId, eras, withActive))
)
);
}
export function stakerRewardsMulti (api: ApiInterfaceRx): (accountIds: (Uint8Array | string)[], withActive?: boolean) => Observable<DeriveStakerReward[][]> {
return memo((accountIds: (Uint8Array | string)[], withActive?: boolean): Observable<DeriveStakerReward[][]> =>
accountIds.length
? api.derive.staking.erasHistoric(withActive).pipe(
switchMap((eras) =>
combineLatest(accountIds.map((acc) => api.derive.staking._stakerRewards(acc, eras, withActive)))
)
)
export function stakerRewardsMultiEras (api: ApiInterfaceRx): (accountIds: (Uint8Array | string)[], eras: EraIndex[]) => Observable<DeriveStakerReward[][]> {
return memo((accountIds: (Uint8Array | string)[], eras: EraIndex[]): Observable<DeriveStakerReward[][]> =>
accountIds.length && eras.length
? combineLatest(accountIds.map((acc) => api.derive.staking._stakerRewards(acc, eras, false)))
: of([])
);
}
export function stakerRewardsMulti (api: ApiInterfaceRx): (accountIds: (Uint8Array | string)[], withActive?: boolean) => Observable<DeriveStakerReward[][]> {
return memo((accountIds: (Uint8Array | string)[], withActive = false): Observable<DeriveStakerReward[][]> =>
api.derive.staking.erasHistoric(withActive).pipe(
switchMap((eras) => api.derive.staking.stakerRewardsMultiEras(accountIds, eras))
)
);
}
@@ -11,11 +11,11 @@ import { map, switchMap } from 'rxjs/operators';
import { memo } from '../util';
export function _stakerSlashes (api: ApiInterfaceRx): (accountId: Uint8Array | string, eras: EraIndex[]) => Observable<DeriveStakerSlashes[]> {
return memo((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[], withActive: boolean): Observable<DeriveStakerSlashes[]> => {
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[] =>
slashes.map(({ era, nominators, validators }): DeriveStakerSlashes => ({
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[]> {
return memo((accountId: Uint8Array | string, withActive?: boolean): Observable<DeriveStakerSlashes[]> =>
return memo((accountId: Uint8Array | string, withActive = false): Observable<DeriveStakerSlashes[]> =>
api.derive.staking.erasHistoric(withActive).pipe(
switchMap((eras) => api.derive.staking._stakerSlashes(accountId, eras))
switchMap((eras) => api.derive.staking._stakerSlashes(accountId, eras, withActive))
)
);
}
+6 -2
View File
@@ -2,11 +2,10 @@
// This software may be modified and distributed under the terms
// 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 { DeriveSessionIndexes } from '../session/types';
import BN from 'bn.js';
export type DeriveEraValPoints = Record<string, RewardPoint>;
export type DeriveEraValPrefs = Record<string, ValidatorPrefs>;
@@ -97,6 +96,11 @@ export interface DeriveStakingElected {
info: DeriveStakingQuery[];
}
export interface DeriveStakingWaiting {
info: DeriveStakingQuery[];
waiting: AccountId[];
}
export interface DeriveStakingValidators {
nextElected: AccountId[];
validators: AccountId[];
@@ -18,9 +18,7 @@ export function nextElected (api: ApiInterfaceRx): () => Observable<AccountId[]>
// only populate for next era in the last session, so track both here - entries are not
// subscriptions, so we need a trigger - currentIndex acts as that trigger to refresh
switchMap(({ currentEra }) => api.query.staking.erasStakers.keys(currentEra)),
map((keys): AccountId[] =>
keys.map((key): AccountId => key.args[1] as AccountId)
)
map((keys) => keys.map((key) => key.args[1] as AccountId))
)
: api.query.staking.currentElected<AccountId[]>()
);
@@ -0,0 +1,32 @@
// 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 { ApiInterfaceRx } from '@polkadot/api/types';
import { DeriveStakingWaiting } from '../types';
import { Observable, combineLatest } from 'rxjs';
import { map, switchMap } from 'rxjs/operators';
import { memo } from '../util';
export function waitingInfo (api: ApiInterfaceRx): () => Observable<DeriveStakingWaiting> {
return memo((): Observable<DeriveStakingWaiting> =>
combineLatest([
api.derive.staking.validators(),
api.derive.staking.stashes()
]).pipe(
switchMap(([{ nextElected }, stashes]): Observable<DeriveStakingWaiting> => {
const elected = nextElected.map((a) => a.toString());
const waiting = stashes.filter((v) => !elected.includes(v.toString()));
return api.derive.staking.queryMulti(waiting).pipe(
map((info): DeriveStakingWaiting => ({
info,
waiting
}))
);
})
)
);
}
+7
View File
@@ -4,4 +4,11 @@
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 MORTAL_PERIOD = new BN(5 * 60 * 1000);
+5 -9
View File
@@ -5,26 +5,22 @@
import { Header, Index } from '@polkadot/types/interfaces';
import { AnyNumber, Codec, IExtrinsicEra } from '@polkadot/types/types';
import BN from 'bn.js';
import { Observable, combineLatest, of } from 'rxjs';
import { map, switchMap } from 'rxjs/operators';
import { ApiInterfaceRx } from '@polkadot/api/types';
import { isNumber, isUndefined } from '@polkadot/util';
import { FALLBACK_PERIOD, MAX_FINALITY_LAG, MORTAL_PERIOD } from './constants';
interface Result {
header: Header | null;
mortalLength: number;
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> {
return api.derive.balances.account(address).pipe(
map(({ accountNonce }): Index => accountNonce)
map(({ accountNonce }) => accountNonce)
);
}
@@ -35,7 +31,7 @@ function signingHeader (api: ApiInterfaceRx): Observable<Header> {
switchMap((hash) => api.rpc.chain.getHeader(hash))
)
]).pipe(
map(([current, finalized]): Header =>
map(([current, finalized]) =>
// determine the hash to use, current when lag > max, else finalized
current.number.unwrap().sub(finalized.number.unwrap()).gt(MAX_FINALITY_LAG)
? current
@@ -61,7 +57,7 @@ export function signingInfo (api: ApiInterfaceRx): (address: string, nonce?: Any
header,
mortalLength: MORTAL_PERIOD
.div(api.consts.babe?.expectedBlockTime || api.consts.timestamp?.minimumPeriod.muln(2) || FALLBACK_PERIOD)
.add(MAX_FINALITY_LAG)
.iadd(MAX_FINALITY_LAG)
.toNumber(),
nonce
}))
@@ -9,7 +9,7 @@ import runtimeTypes from '@polkadot/types/interfaces/runtime/definitions';
import { Struct } from '@polkadot/types';
// 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
@@ -26,7 +26,7 @@ export default class HeaderExtended extends _Header {
}
private _extractAuthor (sessionValidators: AccountId[] = []): AccountId | undefined {
const [pitem] = this.digest.logsWith('PreRuntime');
const [pitem] = this.digest.logs.filter(({ type }) => type === 'PreRuntime');
// extract from the substrate 2.0 PreRuntime digest
if (pitem) {
@@ -34,7 +34,7 @@ export default class HeaderExtended extends _Header {
return engine.extractAuthor(data, sessionValidators);
} else {
const [citem] = this.digest.logsWith('Consensus');
const [citem] = this.digest.logs.filter(({ type }) => type === 'Consensus');
// extract author from the consensus (substrate 1.0, digest)
if (citem) {
+6 -33
View File
@@ -2,48 +2,18 @@
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { AccountId, AccountIndex, Balance, BalanceLock, BalanceLockTo212, BalanceOf, Bid, BidKind, BlockNumber, Hash, Index, Proposal, ProposalIndex, RegistrationJudgement, SetIndex, SocietyVote, StrikeCount, TreasuryProposal, Votes, VoteIndex, VouchingStatus } from '@polkadot/types/interfaces';
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 BN from 'bn.js';
import { u32 } from '@polkadot/types';
export * from './accounts/types';
export * from './council/types';
export * from './democracy/types';
export * from './parachains/types';
export * from './session/types';
export * from './staking/types';
export type AccountIndexes = Record<string, AccountIndex>;
export interface DeriveAccountRegistration {
display?: string;
displayParent?: string;
email?: string;
image?: string;
legal?: string;
other?: Record<string, string>;
parent?: AccountId;
pgp?: string;
riot?: string;
twitter?: string;
web?: string;
judgements: RegistrationJudgement[];
}
export interface DeriveAccountFlags {
isCouncil: boolean;
isSociety: boolean;
isSudo: boolean;
isTechCommittee: boolean;
}
export interface DeriveAccountInfo extends DeriveAccountFlags {
accountId?: AccountId;
accountIndex?: AccountIndex;
identity: DeriveAccountRegistration;
nickname?: string;
}
export interface DeriveBalancesAccount {
accountId: AccountId;
accountNonce: Index;
@@ -61,6 +31,8 @@ export interface DeriveBalancesAll extends DeriveBalancesAccount {
availableBalance: Balance;
votingBalance: Balance;
vestedBalance: Balance;
vestedClaimable: Balance;
vestingLocked: Balance;
vestingTotal: Balance;
}
@@ -72,6 +44,7 @@ export interface DeriveContractFees {
creationFee: BN;
rentByteFee: BN;
rentDepositOffset: BN;
surchargeReward: BN;
tombstoneDeposit: BN;
transactionBaseFee: BN;
transactionByteFee: BN;
+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';
export * from './approvalFlagsToBools';
export * from './cache';
export * from './cacheImpl';
export * from './memo';
export { drr };
+9 -9
View File
@@ -3,15 +3,11 @@
// of the Apache-2.0 license. See the LICENSE file for details.v
import createMemo from 'memoizee';
import { Observable, Observer } from 'rxjs';
import { Observable, Observer, TeardownLogic } from 'rxjs';
import { drr } from '@polkadot/rpc-core/rxjs';
type ObsFn <T> = (...params: any[]) => Observable<T>;
// Normalize via JSON.stringify, allow e.g. AccountId -> ss58
// eslint-disable-next-line @typescript-eslint/unbound-method
const normalizer = JSON.stringify;
// Wraps a derive, doing 2 things to optimize calls -
// 1. creates a memo of the inner fn -> Observable, removing when unsubscribed
// 2. wraps the observable in a drr() (which includes an unsub delay)
@@ -19,15 +15,19 @@ const normalizer = JSON.stringify;
export function memo <T> (inner: ObsFn<T>): ObsFn<T> {
const cached = createMemo(
(...params: any[]): Observable<T> =>
new Observable((observer: Observer<T>): VoidCallback => {
const sub = inner(...params).subscribe(observer);
new Observable((observer: Observer<T>): TeardownLogic => {
const subscription = inner(...params).subscribe(observer);
return (): void => {
cached.delete(...params);
sub.unsubscribe();
subscription.unsubscribe();
};
}).pipe(drr()),
{ normalizer }
{
// Normalize via JSON.stringify, allow e.g. AccountId -> ss58
// eslint-disable-next-line @typescript-eslint/unbound-method
normalizer: JSON.stringify
}
);
return cached;
+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 -
- [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
- [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.
+15 -15
View File
@@ -1,6 +1,6 @@
{
"name": "@polkadot/api",
"version": "1.10.1",
"version": "1.24.1",
"description": "Promise and RxJS wrappers around the Polkadot JS RPC",
"main": "index.js",
"keywords": [
@@ -26,21 +26,21 @@
},
"homepage": "https://github.com/polkadot-js/api/tree/master/packages/api#readme",
"dependencies": {
"@babel/runtime": "^7.9.2",
"@polkadot/api-derive": "1.10.1",
"@polkadot/keyring": "^2.8.1",
"@polkadot/metadata": "1.10.1",
"@polkadot/rpc-core": "1.10.1",
"@polkadot/rpc-provider": "1.10.1",
"@polkadot/types": "1.10.1",
"@polkadot/types-known": "1.10.1",
"@polkadot/util": "^2.8.1",
"@polkadot/util-crypto": "^2.8.1",
"bn.js": "^5.1.1",
"eventemitter3": "^4.0.0",
"rxjs": "^6.5.5"
"@babel/runtime": "^7.10.4",
"@polkadot/api-derive": "1.24.1",
"@polkadot/keyring": "^2.18.1",
"@polkadot/metadata": "1.24.1",
"@polkadot/rpc-core": "1.24.1",
"@polkadot/rpc-provider": "1.24.1",
"@polkadot/types": "1.24.1",
"@polkadot/types-known": "1.24.1",
"@polkadot/util": "^2.18.1",
"@polkadot/util-crypto": "^2.18.1",
"bn.js": "^5.1.2",
"eventemitter3": "^4.0.4",
"rxjs": "^6.6.0"
},
"devDependencies": {
"@polkadot/keyring": "^2.8.1"
"@polkadot/keyring": "^2.18.1"
}
}
+157 -37
View File
@@ -2,11 +2,12 @@
/* eslint-disable */
import { Codec } from '@polkadot/types/types';
import { u32, u64 } from '@polkadot/types/primitive';
import { Gas } from '@polkadot/types/interfaces/contracts';
import { Balance, BalanceOf, BlockNumber, Moment, Percent, Permill } from '@polkadot/types/interfaces/runtime';
import { Vec } from '@polkadot/types/codec';
import { u16, u32, u64 } from '@polkadot/types/primitive';
import { Balance, BalanceOf, BlockNumber, LockIdentifier, ModuleId, Moment, Perbill, Percent, Permill, RuntimeDbWeight, Weight } from '@polkadot/types/interfaces/runtime';
import { SessionIndex } from '@polkadot/types/interfaces/session';
import { EraIndex } from '@polkadot/types/interfaces/staking';
import { WeightToFeeCoefficient } from '@polkadot/types/interfaces/support';
declare module '@polkadot/metadata/Decorated/consts/types' {
export interface Constants {
@@ -36,26 +37,6 @@ declare module '@polkadot/metadata/Decorated/consts/types' {
};
contracts: {
[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
* 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 cost of one byte.
*
* 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.
* But if the balance reduced to 500,000 BU and the storage stayed the same at 1,000,
@@ -80,13 +62,18 @@ declare module '@polkadot/metadata/Decorated/consts/types' {
rentDepositOffset: AugmentedConst<BalanceOf>;
/**
* Number of block delay an extrinsic claim surcharge has.
*
* When claim surcharge is called by an extrinsic the rent is checked
* for current_block - delay
**/
signedClaimHandicap: AugmentedConst<BlockNumber>;
/**
* Size of a contract at the time of instantiation. This is a simple way to ensure that
* empty contracts eventually gets deleted.
* A size offset for an contract. A just created account with untouched storage will have that
* much of storage from the perspective of the state rent.
*
* This is a simple way to ensure that contracts with empty storage eventually get deleted
* by making them pay rent. This creates an incentive to remove them early in order to save
* rent.
**/
storageSizeOffset: AugmentedConst<u32>;
/**
@@ -98,14 +85,6 @@ declare module '@polkadot/metadata/Decorated/consts/types' {
* The minimum amount required to generate a tombstone.
**/
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: {
[index: string]: AugmentedConst<object & Codec>;
@@ -115,6 +94,7 @@ declare module '@polkadot/metadata/Decorated/consts/types' {
cooloffPeriod: AugmentedConst<BlockNumber>;
/**
* 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
* voting stakers have an opportunity to remove themselves from the system in the case where
* they are on the losing side of a vote.
@@ -128,6 +108,10 @@ declare module '@polkadot/metadata/Decorated/consts/types' {
* How often (in blocks) new public referenda are launched.
**/
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.
**/
@@ -146,6 +130,7 @@ declare module '@polkadot/metadata/Decorated/consts/types' {
candidacyBond: AugmentedConst<BalanceOf>;
desiredMembers: AugmentedConst<u32>;
desiredRunnersUp: AugmentedConst<u32>;
moduleId: AugmentedConst<LockIdentifier>;
termDuration: AugmentedConst<BlockNumber>;
votingBond: AugmentedConst<BalanceOf>;
};
@@ -160,6 +145,71 @@ declare module '@polkadot/metadata/Decorated/consts/types' {
**/
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>;
};
proxy: {
[index: string]: AugmentedConst<object & Codec>;
/**
* The maximum amount of proxies allowed for a single account.
**/
maxProxies: AugmentedConst<u16>;
/**
* The base amount of currency needed to reserve for creating a proxy.
**/
proxyDepositBase: AugmentedConst<BalanceOf>;
/**
* The amount of currency needed per proxy added.
**/
proxyDepositFactor: AugmentedConst<BalanceOf>;
};
recovery: {
[index: string]: AugmentedConst<object & Codec>;
/**
* The base amount of currency needed to reserve for creating a recovery configuration.
**/
configDepositBase: AugmentedConst<BalanceOf>;
/**
* The amount of currency needed per additional user when creating a recovery configuration.
**/
friendDepositFactor: AugmentedConst<BalanceOf>;
/**
* The maximum amount of friends allowed in a recovery configuration.
**/
maxFriends: AugmentedConst<u16>;
/**
* The base amount of currency needed to reserve for starting a recovery.
**/
recoveryDeposit: AugmentedConst<BalanceOf>;
};
society: {
[index: string]: AugmentedConst<object & Codec>;
/**
@@ -175,6 +225,10 @@ declare module '@polkadot/metadata/Decorated/consts/types' {
* before they become suspended.
**/
maxStrikes: AugmentedConst<u32>;
/**
* The societies's module id
**/
moduleId: AugmentedConst<ModuleId>;
/**
* The amount of incentive paid within each period. Doesn't include VoterTip.
**/
@@ -195,10 +249,72 @@ declare module '@polkadot/metadata/Decorated/consts/types' {
* Number of eras that staked funds must remain bonded for.
**/
bondingDuration: AugmentedConst<EraIndex>;
/**
* The number of blocks before the end of the era from which election submissions are allowed.
*
* Setting this to zero will disable the offchain compute and only on-chain seq-phragmen will
* be used.
*
* This is bounded by being within the last session. Hence, setting it to a value more than the
* length of a session will be pointless.
**/
electionLookahead: AugmentedConst<BlockNumber>;
/**
* Maximum number of balancing iterations to run in the offchain submission.
*
* If set to 0, balance_solution will not be executed at all.
**/
maxIterations: AugmentedConst<u32>;
/**
* The maximum number of nominators rewarded for each validator.
*
* For each validator only the `$MaxNominatorRewardedPerValidator` biggest stakers can claim
* their reward. This used to limit the i/o cost for the nominator payout.
**/
maxNominatorRewardedPerValidator: AugmentedConst<u32>;
/**
* The threshold of improvement that should be provided for a new solution to be accepted.
**/
minSolutionScoreBump: AugmentedConst<Perbill>;
/**
* Number of sessions per era.
**/
sessionsPerEra: AugmentedConst<SessionIndex>;
/**
* Number of eras that slashes are deferred by, after computation.
*
* This should be less than the bonding duration.
* Set to 0 if slashes should be applied immediately, without opportunity for
* intervention.
**/
slashDeferDuration: AugmentedConst<EraIndex>;
};
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: {
[index: string]: AugmentedConst<object & Codec>;
@@ -212,14 +328,14 @@ declare module '@polkadot/metadata/Decorated/consts/types' {
};
transactionPayment: {
[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.
**/
transactionByteFee: AugmentedConst<BalanceOf>;
/**
* The polynomial that is applied in order to derive fee from weight.
**/
weightToFee: AugmentedConst<Vec<WeightToFeeCoefficient>>;
};
treasury: {
[index: string]: AugmentedConst<object & Codec>;
@@ -227,6 +343,10 @@ declare module '@polkadot/metadata/Decorated/consts/types' {
* Percentage of spare funds (if any) that are burnt per spend period.
**/
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.
* An accepted proposal gets these back. A rejected proposal does not.
+102 -49
View File
@@ -1,33 +1,32 @@
// Auto-generated via `yarn polkadot-types-from-chain`, do not edit
/* eslint-disable */
import { AnyNumber, ITuple } from '@polkadot/types/types';
import { AnyNumber, ITuple, Observable } from '@polkadot/types/types';
import { Option, U8aFixed, Vec } from '@polkadot/types/codec';
import { Bytes, Data, bool, u32, u64 } from '@polkadot/types/primitive';
import { UncleEntryItem } from '@polkadot/types/interfaces/authorship';
import { BabeAuthorityWeight, MaybeVrf, Randomness } from '@polkadot/types/interfaces/babe';
import { AccountData, BalanceLock, ReleasesBalances } from '@polkadot/types/interfaces/balances';
import { BabeAuthorityWeight, MaybeRandomness, NextConfigDescriptor, Randomness } from '@polkadot/types/interfaces/babe';
import { AccountData, BalanceLock } from '@polkadot/types/interfaces/balances';
import { ProposalIndex, Votes } from '@polkadot/types/interfaces/collective';
import { AuthorityId, RawVRFOutput } from '@polkadot/types/interfaces/consensus';
import { CodeHash, ContractInfo, Gas, PrefabWasmModule, Schedule } from '@polkadot/types/interfaces/contracts';
import { PreimageStatus, PropIndex, Proposal, ProxyState, ReferendumIndex, ReferendumInfo, Voting } from '@polkadot/types/interfaces/democracy';
import { AuthorityId } from '@polkadot/types/interfaces/consensus';
import { CodeHash, ContractInfo, PrefabWasmModule, Schedule } from '@polkadot/types/interfaces/contracts';
import { PreimageStatus, PropIndex, Proposal, ReferendumIndex, ReferendumInfo, Voting } from '@polkadot/types/interfaces/democracy';
import { VoteThreshold } from '@polkadot/types/interfaces/elections';
import { SetId, StoredPendingChange, StoredState } from '@polkadot/types/interfaces/grandpa';
import { RegistrarInfo, Registration } from '@polkadot/types/interfaces/identity';
import { AuthIndex } from '@polkadot/types/interfaces/imOnline';
import { DeferredOffenceOf, Kind, OffenceDetails, OpaqueTimeSlot, ReportIdOf } from '@polkadot/types/interfaces/offences';
import { 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, ProxyType, Releases, ValidatorId } from '@polkadot/types/interfaces/runtime';
import { Scheduled, TaskAddress } from '@polkadot/types/interfaces/scheduler';
import { Keys, SessionIndex } from '@polkadot/types/interfaces/session';
import { Bid, BidKind, SocietyVote, StrikeCount, VouchingStatus } from '@polkadot/types/interfaces/society';
import { ActiveEraInfo, ElectionResult, ElectionStatus, EraIndex, EraRewardPoints, Exposure, Forcing, Nominations, PhragmenScore, ReleasesStaking, RewardDestination, SlashingSpans, SpanIndex, SpanRecord, StakingLedger, UnappliedSlash, ValidatorPrefs } from '@polkadot/types/interfaces/staking';
import { ActiveEraInfo, ElectionResult, ElectionScore, ElectionStatus, EraIndex, EraRewardPoints, Exposure, Forcing, Nominations, RewardDestination, SlashingSpans, SpanIndex, SpanRecord, StakingLedger, UnappliedSlash, ValidatorPrefs } from '@polkadot/types/interfaces/staking';
import { AccountInfo, DigestOf, EventIndex, EventRecord, LastRuntimeUpgradeInfo, Phase } from '@polkadot/types/interfaces/system';
import { OpenTip, TreasuryProposal } from '@polkadot/types/interfaces/treasury';
import { Multiplier } from '@polkadot/types/interfaces/txpayment';
import { Multisig } from '@polkadot/types/interfaces/utility';
import { VestingInfo } from '@polkadot/types/interfaces/vesting';
import { Observable } from 'rxjs';
import { ApiTypes } from '@polkadot/api/types';
declare module '@polkadot/api/types/storage' {
@@ -70,21 +69,28 @@ declare module '@polkadot/api/types/storage' {
* Temporary value (cleared at block finalization) which is `Some`
* 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.
*
* This entry is populated as part of block execution and is cleaned up
* on block finalization. Querying this storage entry outside of block
* execution context should always yield zero.
**/
lateness: AugmentedQuery<ApiType, () => Observable<BlockNumber>> & QueryableStorageEntry<ApiType>;
/**
* Next epoch configuration, if changed.
**/
nextEpochConfig: AugmentedQuery<ApiType, () => Observable<Option<NextConfigDescriptor>>> & QueryableStorageEntry<ApiType>;
/**
* Next epoch randomness.
**/
nextRandomness: AugmentedQuery<ApiType, () => Observable<Randomness>> & QueryableStorageEntry<ApiType>;
/**
* The epoch randomness for the *current* epoch.
*
* # Security
*
* 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
* cryptographic protocols, however, so long as one remembers that this
@@ -95,22 +101,26 @@ declare module '@polkadot/api/types/storage' {
randomness: AugmentedQuery<ApiType, () => Observable<Randomness>> & QueryableStorageEntry<ApiType>;
/**
* Randomness under construction.
*
* We make a tradeoff between storage accesses and list length.
* We store the under-construction randomness in segments of up to
* `UNDER_CONSTRUCTION_SEGMENT_LENGTH`.
*
* Once a segment reaches this length, we begin the next one.
* We reset all segments and return to `0` at the beginning of every
* epoch.
**/
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: {
[index: string]: QueryableStorageEntry<ApiType>;
/**
* The balance of an account.
* 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.
*
* 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>;
@@ -121,9 +131,10 @@ declare module '@polkadot/api/types/storage' {
locks: AugmentedQuery<ApiType, (arg: AccountId | string | Uint8Array) => Observable<Vec<BalanceLock>>> & QueryableStorageEntry<ApiType>;
/**
* Storage version of the pallet.
*
* This is set to v2.0.0 for new networks.
**/
storageVersion: AugmentedQuery<ApiType, () => Observable<ReleasesBalances>> & QueryableStorageEntry<ApiType>;
storageVersion: AugmentedQuery<ApiType, () => Observable<Releases>> & QueryableStorageEntry<ApiType>;
/**
* The total units issued in the system.
**/
@@ -141,20 +152,14 @@ declare module '@polkadot/api/types/storage' {
codeStorage: AugmentedQuery<ApiType, (arg: CodeHash | string | Uint8Array) => Observable<Option<PrefabWasmModule>>> & QueryableStorageEntry<ApiType>;
/**
* 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>;
/**
* Current cost schedule for contracts.
**/
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.
**/
@@ -201,8 +206,10 @@ declare module '@polkadot/api/types/storage' {
cancellations: AugmentedQuery<ApiType, (arg: Hash | string | Uint8Array) => Observable<bool>> & QueryableStorageEntry<ApiType>;
/**
* 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
* proposal.
@@ -211,6 +218,8 @@ declare module '@polkadot/api/types/storage' {
/**
* 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.
*
* TWOX-NOTE: OK `AccountId` is a secure hash.
**/
locks: AugmentedQuery<ApiType, (arg: AccountId | string | Uint8Array) => Observable<Option<BlockNumber>>> & QueryableStorageEntry<ApiType>;
/**
@@ -230,11 +239,6 @@ declare module '@polkadot/api/types/storage' {
* The block number is the block at which it was deposited.
**/
preimages: AugmentedQuery<ApiType, (arg: Hash | string | Uint8Array) => Observable<Option<PreimageStatus>>> & QueryableStorageEntry<ApiType>;
/**
* Who is able to vote for whom. Value is the fund-holding account, key is the
* vote-transaction-sending account.
**/
proxy: AugmentedQuery<ApiType, (arg: AccountId | string | Uint8Array) => Observable<Option<ProxyState>>> & QueryableStorageEntry<ApiType>;
/**
* The number of (public) proposals that have been made so far.
**/
@@ -249,11 +253,21 @@ declare module '@polkadot/api/types/storage' {
referendumCount: AugmentedQuery<ApiType, () => Observable<ReferendumIndex>> & QueryableStorageEntry<ApiType>;
/**
* Information concerning any given referendum.
*
* TWOX-NOTE: SAFE as indexes are not under an attackers control.
**/
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<Releases>>> & QueryableStorageEntry<ApiType>;
/**
* 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.
*
* TWOX-NOTE: SAFE as `AccountId`s are crypto hashes anyway.
**/
votingOf: AugmentedQuery<ApiType, (arg: AccountId | string | Uint8Array) => Observable<Voting>> & QueryableStorageEntry<ApiType>;
};
@@ -278,6 +292,8 @@ declare module '@polkadot/api/types/storage' {
runnersUp: AugmentedQuery<ApiType, () => Observable<Vec<ITuple<[AccountId, BalanceOf]>>>> & QueryableStorageEntry<ApiType>;
/**
* 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>;
};
@@ -299,6 +315,8 @@ declare module '@polkadot/api/types/storage' {
/**
* A mapping from grandpa set ID to the index of the *most recent* session for which its
* members were responsible.
*
* TWOX-NOTE: `SetId` is not under user control.
**/
setIdSession: AugmentedQuery<ApiType, (arg: SetId | AnyNumber | Uint8Array) => Observable<Option<SessionIndex>>> & QueryableStorageEntry<ApiType>;
/**
@@ -314,17 +332,23 @@ declare module '@polkadot/api/types/storage' {
[index: string]: QueryableStorageEntry<ApiType>;
/**
* 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>;
/**
* The set of registrars. Not expected to get very big as can only be added through a
* special origin (likely a council motion).
*
* The index into this can be cast to `RegistrarIndex` to get a valid value.
**/
registrars: AugmentedQuery<ApiType, () => Observable<Vec<Option<RegistrarInfo>>>> & QueryableStorageEntry<ApiType>;
/**
* Alternative "sub" identities of this account.
*
* 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>;
/**
@@ -342,6 +366,7 @@ declare module '@polkadot/api/types/storage' {
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.
*
* At the beginning of each session we set this to a value that should
* fall roughly in the middle of the session duration.
* The idea is to first wait for the validators to produce a block
@@ -363,7 +388,15 @@ declare module '@polkadot/api/types/storage' {
/**
* The lookup from index to account.
**/
accounts: AugmentedQuery<ApiType, (arg: AccountIndex | AnyNumber | Uint8Array) => Observable<Option<ITuple<[AccountId, BalanceOf]>>>> & QueryableStorageEntry<ApiType>;
accounts: AugmentedQuery<ApiType, (arg: AccountIndex | AnyNumber | Uint8Array) => Observable<Option<ITuple<[AccountId, BalanceOf, bool]>>>> & QueryableStorageEntry<ApiType>;
};
multisig: {
[index: string]: QueryableStorageEntry<ApiType>;
calls: AugmentedQuery<ApiType, (arg: U8aFixed | string | Uint8Array) => Observable<Option<ITuple<[Bytes, AccountId, BalanceOf]>>>> & QueryableStorageEntry<ApiType>;
/**
* The set of open multisig operations.
**/
multisigs: AugmentedQueryDoubleMap<ApiType, (key1: AccountId | string | Uint8Array, key2: U8aFixed | string | Uint8Array) => Observable<Option<Multisig>>> & QueryableStorageEntry<ApiType>;
};
offences: {
[index: string]: QueryableStorageEntry<ApiType>;
@@ -382,12 +415,22 @@ declare module '@polkadot/api/types/storage' {
reports: AugmentedQuery<ApiType, (arg: ReportIdOf | string | Uint8Array) => Observable<Option<OffenceDetails>>> & QueryableStorageEntry<ApiType>;
/**
* Enumerates all reports of a kind along with the time they happened.
*
* 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
* different types are not supported at the moment so we are doing the manual serialization.
**/
reportsByKindIndex: AugmentedQuery<ApiType, (arg: Kind | string | Uint8Array) => Observable<Bytes>> & QueryableStorageEntry<ApiType>;
};
proxy: {
[index: string]: QueryableStorageEntry<ApiType>;
/**
* The set of account proxies. Maps the account which has delegated to the accounts
* which are being delegated to, together with the amount held on deposit.
**/
proxies: AugmentedQuery<ApiType, (arg: AccountId | string | Uint8Array) => Observable<ITuple<[Vec<ITuple<[AccountId, ProxyType]>>, BalanceOf]>>> & QueryableStorageEntry<ApiType>;
};
randomnessCollectiveFlip: {
[index: string]: QueryableStorageEntry<ApiType>;
/**
@@ -401,12 +444,14 @@ declare module '@polkadot/api/types/storage' {
[index: string]: QueryableStorageEntry<ApiType>;
/**
* Active recovery attempts.
*
* First account is the account to be recovered, and the second 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>;
/**
* The list of allowed proxy accounts.
*
* Map from the user who can access it to the recovered account.
**/
proxy: AugmentedQuery<ApiType, (arg: AccountId | string | Uint8Array) => Observable<Option<AccountId>>> & QueryableStorageEntry<ApiType>;
@@ -434,6 +479,7 @@ declare module '@polkadot/api/types/storage' {
currentIndex: AugmentedQuery<ApiType, () => Observable<SessionIndex>> & QueryableStorageEntry<ApiType>;
/**
* Indices of disabled validators.
*
* The set is cleared when `on_session_ending` returns a new set of identities.
**/
disabledValidators: AugmentedQuery<ApiType, () => Observable<Vec<u32>>> & QueryableStorageEntry<ApiType>;
@@ -532,6 +578,7 @@ declare module '@polkadot/api/types/storage' {
[index: string]: QueryableStorageEntry<ApiType>;
/**
* The active era information, it holds index and start.
*
* The active era is the era currently rewarded.
* Validator set of this era must be equal to `SessionInterface::validators`.
**/
@@ -542,6 +589,7 @@ declare module '@polkadot/api/types/storage' {
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.
*
* Must contains information for eras for the range:
* `[active_era - bounding_duration; active_era]`
**/
@@ -553,6 +601,7 @@ declare module '@polkadot/api/types/storage' {
canceledSlashPayout: AugmentedQuery<ApiType, () => Observable<BalanceOf>> & QueryableStorageEntry<ApiType>;
/**
* The current era index.
*
* This is the latest planned era, depending on how the Session pallet queues the validator
* set, it might be active or not.
**/
@@ -573,18 +622,23 @@ declare module '@polkadot/api/types/storage' {
erasRewardPoints: AugmentedQuery<ApiType, (arg: EraIndex | AnyNumber | Uint8Array) => Observable<EraRewardPoints>> & QueryableStorageEntry<ApiType>;
/**
* Exposure of validator at era.
*
* This is keyed first by the era index to allow bulk deletion and then the stash account.
*
* Is it removed after `HISTORY_DEPTH` eras.
* 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>;
/**
* Clipped Exposure of validator at era.
*
* This is similar to [`ErasStakers`] but number of nominators exposed is reduced to the
* `T::MaxNominatorRewardedPerValidator` biggest stakers.
* (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 keyed fist by the era index to allow bulk deletion and then the stash account.
*
* Is it removed after `HISTORY_DEPTH` eras.
* If stakers hasn't been set or has been removed then empty exposure is returned.
**/
@@ -600,12 +654,15 @@ declare module '@polkadot/api/types/storage' {
erasTotalStake: AugmentedQuery<ApiType, (arg: EraIndex | AnyNumber | Uint8Array) => Observable<BalanceOf>> & QueryableStorageEntry<ApiType>;
/**
* 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.
*
* Is it removed after `HISTORY_DEPTH` eras.
**/
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.
*
* 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>;
@@ -615,10 +672,12 @@ declare module '@polkadot/api/types/storage' {
forceEra: AugmentedQuery<ApiType, () => Observable<Forcing>> & QueryableStorageEntry<ApiType>;
/**
* Number of eras to keep in history.
*
* Information is kept for eras in `[current_era - history_depth; current_era]`.
* 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 > current_era - history_depth` must be guaranteed.
*
* 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 > current_era - history_depth` must be
* guaranteed.
**/
historyDepth: AugmentedQuery<ApiType, () => Observable<u32>> & QueryableStorageEntry<ApiType>;
/**
@@ -636,10 +695,6 @@ declare module '@polkadot/api/types/storage' {
* Map from all (unlocked) "controller" accounts to the info regarding the staking.
**/
ledger: AugmentedQuery<ApiType, (arg: AccountId | string | Uint8Array) => Observable<Option<StakingLedger>>> & QueryableStorageEntry<ApiType>;
/**
* The era where we migrated from Lazy Payouts to Simple Payouts
**/
migrateEra: AugmentedQuery<ApiType, () => Observable<Option<EraIndex>>> & QueryableStorageEntry<ApiType>;
/**
* Minimum number of staking participants before emergency conditions are imposed.
**/
@@ -665,13 +720,14 @@ declare module '@polkadot/api/types/storage' {
/**
* The score of the current [`QueuedElected`].
**/
queuedScore: AugmentedQuery<ApiType, () => Observable<Option<PhragmenScore>>> & QueryableStorageEntry<ApiType>;
queuedScore: AugmentedQuery<ApiType, () => Observable<Option<ElectionScore>>> & QueryableStorageEntry<ApiType>;
/**
* Slashing spans for stash accounts.
**/
slashingSpans: AugmentedQuery<ApiType, (arg: AccountId | string | Uint8Array) => Observable<Option<SlashingSpans>>> & QueryableStorageEntry<ApiType>;
/**
* The percentage of the slash that is distributed to reporters.
*
* The rest of the slashed value is handled by the `Slash`.
**/
slashRewardFraction: AugmentedQuery<ApiType, () => Observable<Perbill>> & QueryableStorageEntry<ApiType>;
@@ -693,9 +749,10 @@ declare module '@polkadot/api/types/storage' {
/**
* True if network has been upgraded to this version.
* Storage version of the pallet.
*
* This is set to v3.0.0 for new networks.
**/
storageVersion: AugmentedQuery<ApiType, () => Observable<ReleasesStaking>> & QueryableStorageEntry<ApiType>;
storageVersion: AugmentedQuery<ApiType, () => Observable<Releases>> & QueryableStorageEntry<ApiType>;
/**
* All unapplied slashes that are queued for later.
**/
@@ -731,14 +788,14 @@ declare module '@polkadot/api/types/storage' {
* Total length (in bytes) for all extrinsics put together, for the current block.
**/
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.
**/
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.
**/
@@ -754,9 +811,11 @@ declare module '@polkadot/api/types/storage' {
/**
* Mapping between a topic (represented by T::Hash) and a vector of indexes
* of events in the `<Events<T>>` list.
*
* All topic vectors have deterministic storage locations depending on the topic. This
* allows light-clients to leverage the changes trie storage tracking mechanism and
* 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 `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.
@@ -844,6 +903,7 @@ declare module '@polkadot/api/types/storage' {
transactionPayment: {
[index: string]: QueryableStorageEntry<ApiType>;
nextFeeMultiplier: AugmentedQuery<ApiType, () => Observable<Multiplier>> & QueryableStorageEntry<ApiType>;
storageVersion: AugmentedQuery<ApiType, () => Observable<Releases>> & QueryableStorageEntry<ApiType>;
};
treasury: {
[index: string]: QueryableStorageEntry<ApiType>;
@@ -871,13 +931,6 @@ declare module '@polkadot/api/types/storage' {
**/
tips: AugmentedQuery<ApiType, (arg: Hash | string | Uint8Array) => Observable<Option<OpenTip>>> & QueryableStorageEntry<ApiType>;
};
utility: {
[index: string]: QueryableStorageEntry<ApiType>;
/**
* The set of open multisig operations.
**/
multisigs: AugmentedQueryDoubleMap<ApiType, (key1: AccountId | string | Uint8Array, key2: U8aFixed | string | Uint8Array) => Observable<Option<Multisig>>> & QueryableStorageEntry<ApiType>;
};
vesting: {
[index: string]: QueryableStorageEntry<ApiType>;
/**
+34 -14
View File
@@ -1,7 +1,7 @@
// Auto-generated via `yarn polkadot-types-from-chain`, do not edit
/* eslint-disable */
import { AnyNumber, Codec, IExtrinsic } from '@polkadot/types/types';
import { AnyNumber, Codec, IExtrinsic, Observable } from '@polkadot/types/types';
import { HashMap, Option, Vec } from '@polkadot/types/codec';
import { Bytes, Null, StorageKey, Text, bool, u32, u64 } from '@polkadot/types/primitive';
import { Metadata } from '@polkadot/types';
@@ -13,22 +13,16 @@ import { AuthorityId } from '@polkadot/types/interfaces/consensus';
import { ContractCallRequest, ContractExecResult } from '@polkadot/types/interfaces/contracts';
import { CreatedBlock } from '@polkadot/types/interfaces/engine';
import { Extrinsic } from '@polkadot/types/interfaces/extrinsics';
import { ReportedRoundStates } from '@polkadot/types/interfaces/grandpa';
import { StorageKind } from '@polkadot/types/interfaces/offchain';
import { RuntimeDispatchInfo } from '@polkadot/types/interfaces/payment';
import { RpcMethods } from '@polkadot/types/interfaces/rpc';
import { AccountId, BlockNumber, H256, Hash, Header, Index, Justification, KeyValue, SignedBlock, StorageData } from '@polkadot/types/interfaces/runtime';
import { RuntimeVersion } from '@polkadot/types/interfaces/state';
import { ChainProperties, ChainType, Health, NetworkState, NodeRole, PeerInfo } from '@polkadot/types/interfaces/system';
import { Observable } from 'rxjs';
import { ReadProof, RuntimeVersion } from '@polkadot/types/interfaces/state';
import { ApplyExtrinsicResult, ChainProperties, ChainType, Health, NetworkState, NodeRole, PeerInfo } from '@polkadot/types/interfaces/system';
declare module '@polkadot/rpc-core/types.jsonrpc' {
export interface RpcInterface {
account: {
/**
* Retrieves the next accountIndex as available on the node
**/
nextIndex: AugmentedRpc<(accountId: AccountId | string | Uint8Array) => Observable<Index>>;
};
author: {
/**
* Returns true if the keystore has private keys for the given public key and key type.
@@ -141,15 +135,21 @@ declare module '@polkadot/rpc-core/types.jsonrpc' {
**/
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: {
/**
* Get offchain local storage under given key and prefix
**/
localStorageGet: AugmentedRpc<(kind: StorageKind | ('__UNUSED' | 'PERSISTENT' | 'LOCAL') | number | Uint8Array, key: Bytes | string | Uint8Array) => Observable<Option<Bytes>>>;
localStorageGet: AugmentedRpc<(kind: StorageKind | '__UNUSED' | 'PERSISTENT' | 'LOCAL' | number | Uint8Array, key: Bytes | string | Uint8Array) => Observable<Option<Bytes>>>;
/**
* Set offchain local storage under given key and prefix
**/
localStorageSet: AugmentedRpc<(kind: StorageKind | ('__UNUSED' | 'PERSISTENT' | 'LOCAL') | number | Uint8Array, key: Bytes | string | Uint8Array, value: Bytes | string | Uint8Array) => Observable<Null>>;
localStorageSet: AugmentedRpc<(kind: StorageKind | '__UNUSED' | 'PERSISTENT' | 'LOCAL' | number | Uint8Array, key: Bytes | string | Uint8Array, value: Bytes | string | Uint8Array) => Observable<Null>>;
};
payment: {
/**
@@ -197,9 +197,13 @@ declare module '@polkadot/rpc-core/types.jsonrpc' {
**/
getMetadata: AugmentedRpc<(at?: BlockHash | string | Uint8Array) => Observable<Metadata>>;
/**
* Returns the keys with prefix, leave empty to get all the keys
* Returns the keys with prefix, leave empty to get all the keys (deprecated: Use getKeysPaged)
**/
getPairs: AugmentedRpc<(prefix: StorageKey | string | Uint8Array | any, at?: BlockHash | string | Uint8Array) => Observable<Vec<KeyValue>>>;
/**
* Returns proof of storage entries at a specific block state
**/
getReadProof: AugmentedRpc<(keys: Vec<StorageKey> | (StorageKey | string | Uint8Array | any)[], at?: BlockHash | string | Uint8Array) => Observable<ReadProof>>;
/**
* Get the runtime version
**/
@@ -231,9 +235,13 @@ declare module '@polkadot/rpc-core/types.jsonrpc' {
/**
* 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: {
/**
* Retrieves the next accountIndex as available on the node
**/
accountNextIndex: AugmentedRpc<(accountId: AccountId | string | Uint8Array) => Observable<Index>>;
/**
* Adds a reserved peer
**/
@@ -246,10 +254,22 @@ declare module '@polkadot/rpc-core/types.jsonrpc' {
* Retrieves the chain type
**/
chainType: AugmentedRpc<() => Observable<ChainType>>;
/**
* Dry run an extrinsic at a given block
**/
dryRun: AugmentedRpc<(extrinsic: Bytes | string | Uint8Array, at?: BlockHash | string | Uint8Array) => Observable<ApplyExtrinsicResult>>;
/**
* Return health status of the node
**/
health: AugmentedRpc<() => Observable<Health>>;
/**
* The addresses include a trailing /p2p/ with the local PeerId, and are thus suitable to be passed to addReservedPeer or as a bootnode address for example
**/
localListenAddresses: AugmentedRpc<() => Observable<Vec<Text>>>;
/**
* Returns the base58-encoded PeerId of the node
**/
localPeerId: AugmentedRpc<() => Observable<Text>>;
/**
* Retrieves the node name
**/
File diff suppressed because it is too large Load Diff
+118 -86
View File
@@ -7,22 +7,21 @@ import { RpcInterface } from '@polkadot/rpc-core/types';
import { Call, Hash, RuntimeVersion } from '@polkadot/types/interfaces';
import { AnyFunction, CallFunction, Codec, CodecArg as Arg, ITuple, InterfaceTypes, ModulesWithCalls, Registry, RegistryTypes } from '@polkadot/types/types';
import { SubmittableExtrinsic } from '../submittable/types';
import { ApiInterfaceRx, ApiOptions, ApiTypes, DecorateMethod, DecoratedRpc, DecoratedRpcSection, QueryableModuleStorage, QueryableStorage, QueryableStorageEntry, QueryableStorageMulti, QueryableStorageMultiArg, SubmittableExtrinsicFunction, SubmittableExtrinsics, SubmittableModuleExtrinsics } from '../types';
import { ApiInterfaceRx, ApiOptions, ApiTypes, DecorateMethod, DecoratedRpc, DecoratedRpcSection, PaginationOptions, QueryableModuleStorage, QueryableStorage, QueryableStorageEntry, QueryableStorageMulti, QueryableStorageMultiArg, SubmittableExtrinsicFunction, SubmittableExtrinsics, SubmittableModuleExtrinsics } from '../types';
import BN from 'bn.js';
import { BehaviorSubject, Observable, combineLatest, from, of } from 'rxjs';
import { concatMap, map, switchMap, take, tap, toArray } from 'rxjs/operators';
import { BehaviorSubject, Observable, combineLatest, of } from 'rxjs';
import { map, switchMap, tap, toArray } from 'rxjs/operators';
import decorateDerive, { ExactDerive } from '@polkadot/api-derive';
import { memo } from '@polkadot/api-derive/util';
import DecoratedMeta from '@polkadot/metadata/Decorated';
import getHasher from '@polkadot/metadata/Decorated/storage/fromMetadata/getHasher';
import RpcCore from '@polkadot/rpc-core';
import { WsProvider } from '@polkadot/rpc-provider';
import { Metadata, Null, Option, Raw, Text, TypeRegistry, u64 } from '@polkadot/types';
import Linkage, { LinkageResult } from '@polkadot/types/codec/Linkage';
import { DEFAULT_VERSION as EXTRINSIC_DEFAULT_VERSION } from '@polkadot/types/extrinsic/constants';
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 augmentObject from '../util/augmentObject';
@@ -32,7 +31,7 @@ import Events from './Events';
interface MetaDecoration {
callIndex?: Uint8Array;
meta: any;
meta: Record<string, unknown>;
method: string;
section: string;
toJSON: () => any;
@@ -146,7 +145,7 @@ export default abstract class Decorate<ApiType extends ApiTypes> extends Events
/**
* @description Creates an instance of a type as registered
*/
public createType <K extends keyof InterfaceTypes> (type: K, ...params: any[]): InterfaceTypes[K] {
public createType <K extends keyof InterfaceTypes> (type: K, ...params: unknown[]): InterfaceTypes[K] {
return this.registry.createType(type, ...params);
}
@@ -235,7 +234,7 @@ export default abstract class Decorate<ApiType extends ApiTypes> extends Events
const unknown = exposed.filter((key) => !allKeys.includes(key));
if (unknown.length) {
l.warn(`RPC methods not decorated: ${unknown.join(', ')}}`);
l.warn(`RPC methods not decorated: ${unknown.join(', ')}`);
}
// loop through all entries we have (populated in decorate) and filter as required
@@ -247,9 +246,9 @@ export default abstract class Decorate<ApiType extends ApiTypes> extends Events
)
// eslint-disable-next-line @typescript-eslint/no-unused-vars
.forEach(([_, { method, section }]): void => {
delete (this._rpc as any)[section][method];
delete (this._rpcCore as any)[section][method];
delete (this._rx.rpc as any)[section][method];
delete (this._rpc as Record<string, Record<string, unknown>>)[section][method];
delete (this._rpcCore as unknown as Record<string, Record<string, unknown>>)[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>;
// 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
if (this.hasSubscriptions || !(methodName.startsWith('subscribe') || methodName.startsWith('unsubscribe'))) {
(section as any)[methodName] = decorateMethod(method, { methodName });
(section as any)[methodName].raw = decorateMethod(method.raw, { methodName });
(section as Record<string, unknown>)[methodName] = decorateMethod(method, { methodName }) as unknown;
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
(section as Record<string, { raw: unknown }>)[methodName].raw = decorateMethod(method.raw, { methodName }) as unknown;
}
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> {
// eslint-disable-next-line @typescript-eslint/no-unsafe-return
return decorateMethod((calls: QueryableStorageMultiArg<ApiType>[]): Observable<Codec[]> =>
this._rpcCore.state.subscribeStorage(
calls.map((arg: QueryableStorageMultiArg<ApiType>): [QueryableStorageEntry<ApiType>, ...Arg[]] =>
// the input is a QueryableStorageEntry, convert to StorageEntry
// eslint-disable-next-line @typescript-eslint/no-unsafe-return
Array.isArray(arg)
? [arg[0].creator, ...arg.slice(1)]
: [arg.creator] as any)));
@@ -300,7 +302,8 @@ export default abstract class Decorate<ApiType extends ApiTypes> extends Events
const decorated = (...params: Arg[]): SubmittableExtrinsic<ApiType> =>
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> {
@@ -317,21 +320,15 @@ export default abstract class Decorate<ApiType extends ApiTypes> extends Events
private _decorateStorageEntry<ApiType extends ApiTypes> (creator: StorageEntry, decorateMethod: DecorateMethod<ApiType>): QueryableStorageEntry<ApiType> {
// get the storage arguments, with DoubleMap as an array entry, otherwise spread
const getArgs = (...args: any[]): any[] => extractStorageArgs(creator, args);
const getArgs = (...args: unknown[]): unknown[] => extractStorageArgs(creator, args);
// Disable this where it occurs for each field we are decorating
/* eslint-disable @typescript-eslint/no-unsafe-member-access,@typescript-eslint/no-unsafe-assignment */
// FIXME We probably want to be able to query the full list with non-subs as well
const decorated = this.hasSubscriptions && creator.iterKey && creator.meta.type.isMap && creator.meta.type.asMap.linked.isTrue
? this._decorateStorageLinked(creator, decorateMethod)
: decorateMethod((...args: any[]): Observable<Codec> => (
this.hasSubscriptions
? this._rpcCore.state
// Unfortunately for one-shot calls we also use .subscribeStorage here
.subscribeStorage<[Codec]>([getArgs(...args)])
// state_storage returns an array of values, since we have just subscribed to
// a single entry, we pull that from the array and return it as-is
.pipe(map(([data]): Codec => data))
: this._rpcCore.state.getStorage(getArgs(...args))
), { methodName: creator.method });
: this._decorateStorageCall(creator, decorateMethod);
decorated.creator = creator;
@@ -344,8 +341,8 @@ export default abstract class Decorate<ApiType extends ApiTypes> extends Events
decorated.key = (arg1?: Arg, arg2?: Arg): string =>
u8aToHex(compactStripLength(creator(creator.meta.type.isDoubleMap ? [arg1, arg2] : arg1))[1]);
decorated.keyPrefix = (): string =>
u8aToHex(creator.keyPrefix);
decorated.keyPrefix = (key1?: Arg): string =>
u8aToHex(creator.keyPrefix(key1));
decorated.range = decorateMethod((range: [Hash, Hash?], arg1?: Arg, arg2?: Arg): Observable<[Hash, Codec][]> =>
this._decorateStorageRange(decorated, [arg1, arg2], range));
@@ -359,9 +356,17 @@ export default abstract class Decorate<ApiType extends ApiTypes> extends Events
memo((doubleMapArg?: Arg): Observable<[StorageKey, Codec][]> =>
this._retrieveMapEntries(creator, doubleMapArg)));
decorated.entriesPaged = decorateMethod(
memo((opts: PaginationOptions): Observable<[StorageKey, Codec][]> =>
this._retrieveMapEntriesPaged(creator, opts)));
decorated.keys = decorateMethod(
memo((doubleMapArg?: Arg): Observable<StorageKey[]> =>
this._retrieveMapKeys(creator, doubleMapArg)));
decorated.keysPaged = decorateMethod(
memo((opts: PaginationOptions): Observable<StorageKey[]> =>
this._retrieveMapKeysPaged(creator, opts)));
}
// only support multi where subs are available
@@ -372,7 +377,25 @@ export default abstract class Decorate<ApiType extends ApiTypes> extends Events
args.map((arg: Arg[] | Arg): [StorageEntry, Arg | Arg[]] => [creator, arg])));
}
return this._decorateFunctionMeta(creator, decorated) as unknown as QueryableStorageEntry<ApiType>;
/* eslint-enable @typescript-eslint/no-unsafe-member-access,@typescript-eslint/no-unsafe-assignment */
return this._decorateFunctionMeta(creator as any, decorated) as unknown as QueryableStorageEntry<ApiType>;
}
// Decorate the base storage call. In the case or rxjs or promise-without-callback (await)
// we make a subscription, alternatively we push this through a single-shot query
private _decorateStorageCall<ApiType extends ApiTypes> (creator: StorageEntry, decorateMethod: DecorateMethod<ApiType>): ReturnType<DecorateMethod<ApiType>> {
// eslint-disable-next-line @typescript-eslint/no-unsafe-return
return decorateMethod((...args: unknown[]): Observable<Codec> => {
return this.hasSubscriptions
? this._rpcCore.state.subscribeStorage<[Codec]>([extractStorageArgs(creator, args)]).pipe(
map(([data]) => data) // extract first/only result from list
)
: this._rpcCore.state.getStorage(extractStorageArgs(creator, args));
}, {
methodName: creator.method,
overrideNoSub: (...args: unknown[]) => this._rpcCore.state.getStorage(extractStorageArgs(creator, args))
});
}
private _decorateStorageRange<ApiType extends ApiTypes> (decorated: QueryableStorageEntry<ApiType>, args: [Arg?, Arg?], range: [Hash, Hash?]): Observable<[Hash, Codec][]> {
@@ -388,10 +411,15 @@ export default abstract class Decorate<ApiType extends ApiTypes> extends Events
));
}
// This is deprecated/removed on substrate - we still have some live chains, eg. Edgeware needing it, so it
// has not been dropped yet. Slated for removal in API 2.0
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 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
// entries can be re-linked in the middle of a list, we subscribe here to make
@@ -449,82 +477,86 @@ export default abstract class Decorate<ApiType extends ApiTypes> extends Events
// 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
return decorateMethod((...args: any[]): Observable<LinkageResult | [Codec, Linkage<Codec>]> =>
// eslint-disable-next-line @typescript-eslint/no-unsafe-return
return decorateMethod((...args: unknown[]): Observable<LinkageResult | [Codec, Linkage<Codec>]> =>
args.length
? this._rpcCore.state
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
.subscribeStorage<[[Codec, Linkage<Codec>]]>([[creator, ...args]])
.pipe(map(([data]): [Codec, Linkage<Codec>] => data))
.pipe(map(([data]) => data))
: this._rpcCore.state
.subscribeStorage<[LinkageResult]>([creator.iterKey])
.pipe(switchMap(([key]): Observable<LinkageResult> => getNext(head = key)))
.subscribeStorage<[LinkageResult]>([iterKey()])
.pipe(switchMap(([key]) => getNext(head = key)))
);
}
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');
const headKey = this.createType('Raw', u8aConcat(
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 headKey = iterKey(arg).toHex();
const startSubject = new BehaviorSubject<string>(headKey);
return this._rpcCore.state.getKeysPaged
? startSubject.pipe(
switchMap((startKey) =>
this._rpcCore.state.getKeysPaged(headKey, PAGE_SIZE_KEYS, startKey).pipe(
map((keys) => keys.map((key) => key.decodeArgsFromMeta(meta)))
)
),
tap((keys): void => {
keys.length === PAGE_SIZE_KEYS
? startSubject.next(keys[PAGE_SIZE_KEYS - 1].toHex())
: startSubject.complete();
}),
toArray(), // toArray since we want to startSubject to be completed
map((keysArr: StorageKey[][]) => keysArr.reduce((result: StorageKey[], keys) => result.concat(keys), []))
)
: this._rpcCore.state.getKeys(headKey).pipe(
map((keys) => keys.map((key) => key.decodeArgsFromMeta(meta)))
);
return startSubject.pipe(
switchMap((startKey) =>
this._rpcCore.state.getKeysPaged(headKey, PAGE_SIZE_KEYS, startKey).pipe(
map((keys) => keys.map((key) => key.setMeta(meta)))
)
),
tap((keys): void => {
keys.length === PAGE_SIZE_KEYS
? startSubject.next(keys[PAGE_SIZE_KEYS - 1].toHex())
: startSubject.complete();
}),
toArray(), // toArray since we want to startSubject to be completed
map((keysArr: StorageKey[][]) => keysArr.reduce((result: StorageKey[], keys) => result.concat(keys), []))
);
}
private _retrieveMapKeysPaged ({ iterKey, meta }: StorageEntry, opts: PaginationOptions): Observable<StorageKey[]> {
assert(iterKey && (meta.type.isMap || meta.type.isDoubleMap), 'keys can only be retrieved on maps, linked maps and double maps');
const headKey = iterKey(opts.arg).toHex();
return this._rpcCore.state.getKeysPaged(headKey, opts.pageSize, opts.startKey || headKey).pipe(
map((keys) => keys.map((key) => key.setMeta(meta)))
);
}
private _retrieveMapEntries (entry: StorageEntry, arg?: Arg): Observable<[StorageKey, Codec][]> {
const outputType = unwrapStorageType(entry.meta.type, entry.meta.modifier.isOptional);
return this._retrieveMapKeys(entry, arg).pipe(
switchMap((keys): Observable<[StorageKey[], Option<Raw>[][]]> =>
combineLatest([
switchMap((keys) =>
combineLatest<[StorageKey[], ...Codec[][]]>([
of(keys),
from(Array(Math.ceil(keys.length / PAGE_SIZE_VALS)).fill(0)).pipe(
concatMap((_, index): Observable<Option<Raw>[]> => {
const keyset = keys.slice(index * PAGE_SIZE_VALS, (index * PAGE_SIZE_VALS) + PAGE_SIZE_VALS);
return this._rpcCore.state.queryStorageAt
? this._rpcCore.state.queryStorageAt<Option<Raw>[]>(keyset)
: this._rpcCore.state.subscribeStorage<Option<Raw>[]>(keyset).pipe(take(1));
}),
toArray()
)
...Array(Math.ceil(keys.length / PAGE_SIZE_VALS))
.fill(0)
.map((_, index): Observable<Codec[]> =>
this._rpcCore.state.queryStorageAt<Codec[]>(
keys.slice(index * PAGE_SIZE_VALS, (index * PAGE_SIZE_VALS) + PAGE_SIZE_VALS)
)
)
])
),
map(([keys, valsArr]): [StorageKey, Codec][] => {
const vals = valsArr.reduce((result: Option<Raw>[], vals) => result.concat(vals), []);
map(([keys, ...valsArr]): [StorageKey, Codec][] =>
valsArr
.reduce((result: Codec[], vals) => result.concat(vals), [])
.map((value, index) => [keys[index], value])
)
);
}
return keys.map((key, index): [StorageKey, Codec] => [
key,
this.createType(
outputType,
vals[index].isSome
? vals[index].unwrap().toHex()
: undefined
)
]);
})
private _retrieveMapEntriesPaged (entry: StorageEntry, opts: PaginationOptions): Observable<[StorageKey, Codec][]> {
return this._retrieveMapKeysPaged(entry, opts).pipe(
switchMap((keys) =>
combineLatest<[StorageKey[], ...Codec[][]]>([
of(keys),
this._rpcCore.state.queryStorageAt<Codec[]>(keys)
])
),
map(([keys, ...valsArr]): [StorageKey, Codec][] =>
valsArr
.reduce((result: Codec[], vals) => result.concat(vals), [])
.map((value, index) => [keys[index], value])
)
);
}
+23 -23
View File
@@ -5,7 +5,7 @@
import { SignedBlock, RuntimeVersion } from '@polkadot/types/interfaces';
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 { Metadata, Text } from '@polkadot/types';
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
// cater for this case, we call manually `this._onProviderConnect`.
if (this._rpcCore.provider.isConnected()) {
// eslint-disable-next-line @typescript-eslint/no-floating-promises
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
// 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 as any)[section]).forEach((method): void => {
Object.keys((source.rpc as Record<string, Record<string, unknown>>)[section]).forEach((method): void => {
methods.push(`${section}_${method}`);
});
});
@@ -119,32 +120,30 @@ export default abstract class Init<ApiType extends ApiTypes> extends Decorate<Ap
// subscribe to metadata updates, inject the types on changes
private _subscribeUpdates (): void {
if (this.#updateSub) {
if (this.#updateSub || !this.hasSubscriptions) {
return;
}
this.#updateSub = this._rpcCore.state.subscribeRuntimeVersion().pipe(
switchMap((version: RuntimeVersion) =>
combineLatest(
of(version),
this._rpcCore.state.getMetadata()
)
),
map(([version, metadata]: [RuntimeVersion, Metadata]): boolean => {
if (this._runtimeVersion?.specVersion.eq(version.specVersion)) {
return false;
}
switchMap((version: RuntimeVersion): Observable<boolean> =>
// only retrieve the metadata when the on-chain version has been changed
this._runtimeVersion?.specVersion.eq(version.specVersion)
? of(false)
: this._rpcCore.state.getMetadata().pipe(
map((metadata: Metadata): boolean => {
l.log(`Runtime version updated to spec=${version.specVersion.toString()}, tx=${version.transactionVersion.toString()}`);
l.log(`Runtime version updated to ${version.specVersion}`);
this._runtimeMetadata = metadata;
this._runtimeVersion = version;
this._rx.runtimeVersion = version;
this._runtimeMetadata = metadata;
this._runtimeVersion = version;
this.registerTypes(getSpecTypes(this.registry, this._runtimeChain as Text, version.specName, version.specVersion));
this.injectMetadata(metadata, false);
this.registerTypes(getSpecTypes(this.registry, this._runtimeChain as Text, version.specName, version.specVersion));
this.injectMetadata(metadata, false);
return true;
})
return true;
})
)
)
).subscribe();
}
@@ -158,6 +157,7 @@ export default abstract class Init<ApiType extends ApiTypes> extends Decorate<Ap
// set our chain version & genesisHash as returned
this._runtimeChain = chain;
this._runtimeVersion = runtimeVersion;
this._rx.runtimeVersion = runtimeVersion;
// do the setup for the specific chain
this.registry.setChainProperties(chainProps);
@@ -168,7 +168,7 @@ export default abstract class Init<ApiType extends ApiTypes> extends Decorate<Ap
await this._filterRpc();
// 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
? new Metadata(this.registry, optMetadata[metadataKey])
: await this._rpcCore.state.getMetadata().toPromise();
@@ -233,7 +233,7 @@ export default abstract class Init<ApiType extends ApiTypes> extends Decorate<Ap
});
}, KEEPALIVE_INTERVAL);
} 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);
+2 -2
View File
@@ -29,8 +29,8 @@ interface PkgJson {
let pkgJson: PkgJson = { name: '@polkadot/api', version: '-' };
import('../package.json')
.then((_pkgJson: any): void => {
pkgJson = _pkgJson;
.then((_pkgJson: unknown): void => {
pkgJson = _pkgJson as PkgJson;
})
.catch((): void => {
// ignore

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