Compare commits

...
172 Commits
Author SHA1 Message Date
Github Actions 92022bda94 [CI Skip] release/stable 1.32.1
skip-checks: true
2020-09-07 07:22:50 +00:00
Jaco Greeff 609581430f 1.32 (#2589)
* 1.32

* CHANGELOG
2020-09-07 09:10:35 +02:00
Github Actions ec083f623d [CI Skip] release/beta 1.32.0-beta.25
skip-checks: true
2020-09-06 16:18:27 +00:00
Jaco Greeff 395dc79ef7 Adjust derive.staking.query (no opt) (#2588)
* Adjust derive.staking.query (no opt)

* Rewrite
2020-09-06 18:06:37 +02:00
Github Actions a968fe05b5 [CI Skip] release/beta 1.32.0-beta.24
skip-checks: true
2020-09-06 11:05:18 +00:00
Jaco Greeff 4b3b853c27 Extract derive for staking keys (#2587)
* Extract derive for staking keys

* CHANGELOG
2020-09-06 12:53:46 +02:00
Github Actions ea5843f7c9 [CI Skip] release/beta 1.32.0-beta.23
skip-checks: true
2020-09-06 08:04:07 +00:00
Jaco Greeff 467ccc5681 Westend known upgrade (#2584) 2020-09-06 09:51:16 +02:00
Github Actions 59922eee8f [CI Skip] release/beta 1.32.0-beta.22
skip-checks: true
2020-09-05 12:44:02 +00:00
Jaco Greeff 5af98cc89e Retry WS on initial connection failures (#2585) 2020-09-05 14:30:55 +02:00
Github Actions 1b7265048d [CI Skip] release/beta 1.32.0-beta.21
skip-checks: true
2020-09-05 06:33:47 +00:00
Jaco Greeff 3151c08aca Bump deps (#2583) 2020-09-05 08:22:29 +02:00
Github Actions 71332fde1b [CI Skip] release/beta 1.32.0-beta.20
skip-checks: true
2020-09-04 16:08:24 +00:00
Jaco Greeff 00bc441f0e Add connected() to API interface (#2580)
* Add connected() to API interface

* Slight doc update

* Align ApiRx

* isConnected() usage

* Updates

* Retrieve isConnected for API via observable

* Remove (now) useless Rx test
2020-09-04 17:57:02 +02:00
Github Actions 4f4833da74 [CI Skip] release/beta 1.32.0-beta.19
skip-checks: true
2020-09-04 08:47:58 +00:00
qiuhao 825365bb13 update DeriveCustom type (#2581) 2020-09-04 10:37:16 +02:00
Github Actions 48a3a976f9 [CI Skip] release/beta 1.32.0-beta.18
skip-checks: true
2020-09-04 06:06:45 +00:00
Jaco Greeff b579b18fad Adjust toHuman display (#2579)
* Adjust toHuman display

* revert args breakdown
2020-09-04 07:55:13 +02:00
Github Actions 27f5547bbf [CI Skip] release/beta 1.32.0-beta.17
skip-checks: true
2020-09-03 15:22:39 +00:00
Shawn Tabrizi 4654d15097 Add isReadyOrError when connecting to API (#2577)
* Add `isReadyOrError`

* lint
2020-09-03 17:10:07 +02:00
Github Actions 10574ecc33 [CI Skip] release/beta 1.32.0-beta.16
skip-checks: true
2020-09-03 14:00:02 +00:00
Jaco Greeff 6ae75ba92e Bump dev (#2576)
* Bump dev

* type linting

* linting

* linting

* missed
2020-09-03 15:47:29 +02:00
Github Actions 5a48a2a3f7 [CI Skip] release/beta 1.32.0-beta.15
skip-checks: true
2020-09-03 12:02:17 +00:00
Jaco Greeff 40899adf82 Optiona nominators (#2575) 2020-09-03 13:50:19 +02:00
Github Actions 020effecc8 [CI Skip] release/beta 1.32.0-beta.14
skip-checks: true
2020-09-03 10:58:35 +00:00
Jaco Greeff 430beb9f25 staking.currentEra returns Option (#2574)
* staking.currentEra returns Option

* Flatten

* Cleanups.

* Option<EraIndex> or EraIndex

* Test unwrapOrDefault
2020-09-03 12:45:50 +02:00
Github Actions 533d6dd441 [CI Skip] release/beta 1.32.0-beta.13
skip-checks: true
2020-09-03 06:54:48 +00:00
Jaco Greeff 95dd13e218 Dedup class creation (#2573) 2020-09-03 08:41:15 +02:00
Github Actions c8cb441a82 [CI Skip] release/beta 1.32.0-beta.12
skip-checks: true
2020-09-02 15:27:23 +00:00
Jaco Greeff b6d1be6ee5 Only memomize via instanceId (#2572)
* Add memoizee instanceId

* Gotcha.

* linitng
2020-09-02 17:13:38 +02:00
Github Actions e13514cd94 [CI Skip] release/beta 1.32.0-beta.11
skip-checks: true
2020-09-02 13:26:45 +00:00
Jaco Greeff 5a90da5df8 accountId-only lookups on paymentInfo (#2569) 2020-09-02 15:13:45 +02:00
Github Actions 8fdc518651 [CI Skip] release/beta 1.32.0-beta.10
skip-checks: true
2020-09-02 10:31:41 +00:00
Jaco Greeff eb6b3c5bd4 Align costs typing with queries (#2564)
* Align costs typing with queries

* better...

* ... and better

* ... progress

* better, down to 8

* ... down to 3

* ... 2

* Down to 1

* It builds.

* ... it really builds
2020-09-02 12:19:09 +02:00
Github Actions 1214572f02 [CI Skip] release/beta 1.32.0-beta.9
skip-checks: true
2020-09-02 07:37:22 +00:00
Jaco Greeff df229ffb8a Known Kusama update (slight upgrades rework) (#2567)
* Known Kusama update (slight upgrades rework)

* linting
2020-09-02 09:23:48 +02:00
Github Actions 334e0bb730 [CI Skip] release/beta 1.32.0-beta.8
skip-checks: true
2020-09-01 11:22:21 +00:00
Nikhil Ranjan f43bc32573 add vestingPerBlock and vestingEndBlock in DeriveBalancesAll when doing calcBalances (#2563)
* add vesting perBlock and vestingEndBlock in DeriveBalancesAll when doing calcBalances

* perBlock renamed to vestingPerBlock
2020-09-01 13:09:29 +02:00
Github Actions bf4a8e28a3 [CI Skip] release/beta 1.32.0-beta.7
skip-checks: true
2020-09-01 11:06:46 +00:00
Jaco Greeff 9188e29dcc Add grandpa_subscribeJustifications (#2562) 2020-09-01 12:54:32 +02:00
Github Actions 7ea89950fe [CI Skip] release/beta 1.32.0-beta.6
skip-checks: true
2020-09-01 10:04:40 +00:00
Jaco Greeff 7a1089df79 Cater for nested aliassed types (#2560)
* Cater for nested aliassed types

* linting
2020-09-01 11:52:11 +02:00
Github Actions f1ca28adcb [CI Skip] release/beta 1.32.0-beta.5
skip-checks: true
2020-09-01 09:26:04 +00:00
Jaco Greeff 8f675053a4 Add toHuman() & toBigInt() to type basics (#2558) 2020-09-01 11:13:46 +02:00
Github Actions 64de91a96b [CI Skip] release/beta 1.32.0-beta.4
skip-checks: true
2020-08-31 21:19:25 +00:00
Jaco Greeff 6bd10daf43 Bump static metadata (#2557) 2020-08-31 23:06:18 +02:00
Github Actions 57c54c860a [CI Skip] release/beta 1.32.0-beta.3
skip-checks: true
2020-08-31 21:03:09 +00:00
Jaco Greeff 0e9a50e020 Make metadata available on registry swap (#2556)
* Make metadata available on registry swap

* Return full VersionedRegistry
2020-08-31 22:52:33 +02:00
Github Actions 15c35900ac [CI Skip] release/beta 1.32.0-beta.2
skip-checks: true
2020-08-31 19:25:29 +00:00
Jaco Greeff 6f092a1818 api.derive.chain.getBlock(<hash>) with author getter (#2555)
* api.derive.chain.getBlock<hash>) with author getter

* Update CHANGELOG.md
2020-08-31 21:12:14 +02:00
Github Actions c0c6928394 [CI Skip] release/beta 1.32.0-beta.1
skip-checks: true
2020-08-31 17:48:54 +00:00
Jaco Greeff 391c98c845 Next beta 2020-08-31 19:34:37 +02:00
Github Actions 2e125c5542 [CI Skip] release/stable 1.31.2
skip-checks: true
2020-08-31 17:30:12 +00:00
Jaco Greeff 3d67b75059 Proxy Announcement override (#2553) 2020-08-31 19:17:48 +02:00
Github Actions d958ef8f15 [CI Skip] release/stable 1.31.1
skip-checks: true
2020-08-31 15:44:17 +00:00
Jaco Greeff 97527871d6 1.31 (#2551) 2020-08-31 17:32:20 +02:00
Github Actions 0317f28e5a [CI Skip] release/beta 1.31.0-beta.26
skip-checks: true
2020-08-31 15:06:05 +00:00
Jaco Greeff ebe6d03762 Update types for Polkadot runtime 23 (#2550)
* Update types for Polkadot runtime 23

* Expand change info

* version upgrades

* Linting
2020-08-31 16:50:56 +02:00
Github Actions 59e92fa344 [CI Skip] release/beta 1.31.0-beta.25
skip-checks: true
2020-08-31 14:24:05 +00:00
Jaco Greeff cab338e26d CHANGELOG (#2549) 2020-08-31 16:11:17 +02:00
Github Actions 743ea431b4 [CI Skip] release/beta 1.31.0-beta.24
skip-checks: true
2020-08-31 13:32:50 +00:00
Jaco Greeff 533f9ce249 Explicit delay for per-hash single queries (#2548)
* Explicit delay for per-hash single queries

* Expand delay

* Update packages/rpc-core/src/index.ts
2020-08-31 15:20:06 +02:00
Github Actions 797ee9c24a [CI Skip] release/beta 1.31.0-beta.23
skip-checks: true
2020-08-31 12:44:38 +00:00
Jaco Greeff 2f5e2537a3 Align single-shot memoization (#2546)
* Align single-shot memoization

* Small tweaks

* Test for delayed creates

* With actual sub

* Expand delay test

* Bump delay
2020-08-31 14:31:44 +02:00
Github Actions dd52ea4b32 [CI Skip] release/beta 1.31.0-beta.22
skip-checks: true
2020-08-31 12:27:52 +00:00
Jaco Greeff 5e8ae793c3 Westend known upgrades (#2547) 2020-08-31 14:16:45 +02:00
Github Actions 8713a1f2b6 [CI Skip] release/beta 1.31.0-beta.21
skip-checks: true
2020-08-31 11:22:44 +00:00
Jaco Greeff 6e6fa4a97c Known upgrade points for on-chain version skip (#2545)
* Known upgrade points for on-chain version skip

* Update packages/types-known/src/index.ts

* Update packages/api/src/base/Init.ts

* Actual known upgrade blocks for Polkadot & Kusama

* Update with known Kusama upgrade history

* linting
2020-08-31 13:09:52 +02:00
Github Actions ac2a0a34ca [CI Skip] release/beta 1.31.0-beta.20
skip-checks: true
2020-08-31 07:51:33 +00:00
Jaco Greeff 45fb6d44ad Bump deps (#2544) 2020-08-31 09:38:21 +02:00
Github Actions 6d2265d4ff [CI Skip] release/beta 1.31.0-beta.19
skip-checks: true
2020-08-31 07:11:57 +00:00
Jaco Greeff 4ec42f1750 Ensure non-destructive registry swap (#2543)
* Ensure non-destructive registry swap

* Update packages/api/src/base/Init.ts
2020-08-31 08:59:20 +02:00
Github Actions 01166b9684 [CI Skip] release/beta 1.31.0-beta.18
skip-checks: true
2020-08-30 19:24:47 +00:00
Jaco Greeff 0075dce720 Remove outdated historic query FAQ (#2540) 2020-08-30 21:11:15 +02:00
Github Actions 7fbb30066e [CI Skip] release/beta 1.31.0-beta.17
skip-checks: true
2020-08-30 18:41:28 +00:00
Jaco Greeff 637069d723 Shortcut registry for subsequent same-hash queries (#2539) 2020-08-30 20:28:37 +02:00
Github Actions d639a7ee8c [CI Skip] release/beta 1.31.0-beta.16
skip-checks: true
2020-08-30 18:17:47 +00:00
Jaco Greeff 28ef291c40 Mark submittable .sign as deprecated (#2538) 2020-08-30 20:06:42 +02:00
Github Actions 48ddd0b0d4 [CI Skip] release/beta 1.31.0-beta.15
skip-checks: true
2020-08-30 10:52:55 +00:00
Jaco Greeff e88ebf7b2e Support Vec .concat (#2537)
* Support Vec .concat

* CHANGELOG
2020-08-30 12:40:20 +02:00
Github Actions 72700e6baf [CI Skip] release/beta 1.31.0-beta.14
skip-checks: true
2020-08-30 10:36:12 +00:00
Hamza Tokuchi f748fcd46d more typos (#2532) 2020-08-30 12:24:50 +02:00
Jaco Greeff 7876bb9ced Add isHistoric flags to RPC with hash params (#2535)
* Add isHistoric flags to RPC with hash params

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

* Apply suggestions from code review

* Transparently swap registry on RPC layer

* Simplify (& linting fixes)

* Cleanups

* CHANGELOG
2020-08-30 12:12:18 +02:00
Github Actions a83980b213 [CI Skip] release/beta 1.31.0-beta.13
skip-checks: true
2020-08-29 13:59:29 +00:00
Jaco Greeff c4323d5e94 Add swapRegistry(hash?) to initlize clean registry (#2534)
* Add swapRegistry(hash?) to initlize clean registry

* Cater for genesisHash queries
2020-08-29 15:46:42 +02:00
Github Actions 11694f1393 [CI Skip] release/beta 1.31.0-beta.12
skip-checks: true
2020-08-29 12:31:27 +00:00
Jaco Greeff 3989ae67b2 Bump deps (#2533) 2020-08-29 14:19:56 +02:00
Github Actions b78df57907 [CI Skip] release/beta 1.31.0-beta.11
skip-checks: true
2020-08-28 12:35:54 +00:00
Jaco Greeff 2f78329738 Return democracy locks for delegations (#2531) 2020-08-28 14:23:05 +02:00
Github Actions 6063054712 [CI Skip] release/beta 1.31.0-beta.10
skip-checks: true
2020-08-28 10:15:36 +00:00
Jaco Greeff e42af97928 Bump deps (#2530) 2020-08-28 12:03:49 +02:00
Hamza Tokuchi d05ccdb5d7 small typos (#2529) 2020-08-28 12:03:13 +02:00
Github Actions c33334b72b [CI Skip] release/beta 1.31.0-beta.9
skip-checks: true
2020-08-28 08:50:51 +00:00
Jaco Greeff 94e9fd2b17 Fix for in-place unlocking (#2528) 2020-08-28 10:40:53 +02:00
Github Actions 9c1327ea22 [CI Skip] release/beta 1.31.0-beta.8
skip-checks: true
2020-08-26 16:56:17 +00:00
Jaco Greeff 9f195e9402 Update RewardDesitination enum (any payout) (#2474) 2020-08-26 18:43:51 +02:00
Github Actions 3e5e089c68 [CI Skip] release/beta 1.31.0-beta.7
skip-checks: true
2020-08-26 11:00:13 +00:00
Jaco Greeff 35c37aa66c Allow AccountId null in constructor 2020-08-26 12:47:15 +02:00
Github Actions f1aeb564e3 [CI Skip] release/beta 1.31.0-beta.6
skip-checks: true
2020-08-26 10:41:27 +00:00
Kian Paimani c2ff1b32ae Update definitions.ts (#2514)
* Update definitions.ts

Will fix the decoding of these types. Sadly cannot provide a compact test case.

* Add more tests.

* Make the tests work.

* Fix linting as well.
2020-08-26 12:29:27 +02:00
Github Actions 288427cbb8 [CI Skip] release/beta 1.31.0-beta.5
skip-checks: true
2020-08-26 09:40:00 +00:00
Jaco Greeff d099ccedad Additional AccountId length check (protect users against themselves) (#2520)
* Additional AccountId length check

* Allow all-0

* Spaceing.
2020-08-26 11:27:57 +02:00
Github Actions 79c7983199 [CI Skip] release/beta 1.31.0-beta.4
skip-checks: true
2020-08-26 09:26:32 +00:00
Jaco Greeff 80c578fe76 Bump deps (#2521)
* Bump deps

* Rewrite yarn.lock

* Debump markdown plugin

* Explicit add of typedoc plugins

* Bump dev typedoc exec

* Bump md

* Common bump
2020-08-26 11:15:23 +02:00
Github Actions de90c048bf [CI Skip] release/beta 1.31.0-beta.3
skip-checks: true
2020-08-26 05:12:55 +00:00
aniiantt 01a36a994d add TransactionPriority def (#2519) 2020-08-26 07:03:20 +02:00
Github Actions b1ce22d51d [CI Skip] release/beta 1.31.0-beta.2
skip-checks: true
2020-08-25 22:01:24 +00:00
Jaco Greeff fe951c2645 Support bare flag on enums (#2518)
* Support bare flag on enums

* Remove extra var allocation
2020-08-25 23:50:30 +02:00
Github Actions 5a17c542a7 [CI Skip] release/beta 1.31.0-beta.1
skip-checks: true
2020-08-25 21:35:20 +00:00
Jaco Greeff 59bb5f864f Add toBigInt to number types (#2517)
* Add toBigInt to number types

* Update packages/types/src/codec/UInt.spec.ts

* Update packages/types/src/codec/Compact.spec.ts

* Update packages/types/src/codec/Compact.ts
2020-08-25 23:24:02 +02:00
Github Actions abcba20f90 [CI Skip] release/beta 1.31.0-beta.0
skip-checks: true
2020-08-25 13:48:28 +00:00
Hamza Tokuchi 014f08c7cc Small typo (#2515)
teh -> the
2020-08-25 15:36:59 +02:00
Github Actions 7ecd00a4e6 [CI Skip] release/stable 1.30.1
skip-checks: true
2020-08-24 09:27:18 +00:00
Jaco Greeff 6239818c26 1.30 (#2511) 2020-08-24 11:14:32 +02:00
Github Actions 6af22f41c7 [CI Skip] release/beta 1.30.0-beta.8
skip-checks: true
2020-08-24 07:40:12 +00:00
Jaco Greeff 77c3a701d0 Bump deps (#2510) 2020-08-24 09:27:49 +02:00
Github Actions 46b17a466c [CI Skip] release/beta 1.30.0-beta.7
skip-checks: true
2020-08-24 05:35:43 +00:00
Jaco Greeff e592c6c878 Fix circular know-type refs (#2509) 2020-08-24 07:23:06 +02:00
Github Actions ef37586dfc [CI Skip] release/beta 1.30.0-beta.6
skip-checks: true
2020-08-22 12:13:04 +00:00
Jaco Greeff 5856ce24cc User pair addressRaw for signing (#2504)
* User pair addressRaw for signing

* Bump common

* Bump common after merge
2020-08-22 14:02:28 +02:00
Github Actions 8b79056bf9 [CI Skip] release/beta 1.30.0-beta.5
skip-checks: true
2020-08-22 11:20:28 +00:00
Jaco Greeff 70e0f19ade Allow for configurable hashers (#2503) 2020-08-22 13:09:04 +02:00
Github Actions cf1e242c17 [CI Skip] release/beta 1.30.0-beta.4
skip-checks: true
2020-08-22 10:41:32 +00:00
Jaco Greeff 68856e9692 Ethereum-compatible AccountId/Address (#2501)
* Ethereum-compatible AccountId/Address

* With tests

* Adjust definitions

* Update packages/types/src/ethereum/LookupSource.ts

* Renames
2020-08-22 12:30:24 +02:00
Github Actions e0626c3dad [CI Skip] release/beta 1.30.0-beta.3
skip-checks: true
2020-08-22 09:53:13 +00:00
Jaco Greeff 277ea92fda Adjust Address <-> LookupSource definitions (#2502) 2020-08-22 11:43:19 +02:00
Github Actions aec6694028 [CI Skip] release/beta 1.30.0-beta.2
skip-checks: true
2020-08-22 08:31:53 +00:00
Jaco Greeff 533abb76f7 Bump deps (#2500)
* Bump deps

* Rewrite
2020-08-22 10:20:40 +02:00
Github Actions 7660bab86b [CI Skip] release/beta 1.30.0-beta.1
skip-checks: true
2020-08-20 08:45:46 +00:00
Jaco Greeff f7c1b6e81b Check system.account (& balances) for new queries (#2495) 2020-08-20 10:33:47 +02:00
Github Actions b6e9b29570 [CI Skip] release/beta 1.30.0-beta.0
skip-checks: true
2020-08-18 09:51:26 +00:00
Jaco Greeff 519d9c8fa9 Types for proposeParachain module (#2493) 2020-08-18 11:40:30 +02:00
Github Actions ad905db53b [CI Skip] release/stable 1.29.1
skip-checks: true
2020-08-17 10:56:06 +00:00
Jaco Greeff 0a0aa742b4 1.29 (#2489) 2020-08-17 12:43:56 +02:00
Github Actions dfbb06a4d6 [CI Skip] release/beta 1.29.0-beta.5
skip-checks: true
2020-08-13 09:05:15 +00:00
Jaco Greeff 82e71fd51e Bump deps (#2486) 2020-08-13 10:54:45 +02:00
Github Actions a8b88af97a [CI Skip] release/beta 1.29.0-beta.4
skip-checks: true
2020-08-13 07:59:11 +00:00
sung wu eee36537de Update tx.md (#2485)
fix sample code
2020-08-13 09:47:22 +02:00
Github Actions 20a75eafb6 [CI Skip] release/beta 1.29.0-beta.3
skip-checks: true
2020-08-11 15:33:01 +00:00
Jaco Greeff 00d3a1174b Add desiredRunnersUp (#2484) 2020-08-11 17:21:30 +02:00
Github Actions e293c7c1cf [CI Skip] release/beta 1.29.0-beta.2
skip-checks: true
2020-08-11 11:54:13 +00:00
Jaco Greeff 3c8cd499c4 Introduce compact version of CompactAssignments (#2483)
* Introduce compact version of CompactAssignments

* Rebuild interfaces, update tests
2020-08-11 13:43:24 +02:00
Github Actions cb3816df78 [CI Skip] release/beta 1.29.0-beta.1
skip-checks: true
2020-08-11 08:01:38 +00:00
Jaco Greeff fcfcbb2d97 Additional Fixed* types (#2481) 2020-08-11 09:50:28 +02:00
Github Actions 321b80ed63 [CI Skip] release/beta 1.29.0-beta.0
skip-checks: true
2020-08-10 14:55:58 +00:00
Jaco Greeff 73eaa9fe17 Cleanup id from index lookups (#2479) 2020-08-10 16:42:27 +02:00
Github Actions 4d8910f3da [CI Skip] release/stable 1.28.1
skip-checks: true
2020-08-10 06:20:15 +00:00
Jaco Greeff e6806ed7f9 jg-1.28 (#2478) 2020-08-10 08:10:21 +02:00
Github Actions 218abf9568 [CI Skip] release/beta 1.28.0-beta.6
skip-checks: true
2020-08-08 07:21:20 +00:00
Jaco Greeff a1df864681 Nump deps (#2477) 2020-08-08 09:09:30 +02:00
Github Actions 45640edcff [CI Skip] release/beta 1.28.0-beta.5
skip-checks: true
2020-08-07 09:29:23 +00:00
Jaco Greeff 53655019b5 Cookbook for viewing block extrinsics (#2476) 2020-08-07 11:16:33 +02:00
Github Actions a1f8bedb6d [CI Skip] release/beta 1.28.0-beta.4
skip-checks: true
2020-08-06 19:08:46 +00:00
Miguel Hervas 9d1af1eaeb Add Centrifuge missing types (#2475)
* Add missing types

* sort attempt

* sort attempt 1

* sort attempt 2
2020-08-06 20:57:07 +02:00
Github Actions 38bfd26511 [CI Skip] release/beta 1.28.0-beta.3
skip-checks: true
2020-08-06 13:07:18 +00:00
Jaco Greeff 1beaf9f208 Bump berry (#2473)
* Bump berry

* Rewrite
2020-08-06 14:56:43 +02:00
Github Actions 29c29978dd [CI Skip] release/beta 1.28.0-beta.2
skip-checks: true
2020-08-05 15:06:31 +00:00
Jaco Greeff a8d1dd0637 Bump deps (#2472) 2020-08-05 16:53:11 +02:00
Github Actions 74571dcd26 [CI Skip] release/beta 1.28.0-beta.1
skip-checks: true
2020-08-04 20:51:40 +00:00
Jaco Greeff 54b4c2620a Types for time-delay proxies (#2468)
* Types for time-delay proxies

* Remove duplicated CallHash (& generate output)
2020-08-04 22:38:56 +02:00
Github Actions da05828e74 [CI Skip] release/beta 1.28.0-beta.0
skip-checks: true
2020-08-04 11:07:26 +00:00
Jaco Greeff fa935156e1 Add ValidationFunctionParams type (#2467) 2020-08-04 12:56:55 +02:00
Github Actions 19510c1ede [CI Skip] release/stable 1.27.1
skip-checks: true
2020-08-03 07:18:56 +00:00
Jaco Greeff 97b5c699b1 1.27 (#2462) 2020-08-03 09:08:09 +02:00
Github Actions d2befda86e [CI Skip] release/beta 1.27.0-beta.3
skip-checks: true
2020-07-31 09:46:53 +00:00
Jaco Greeff 740348b48f Bump deps (#2460) 2020-07-31 11:34:00 +02:00
Github Actions 9e2a5cf532 [CI Skip] release/beta 1.27.0-beta.2
skip-checks: true
2020-07-30 16:28:52 +00:00
Jaco Greeff 6df466d9ea Known types for Rococo (#2459)
* Known types for Rococo

* Update rococo.ts
2020-07-30 18:17:32 +02:00
Github Actions e2a2ac2842 [CI Skip] release/beta 1.27.0-beta.1
skip-checks: true
2020-07-28 11:11:30 +00:00
sung wu 5adc846e45 update doc - "create instance" page (#2456)
poc-3.polkadot.io is not available right now. use rpc.polkadot.io instead.
2020-07-28 12:59:27 +02:00
Github Actions 75aa310837 [CI Skip] release/beta 1.27.0-beta.0
skip-checks: true
2020-07-28 10:27:07 +00:00
Jaco Greeff ce0523eb1c Raw toHuman Ascii detection (#2455) 2020-07-28 12:17:26 +02:00
262 changed files with 7269 additions and 4567 deletions
+1
View File
@@ -4,3 +4,4 @@
1.11.2
1.12.2
1.17.2
1.31.2
+3 -1
View File
@@ -13,6 +13,8 @@ module.exports = {
// add override for any (a metric ton of them, initial conversion)
'@typescript-eslint/no-explicit-any': 'off',
// these should be removed, there are 8 of them as errors
'@typescript-eslint/no-non-null-assertion': 'off'
'@typescript-eslint/no-non-null-assertion': 'off',
// this seems very broken atm, false positives
'@typescript-eslint/unbound-method': 'off'
}
};
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+55
View File
File diff suppressed because one or more lines are too long
-56
View File
File diff suppressed because one or more lines are too long
+2 -2
View File
@@ -5,7 +5,7 @@ enableProgressBars: false
nodeLinker: node-modules
plugins:
- path: .yarn/plugins/@yarnpkg/plugin-interactive-tools.js
- path: .yarn/plugins/@yarnpkg/plugin-interactive-tools.cjs
spec: "@yarnpkg/plugin-interactive-tools"
yarnPath: .yarn/releases/yarn-rc.js
yarnPath: .yarn/releases/yarn-2.2.2.cjs
+396 -4
View File
@@ -1,21 +1,161 @@
# CHANGELOG
## 1.32.1 Sep 7, 2020
Upgrade priority: Low. Recommended when manually using provider connect/disconnect or using multiple instances in a single process.
- **Breaking change** Previously `.isReady` could throw an error, now it will always succeed on connection. For trapping errors, use the `.isReadyOrError` variant on the API
- **Breaking change** The `isConnected` provider interface is now a getter, replacing previous calls to `provider.isConnected()`. Additionally the `provider.disconnect()` is now async, aligning with `.connect()`.
Contributed:
- Expand vesting information via derive balances (Thanks to https://github.com/niklabh)
- Add `isReadyOrError` to API, `isReady` always succeeds (Thanks to https://github.com/shawntabrizi)
Changes:
- Adjust memoization to work on a per-instance basis, with no contamination between multiple api/provider instances
- Added `derive.chain.getBlock(hash)` to retrieve a `SignedBlock` extended with an `.author` (same as `derive.chain.getHeader(...)`)
- Added `api.{connect, disconnect}()` as well as `isConnected` interfaces. The first functions async returning `Promise<void>`
- Error on provider connections will now emit all (as expected) via the event emitter
- Ensure that initial connection failures always retry (when using auto-connection management)
- The `api.derive.staking.query/queryMulti` no longer retrieves session keys (can be done via `.keys/keysMulti`)
- Add `api.derive.accounts.accountId` to perform AccountId lookups (from indices or actual AccountId)
- Lessen load of `paymentInfo` queries to only use accounId mappings as available
- Adjust staking derives to cater for early Substrate 2.0 chains (optional/non-optional EraIndexes)
- Cater for the handling of nested aliased types, e.g. wrapped inside Vec or Tuple
- Add the support for the `grandpa_subscribeJustifications` RPC
- Adjust `Call.toHuman()` to remove decoding-related technical internal details
- Static metadata & tests updated for the latest substrate master
- `toHuman()` & `.toBigInt()` has been explicitly added to the API documentation
- Adjust known types for latest Kusama network state
## 1.31.1 Aug 31, 2020
Upgrade priority: Medium, especially for staking users on Polkadot, Kusama & Westend (type updates applied for v23 onwards) or if transparent `.at(hash)` queries are required/used
- **Important** Substrate changed the `RewardDestination` enum with an extra field for payout-to-any account for staking preferences. If on an older chain consider adding `RewardDestination: 'RewardDestinationTo257'`
- **Important** Substrate changed the `CompactAssignment` type enhanced types for session solution submissions. If on an older chain consider adding `CompactAssignments: 'CompactAssignmentsTo257'`
Contributed:
- Fix documentation language and typos (Thanks to https://github.com/Meuko)
- Add missing `TransactionPriority` type (Thanks to https://github.com/aniiantt)
- Update definitions for new `CompactAssignments`, including tests (Thanks to https://github.com/kianenigma)
Changes:
- Add transparent support for types/metadata, i.e. hash queries such as `rpc.chain.getBlock(<hash>)` & `query.system.events.at(<hash>)` now works out-of-the-box injecting the correct metadata & types.
- Optimize RPC-layer calls with detection of short-term cacheable calls (in the same way subscriptions are done)
- Additional checks on `AccountId` for valid sizes
- Add `toBigInt()` (JS built-in `BigInt`) on `Int/Uint`, & `Compact<*>` types
- Support for `.concat` on Codec arrays
- Support for serialization with `isBare` flag on enums
- Add `api.getBlockRegistry(blockHash?)` to create registry/types for a specific block
- `derive.democracy.locks` now returns delegated locks for an account as well
- Adjust unlocking derives with appropriate in-place additions (less object allocations)
- `.sign` on submittables is marked deprecated (not due for removal, but rather use `.signAsync` for consistency with `.signAndSend`)
- Adjust types for `CompactAssignments` & `RewardDestination` for Polkadot, Kusama & Westend
- `@polkadot/util` 3.4
- `@polkadot/wasm-crypto` 1.4
## 1.30.1 Aug 24, 2020
Upgrade priority: Low, unless using the `proposeParachain` module.
Changes:
- Adjust balance retrievals to check for `system.account` for new/old determination
- Add types for the new `proposeParachain` module (as per Rococo)
- Adjust `Address` <-> `LookupSource` definitions (no external impact, both in existence)
- Add Ethereum-compatible `Ethereum{AccountId, LookupSource}` types, underlying `H160`
- Allow for configurable hashers via `registry.setHasher(...)` (defaults to `blake2AsU8a`)
- `@polkadot/util` 3.3
## 1.29.1 Aug 17, 2020
Upgrade priority: Low, unless on bleeding-edge chain with new compact `CompactAssignments`.
- **Important** The Substrate `CompactAssignments` type has changed for better space utilization. On older chains, supply `CompactAssignments: 'CompactAssignmentsTo257'`
Contributed:
- Clean tx cookbook param expansion (Thanks to https://github.com/swswsw)
Changes:
- Add additional `Fixed{I,U}{64,128}` and `{I,U}32F32` types
- Add `desiredRunnersUp` to council derives
- Cleanup indices/AccountId combination derive lookups
- `@polkadot/util` 3.2
## 1.28.1 Aug 10, 2020
Upgrade priority: Low, unless using Centrifuge or parachains
Contributed:
- Update Centrifuge types to latest (Thanks to https://github.com/mikiquantum)
Changes:
- Add cookbook entry for viewing block extrinsics
- Support types for time-delay proxies
- Update types for parachains
- `@polkadot/util` 3.1
- `@polkadot/wasm-crypto` 1.3
## 1.27.1 Aug 3, 2020
Upgrade priority: Low, unless using the Rococo chain
Contributed:
- Remove outdated example poc-3 RPC reference (Thanks to https://github.com/swswsw)
Changes:
- Raw/Bytes `toHuman` detects ASCII sequence for text output
- Add know types for the Rococo chain
## 1.26.1 Jul 27, 2020
Upgrade priority: Low
Contributed:
- Update docs for the new `system.accountNextIndex` (Thanks to https://github.com/shawntabrizi)
- Update contracts call parameter typing (Thanks to https://github.com/kwingram25)
Changes:
- Adjust votingBalance to only return `freeBalance` (only council voting is free + reserved)
- Additional checks for referenced Vec sub-type deconstruction in typegen
- Allow for API `typesBundle` option to inject a group of chain versions types
- Update metadata static tests for latest Substrate
- `@polkadot/util` 3.0
## 1.25.1 Jul 20, 2020
Upgrade priority: Medium, especially if using contracts.
- **Important** Contract RPC result updated on Substrate, on older chains supply `ContractExecResult: 'ContractExecResultTo255'`
Contributed:
- Support for custom HTTP headers in providers (Thanks to https://github.com/brad-larson)
- Update known types for Centrifuge (Thanks to https://github.com/philipstanislaus)
- Update API users with Registrar #1 (Thanks to https://github.com/chevdor)
Changes:
- Raw/Bytes `toHuman()` displays utf-8 as available
- Add fallback for `setImmediate` when not polyfilled
- Update `NetworkState` reputation type for `system_networkState` RPC
@@ -23,15 +163,24 @@
- Fix class prototype for (basically-deprecated) Linkage type
- Add Polkadot types for `purchase` pallet
## 1.24.1 Jul 13, 2020
Changes:
- 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
Contributed:
- Small README typo fix (Thanks to https://github.com/woss)
Changes:
- Add latest Substrate master types
- Adjust `<Codec>.toRawType()` to use registry name as available
- Update `ProxyType` for Kusama, Polkadot & Westend with `IdentityJudgement`
@@ -39,27 +188,44 @@
- 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'`
Contributed:
- Allow for `[u8; 33]` in U8aFixed (Thanks to https://github.com/akru)
Changes:
- 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
Contributed:
- Fix subscriptions never unsubscribing after the id swap in 1.18.1 (Thanks to https://github.com/dillu24 for testing iterations)
Changes:
- 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)
Changes:
- 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
@@ -67,33 +233,54 @@
- Adjust types & metadata for latest Substrate
- `@polkadot/util` 2.15
## 1.19.1 Jun 16, 2020
Contributed:
- Improve typing on `.entries()` queries (Thanks to https://github.com/monitz87)
Changes:
- 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
Contributed:
- 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)
Changes:
- 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
Changes:
- Ensure subscription promise resolves before first result
## 1.17.1 Jun 2, 2020
Contributed:
- Fix `ElectionSize` type (Thanks to https://github.com/arjanz)
Changes:
- 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)
@@ -101,8 +288,11 @@
- Support for latest Substrate types & metadata
- `@polkadot/util` 2.12
## 1.16.1 May 26, 2020
Changes:
- Support for Polkadot CC1 types & signed extensions
- Add support for Babe VRF secondary digests (author extraction)
- Adjust `Perbill/Permill` `toHuman()` formatting to output percentage
@@ -110,24 +300,36 @@
- Update to latest TypeScript, eslint & typescript-eslint
- `@polkadot/util` 2.11
## 1.15.1 May 23, 2020
Contributed:
- 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)
Changes:
- 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'`
Contributed:
- 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
Changes:
- 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)
@@ -139,45 +341,70 @@
- Extends types for Polkadot claims
- Update `@polkadot/util` to 2.10
## 1.13.1 May 6, 2020
Contributed:
- 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)
Changes:
- 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
Changes:
- 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
Contributed:
- 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)
Changes:
- 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
Changes:
- 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)
Contributed:
- 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)
Changes:
- 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
@@ -190,9 +417,13 @@
- 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'`
Changes:
- Add `rpc.system.chainType` to retrieve the chain type (Development. Local, Live & Custom)
- Adjust types for Westend after the reset
- Adjust democracy derives, including the support of the frame-scheduler for scheduled deployments
@@ -203,10 +434,14 @@
- 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
- **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
Changes:
- Tx signing via `signAndSend` & `signAsync` now tries to use the last finalized block (depending on finalized drift)
- Add support for `api.rpc.childstate.*` Substrate RPCs, older nodes with still populate `api.rpc.state.*` with the child methods
- Adjust `Error.message` on RPC failures to not include the (already known) method signature
@@ -218,11 +453,15 @@
- 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
- **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`
- **Important** Substrate has an updated democracy module. If using an older chain add the `ReferendumInfo: 'ReferendumInfoTo239'` type when using referendums
Changes:
- The `isRetracted` Extrinsic status is now a warning, not a fatal error, correctly aligning with Polkadot/Substrate
- The Substrate extrinsic phase definitions has been expanded with `Initialization` to align with the latest versions
- Add support for all known substrate RPC methods
@@ -230,9 +469,13 @@
- 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
- **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.
Changes:
- Pull in support and types for latest Polkadot/Substrate
- Add support for the new Substrate `state_getKeysPaged` RPC, including use in storage keys
- Move `derive.staking.controllers` to `derive.staking.stashes`, reflecting actual content
@@ -240,13 +483,20 @@
- 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
Changes:
- Revert checks for query args, not working on `.at()` queries (proper fix in next version)
## 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.
Changes:
- `StorageKey` now has an `.args` property, decoded from meta where `twox64_concat` or `blake128_concat` are used on maps
- Fix `api.query.*.*.entries` type conversions to return exact types (not `Option` in some cases)
- Add `api.query.*.*.keys` to retrieve only the storage keys, similar to `.entries`
@@ -258,13 +508,20 @@
- 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
- **Important** Substrate master has updated staking, on older chains supply `StakingLedger: 'StakingLedgerTo223'`
- **Important** Substrate master has updated collective, on older chains supply `Votes: 'VotesTo230'`
Contributed:
- Add proper support for type generation with an Enum containing an Tuple (Thanks to https://github.com/monitz87)
- Fix storage parsing not resulting in rejected Promises (Fix from https://github.com/aniiantt applied)
- Remove use of deprecated `Observable.create` (Thanks to https://github.com/Himself65)
Changes:
- Add types & metadata for the latest Polkadot/Substrate runtime versions (master branches)
- Type extraction will now allow the same sub-module name across packages, i.e. `@polkadot/types/interfaces/runtime` & `@mine/interfaces/runtime` will be valid
- Add `.range([from, to]: [Hash, Hash?], ...args: any[]): [Hash, Codec][]` on all storage entries
@@ -278,17 +535,27 @@
- 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
Changes:
- Fix `api.tx(<extrinsic>): Submittable` decoration (non-working in 1.4.1, now with proper test)
## 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
Contributed:
- Rework type generation for `api.{query, tx}` to properly handle complex type inputs (Thanks to https://github.com/monitz87)
- Rework metadata `--strict` mode to effectively decorate chain metadata (Thanks to https://github.com/monitz87)
- Add `api.rpc.chain.subscribeAllHeads` (not just best) (Thanks to https://github.com/jak-pan)
Changes:
- Add `api.rpc.engine.*` for manual seal support
- Add `api.injectMetadata(metadata)` to initialize API with a specific metadata version
- The api now checks for runtime upgrades, augmenting the interfaces with new metadata when found
@@ -308,18 +575,31 @@
- 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
Contributed:
- Add `@types/bn.js` as a normal dependency, exposed in `*.d.ts` (Thanks to https://github.com/monitz87)
Changes:
- Type generation scripts (including `polkadot-types-from-{chain,defs}`) has been moved to the `@polkadot/typegen` package
- The `@polkadot/types/codec/create` has been moved to `@polkadot/types/create`, imports from `@polkadot/types` are unaffected
- 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
- **Important** Update RPC status codes (latest Substrate 2), with the `isInBlock` (`isFinalized` now indicates finality)
Contributed:
- Storage `.entries(arg?: any)` now has the correct argument type for DoubleMap (Thanks to https://github.com/monitz87)
Changes:
- Swap Kusama and Polkadot aliases for `Address` to `AccountId` (future update)
- Add `LookupSource` and `LookupTarget` types instead of mapping these directly for aliasing
- Add `BitVec` type primitive
@@ -334,9 +614,13 @@
- 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
- **Important** Chains without `balances.account` or `system.account` should supply `"BalanceLock": "BalanceLockTo212"` to their types to use the previous-generation `BalanceLock` (when querying locks)
Changes:
- Add support for `balances.account` in all applicable derives (incl. `vesting` module)
- Inject and use SignedExtensions by name from V11 metadata (V4 extrinsics only)
- Add typings for `api.tx.*.*` - the `polkadot-types-from-chain` now also generates these
@@ -348,11 +632,18 @@
- 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
- **Breaking change** Drop support for Substrate v1 chain in all derives
Contributed:
- Return unsub functions from provider .on emitters (Thanks to https://github.com/jak-pan)
- `ApiPromise.isReady` now rejects on unrecoverable errors (Thanks to https://github.com/laec)
Changes:
- Add `polkadot-types-from-chain` & `polkadot-types-from-defs` TypeScript generators to `@polkadot/types`
- Only decorate derives where relevant parent `api.query.*` is available
- Support `.entries(arg?: any)` lookups on DoubleMaps (in addition to previously supported maps)
@@ -367,49 +658,73 @@
- Remove support for un-deployed metadata
- Remove old known types for Substrate V1
## 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.
Contributed:
- Add support for `BTreeSet` (Thanks to https://github.com/satellitex)
Changes:
- Add support for the Substrate identity module
- Remove the `codec/Data` type, to remove a conflict with Substrate. This type is now named `Raw`
- Fix for linked maps using `Option`
- Add support for `BTreeSet` (Thanks to https://github.com/satellitex)
- Add support for Metadata v10
- Add support for latest Polkadot/Substrate types
- Add `paymentInfo` to submittables to calculate fees
## 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`
Changes:
- Cleanup `DoubleMap` hashing to always hash over the full value (in the case of `Vec<T>`, this includes the length)
- Update democracy derives to take care of nextTally and lowestUnbaked
- Add additional derives for both council & treasury
- Alignment with latest Polkadot/Substrate master branch types
## 0.98.1 Dec 04, 2019
Contributed:
- 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
- Add `.signAsync` to submittable extrinsics (Thanks to https://github.com/c410-f3r)
Changes:
- Cleanup circular references between internal dependencies
- Support for new Substrate democracy with preimages in derive
- Alignment of types with Substrate/Polkadot master branches
## 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.*`.
- **Breaking change** Session `Keys` defaults to 4 keys now (Substrate master), depending on your node config, you would want to override with e.g. `Keys: 'SessionKeys3'` (1, 2, 3, 4, 5 & 6)
- **Breaking change** `ValidatorPrefs` now default to the new percentage commission model, to use the previous `validatorPayment`, you can override with `ValidatorPrefs: 'ValidatorPrefsTo196'`
Changes:
- `api.derive.*` now has built-in memomization
- Various fixes and cleanups to `api.derive.*` including era length progress and vesting calculations
- Aligned all types with the latest Polkadot & Substrate, including Kusama CC3
- 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
Changes:
- Updated types for latest Kusama
- Add `filterRecords` (in addition to `findRecord`) on submittable results
- Various ABI v2 contract fixes
@@ -418,22 +733,31 @@
- 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
Changes:
- Temporary removal of `account_nextIndex` use, will be re-added in a future release
## 0.95.1 Oct 25, 2019
- **Breaking change** `Call.injectMethods` is moved to `Call.injectMetadata` to align with `Events` (This _should_ not be used externally, however mentioned as breaking here)
Changes:
- Support Extrinsic V4 with additional signature indicator (Latest Polkadot/Substrate/Kusama)
- Adjust subscription update checks to avoid duplicated data updates
- Support Metadata V8 (exposes per-module `decl_error` definitions)
- Support next generation contracts ABI (with additional type definitions)
- Support for `BTreeMap<K, V>` types and definitions
- 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
Changes:
- Add handling of `Result<Ok, Error>` definitions
- Adjust API cloning now takes RPC filters from source into account
- Simplification of isPedantic checks and less overhead on StorageData types
@@ -444,8 +768,11 @@
- Add documentation for custom extrinsic formats (advanced chains)
- Update to latest substrate master metadata
## 0.93.1 Sep 26, 2019
Changes:
- Support for Kusama CC2
- In extrinsic submission, use `rpc.account.nextIndex` to retrieve the nonce when available
- For TypeScript users `api.query.*.*` is now properly typed for default Substrate calls, i.e. `api.query.balances.freeBalance(...)` will return a `Balance` type. Additionally the `api.queryMulti` and `.multi` on queries not allow generic type params.
@@ -454,16 +781,22 @@
- 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
Changes:
- 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`
- The `Keyring` from `@polkadot/keyring` is now exposed on the API as well. You can do `import { Keyring } from '@polkadot/api'` - this alleviates the need for extra dependencies (apart from `@polkadot/api`), and since the keyring is critical for signing operations, aligns everything in one bundle
- Support the latest Polkadot & Substrate master branches (incl. metadata updates)
- Getting started documentation has been made available
## 0.91.1 Sep 09, 2019
Changes:
- 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
- The `getRuntimeVersion` and `subscribeRuntimeVersion` RPCs are now only available on the `rpc.state.*` endpoints. This aligns with the Substrate implementation.
@@ -476,6 +809,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
If you are upgrading form an older version, use the CHANGELOG hand-in-hand with the [migration guide](UPGRADING.md).
@@ -489,6 +823,9 @@ If you are upgrading form an older version, use the CHANGELOG hand-in-hand with
- For creation of types, it is recommended to use `createType(<TypeName>, <value>)` instead of e.g. `new Proposal(...)`. When passing these to methods/queries, construction should not be needed, the raw value can be passed.
- For moved types, a previous import would have been from `@polkadot/types`, i.e. `import { SetIndex } from '@polkadot/types`, now just the interfaces (TypeScript) are available via `import { SetIndex } from '@polkadot/types/interfaces`
- `usize` is now a blacklisted type that will throw on construction. Since it is platform-specific, it creates incompatibilities between native (generally `u64`) and WASM (always `u32`) code. Use one of the `u32` or `u64` types explicitly.
Changes:
- Support substrate v7 metadata
- The `Method.findFunction(callIndex)` (allowing decoding of raw data), is now available on `api.findCall(callIndex)`. To keep backwards compatibility, it is still available on `GenericCall.findMethod` but the `api.findCall` is recommended and suggested.
- 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
@@ -496,6 +833,8 @@ If you are upgrading form an older version, use the CHANGELOG hand-in-hand with
## 0.82.0-beta.x Jul 28, 2019
Changes:
- Support for substrate 2.x (master) has been extended,
- Additional types have been addedd for the modules
- `api.derive.contract` is now `api.derive.contracts` to align with the substrate 2.x rename. (Feature detection is used so it supports both 1.x and 2.x chains)
@@ -515,6 +854,8 @@ If you are upgrading form an older version, use the CHANGELOG hand-in-hand with
## 0.81.1 Jun 14, 2019
Changes:
- 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)
- `api.derive.staking.info` now returns the `rewardDestination`
@@ -535,6 +876,8 @@ If you are upgrading form an older version, use the CHANGELOG hand-in-hand with
## 0.80.1 Jun 04, 2019
Changes:
- Support for mortal transactions
- Better DoubleMap storage support
- api-derive cleanups, including additional info for balances.all and taking.info returning redeemable and locked balances
@@ -545,6 +888,8 @@ If you are upgrading form an older version, use the CHANGELOG hand-in-hand with
## 0.79.1 May 22, 2019
Changes:
- DoubleMap query support
- Support latest EventRecord metadata (substrate master)
- Introduce RuntimeVersion type overrides in api/nodeCompat.ts
@@ -557,6 +902,8 @@ If you are upgrading form an older version, use the CHANGELOG hand-in-hand with
## 0.78.1 May 08, 2019
Changes:
- Fix linked-maps (not working since 0.77.1)
- Convert Usize to U32 (as found in WASM environments)
- Allow pre-bundled metadata in API create & constructor
@@ -568,12 +915,16 @@ If you are upgrading form an older version, use the CHANGELOG hand-in-hand with
## 0.77.1 Apr 25, 2019
Changes:
- 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
Changes:
- Caching improvements (duplicate queries, no duplicate subscriptions)
- Experimental contract API
- Update @polkadot/keyring to enable Alice's stash account on dev chains
@@ -582,15 +933,18 @@ If you are upgrading form an older version, use the CHANGELOG hand-in-hand with
## 0.75.1 Mar 29, 2019
Changes:
- Start journey to 1.0
## 0.53.1 Mar 29, 2019
Changes:
- 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`)
- If using `subscribeFinalisedHeads` update this to `subscribeFinalizedHeads` (likewise `getFinalisedHead` should be updated to `getFinalizedHead` and `derive.bestNumberFinalized`)
- The underlying ss58 address checksums have changed
- The updated keyring with support for this has been made available
- All examples have been updated with sr25519 addresses (with the new checksums)
@@ -598,6 +952,8 @@ If you are upgrading form an older version, use the CHANGELOG hand-in-hand with
## 0.52.1 Mar 28, 2019
Changes:
- Support queries to linked mapped storage (found in new staking interfaces)
- Add `derive.staking.controllers` to retrieve all active staking controllers
- Align types as per latest substrate master
@@ -608,34 +964,46 @@ If you are upgrading form an older version, use the CHANGELOG hand-in-hand with
## 0.51.1 Mar 25, 2019
Changes:
- Support metadata V2 as per latest substrate master
- Update metadata with new types as per latest substrate master
## 0.50.1 Mar 23, 2019
Changes:
- 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
Changes:
- 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
Changes:
- 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
Changes:
- Swap to publishing -beta.x on merge (non-breaking testing)
## 0.46.1 Mar 01, 2019
Changes:
- 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
@@ -643,6 +1011,8 @@ If you are upgrading form an older version, use the CHANGELOG hand-in-hand with
## 0.45.1 Feb 19, 2019
Changes:
- Storage with option values now correctly return `Option<Type>` and is indicated as such in the documentation
```js
@@ -660,6 +1030,8 @@ console.log('llo', llo.unwrapOr('not set') /* Option<BlockNumber> */)
## 0.44.1 Feb 19, 2019
Changes:
- 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.
```js
@@ -678,37 +1050,51 @@ import { Method, Signature } from '@polkadot/types';
## 0.43.1 Feb 14, 2019
Changes:
- 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
Changes:
- 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
Changes:
- Support the V1 metadata specification from Substrate in addition to the currently testnet active V0 version
## 0.40.1 Jan 16, 2019
Changes:
- 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
Changes:
- The Promise API now returns a `Promise<UnsubFunction>` instead of `UnsubFunction` when making subscriptions.
## 0.38.1 Jan 08, 2019
Changes:
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
Changes:
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.
@@ -716,6 +1102,8 @@ Tuples now return single types when only one type is available, i.e. `(AccountId
## 0.36.1 Jan 03, 2019
Changes:
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.
```js
@@ -727,11 +1115,15 @@ unsubscribe(); // here we destroy the subscription
## 0.35.1 Dec 20, 2018
Changes:
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
Changes:
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
+23
View File
@@ -0,0 +1,23 @@
#!/usr/bin/env bash
function copy_folder () {
SRC="packages/$1/build"
DST="../test/js-test/node_modules/@polkadot/$1"
echo "** Copying $SRC to $DST"
rm -rf $DST
cp -r $SRC $DST
}
yarn polkadot-dev-build-ts
copy_folder "api"
copy_folder "api-contract"
copy_folder "api-derive"
copy_folder "metadata"
copy_folder "rpc-core"
copy_folder "rpc-provider"
copy_folder "types"
copy_folder "types-known"
copy_folder "typegen"
+17
View File
@@ -42,3 +42,20 @@ const header = await api.derive.chain.getHeader();
console.log(`#${header.number}: ${header.author}`);
```
## How do I view block extrinsic information?
The transactions are included in a signed block as part of the extrinsics - some of these will be unsigned and generated by the block author and some of these may be submitted from external sources and be signed. (Some palettes do use unsigned transactions, so signed/unsigned is not an indication of origin). To retrieve the block and display the transaction information, we can do the following -
```js
// no blockHash is specified, so we retrieve the latest
const signedBlock = await this.api.rpc.chain.getBlock();
// the information for each of the contained extrinsics
signedBlock.block.extrinsics.forEach((ex, index) => {
// the extrinsics are decoded by the API
console.log(index, ex.toHuman());
});
```
In the above `.toHuman()` is used to format into a human-readable representation. You can inspect/extract specific fields from the decoded extrinsic as required, for instance `ex.method.section` would return the pallete that executed this transaction.
+3 -3
View File
@@ -16,9 +16,9 @@ const info = await api.tx.balances
// log relevant info, partialFee is Balance, estimated for current
console.log(`
class=${class.toString()},
weight=${weight.toString()},
partialFee=${partialFee.toHuman()}
class=${info.class.toString()},
weight=${info.weight.toString()},
partialFee=${info.partialFee.toHuman()}
`);
```
+2 -2
View File
@@ -90,7 +90,7 @@ Looking at the example in this repo, it also has `augment*`, `index.ts` and `typ
## Generating
Now that both the metadata nd types setup is completed, we just run the build command via `yarn build` and magically (assuming you didn't have the `augment*` and other generated files), these files will be added. When running this command, the console should display something like -
Now that both the metadata and types setup is completed, we just run the build command via `yarn build` and magically (assuming you didn't have the `augment*` and other generated files), these files will be added. When running this command, the console should display something like -
```
> yarn build
@@ -166,7 +166,7 @@ As mentioned earlier, here you will notice the `import { VoteStage }`, the gener
## TypeScript config
Now that we have files generated, it is time to make TypeScript aware of the types and add an explicit override into out `tsconfig.json`. After some changes, the paths in the config looks as follow (comments are in teh actual config file here) -
Now that we have files generated, it is time to make TypeScript aware of the types and add an explicit override into out `tsconfig.json`. After some changes, the paths in the config looks as follow (comments are in the actual config file here) -
```json
{
-14
View File
@@ -22,7 +22,6 @@ To fix this, you should look at the specific `api.tx.*` params and adjust the ty
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).
@@ -66,16 +65,3 @@ Due to these customizations and differences that bleed through to the transactio
Recently Substrate master updated the `Weight` type from `u32` -> `u64`. This type is used in the `DispatchInfo` struct in the `system.ExtrinsicSuccess` events, to return the applied call weights as well as the resulting fees. Since the API master branch tracks Substrate master, this means the change has been applied by default, with the default set to `u64`.
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
+3 -3
View File
@@ -8,7 +8,7 @@ import { ApiPromise, WsProvider } from '@polkadot/api';
...
// Construct
const wsProvider = new WsProvider('wss://poc-3.polkadot.io');
const wsProvider = new WsProvider('wss://rpc.polkadot.io');
const api = await ApiPromise.create({ provider: wsProvider });
// Do something
@@ -49,7 +49,7 @@ The API creation is done via the `ApiPromise.create` interface which is a shortc
```js
ApiPromise
.create({ provider: wsProvider })
.create({ provider: wsProvider }).isReady
.then((api) =>
console.log(api.genesisHash.toHex())
);
@@ -70,7 +70,7 @@ console.log(api.genesisHash.toHex());
## Failures
In all cases the API will handle reconnections automatically. This means that when you connect and the endpoint is not (yet) ready, the promise will not resolve immediately, but rather when connected. The same applies to when connection is lost, the API will manage re-connections.
In all cases the API will handle reconnecting automatically. This means that when you connect and the endpoint is not (yet) ready, the promise will not resolve immediately, but rather when connected. The same applies to when connection is lost, the API will manage re-connections.
In cases where the API does not support the chain being connected to, such as it using an unknown metadata version, the ready promise will fail to resolve and instead reject.
+1 -1
View File
@@ -42,7 +42,7 @@ Be aware that while defined, the method will only appear on the API if it is in
## Definition breakdown
While the above example should be self-explanatory, it is important to understand teh structure. The `rpc: { ... }` definitions are keyed first and foremost by the name of the module exposing the RPC. This means that when we have 2 modules `firstModule` & `testModule`, the first-level structure would follow the following pattern,
While the above example should be self-explanatory, it is important to understand the structure. The `rpc: { ... }` definitions are keyed first and foremost by the name of the module exposing the RPC. This means that when we have 2 modules `firstModule` & `testModule`, the first-level structure would follow the following pattern,
```js
...
+2
View File
@@ -10,6 +10,7 @@ As a minimum, anything returned by the API, be it a `Vec<...>`, `Option<...>`, `
- `.eq(<other value>)` - checks for equality against the other value. In all cases, it will accept "like" values, i.e. in the case of a number you can pass a primitive (such as `1`), a hex value (such as `0x01`) or even an `Unit8Array`
- `toHex()` - returns a hex-base representation of the value, always prefixed by `0x`
- `toHuman()` - returns Human-parsable JSON structure with values formatted as per the settings
- `toJSON()` - returns a JSON-like representation of the value, this is generally used when calling `JSON.stringify(...)` on the value
- `toString()` - returns a string representation, in some cases this performs additional encoding, i.e. for `Address`, `AccountId` and `AccountIndex` it will encode to the ss58 address
- `.toU8a()` - returns a `Uint8Array` representation of the encoded value (generally exactly as passed to the node, where values are SCALE encoded)
@@ -41,6 +42,7 @@ const system = modules.find(m => m.name.eq('system'));
All numbers wrap and extend an instance of [bn.js](https://github.com/indutny/bn.js/). This means that in addition to the interfaces defined above, they have some additional methods -
- `.toNumber()` - a JS number (limited to 2^53 - 1). This does mean that for large values, e.g. `Balance` (a `u128` extension), this can cause overflows
- `.toBigInt()` - a JS `BigInt` object (on supported platforms)
- `.add(...)`, `.sub(...)`, ... - all the base methods available on the `BN` object
In cases where a `Compact` is returned, i.e. `Compact<Balance>`, the value is wrapped. This object should be `.unwrap()`-ed first to gain access to the underlying `Balance` object.
+1 -1
View File
@@ -20,7 +20,7 @@ With the conversions done in the API, there are limited reasons to create types
import type { Balance } from '@polkadot/types/interfaces';
...
// unwrap out option into a zero Balance whn not found
// unwrap out option into a zero Balance when not found
// (This can be done via `.unwrapOrDefault()`, which does the same underlying)
const balance: Balance = balanceOpt.unwrapOr(api.createType('Balance'));
```
+3 -3
View File
@@ -6,7 +6,7 @@ Therefore to cater for all types, a mapping in done on the [@polkadot/types libr
Additionally, the API contains some logic for chain type detection, for instance in the case of Substrate 1.x based chains, it will define `BlockNumber` & `Index` (nonce) as a `u64`, while for current-generation chains, these will be defined as `u32`. Some of the work in maintaining the API for Polkadot/Substrate is the addition of types as they appear and gets used in the Rust codebase.
There is a the [recommendation](install.md#betas) to use a `@polkadot/api@beta` should you wish to track the master branches of Polkadot or Substrate, since master changes for the addition of new types do not make it into a stable release immediately.
There is the [recommendation](install.md#betas) to use a `@polkadot/api@beta` should you wish to track the master branches of Polkadot or Substrate, since master changes for the addition of new types do not make it into a stable release immediately.
## Extension
@@ -87,7 +87,7 @@ Document: {
## User-defined enum
One form of types that appear regularly is enums, these can be defined as follow -
One form of types that appear regularly is enums, these can be defined as follows -
```js
...
@@ -212,4 +212,4 @@ Always look at customization and understand the impacts, replicating these chang
## Custom RPC
In addition to customizing modules and types on your node, you can also add custom RPC definitions. Like the type definitions in ths section, [these can be defined and passed to the API](rpc.custom.md) for decoration.
In addition to customizing your node's modules and types, you can also add custom RPC definitions. Like the type definitions in this section, [these can be defined and passed to the API](rpc.custom.md) for decoration.
+3 -3
View File
@@ -1,6 +1,6 @@
# TypeScript user generated
In the previous section we looked at the TypeScript definitions that are available and is generated from both the chain and definitions. Here we will expand upon the use of the infrastructure created to define types as part of the `@polkadot/types` library and see how to use them to generate your own definitions and chain types.
In the previous section we looked at the TypeScript definitions that are available and are generated from both the chain and definitions. Here we will expand upon the use of the infrastructure created to define types as part of the `@polkadot/types` library and see how to use them to generate your own definitions and chain types.
## Definitions
@@ -17,7 +17,7 @@ In the root of your project (with the `@polkadot/typegen` package installed), yo
## Chain modules
In the same way as the type library provides defaults from a substrate-base chain, you can also, directly from chain from metadata, generate a complete `api.{consts,query}.*` definition for your specific chain. The command will create 2 files, `{consts, query}.types.ts` which you can either use to augment the TypeScript definitions, or replace those in `@polkadot/api/*` with your versions (copy, TypeScript replacement or browser/node aliasing).
In the same way as the type library provides defaults from a substrate-base chain, you can also, directly from the chain's metadata, generate a complete `api.{consts,query}.*` definition for your specific chain. The command will create 2 files, `{consts, query}.types.ts` which you can either use to augment the TypeScript definitions, or replace those in `@polkadot/api/*` with your versions (copy, TypeScript replacement or browser/node aliasing).
In the root of your project, you can run `yarn polkadot-types-from-chain --endpoint wss://<url> --output ./stuff` and it will create the required output. (Here you can specify an optional `--package @MeInc/stuff` to read definitions for the targeted output folder with the specified package name.)
@@ -27,4 +27,4 @@ The [TypeScript augmentation example](../examples/promise/90_typegen/) example p
## And that's a wrap
This brings us to the end of our overview and jump through the API. While the documentation is still very much and ever evolving item, we can encourage you to try out what you have learned with some [examples](../examples). As we [indicated right at the start of this journey](README.md#help-us-help-others), if there are areas for improvement, let us know.
This brings us to the end of our overview and jump through the API. While the documentation is still very much an ever evolving item, we can encourage you to try out what you have learned with some [examples](../examples). As we [indicated right at the start of this journey](README.md#help-us-help-others), if there are areas for improvement, let us know.
+1 -1
View File
@@ -9,5 +9,5 @@
"packages": [
"packages/*"
],
"version": "1.26.1"
"version": "1.32.1"
}
+14 -10
View File
@@ -7,7 +7,8 @@
"packages/*"
],
"resolutions": {
"babel-core": "^7.0.0-bridge.0"
"babel-core": "^7.0.0-bridge.0",
"typescript": "^4.0.2"
},
"scripts": {
"build": "yarn build:interfaces && polkadot-dev-build-ts && (cd packages/typegen && copyfiles scripts/* build)",
@@ -24,15 +25,18 @@
"test:watch": "polkadot-dev-run-test --watch"
},
"devDependencies": {
"@babel/core": "^7.10.5",
"@babel/register": "^7.10.5",
"@babel/runtime": "^7.10.5",
"@polkadot/dev": "^0.55.28",
"@polkadot/ts": "^0.3.29",
"@babel/core": "^7.11.6",
"@babel/register": "^7.11.5",
"@babel/runtime": "^7.11.2",
"@polkadot/dev": "^0.55.47",
"@polkadot/ts": "^0.3.43",
"@polkadot/typegen": "workspace:packages/typegen",
"@types/jest": "^26.0.7",
"@vuepress/plugin-search": "^1.5.2",
"copyfiles": "^2.3.0"
"@types/jest": "^26.0.13",
"@vuepress/plugin-search": "^1.5.4",
"copyfiles": "^2.3.0",
"typedoc": "^0.19.1",
"typedoc-plugin-markdown": "^2.4.2",
"typedoc-plugin-no-inherit": "^1.1.10"
},
"version": "1.26.1"
"version": "1.32.1"
}
+8 -8
View File
@@ -1,6 +1,6 @@
{
"name": "@polkadot/api-contract",
"version": "1.26.1",
"version": "1.32.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.10.5",
"@polkadot/api": "1.26.1",
"@polkadot/rpc-core": "1.26.1",
"@polkadot/types": "1.26.1",
"@polkadot/util": "^3.0.1",
"bn.js": "^5.1.2",
"rxjs": "^6.6.0"
"@babel/runtime": "^7.11.2",
"@polkadot/api": "1.32.1",
"@polkadot/rpc-core": "1.32.1",
"@polkadot/types": "1.32.1",
"@polkadot/util": "^3.4.1",
"bn.js": "^5.1.3",
"rxjs": "^6.6.2"
}
}
@@ -17,6 +17,7 @@ import Abi from '../Abi';
import Contract from './Contract';
import { BaseWithTx } from './util';
// eslint-disable-next-line no-use-before-define
type BlueprintCreateResultSubscription<ApiType extends ApiTypes> = Observable<BlueprintCreateResult<ApiType>>;
export interface BlueprintCreate<ApiType extends ApiTypes> {
+1
View File
@@ -17,6 +17,7 @@ import Abi from '../Abi';
import Blueprint from './Blueprint';
import { BaseWithTx } from './util';
// eslint-disable-next-line no-use-before-define
type CodePutCodeResultSubscription<ApiType extends ApiTypes> = Observable<CodePutCodeResult<ApiType>>;
export interface CodePutCode<ApiType extends ApiTypes> {
@@ -18,7 +18,9 @@ import { BaseWithTxAndRpcCall } from './util';
type ContractCallTypes = 'tx' | 'rpc';
type ContractCallResultSubscription<ApiType extends ApiTypes, CallType extends ContractCallTypes> = ApiType extends 'rxjs'
// eslint-disable-next-line no-use-before-define
? Observable<ContractCallResult<CallType>>
// eslint-disable-next-line no-use-before-define
: Promise<ObsInnerType<ContractCallResult<CallType>>>;
export interface ContractCall<ApiType extends ApiTypes, CallType extends ContractCallTypes> {
+4
View File
@@ -4,11 +4,15 @@
import { ApiTypes, DecorateMethod } from '@polkadot/api/types';
import { AccountId, Address, ContractExecResult } from '@polkadot/types/interfaces';
// eslint-disable-next-line @typescript-eslint/no-unused-vars
import { Codec, CodecArg } from '@polkadot/types/types';
import { MetaRegistryJson, StringIndex, TypeIndex, TypeDef } from '@polkadot/types/create/types';
import { ApiPromise, ApiRx } from '@polkadot/api';
// I give up, too hard to untangle atm... and is basically deprecated
/* eslint-disable no-use-before-define */
export type ApiObject<ApiType extends ApiTypes> = ApiType extends 'rxjs'
? ApiRx
: ApiPromise;
+11 -11
View File
@@ -1,6 +1,6 @@
{
"name": "@polkadot/api-derive",
"version": "1.26.1",
"version": "1.32.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.10.5",
"@polkadot/api": "1.26.1",
"@polkadot/rpc-core": "1.26.1",
"@polkadot/rpc-provider": "1.26.1",
"@polkadot/types": "1.26.1",
"@polkadot/util": "^3.0.1",
"@polkadot/util-crypto": "^3.0.1",
"bn.js": "^5.1.2",
"@babel/runtime": "^7.11.2",
"@polkadot/api": "1.32.1",
"@polkadot/rpc-core": "1.32.1",
"@polkadot/rpc-provider": "1.32.1",
"@polkadot/types": "1.32.1",
"@polkadot/util": "^3.4.1",
"@polkadot/util-crypto": "^3.4.1",
"bn.js": "^5.1.3",
"memoizee": "^0.4.14",
"rxjs": "^6.6.0"
"rxjs": "^6.6.2"
},
"devDependencies": {
"@polkadot/keyring": "^3.0.1"
"@polkadot/keyring": "^3.4.1"
}
}
@@ -0,0 +1,43 @@
// 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, Address } from '@polkadot/types/interfaces';
import { Observable, of } from 'rxjs';
import { map } from 'rxjs/operators';
import { ApiInterfaceRx } from '@polkadot/api/types';
import { isU8a, assert } from '@polkadot/util';
import { decodeAddress } from '@polkadot/util-crypto';
import { memo } from '../util';
function retrieve (api: ApiInterfaceRx, address: Address | AccountId | AccountIndex | string | null | undefined): Observable<AccountId> {
const decoded = isU8a(address)
? address
: decodeAddress((address || '').toString());
if (decoded.length === 32) {
return of(api.registry.createType('AccountId', decoded));
}
const accountIndex = api.registry.createType('AccountIndex', decoded);
return api.derive.accounts.indexToId(accountIndex.toString()).pipe(
map((accountId) => {
assert(accountId, 'Unable to retrieve accountId');
return accountId;
})
);
}
/**
* @name accountId
* @param {(Address | AccountId | AccountIndex | string | null)} address - An accounts address in various formats.
* @description An [[AccountId]]
*/
export function accountId (instanceId: string, api: ApiInterfaceRx): (address?: Address | AccountId | AccountIndex | string | null) => Observable<AccountId> {
return memo(instanceId, (address?: Address | AccountId | AccountIndex | string | null): Observable<AccountId> =>
retrieve(api, address));
}
+2 -2
View File
@@ -31,8 +31,8 @@ function isIncludedFn (accountId: AccountId | Address | string): (_: AccountId |
* @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> => {
export function flags (instanceId: string, api: ApiInterfaceRx): (address?: AccountId | Address | string | null) => Observable<DeriveAccountFlags> {
return memo(instanceId, (address?: AccountId | Address | string | null): Observable<DeriveAccountFlags> => {
const councilSection = api.query.electionsPhragmen ? 'electionsPhragmen' : 'elections';
return (
@@ -30,7 +30,7 @@ function retrieve (api: ApiInterfaceRx, address: Address | AccountId | AccountIn
const accountIndex = api.registry.createType('AccountIndex', decoded);
return api.derive.accounts.indexToId(accountIndex).pipe(
return api.derive.accounts.indexToId(accountIndex.toString()).pipe(
map((accountId): AccountIdAndIndex => [accountId, accountIndex])
);
} catch (error) {
@@ -51,7 +51,7 @@ function retrieve (api: ApiInterfaceRx, address: Address | AccountId | AccountIn
* });
* ```
*/
export function idAndIndex (api: ApiInterfaceRx): (address?: Address | AccountId | AccountIndex | string | null) => Observable<AccountIdAndIndex> {
return memo((address?: Address | AccountId | AccountIndex | string | null): Observable<AccountIdAndIndex> =>
export function idAndIndex (instanceId: string, api: ApiInterfaceRx): (address?: Address | AccountId | AccountIndex | string | null) => Observable<AccountIdAndIndex> {
return memo(instanceId, (address?: Address | AccountId | AccountIndex | string | null): Observable<AccountIdAndIndex> =>
retrieve(api, address));
}
@@ -25,8 +25,8 @@ import { memo } from '../util';
* });
* ```
*/
export function idToIndex (api: ApiInterfaceRx): (accountId: AccountId | string) => Observable<AccountIndex | undefined> {
return memo((accountId: AccountId | string): Observable<AccountIndex | undefined> =>
export function idToIndex (instanceId: string, api: ApiInterfaceRx): (accountId: AccountId | string) => Observable<AccountIndex | undefined> {
return memo(instanceId, (accountId: AccountId | string): Observable<AccountIndex | undefined> =>
api.derive.accounts.indexes().pipe(
map((indexes: AccountIndexes): AccountIndex | undefined =>
(indexes || {})[accountId.toString()]
@@ -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 './accountId';
export * from './flags';
export * from './idAndIndex';
export * from './idToIndex';
@@ -49,8 +49,8 @@ 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> =>
export function indexToId (instanceId: string, api: ApiInterfaceRx): (accountIndex: AccountIndex | string) => Observable<AccountId | undefined> {
return memo(instanceId, (accountIndex: AccountIndex | string): Observable<AccountId | undefined> =>
api.query.indices
? isFunction(api.query.indices.accounts)
? query(api, accountIndex)
+2 -2
View File
@@ -72,8 +72,8 @@ function queryAccounts (api: ApiInterfaceRx): Observable<AccountIndexes> {
* });
* ```
*/
export function indexes (api: ApiInterfaceRx): () => Observable<AccountIndexes> {
return memo((): Observable<AccountIndexes> =>
export function indexes (instanceId: string, api: ApiInterfaceRx): () => Observable<AccountIndexes> {
return memo(instanceId, (): Observable<AccountIndexes> =>
indicesCache
? of(indicesCache)
: (
+2 -2
View File
@@ -113,8 +113,8 @@ function retrieveIdentity (api: ApiInterfaceRx, accountId?: AccountId): Observab
* @name info
* @description Returns aux. info with regards to an account, current that includes the accountId, accountIndex and nickname
*/
export function info (api: ApiInterfaceRx): (address?: AccountIndex | AccountId | Address | string | null) => Observable<DeriveAccountInfo> {
return memo((address?: AccountIndex | AccountId | Address | string | null): Observable<DeriveAccountInfo> =>
export function info (instanceId: string, api: ApiInterfaceRx): (address?: AccountIndex | AccountId | Address | string | null) => Observable<DeriveAccountInfo> {
return memo(instanceId, (address?: AccountIndex | AccountId | Address | string | null): Observable<DeriveAccountInfo> =>
api.derive.accounts.idAndIndex(address).pipe(
switchMap(([accountId, accountIndex]): Observable<[Partial<DeriveAccountInfo>, DeriveAccountRegistration, string?]> =>
combineLatest([
+4 -4
View File
@@ -80,10 +80,10 @@ function queryCurrent (api: ApiInterfaceRx, accountId: AccountId): Observable<Re
* });
* ```
*/
export function account (api: ApiInterfaceRx): (address: AccountIndex | AccountId | Address | string) => Observable<DeriveBalancesAccount> {
return memo((address: AccountIndex | AccountId | Address | string): Observable<DeriveBalancesAccount> =>
api.derive.accounts.info(address).pipe(
switchMap(({ accountId }): Observable<[AccountId, Result]> =>
export function account (instanceId: string, api: ApiInterfaceRx): (address: AccountIndex | AccountId | Address | string) => Observable<DeriveBalancesAccount> {
return memo(instanceId, (address: AccountIndex | AccountId | Address | string): Observable<DeriveBalancesAccount> =>
api.derive.accounts.accountId(address).pipe(
switchMap((accountId): Observable<[AccountId, Result]> =>
(accountId
? combineLatest([
of(accountId),
+9 -4
View File
@@ -17,6 +17,8 @@ import { memo } from '../util';
type ResultBalance = [VestingInfo | null, (BalanceLock | BalanceLockTo212)[]];
type Result = [DeriveBalancesAccount, BlockNumber, ResultBalance];
const VESTING_ID = '0x76657374696e6720';
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)[] = [];
@@ -30,7 +32,7 @@ function calcBalances (api: ApiInterfaceRx, [{ accountId, accountNonce, freeBala
const notAll = lockedBreakdown.filter(({ amount }) => !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)));
vestingLocked = api.registry.createType('Balance', lockedBreakdown.filter(({ id }) => id.eq(VESTING_ID)).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) {
@@ -48,6 +50,7 @@ function calcBalances (api: ApiInterfaceRx, [{ accountId, accountNonce, freeBala
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)));
const vestingEndBlock = api.registry.createType('BlockNumber', isVesting ? vestingTotal.div(perBlock).add(startingBlock) : 0);
return {
accountId,
@@ -62,7 +65,9 @@ function calcBalances (api: ApiInterfaceRx, [{ accountId, accountNonce, freeBala
reservedBalance,
vestedBalance,
vestedClaimable,
vestingEndBlock,
vestingLocked,
vestingPerBlock: perBlock,
vestingTotal,
votingBalance
};
@@ -123,15 +128,15 @@ function queryCurrent (api: ApiInterfaceRx, accountId: AccountId): Observable<Re
* });
* ```
*/
export function all (api: ApiInterfaceRx): (address: AccountIndex | AccountId | Address | string) => Observable<DeriveBalancesAll> {
return memo((address: AccountIndex | AccountId | Address | string): Observable<DeriveBalancesAll> =>
export function all (instanceId: string, api: ApiInterfaceRx): (address: AccountIndex | AccountId | Address | string) => Observable<DeriveBalancesAll> {
return memo(instanceId, (address: AccountIndex | AccountId | Address | string): Observable<DeriveBalancesAll> =>
api.derive.balances.account(address).pipe(
switchMap((account): Observable<Result> =>
(!account.accountId.isEmpty
? combineLatest([
of(account),
api.derive.chain.bestNumber(),
isFunction(api.query.balances.account)
isFunction(api.query.system.account) || isFunction(api.query.balances.account)
? queryCurrent(api, account.accountId)
: queryOld(api, account.accountId)
])
+2 -2
View File
@@ -24,8 +24,8 @@ import { memo } from '../util';
* });
* ```
*/
export function fees (api: ApiInterfaceRx): () => Observable<DeriveFees> {
return memo((): Observable<DeriveFees> =>
export function fees (instanceId: string, api: ApiInterfaceRx): () => Observable<DeriveFees> {
return memo(instanceId, (): Observable<DeriveFees> =>
of([
// deprecated - remove
(api.consts.balances?.creationFee as unknown as Balance) || api.registry.createType('Balance'),
@@ -10,8 +10,8 @@ import { ApiInterfaceRx } from '@polkadot/api/types';
import { memo } from '../util';
export function votingBalances (api: ApiInterfaceRx): (addresses?: (AccountId | AccountIndex | Address | string)[]) => Observable<DeriveBalancesAccount[]> {
return memo((addresses?: (AccountId | AccountIndex | Address | string)[]): Observable<DeriveBalancesAccount[]> =>
export function votingBalances (instanceId: string, api: ApiInterfaceRx): (addresses?: (AccountId | AccountIndex | Address | string)[]) => Observable<DeriveBalancesAccount[]> {
return memo(instanceId, (addresses?: (AccountId | AccountIndex | Address | string)[]): Observable<DeriveBalancesAccount[]> =>
!addresses || !addresses.length
? of([] as DeriveBalancesAccount[])
: combineLatest(
+2 -2
View File
@@ -22,8 +22,8 @@ import { memo } from '../util';
* });
* ```
*/
export function bestNumber (api: ApiInterfaceRx): () => Observable<BlockNumber> {
return memo((): Observable<BlockNumber> =>
export function bestNumber (instanceId: string, api: ApiInterfaceRx): () => Observable<BlockNumber> {
return memo(instanceId, (): Observable<BlockNumber> =>
api.derive.chain.subscribeNewHeads().pipe(
map((header) => header.number.unwrap())
));
@@ -23,8 +23,8 @@ import { memo } from '../util';
* });
* ```
*/
export function bestNumberFinalized (api: ApiInterfaceRx): () => Observable<BlockNumber> {
return memo((): Observable<BlockNumber> =>
export function bestNumberFinalized (instanceId: string, api: ApiInterfaceRx): () => Observable<BlockNumber> {
return memo(instanceId, (): Observable<BlockNumber> =>
api.rpc.chain.subscribeFinalizedHeads().pipe(
map((header) => header.number.unwrap())
));
@@ -23,8 +23,8 @@ import { memo } from '../util';
* });
* ```
*/
export function bestNumberLag (api: ApiInterfaceRx): () => Observable<BlockNumber> {
return memo((): Observable<BlockNumber> =>
export function bestNumberLag (instanceId: string, api: ApiInterfaceRx): () => Observable<BlockNumber> {
return memo(instanceId, (): Observable<BlockNumber> =>
combineLatest([
api.derive.chain.bestNumber(),
api.derive.chain.bestNumberFinalized()
+44
View File
@@ -0,0 +1,44 @@
// 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 { Observable, combineLatest, of } from 'rxjs';
import { catchError, map } from 'rxjs/operators';
import { SignedBlockExtended } from '../type';
import { memo } from '../util';
/**
* @name getBlock
* @param {( Uint8Array | string )} hash - A block hash as U8 array or string.
* @description Get a specific block (e.g. rpc.chain.getBlock) and extend it with the author
* @example
* <BR>
*
* ```javascript
* const { author, number } = await api.derive.chain.getHeader('0x123...456');
*
* console.log(`block #${number} was authored by ${author}`);
* ```
*/
export function getHeader (instanceId: string, api: ApiInterfaceRx): (hash: Uint8Array | string) => Observable<SignedBlockExtended | undefined> {
return memo(instanceId, (hash: Uint8Array | string): Observable<SignedBlockExtended | undefined> =>
combineLatest([
api.rpc.chain.getBlock(hash),
api.query.session
? api.query.session.validators.at(hash)
: of([])
]).pipe(
map(([signedBlock, validators]): SignedBlockExtended =>
new SignedBlockExtended(api.registry, signedBlock, validators)
),
catchError((): Observable<undefined> =>
// where rpc.chain.getHeader throws, we will land here - it can happen that
// we supplied an invalid hash. (Due to defaults, storeage will have an
// empty value, so only the RPC is affected). So return undefined
of()
)
));
}
+3 -3
View File
@@ -11,7 +11,7 @@ import { HeaderExtended } from '../type';
import { memo } from '../util';
/**
* @name bestNumberFinalized
* @name getHeader
* @param {( Uint8Array | string )} hash - A block hash as U8 array or string.
* @returns An array containing the block header and the block author
* @description Get a specific block header and extend it with the author
@@ -24,8 +24,8 @@ import { memo } from '../util';
* console.log(`block #${number} was authored by ${author}`);
* ```
*/
export function getHeader (api: ApiInterfaceRx): (hash: Uint8Array | string) => Observable<HeaderExtended | undefined> {
return memo((hash: Uint8Array | string): Observable<HeaderExtended | undefined> =>
export function getHeader (instanceId: string, api: ApiInterfaceRx): (hash: Uint8Array | string) => Observable<HeaderExtended | undefined> {
return memo(instanceId, (hash: Uint8Array | string): Observable<HeaderExtended | undefined> =>
combineLatest([
api.rpc.chain.getHeader(hash),
api.query.session
@@ -23,8 +23,8 @@ import { memo } from '../util';
* });
* ```
*/
export function subscribeNewHeads (api: ApiInterfaceRx): () => Observable<HeaderExtended> {
return memo((): Observable<HeaderExtended> =>
export function subscribeNewHeads (instanceId: string, api: ApiInterfaceRx): () => Observable<HeaderExtended> {
return memo(instanceId, (): Observable<HeaderExtended> =>
combineLatest([
api.rpc.chain.subscribeNewHeads(),
api.query.session
@@ -29,8 +29,8 @@ function parse ([hashes, proposals, votes]: Result): DeriveCollectiveProposal[]
.filter((proposal): proposal is DeriveCollectiveProposal => !!proposal);
}
export function proposals (api: ApiInterfaceRx, section: 'council' | 'technicalCommittee'): () => Observable<DeriveCollectiveProposal[]> {
return memo((): Observable<DeriveCollectiveProposal[]> =>
export function proposals (instanceId: string, api: ApiInterfaceRx, section: 'council' | 'technicalCommittee'): () => Observable<DeriveCollectiveProposal[]> {
return memo(instanceId, (): Observable<DeriveCollectiveProposal[]> =>
isFunction(api.query[section]?.proposals)
? api.query[section].proposals().pipe(
switchMap((hashes: Hash[]): Observable<Result> =>
+2 -2
View File
@@ -45,8 +45,8 @@ function queryConstants (api: ApiInterfaceRx): Observable<ResultV2> {
* });
* ```
*/
export function fees (api: ApiInterfaceRx): () => Observable<DeriveContractFees> {
return memo((): Observable<DeriveContractFees> => {
export function fees (instanceId: string, api: ApiInterfaceRx): () => Observable<DeriveContractFees> {
return memo(instanceId, (): Observable<DeriveContractFees> => {
return queryConstants(api).pipe(
map(([callBaseFee, contractFee, creationFee, transactionBaseFee, transactionByteFee, transferFee, rentByteFee, rentDepositOffset, surchargeReward, tombstoneDeposit]): DeriveContractFees => ({
callBaseFee,
+2 -2
View File
@@ -9,6 +9,6 @@ import { Observable } from 'rxjs';
import { proposals as collectiveProposals } from '../collective';
import { memo } from '../util';
export function proposals (api: ApiInterfaceRx): () => Observable<DeriveCollectiveProposals> {
return memo(collectiveProposals(api, 'council'));
export function proposals (instanceId: string, api: ApiInterfaceRx): () => Observable<DeriveCollectiveProposals> {
return memo(instanceId, collectiveProposals(instanceId, api, 'council'));
}
+2 -2
View File
@@ -81,8 +81,8 @@ function retrieveCurrent (api: ApiInterfaceRx): Observable<DeriveCouncilVotes> {
);
}
export function votes (api: ApiInterfaceRx): () => Observable<DeriveCouncilVotes> {
return memo((): Observable<DeriveCouncilVotes> =>
export function votes (instanceId: string, api: ApiInterfaceRx): () => Observable<DeriveCouncilVotes> {
return memo(instanceId, (): Observable<DeriveCouncilVotes> =>
(api.query.electionsPhragmen || api.query.elections).stakeOf
? retrievePrev(api)
: retrieveCurrent(api)
+2 -2
View File
@@ -10,8 +10,8 @@ import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { memo } from '../util';
export function votesOf (api: ApiInterfaceRx): (accountId: string | Uint8Array | AccountId) => Observable<DeriveCouncilVote> {
return memo((accountId: string | Uint8Array | AccountId): Observable<DeriveCouncilVote> =>
export function votesOf (instanceId: string, api: ApiInterfaceRx): (accountId: string | Uint8Array | AccountId) => Observable<DeriveCouncilVote> {
return memo(instanceId, (accountId: string | Uint8Array | AccountId): Observable<DeriveCouncilVote> =>
api.derive.council.votes().pipe(
map((votes): DeriveCouncilVote =>
(
@@ -94,8 +94,8 @@ function queryScheduler (api: ApiInterfaceRx): Observable<DeriveDispatch[]> {
);
}
export function dispatchQueue (api: ApiInterfaceRx): () => Observable<DeriveDispatch[]> {
return memo((): Observable<DeriveDispatch[]> =>
export function dispatchQueue (instanceId: string, api: ApiInterfaceRx): () => Observable<DeriveDispatch[]> {
return memo(instanceId, (): Observable<DeriveDispatch[]> =>
isFunction(api.query.scheduler?.agenda)
? queryScheduler(api)
: api.query.democracy.dispatchQueue
+28 -5
View File
@@ -2,7 +2,7 @@
// 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 { AccountId, ReferendumInfo, ReferendumInfoTo239, VotingDelegating, VotingDirect, VotingDirectVote } from '@polkadot/types/interfaces';
import { ApiInterfaceRx } from '@polkadot/api/types';
import { DeriveDemocracyLock } from '../types';
@@ -20,16 +20,37 @@ const ZERO = new BN(0);
function parseLock (api: ApiInterfaceRx, [referendumId, accountVote]: VotingDirectVote, referendum: ReferendumInfo): DeriveDemocracyLock {
const { balance, vote } = accountVote.asStandard;
let unlockAt = ZERO;
let referendumEnd = ZERO;
if (referendum.isFinished) {
const { approved, end } = referendum.asFinished;
referendumEnd = end;
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 };
return { balance, isDelegated: false, isFinished: referendum.isFinished, referendumEnd, referendumId, unlockAt, vote };
}
function delegateLocks (api: ApiInterfaceRx, { balance, conviction, target }: VotingDelegating): Observable<DeriveDemocracyLock[]> {
return api.derive.democracy.locks(target).pipe(
map((available): DeriveDemocracyLock[] =>
available.map(({ isFinished, referendumEnd, referendumId, unlockAt, vote }): DeriveDemocracyLock => ({
balance,
isDelegated: true,
isFinished,
referendumEnd,
referendumId,
unlockAt: unlockAt.isZero()
? unlockAt
: referendumEnd.add(api.consts.democracy.enactmentPeriod.muln(LOCKUPS[conviction.index])),
vote: api.registry.createType('Vote', { aye: vote.isAye, conviction })
}))
)
);
}
function directLocks (api: ApiInterfaceRx, { votes }: VotingDirect): Observable<DeriveDemocracyLock[]> {
@@ -53,13 +74,15 @@ function directLocks (api: ApiInterfaceRx, { votes }: VotingDirect): Observable<
);
}
export function locks (api: ApiInterfaceRx): (accountId: string | AccountId) => Observable<DeriveDemocracyLock[]> {
return memo((accountId: string | AccountId): Observable<DeriveDemocracyLock[]> =>
export function locks (instanceId: string, api: ApiInterfaceRx): (accountId: string | AccountId) => Observable<DeriveDemocracyLock[]> {
return memo(instanceId, (accountId: string | AccountId): Observable<DeriveDemocracyLock[]> =>
api.query.democracy.votingOf(accountId).pipe(
switchMap((voting): Observable<DeriveDemocracyLock[]> =>
voting.isDirect
? directLocks(api, voting.asDirect)
: of([])
: voting.isDelegating
? delegateLocks(api, voting.asDelegating)
: of([])
)
)
);
@@ -29,8 +29,8 @@ function withImage (api: ApiInterfaceRx, nextOpt: Option<ITuple<[Hash, VoteThres
);
}
export function nextExternal (api: ApiInterfaceRx): () => Observable<DeriveProposalExternal | null> {
return memo((): Observable<DeriveProposalExternal | null> =>
export function nextExternal (instanceId: string, api: ApiInterfaceRx): () => Observable<DeriveProposalExternal | null> {
return memo(instanceId, (): Observable<DeriveProposalExternal | null> =>
api.query.democracy?.nextExternal
? api.query.democracy.nextExternal<Option<ITuple<[Hash, VoteThreshold]>>>().pipe(
switchMap((nextOpt) => withImage(api, nextOpt))
@@ -16,8 +16,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((hash: Hash): Observable<DeriveProposalImage | undefined> =>
export function preimage (instanceId: string, api: ApiInterfaceRx): (hash: Hash) => Observable<DeriveProposalImage | undefined> {
return memo(instanceId, (hash: Hash): Observable<DeriveProposalImage | undefined> =>
api.query.democracy.preimages<PreImage>(hash).pipe(
map((imageOpt) => parseImage(api, imageOpt))
)
@@ -16,8 +16,8 @@ import { parseImage } from './util';
type PreImage = Option<ITuple<[Bytes, AccountId, Balance, BlockNumber]>>;
export function preimages (api: ApiInterfaceRx): (hashes: Hash[]) => Observable<(DeriveProposalImage | undefined)[]> {
return memo((hashes: Hash[]): Observable<(DeriveProposalImage | undefined)[]> =>
export function preimages (instanceId: string, api: ApiInterfaceRx): (hashes: Hash[]) => Observable<(DeriveProposalImage | undefined)[]> {
return memo(instanceId, (hashes: Hash[]): Observable<(DeriveProposalImage | undefined)[]> =>
api.query.democracy.preimages.multi<PreImage>(hashes).pipe(
map((images): (DeriveProposalImage | undefined)[] =>
images.map((imageOpt) => parseImage(api, imageOpt))
@@ -49,8 +49,8 @@ function parse ([proposals, images, optDepositors]: Result): DeriveProposal[] {
});
}
export function proposals (api: ApiInterfaceRx): () => Observable<DeriveProposal[]> {
return memo((): Observable<DeriveProposal[]> =>
export function proposals (instanceId: string, api: ApiInterfaceRx): () => Observable<DeriveProposal[]> {
return memo(instanceId, (): Observable<DeriveProposal[]> =>
api.query.democracy?.publicProps && api.query.democracy?.preimages
? api.query.democracy.publicProps<Proposals>().pipe(
switchMap((proposals) =>
@@ -11,8 +11,8 @@ import { map } from 'rxjs/operators';
import { memo } from '../util';
export function referendumIds (api: ApiInterfaceRx): () => Observable<BN[]> {
return memo((): Observable<BN[]> =>
export function referendumIds (instanceId: string, api: ApiInterfaceRx): () => Observable<BN[]> {
return memo(instanceId, (): Observable<BN[]> =>
api.query.democracy?.lowestUnbaked
? api.queryMulti<[ReferendumIndex, ReferendumIndex]>([
api.query.democracy.lowestUnbaked,
@@ -10,8 +10,8 @@ import { map, switchMap } from 'rxjs/operators';
import { memo } from '../util';
export function referendums (api: ApiInterfaceRx): () => Observable<DeriveReferendumExt[]> {
return memo((): Observable<DeriveReferendumExt[]> =>
export function referendums (instanceId: string, api: ApiInterfaceRx): () => Observable<DeriveReferendumExt[]> {
return memo(instanceId, (): Observable<DeriveReferendumExt[]> =>
api.derive.democracy.referendumsActive().pipe(
switchMap((referendums) =>
combineLatest([
@@ -10,8 +10,8 @@ import { switchMap } from 'rxjs/operators';
import { memo } from '../util';
export function referendumsActive (api: ApiInterfaceRx): () => Observable<DeriveReferendum[]> {
return memo((): Observable<DeriveReferendum[]> =>
export function referendumsActive (instanceId: string, api: ApiInterfaceRx): () => Observable<DeriveReferendum[]> {
return memo(instanceId, (): Observable<DeriveReferendum[]> =>
api.derive.democracy.referendumIds().pipe(
switchMap((ids): Observable<DeriveReferendum[]> =>
ids.length
@@ -11,8 +11,8 @@ import { Option } from '@polkadot/types';
import { memo } from '../util';
export function referendumsFinished (api: ApiInterfaceRx): () => Observable<ReferendumInfoFinished[]> {
return memo((): Observable<ReferendumInfoFinished[]> =>
export function referendumsFinished (instanceId: string, api: ApiInterfaceRx): () => Observable<ReferendumInfoFinished[]> {
return memo(instanceId, (): Observable<ReferendumInfoFinished[]> =>
api.derive.democracy.referendumIds().pipe(
switchMap((ids) => api.query.democracy.referendumInfoOf.multi<Option<ReferendumInfo>>(ids)),
map((infos): ReferendumInfoFinished[] =>
@@ -92,8 +92,8 @@ function votesCurr (api: ApiInterfaceRx, referendumId: BN): Observable<DeriveRef
);
}
export function _referendumVotes (api: ApiInterfaceRx): (referendum: DeriveReferendum) => Observable<DeriveReferendumVotes> {
return memo((referendum: DeriveReferendum): Observable<DeriveReferendumVotes> =>
export function _referendumVotes (instanceId: string, api: ApiInterfaceRx): (referendum: DeriveReferendum) => Observable<DeriveReferendumVotes> {
return memo(instanceId, (referendum: DeriveReferendum): Observable<DeriveReferendumVotes> =>
combineLatest([
api.derive.democracy.sqrtElectorate(),
isFunction(api.query.democracy.votingOf)
@@ -107,8 +107,8 @@ export function _referendumVotes (api: ApiInterfaceRx): (referendum: DeriveRefer
);
}
export function _referendumsVotes (api: ApiInterfaceRx): (referendums: DeriveReferendum[]) => Observable<DeriveReferendumVotes[]> {
return memo((referendums: DeriveReferendum[]): Observable<DeriveReferendumVotes[]> =>
export function _referendumsVotes (instanceId: string, api: ApiInterfaceRx): (referendums: DeriveReferendum[]) => Observable<DeriveReferendumVotes[]> {
return memo(instanceId, (referendums: DeriveReferendum[]): Observable<DeriveReferendumVotes[]> =>
referendums.length
? combineLatest(
referendums.map((referendum): Observable<DeriveReferendumVotes> =>
@@ -119,8 +119,8 @@ export function _referendumsVotes (api: ApiInterfaceRx): (referendums: DeriveRef
);
}
export function _referendumInfo (api: ApiInterfaceRx): (index: BN, info: Option<ReferendumInfo | ReferendumInfoTo239>) => Observable<DeriveReferendum | null> {
return memo((index: BN, info: Option<ReferendumInfo | ReferendumInfoTo239>): Observable<DeriveReferendum | null> => {
export function _referendumInfo (instanceId: string, api: ApiInterfaceRx): (index: BN, info: Option<ReferendumInfo | ReferendumInfoTo239>) => Observable<DeriveReferendum | null> {
return memo(instanceId, (index: BN, info: Option<ReferendumInfo | ReferendumInfoTo239>): Observable<DeriveReferendum | null> => {
const status = getStatus(info);
return status
@@ -136,8 +136,8 @@ export function _referendumInfo (api: ApiInterfaceRx): (index: BN, info: Option<
});
}
export function referendumsInfo (api: ApiInterfaceRx): (ids: BN[]) => Observable<DeriveReferendum[]> {
return memo((ids: BN[]): Observable<DeriveReferendum[]> =>
export function referendumsInfo (instanceId: string, api: ApiInterfaceRx): (ids: BN[]) => Observable<DeriveReferendum[]> {
return memo(instanceId, (ids: BN[]): Observable<DeriveReferendum[]> =>
ids.length
? api.query.democracy.referendumInfoOf.multi<Option<ReferendumInfo>>(ids).pipe(
switchMap((infos): Observable<(DeriveReferendum | null)[]> =>
@@ -11,8 +11,8 @@ import { bnSqrt } from '@polkadot/util';
import { memo } from '../util';
export function sqrtElectorate (api: ApiInterfaceRx): () => Observable<BN> {
return memo((): Observable<BN> =>
export function sqrtElectorate (instanceId: string, api: ApiInterfaceRx): () => Observable<BN> {
return memo(instanceId, (): Observable<BN> =>
api.query.balances.totalIssuance().pipe(
map((totalIssuance) =>
bnSqrt(totalIssuance)
+9 -7
View File
@@ -9,19 +9,14 @@ import { Vec } from '@polkadot/types';
export interface DeriveDemocracyLock {
balance: Balance;
isDelegated: boolean;
isFinished: boolean;
referendumEnd: BN;
referendumId: ReferendumIndex;
unlockAt: BN;
vote: Vote;
}
export interface DeriveDispatch {
at: BlockNumber;
index: ReferendumIndex;
imageHash: Hash;
image?: DeriveProposalImage;
}
export interface DeriveProposalImage {
at: BlockNumber;
balance: Balance;
@@ -29,6 +24,13 @@ export interface DeriveProposalImage {
proposer: AccountId;
}
export interface DeriveDispatch {
at: BlockNumber;
index: ReferendumIndex;
imageHash: Hash;
image?: DeriveProposalImage;
}
export interface DeriveProposal {
balance?: Balance;
index: PropIndex;
+4 -3
View File
@@ -4,13 +4,13 @@
import { AccountId, Balance, BlockNumber } from '@polkadot/types/interfaces';
import { ITuple } from '@polkadot/types/types';
import { DeriveElectionsInfo } from './types';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { ApiInterfaceRx } from '@polkadot/api/types';
import { Vec, u32 } from '@polkadot/types';
import { DeriveElectionsInfo } from '../types';
import { memo } from '../util';
function sortAccounts ([, balanceA]: ITuple<[AccountId, Balance]>, [, balanceB]: ITuple<[AccountId, Balance]>): number {
@@ -30,6 +30,7 @@ function queryElections (api: ApiInterfaceRx): Observable<DeriveElectionsInfo> {
candidacyBond: api.consts[section].candidacyBond as Balance,
candidateCount: api.registry.createType('u32', candidates.length),
candidates,
desiredRunnersUp: api.consts[section].desiredRunnersUp as u32,
desiredSeats: api.consts[section].desiredMembers as u32,
members: members.length
? members.sort(sortAccounts)
@@ -54,6 +55,6 @@ function queryElections (api: ApiInterfaceRx): Observable<DeriveElectionsInfo> {
* });
* ```
*/
export function info (api: ApiInterfaceRx): () => Observable<DeriveElectionsInfo> {
return memo((): Observable<DeriveElectionsInfo> => queryElections(api));
export function info (instanceId: string, api: ApiInterfaceRx): () => Observable<DeriveElectionsInfo> {
return memo(instanceId, (): Observable<DeriveElectionsInfo> => queryElections(api));
}
@@ -0,0 +1,22 @@
// 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, Balance, BlockNumber, SetIndex, VoteIndex } from '@polkadot/types/interfaces';
import { u32 } from '@polkadot/types';
export interface DeriveElectionsInfo {
candidates: AccountId[];
candidateCount: u32;
candidacyBond?: Balance;
desiredRunnersUp: u32;
desiredSeats: u32;
members: [AccountId, Balance][];
nextVoterSet?: SetIndex;
runnersUp: [AccountId, Balance][];
termDuration: BlockNumber;
voteCount?: VoteIndex;
voterCount?: SetIndex;
votingBond?: Balance;
}
@@ -9,14 +9,15 @@ import { Observable, of, combineLatest } from 'rxjs';
import { map, switchMap } from 'rxjs/operators';
import { ApiInterfaceRx } from '@polkadot/api/types';
import { Bytes, Option, u32 } from '@polkadot/types';
import { BN_ZERO } from '@polkadot/util';
import { memo } from '../util';
/**
* @description Return a boolean array indicating whether the passed accounts had received heartbeats in the current session
*/
export function receivedHeartbeats (api: ApiInterfaceRx): () => Observable<DeriveHeartbeats> {
return memo((): Observable<DeriveHeartbeats> =>
export function receivedHeartbeats (instanceId: string, api: ApiInterfaceRx): () => Observable<DeriveHeartbeats> {
return memo(instanceId, (): Observable<DeriveHeartbeats> =>
api.query.imOnline?.receivedHeartbeats
? api.derive.staking.overview().pipe(
switchMap(({ currentIndex, validators }): Observable<[AccountId[], Option<Bytes>[], u32[]]> =>
@@ -34,7 +35,7 @@ export function receivedHeartbeats (api: ApiInterfaceRx): () => Observable<Deriv
[validator.toString()]: {
blockCount: numBlocks[index],
hasMessage: !heartbeats[index].isEmpty,
isOnline: !heartbeats[index].isEmpty || numBlocks[index].gtn(0)
isOnline: !heartbeats[index].isEmpty || numBlocks[index].gt(BN_ZERO)
}
}), {})
)
+6 -6
View File
@@ -36,7 +36,7 @@ type DeriveAllSections<AllSections> = {
[Section in keyof AllSections]: DeriveSection<AllSections[Section]>
};
export type DeriveCustom = Record<string, Record<string, (api: ApiInterfaceRx) => (...args: any[]) => Observable<any>>>;
export type DeriveCustom = Record<string, Record<string, (instanceId: string, api: ApiInterfaceRx) => (...args: any[]) => Observable<any>>>;
export type ExactDerive = DeriveAllSections<typeof derive>;
@@ -60,7 +60,7 @@ const deriveAvail: Record<string, string[]> = {
* `allSections`, and keep the object architecture of `allSections`.
*/
/** @internal */
function injectFunctions<AllSections> (api: ApiInterfaceRx, allSections: AllSections): DeriveAllSections<AllSections> {
function injectFunctions<AllSections> (instanceId: string, api: ApiInterfaceRx, allSections: AllSections): DeriveAllSections<AllSections> {
const queryKeys = Object.keys(api.query);
return Object
@@ -77,7 +77,7 @@ function injectFunctions<AllSections> (api: ApiInterfaceRx, allSections: AllSect
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);
const method = (section[methodName] as any)(instanceId, api);
// idem
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment,@typescript-eslint/no-unsafe-member-access
@@ -93,9 +93,9 @@ function injectFunctions<AllSections> (api: ApiInterfaceRx, allSections: AllSect
// FIXME The return type of this function should be {...ExactDerive, ...DeriveCustom}
// For now we just drop the custom derive typings
/** @internal */
export default function decorateDerive (api: ApiInterfaceRx, custom: DeriveCustom = {}): ExactDerive {
export default function decorateDerive (instanceId: string, api: ApiInterfaceRx, custom: DeriveCustom = {}): ExactDerive {
return {
...injectFunctions(api, derive),
...injectFunctions(api, custom)
...injectFunctions(instanceId, api, derive),
...injectFunctions(instanceId, api, custom)
};
}
+2 -2
View File
@@ -77,8 +77,8 @@ function parse (id: ParaId, [active, retryQueue, selectedThreads, didUpdate, inf
};
}
export function info (api: ApiInterfaceRx): (id: ParaId | number) => Observable<DeriveParachainFull | null> {
return memo((id: ParaId | number): Observable<DeriveParachainFull | null> =>
export function info (instanceId: string, api: ApiInterfaceRx): (id: ParaId | number) => Observable<DeriveParachainFull | null> {
return memo(instanceId, (id: ParaId | number): Observable<DeriveParachainFull | null> =>
api.query.registrar && api.query.parachains
? api.queryMulti<Result>([
api.query.registrar.active,
@@ -34,8 +34,8 @@ function parse ([ids, didUpdate, infos, pendingSwaps, relayDispatchQueueSizes]:
});
}
export function overview (api: ApiInterfaceRx): () => Observable<DeriveParachain[]> {
return memo((): Observable<DeriveParachain[]> =>
export function overview (instanceId: string, api: ApiInterfaceRx): () => Observable<DeriveParachain[]> {
return memo(instanceId, (): Observable<DeriveParachain[]> =>
api.query.registrar?.parachains && api.query.parachains
? api.query.registrar.parachains<ParaId[]>().pipe(
switchMap((paraIds) =>
+2 -2
View File
@@ -10,8 +10,8 @@ import { ApiInterfaceRx } from '@polkadot/api/types';
import { memo } from '../util';
export function eraLength (api: ApiInterfaceRx): () => Observable<BlockNumber> {
return memo((): Observable<BlockNumber> =>
export function eraLength (instanceId: string, api: ApiInterfaceRx): () => Observable<BlockNumber> {
return memo(instanceId, (): Observable<BlockNumber> =>
api.derive.session.info().pipe(
map((info) => info.eraLength)
));
@@ -10,8 +10,8 @@ import { ApiInterfaceRx } from '@polkadot/api/types';
import { memo } from '../util';
export function eraProgress (api: ApiInterfaceRx): () => Observable<BlockNumber> {
return memo((): Observable<BlockNumber> =>
export function eraProgress (instanceId: string, api: ApiInterfaceRx): () => Observable<BlockNumber> {
return memo(instanceId, (): Observable<BlockNumber> =>
api.derive.session.progress().pipe(
map((info) => info.eraProgress)
));
+37 -31
View File
@@ -13,10 +13,12 @@ import { isFunction } from '@polkadot/util';
import { memo } from '../util';
type Result = [EraIndex, Option<Moment>, EraIndex, SessionIndex, u32];
function isEraOpt (era: Option<EraIndex> | EraIndex): era is Option<EraIndex> {
return isFunction((era as Option<EraIndex>).unwrapOrDefault);
}
// parse into Indexes
function parse ([activeEra, activeEraStart, currentEra, currentIndex, validatorCount]: Result): DeriveSessionIndexes {
function parse ([activeEra, activeEraStart, currentEra, currentIndex, validatorCount]: [EraIndex, Option<Moment>, EraIndex, SessionIndex, u32]): DeriveSessionIndexes {
return {
activeEra,
activeEraStart,
@@ -27,63 +29,67 @@ function parse ([activeEra, activeEraStart, currentEra, currentIndex, validatorC
}
// query for previous V2
function queryNoActive (api: ApiInterfaceRx): Observable<Result> {
return api.queryMulti<[EraIndex, SessionIndex, u32]>([
function queryNoActive (api: ApiInterfaceRx): Observable<DeriveSessionIndexes> {
return api.queryMulti<[Option<EraIndex> | EraIndex, SessionIndex, u32]>([
api.query.staking.currentEra,
api.query.session.currentIndex,
api.query.staking.validatorCount
]).pipe(
map(([currentEra, currentIndex, validatorCount]): Result => [
currentEra,
api.registry.createType('Option<Moment>'),
currentEra,
currentIndex,
validatorCount
])
map(([currentEraOpt, currentIndex, validatorCount]): DeriveSessionIndexes => {
const currentEra = isEraOpt(currentEraOpt)
? currentEraOpt.unwrapOrDefault()
: currentEraOpt;
return parse([
currentEra,
api.registry.createType('Option<Moment>'),
currentEra,
currentIndex,
validatorCount
]);
})
);
}
// query based on latest
function query (api: ApiInterfaceRx): Observable<Result> {
function query (api: ApiInterfaceRx): Observable<DeriveSessionIndexes> {
return api.queryMulti<[Option<ActiveEraInfo>, Option<EraIndex>, SessionIndex, u32]>([
api.query.staking.activeEra,
api.query.staking.currentEra,
api.query.session.currentIndex,
api.query.staking.validatorCount
]).pipe(
map(([activeOpt, currentEra, currentIndex, validatorCount]): Result => {
const { index: activeEra, start: activeEraStart } = activeOpt.unwrapOrDefault();
map(([activeOpt, currentEra, currentIndex, validatorCount]): DeriveSessionIndexes => {
const { index, start } = activeOpt.unwrapOrDefault();
return [
activeEra,
activeEraStart,
currentEra.unwrapOr(api.registry.createType('EraIndex')),
return parse([
index,
start,
currentEra.unwrapOrDefault(),
currentIndex,
validatorCount
];
]);
})
);
}
// empty set when none is available
function empty (api: ApiInterfaceRx): Observable<Result> {
return of([
function empty (api: ApiInterfaceRx): Observable<DeriveSessionIndexes> {
return of(parse([
api.registry.createType('EraIndex'),
api.registry.createType('Option<Moment>'),
api.registry.createType('EraIndex'),
api.registry.createType('SessionIndex', 1),
api.registry.createType('u32')
]);
]));
}
export function indexes (api: ApiInterfaceRx): () => Observable<DeriveSessionIndexes> {
return memo((): Observable<DeriveSessionIndexes> =>
(
api.query.session && api.query.staking
? isFunction(api.query.staking.activeEra)
? query(api)
: queryNoActive(api)
: empty(api)
).pipe(map(parse))
export function indexes (instanceId: string, api: ApiInterfaceRx): () => Observable<DeriveSessionIndexes> {
return memo(instanceId, (): Observable<DeriveSessionIndexes> =>
api.query.session && api.query.staking
? isFunction(api.query.staking.activeEra)
? query(api)
: queryNoActive(api)
: empty(api)
);
}
+2 -2
View File
@@ -62,8 +62,8 @@ function queryBabe (api: ApiInterfaceRx): Observable<DeriveSessionInfo> {
/**
* @description Retrieves all the session and era query and calculates specific values on it as the length of the session and eras
*/
export function info (api: ApiInterfaceRx): () => Observable<DeriveSessionInfo> {
return memo((): Observable<DeriveSessionInfo> =>
export function info (instanceId: string, api: ApiInterfaceRx): () => Observable<DeriveSessionInfo> {
return memo(instanceId, (): Observable<DeriveSessionInfo> =>
api.consts.babe
? queryBabe(api)
: queryAura(api)
+2 -2
View File
@@ -72,8 +72,8 @@ function queryBabeNoHistory (api: ApiInterfaceRx): Observable<[DeriveSessionInfo
/**
* @description Retrieves all the session and era query and calculates specific values on it as the length of the session and eras
*/
export function progress (api: ApiInterfaceRx): () => Observable<DeriveSessionProgress> {
return memo((): Observable<DeriveSessionProgress> =>
export function progress (instanceId: string, api: ApiInterfaceRx): () => Observable<DeriveSessionProgress> {
return memo(instanceId, (): Observable<DeriveSessionProgress> =>
api.consts.babe
? (
isFunction(api.query.staking.erasStartSessionIndex)
@@ -10,8 +10,8 @@ import { ApiInterfaceRx } from '@polkadot/api/types';
import { memo } from '../util';
export function sessionProgress (api: ApiInterfaceRx): () => Observable<BlockNumber> {
return memo((): Observable<BlockNumber> =>
export function sessionProgress (instanceId: string, api: ApiInterfaceRx): () => Observable<BlockNumber> {
return memo(instanceId, (): Observable<BlockNumber> =>
api.derive.session.progress().pipe(
map((info) => info.sessionProgress)
));
@@ -19,8 +19,8 @@ type Result = [Bid[], ResultSuspend[]]
/**
* @description Get the candidate info for a society
*/
export function candidates (api: ApiInterfaceRx): () => Observable<DeriveSocietyCandidate[]> {
return memo((): Observable<DeriveSocietyCandidate[]> =>
export function candidates (instanceId: string, api: ApiInterfaceRx): () => Observable<DeriveSocietyCandidate[]> {
return memo(instanceId, (): Observable<DeriveSocietyCandidate[]> =>
api.query.society.candidates<Vec<Bid>>().pipe(
switchMap((candidates: Vec<Bid>): Observable<Result> =>
combineLatest([
+2 -2
View File
@@ -17,8 +17,8 @@ type Result = [Vec<Bid>, Option<AccountId>, Option<AccountId>, Option<AccountId>
/**
* @description Get the overall info for a society
*/
export function info (api: ApiInterfaceRx): () => Observable<DeriveSociety> {
return memo((): Observable<DeriveSociety> =>
export function info (instanceId: string, api: ApiInterfaceRx): () => Observable<DeriveSociety> {
return memo(instanceId, (): Observable<DeriveSociety> =>
api.queryMulti<Result>([
api.query.society.bids,
api.query.society.defender,
+2 -2
View File
@@ -18,8 +18,8 @@ type Result = [Vec<ITuple<[BlockNumber, Balance]>>, StrikeCount, Option<SocietyV
/**
* @description Get the member info for a society
*/
export function member (api: ApiInterfaceRx): (accountId: AccountId) => Observable<DeriveSocietyMember> {
return memo((accountId: AccountId): Observable<DeriveSocietyMember> =>
export function member (instanceId: string, api: ApiInterfaceRx): (accountId: AccountId) => Observable<DeriveSocietyMember> {
return memo(instanceId, (accountId: AccountId): Observable<DeriveSocietyMember> =>
api.queryMulti<Result>([
[api.query.society.payouts, accountId],
[api.query.society.strikes, accountId],
+2 -2
View File
@@ -14,8 +14,8 @@ import { memo } from '../util';
/**
* @description Get the member info for a society
*/
export function members (api: ApiInterfaceRx): () => Observable<DeriveSocietyMember[]> {
return memo((): Observable<DeriveSocietyMember[]> =>
export function members (instanceId: string, api: ApiInterfaceRx): () => Observable<DeriveSocietyMember[]> {
return memo(instanceId, (): Observable<DeriveSocietyMember[]> =>
api.query.society.members<AccountId[]>().pipe(
switchMap((members): Observable<DeriveSocietyMember[]> =>
combineLatest(
+24 -38
View File
@@ -4,48 +4,34 @@
import { ApiInterfaceRx } from '@polkadot/api/types';
import { Balance, StakingLedger, UnlockChunk } from '@polkadot/types/interfaces';
import { DeriveSessionInfo, DeriveStakingAccount, DeriveStakingQuery, DeriveUnlocking } from '../types';
import { DeriveSessionInfo, DeriveStakingAccount, DeriveStakingKeys, DeriveStakingQuery, DeriveUnlocking } from '../types';
import BN from 'bn.js';
import { Observable } from 'rxjs';
import { combineLatest, Observable } from 'rxjs';
import { map, switchMap } from 'rxjs/operators';
import { isUndefined } from '@polkadot/util';
import { BN_ZERO } from '@polkadot/util';
import { memo } from '../util';
// groups the supplied chunks by era, i.e. { [era]: BN(total of values) }
function groupByEra (list: UnlockChunk[]): Record<string, BN> {
return list.reduce((map: Record<string, BN>, { era, value }): Record<string, BN> => {
const key = era.toString();
map[key] = !map[key]
? value.unwrap()
: map[key].iadd(value.unwrap());
map[key] = (map[key] || BN_ZERO).add(value.unwrap());
return map;
}, {});
}
function calculateUnlocking (api: ApiInterfaceRx, stakingLedger: StakingLedger | undefined, sessionInfo: DeriveSessionInfo): DeriveUnlocking[] | undefined {
if (isUndefined(stakingLedger)) {
return undefined;
}
const unlockingChunks = stakingLedger.unlocking.filter(({ era }) =>
era.unwrap().gt(sessionInfo.activeEra)
);
if (!unlockingChunks.length) {
return undefined;
}
// 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).isub(sessionInfo.activeEra),
value: api.registry.createType('Balance', value)
}));
const results = Object
.entries(groupByEra(
(stakingLedger?.unlocking || []).filter(({ era }) => era.unwrap().gt(sessionInfo.activeEra))
))
.map(([eraString, value]): DeriveUnlocking => ({
remainingEras: new BN(eraString).isub(sessionInfo.activeEra),
value: api.registry.createType('Balance', value)
}));
return results.length
? results
@@ -53,19 +39,16 @@ function calculateUnlocking (api: ApiInterfaceRx, stakingLedger: StakingLedger |
}
function redeemableSum (api: ApiInterfaceRx, stakingLedger: StakingLedger | undefined, sessionInfo: DeriveSessionInfo): Balance {
if (isUndefined(stakingLedger)) {
return api.registry.createType('Balance');
}
return api.registry.createType('Balance', stakingLedger.unlocking.reduce((total, { era, value }): BN => {
return api.registry.createType('Balance', (stakingLedger?.unlocking || [] as UnlockChunk[]).reduce((total, { era, value }): BN => {
return sessionInfo.activeEra.gte(era.unwrap())
? total.iadd(value.unwrap())
: total;
}, new BN(0)));
}
function parseResult (api: ApiInterfaceRx, sessionInfo: DeriveSessionInfo, query: DeriveStakingQuery): DeriveStakingAccount {
function parseResult (api: ApiInterfaceRx, sessionInfo: DeriveSessionInfo, keys: DeriveStakingKeys, query: DeriveStakingQuery): DeriveStakingAccount {
return {
...keys,
...query,
redeemable: redeemableSum(api, query.stakingLedger, sessionInfo),
unlocking: calculateUnlocking(api, query.stakingLedger, sessionInfo)
@@ -75,12 +58,15 @@ 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[]> =>
export function accounts (instanceId: string, api: ApiInterfaceRx): (accountIds: (Uint8Array | string)[]) => Observable<DeriveStakingAccount[]> {
return memo(instanceId, (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)))
combineLatest([
api.derive.staking.keysMulti(accountIds),
api.derive.staking.queryMulti(accountIds)
]).pipe(
map(([keys, queries]) => queries.map((query, index) => parseResult(api, sessionInfo, keys[index], query)))
)
)
)
@@ -90,8 +76,8 @@ export function accounts (api: ApiInterfaceRx): (accountIds: (Uint8Array | strin
/**
* @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> =>
export function account (instanceId: string, api: ApiInterfaceRx): (accountId: Uint8Array | string) => Observable<DeriveStakingAccount> {
return memo(instanceId, (accountId: Uint8Array | string): Observable<DeriveStakingAccount> =>
api.derive.staking.accounts([accountId]).pipe(
map(([first]) => first)
)
@@ -28,8 +28,8 @@ function retrievePointsPrev (api: ApiInterfaceRx, currentElected: AccountId[]):
/**
* @description Retrieve the staking overview, including elected and points earned
*/
export function currentPoints (api: ApiInterfaceRx): () => Observable<EraRewardPoints> {
return memo((): Observable<EraRewardPoints> =>
export function currentPoints (instanceId: string, api: ApiInterfaceRx): () => Observable<EraRewardPoints> {
return memo(instanceId, (): Observable<EraRewardPoints> =>
api.derive.staking.overview().pipe(
switchMap(({ activeEra, nextElected }) =>
api.query.staking.erasRewardPoints
@@ -10,8 +10,8 @@ import { map, switchMap } from 'rxjs/operators';
import { memo } from '../util';
export function electedInfo (api: ApiInterfaceRx): () => Observable<DeriveStakingElected> {
return memo((): Observable<DeriveStakingElected> =>
export function electedInfo (instanceId: string, api: ApiInterfaceRx): () => Observable<DeriveStakingElected> {
return memo(instanceId, (): Observable<DeriveStakingElected> =>
api.derive.staking.validators().pipe(
switchMap(({ nextElected }): Observable<DeriveStakingElected> =>
api.derive.staking.queryMulti(nextElected).pipe(
@@ -36,8 +36,8 @@ 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> => {
export function _eraExposure (instanceId: string, api: ApiInterfaceRx): (era: EraIndex, withActive: boolean) => Observable<DeriveEraExposure> {
return memo(instanceId, (era: EraIndex, withActive: boolean): Observable<DeriveEraExposure> => {
const cacheKey = `${CACHE_KEY}-${era.toString()}`;
const cached = withActive
? undefined
@@ -57,22 +57,22 @@ export function _eraExposure (api: ApiInterfaceRx): (era: EraIndex, withActive:
});
}
export function eraExposure (api: ApiInterfaceRx): (era: EraIndex) => Observable<DeriveEraExposure> {
return memo((era: EraIndex): Observable<DeriveEraExposure> =>
export function eraExposure (instanceId: string, api: ApiInterfaceRx): (era: EraIndex) => Observable<DeriveEraExposure> {
return memo(instanceId, (era: EraIndex): Observable<DeriveEraExposure> =>
api.derive.staking._eraExposure(era, true)
);
}
export function _erasExposure (api: ApiInterfaceRx): (eras: EraIndex[], withActive: boolean) => Observable<DeriveEraExposure[]> {
return memo((eras: EraIndex[], withActive: boolean): Observable<DeriveEraExposure[]> =>
export function _erasExposure (instanceId: string, api: ApiInterfaceRx): (eras: EraIndex[], withActive: boolean) => Observable<DeriveEraExposure[]> {
return memo(instanceId, (eras: EraIndex[], withActive: boolean): Observable<DeriveEraExposure[]> =>
eras.length
? combineLatest(eras.map((era) => api.derive.staking._eraExposure(era, withActive)))
: of([])
);
}
export function erasExposure (api: ApiInterfaceRx): (withActive?: boolean) => Observable<DeriveEraExposure[]> {
return memo((withActive = false): Observable<DeriveEraExposure[]> =>
export function erasExposure (instanceId: string, api: ApiInterfaceRx): (withActive?: boolean) => Observable<DeriveEraExposure[]> {
return memo(instanceId, (withActive = false): Observable<DeriveEraExposure[]> =>
api.derive.staking.erasHistoric(withActive).pipe(
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 (instanceId: string, api: ApiInterfaceRx): (withActive: boolean) => Observable<EraIndex[]> {
return memo(instanceId, (withActive: boolean): Observable<EraIndex[]> =>
api.query.staking?.activeEra
? api.queryMulti<[Option<ActiveEraInfo>, u32]>([
api.query.staking.activeEra,
@@ -8,6 +8,7 @@ import { DeriveEraPoints, DeriveEraValPoints } from '../types';
import { Observable, of } from 'rxjs';
import { map, switchMap } from 'rxjs/operators';
import { BN_ZERO } from '@polkadot/util';
import { deriveCache, memo } from '../util';
@@ -15,7 +16,7 @@ const CACHE_KEY = 'eraPoints';
function mapValidators ({ individual }: EraRewardPoints): DeriveEraValPoints {
return [...individual.entries()]
.filter(([, points]): boolean => points.gtn(0))
.filter(([, points]) => points.gt(BN_ZERO))
.reduce((result: DeriveEraValPoints, [validatorId, points]): DeriveEraValPoints => {
result[validatorId.toString()] = points;
@@ -31,8 +32,8 @@ function mapPoints (eras: EraIndex[], points: EraRewardPoints[]): DeriveEraPoint
}));
}
export function _erasPoints (api: ApiInterfaceRx): (eras: EraIndex[], withActive: boolean) => Observable<DeriveEraPoints[]> {
return memo((eras: EraIndex[], withActive: boolean): Observable<DeriveEraPoints[]> => {
export function _erasPoints (instanceId: string, api: ApiInterfaceRx): (eras: EraIndex[], withActive: boolean) => Observable<DeriveEraPoints[]> {
return memo(instanceId, (eras: EraIndex[], withActive: boolean): Observable<DeriveEraPoints[]> => {
if (!eras.length) {
return of([]);
}
@@ -61,8 +62,8 @@ export function _erasPoints (api: ApiInterfaceRx): (eras: EraIndex[], withActive
});
}
export function erasPoints (api: ApiInterfaceRx): (withActive?: boolean) => Observable<DeriveEraPoints[]> {
return memo((withActive = false): Observable<DeriveEraPoints[]> =>
export function erasPoints (instanceId: string, api: ApiInterfaceRx): (withActive?: boolean) => Observable<DeriveEraPoints[]> {
return memo(instanceId, (withActive = false): Observable<DeriveEraPoints[]> =>
api.derive.staking.erasHistoric(withActive).pipe(
switchMap((eras) => api.derive.staking._erasPoints(eras, withActive))
)
+8 -8
View File
@@ -24,8 +24,8 @@ 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> => {
export function _eraPrefs (instanceId: string, api: ApiInterfaceRx): (era: EraIndex, withActive: boolean) => Observable<DeriveEraPrefs> {
return memo(instanceId, (era: EraIndex, withActive: boolean): Observable<DeriveEraPrefs> => {
const cacheKey = `${CACHE_KEY}-${era.toString()}`;
const cached = withActive
? undefined
@@ -45,22 +45,22 @@ export function _eraPrefs (api: ApiInterfaceRx): (era: EraIndex, withActive: boo
});
}
export function eraPrefs (api: ApiInterfaceRx): (era: EraIndex) => Observable<DeriveEraPrefs> {
return memo((era: EraIndex): Observable<DeriveEraPrefs> =>
export function eraPrefs (instanceId: string, api: ApiInterfaceRx): (era: EraIndex) => Observable<DeriveEraPrefs> {
return memo(instanceId, (era: EraIndex): Observable<DeriveEraPrefs> =>
api.derive.staking._eraPrefs(era, true)
);
}
export function _erasPrefs (api: ApiInterfaceRx): (eras: EraIndex[], withActive: boolean) => Observable<DeriveEraPrefs[]> {
return memo((eras: EraIndex[], withActive: boolean): Observable<DeriveEraPrefs[]> =>
export function _erasPrefs (instanceId: string, api: ApiInterfaceRx): (eras: EraIndex[], withActive: boolean) => Observable<DeriveEraPrefs[]> {
return memo(instanceId, (eras: EraIndex[], withActive: boolean): Observable<DeriveEraPrefs[]> =>
eras.length
? combineLatest(eras.map((era) => api.derive.staking._eraPrefs(era, withActive)))
: of([])
);
}
export function erasPrefs (api: ApiInterfaceRx): (withActive?: boolean) => Observable<DeriveEraPrefs[]> {
return memo((withActive = false): Observable<DeriveEraPrefs[]> =>
export function erasPrefs (instanceId: string, api: ApiInterfaceRx): (withActive?: boolean) => Observable<DeriveEraPrefs[]> {
return memo(instanceId, (withActive = false): Observable<DeriveEraPrefs[]> =>
api.derive.staking.erasHistoric(withActive).pipe(
switchMap((eras) => api.derive.staking._erasPrefs(eras, withActive))
)
@@ -21,8 +21,8 @@ function mapRewards (eras: EraIndex[], optRewards: Option<Balance>[]): DeriveEra
}));
}
export function _erasRewards (api: ApiInterfaceRx): (eras: EraIndex[], withActive: boolean) => Observable<DeriveEraRewards[]> {
return memo((eras: EraIndex[], withActive: boolean): Observable<DeriveEraRewards[]> => {
export function _erasRewards (instanceId: string, api: ApiInterfaceRx): (eras: EraIndex[], withActive: boolean) => Observable<DeriveEraRewards[]> {
return memo(instanceId, (eras: EraIndex[], withActive: boolean): Observable<DeriveEraRewards[]> => {
if (!eras.length) {
return of([]);
}
@@ -53,8 +53,8 @@ export function _erasRewards (api: ApiInterfaceRx): (eras: EraIndex[], withActiv
});
}
export function erasRewards (api: ApiInterfaceRx): (withActive?: boolean) => Observable<DeriveEraRewards[]> {
return memo((withActive = false): Observable<DeriveEraRewards[]> =>
export function erasRewards (instanceId: string, api: ApiInterfaceRx): (withActive?: boolean) => Observable<DeriveEraRewards[]> {
return memo(instanceId, (withActive = false): Observable<DeriveEraRewards[]> =>
api.derive.staking.erasHistoric(withActive).pipe(
switchMap((eras) => api.derive.staking._erasRewards(eras, withActive))
)
@@ -30,8 +30,8 @@ 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> => {
export function _eraSlashes (instanceId: string, api: ApiInterfaceRx): (era: EraIndex, withActive: boolean) => Observable<DeriveEraSlashes> {
return memo(instanceId, (era: EraIndex, withActive: boolean): Observable<DeriveEraSlashes> => {
const cacheKey = `${CACHE_KEY}-${era.toString()}`;
const cached = withActive
? undefined
@@ -54,14 +54,14 @@ export function _eraSlashes (api: ApiInterfaceRx): (era: EraIndex, withActive: b
});
}
export function eraSlashes (api: ApiInterfaceRx): (era: EraIndex) => Observable<DeriveEraSlashes> {
return memo((era: EraIndex): Observable<DeriveEraSlashes> =>
export function eraSlashes (instanceId: string, api: ApiInterfaceRx): (era: EraIndex) => Observable<DeriveEraSlashes> {
return memo(instanceId, (era: EraIndex): Observable<DeriveEraSlashes> =>
api.derive.staking._eraSlashes(era, true)
);
}
export function _erasSlashes (api: ApiInterfaceRx): (eras: EraIndex[], withActive: boolean) => Observable<DeriveEraSlashes[]> {
return memo((eras: EraIndex[], withActive: boolean): Observable<DeriveEraSlashes[]> =>
export function _erasSlashes (instanceId: string, api: ApiInterfaceRx): (eras: EraIndex[], withActive: boolean) => Observable<DeriveEraSlashes[]> {
return memo(instanceId, (eras: EraIndex[], withActive: boolean): Observable<DeriveEraSlashes[]> =>
eras.length
? combineLatest(
eras.map((era) => api.derive.staking._eraSlashes(era, withActive))
@@ -70,8 +70,8 @@ export function _erasSlashes (api: ApiInterfaceRx): (eras: EraIndex[], withActiv
);
}
export function erasSlashes (api: ApiInterfaceRx): (withActive?: boolean) => Observable<DeriveEraSlashes[]> {
return memo((withActive = false): Observable<DeriveEraSlashes[]> =>
export function erasSlashes (instanceId: string, api: ApiInterfaceRx): (withActive?: boolean) => Observable<DeriveEraSlashes[]> {
return memo(instanceId, (withActive = false): Observable<DeriveEraSlashes[]> =>
api.derive.staking.erasHistoric(withActive).pipe(
switchMap((eras) => api.derive.staking._erasSlashes(eras, withActive))
)
+1
View File
@@ -11,6 +11,7 @@ export * from './erasPrefs';
export * from './erasRewards';
export * from './erasSlashes';
export * from './electedInfo';
export * from './keys';
export * from './overview';
export * from './ownExposure';
export * from './ownSlashes';
+52
View File
@@ -0,0 +1,52 @@
// 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, Keys } from '@polkadot/types/interfaces';
import { ITuple } from '@polkadot/types/types';
import { DeriveStakingKeys } from './types';
import { Observable, combineLatest, of } from 'rxjs';
import { map, switchMap } from 'rxjs/operators';
import { Option, Vec } from '@polkadot/types';
import { memo } from '../util';
function extractsIds (stashId: Uint8Array | string, queuedKeys: [AccountId, Keys][], nextKeys: Option<Keys>): DeriveStakingKeys {
const sessionIds = (queuedKeys.find(([currentId]) => currentId.eq(stashId)) || [undefined, [] as AccountId[]])[1];
const nextSessionIds = nextKeys.unwrapOr([] as AccountId[]);
return {
nextSessionIds,
sessionIds
};
}
export function keys (instanceId: string, api: ApiInterfaceRx): (stashId: Uint8Array | string) => Observable<DeriveStakingKeys> {
return memo(instanceId, (stashId: Uint8Array | string): Observable<DeriveStakingKeys> =>
api.derive.staking.keysMulti([stashId]).pipe(
map(([first]) => first)
)
);
}
export function keysMulti (instanceId: string, api: ApiInterfaceRx): (stashIds: (Uint8Array | string)[]) => Observable<DeriveStakingKeys[]> {
return memo(instanceId, (stashIds: (Uint8Array | string)[]): Observable<DeriveStakingKeys[]> =>
stashIds.length
? api.query.session.queuedKeys<Vec<ITuple<[AccountId, Keys]>>>().pipe(
switchMap((queuedKeys): Observable<[Vec<ITuple<[AccountId, Keys]>>, Option<Keys>[]]> =>
combineLatest([
of(queuedKeys),
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)
])
),
map(([queuedKeys, nextKeys]) =>
stashIds.map((stashId, index) => extractsIds(stashId, queuedKeys, nextKeys[index]))
)
)
: of([])
);
}
+2 -2
View File
@@ -13,8 +13,8 @@ import { memo } from '../util';
/**
* @description Retrieve the staking overview, including elected and points earned
*/
export function overview (api: ApiInterfaceRx): () => Observable<DeriveStakingOverview> {
return memo((): Observable<DeriveStakingOverview> =>
export function overview (instanceId: string, api: ApiInterfaceRx): () => Observable<DeriveStakingOverview> {
return memo(instanceId, (): Observable<DeriveStakingOverview> =>
combineLatest([
api.derive.session.indexes(),
api.derive.staking.validators()
@@ -13,8 +13,8 @@ import { deriveCache, memo } from '../util';
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> => {
export function _ownExposure (instanceId: string, api: ApiInterfaceRx): (accountId: Uint8Array | string, era: EraIndex, withActive: boolean) => Observable<DeriveOwnExposure> {
return memo(instanceId, (accountId: Uint8Array | string, era: EraIndex, withActive: boolean): Observable<DeriveOwnExposure> => {
const cacheKey = `${CACHE_KEY}-${era.toString()}-${accountId.toString()}`;
const cached = withActive
? undefined
@@ -37,14 +37,14 @@ export function _ownExposure (api: ApiInterfaceRx): (accountId: Uint8Array | str
});
}
export function ownExposure (api: ApiInterfaceRx): (accountId: Uint8Array | string, era: EraIndex) => Observable<DeriveOwnExposure> {
return memo((accountId: Uint8Array | string, era: EraIndex): Observable<DeriveOwnExposure> =>
export function ownExposure (instanceId: string, api: ApiInterfaceRx): (accountId: Uint8Array | string, era: EraIndex) => Observable<DeriveOwnExposure> {
return memo(instanceId, (accountId: Uint8Array | string, era: EraIndex): Observable<DeriveOwnExposure> =>
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[]> =>
export function _ownExposures (instanceId: string, api: ApiInterfaceRx): (accountId: Uint8Array | string, eras: EraIndex[], withActive: boolean) => Observable<DeriveOwnExposure[]> {
return memo(instanceId, (accountId: Uint8Array | string, eras: EraIndex[], withActive: boolean): Observable<DeriveOwnExposure[]> =>
eras.length
? combineLatest(
eras.map((era) => api.derive.staking._ownExposure(accountId, era, withActive))
@@ -53,8 +53,8 @@ export function _ownExposures (api: ApiInterfaceRx): (accountId: Uint8Array | st
);
}
export function ownExposures (api: ApiInterfaceRx): (accountId: Uint8Array | string, withActive?: boolean) => Observable<DeriveOwnExposure[]> {
return memo((accountId: Uint8Array | string, withActive = false): Observable<DeriveOwnExposure[]> => {
export function ownExposures (instanceId: string, api: ApiInterfaceRx): (accountId: Uint8Array | string, withActive?: boolean) => Observable<DeriveOwnExposure[]> {
return memo(instanceId, (accountId: Uint8Array | string, withActive = false): Observable<DeriveOwnExposure[]> => {
return api.derive.staking.erasHistoric(withActive).pipe(
switchMap((eras) =>
api.derive.staking._ownExposures(accountId, eras, withActive)
@@ -15,8 +15,8 @@ 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> => {
export function _ownSlash (instanceId: string, api: ApiInterfaceRx): (accountId: Uint8Array | string, era: EraIndex, withActive: boolean) => Observable<DeriveStakerSlashes> {
return memo(instanceId, (accountId: Uint8Array | string, era: EraIndex, withActive: boolean): Observable<DeriveStakerSlashes> => {
const cacheKey = `${CACHE_KEY}-${era.toString()}-${accountId.toString()}`;
const cached = withActive
? undefined
@@ -44,14 +44,14 @@ export function _ownSlash (api: ApiInterfaceRx): (accountId: Uint8Array | string
});
}
export function ownSlash (api: ApiInterfaceRx): (accountId: Uint8Array | string, era: EraIndex) => Observable<DeriveStakerSlashes> {
return memo((accountId: Uint8Array | string, era: EraIndex): Observable<DeriveStakerSlashes> =>
export function ownSlash (instanceId: string, api: ApiInterfaceRx): (accountId: Uint8Array | string, era: EraIndex) => Observable<DeriveStakerSlashes> {
return memo(instanceId, (accountId: Uint8Array | string, era: EraIndex): Observable<DeriveStakerSlashes> =>
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[]> =>
export function _ownSlashes (instanceId: string, api: ApiInterfaceRx): (accountId: Uint8Array | string, eras: EraIndex[], withActive: boolean) => Observable<DeriveStakerSlashes[]> {
return memo(instanceId, (accountId: Uint8Array | string, eras: EraIndex[], withActive: boolean): Observable<DeriveStakerSlashes[]> =>
eras.length
? combineLatest(
eras.map((era) => api.derive.staking._ownSlash(accountId, era, withActive))
@@ -60,8 +60,8 @@ export function _ownSlashes (api: ApiInterfaceRx): (accountId: Uint8Array | stri
);
}
export function ownSlashes (api: ApiInterfaceRx): (accountId: Uint8Array | string, withActive?: boolean) => Observable<DeriveStakerSlashes[]> {
return memo((accountId: Uint8Array | string, withActive = false): Observable<DeriveStakerSlashes[]> => {
export function ownSlashes (instanceId: string, api: ApiInterfaceRx): (accountId: Uint8Array | string, withActive?: boolean) => Observable<DeriveStakerSlashes[]> {
return memo(instanceId, (accountId: Uint8Array | string, withActive = false): Observable<DeriveStakerSlashes[]> => {
return api.derive.staking.erasHistoric(withActive).pipe(
switchMap((eras) =>
api.derive.staking._ownSlashes(accountId, eras, withActive)
+32 -53
View File
@@ -3,54 +3,38 @@
// of the Apache-2.0 license. See the LICENSE file for details.
import { ApiInterfaceRx } from '@polkadot/api/types';
import { AccountId, EraIndex, Exposure, Keys, Nominations, RewardDestination, StakingLedger, ValidatorPrefs } from '@polkadot/types/interfaces';
import { AccountId, EraIndex, Exposure, 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 { Option } 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];
type MultiResult = [Option<AccountId>, Option<ITuple<[Nominations]> | Nominations>, RewardDestination, ITuple<[ValidatorPrefs]> | ValidatorPrefs, Exposure];
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];
const nextSessionIds = nextKeys.unwrapOr([] as AccountId[]);
return {
nextSessionIds,
sessionIds
};
}
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);
function parseController (stashId: AccountId, [controllerIdOpt, nominatorsOpt, rewardDestination, validatorPrefs, exposure]: MultiResult, stakingLedgerOpt: Option<StakingLedger>): DeriveStakingQuery {
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: [] };
return {
accountId: stashId,
controllerId: controllerIdOpt.unwrapOr(null),
exposure,
nominators: nominators
? Array.isArray(nominators)
? nominators[0].targets
: nominators.targets
: [],
rewardDestination,
stakingLedger: stakingLedgerOpt.unwrapOrDefault(),
stashId,
validatorPrefs: Array.isArray(validatorPrefs)
? validatorPrefs[0]
: validatorPrefs
};
}
function retrievePrev (api: ApiInterfaceRx, stashId: AccountId): Observable<MultiResult> {
@@ -59,7 +43,6 @@ function retrievePrev (api: ApiInterfaceRx, stashId: AccountId): Observable<Mult
[api.query.staking.nominators, stashId],
[api.query.staking.payee, stashId],
[api.query.staking.validators, stashId],
[api.query.session.nextKeys, [api.consts.session.dedupKeyPrefix, stashId]],
[api.query.staking.stakers, stashId]
]);
}
@@ -67,17 +50,16 @@ function retrievePrev (api: ApiInterfaceRx, stashId: AccountId): Observable<Mult
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.nominators
? api.query.staking.nominators.multi<Option<Nominations>>(stashIds)
: of(stashIds.map(() => api.registry.createType('Option<Nominations>'))),
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[] =>
map(([controllerIdOpt, nominatorsOpt, rewardDestination, validatorPrefs, exposure]): MultiResult[] =>
controllerIdOpt.map((controllerIdOpt, index): MultiResult =>
[controllerIdOpt, nominatorsOpt[index], rewardDestination[index], validatorPrefs[index], nextKeys[index], exposure[index]]
[controllerIdOpt, nominatorsOpt[index], rewardDestination[index], validatorPrefs[index], exposure[index]]
)
)
);
@@ -106,22 +88,19 @@ function retrieveControllers (api: ApiInterfaceRx, optControllerIds: Option<Acco
/**
* @description From a stash, retrieve the controllerId and all relevant details
*/
export function query (api: ApiInterfaceRx): (accountId: Uint8Array | string) => Observable<DeriveStakingQuery> {
return memo((accountId: Uint8Array | string): Observable<DeriveStakingQuery> =>
export function query (instanceId: string, api: ApiInterfaceRx): (accountId: Uint8Array | string) => Observable<DeriveStakingQuery> {
return memo(instanceId, (accountId: Uint8Array | string): Observable<DeriveStakingQuery> =>
api.derive.staking.queryMulti([accountId]).pipe(
map(([first]) => first)
)
);
}
export function queryMulti (api: ApiInterfaceRx): (accountIds: (Uint8Array | string)[]) => Observable<DeriveStakingQuery[]> {
return memo((accountIds: (Uint8Array | string)[]): Observable<DeriveStakingQuery[]> =>
export function queryMulti (instanceId: string, api: ApiInterfaceRx): (accountIds: (Uint8Array | string)[]) => Observable<DeriveStakingQuery[]> {
return memo(instanceId, (accountIds: (Uint8Array | string)[]): Observable<DeriveStakingQuery[]> =>
accountIds.length
? combineLatest([
api.query.session.queuedKeys<Vec<ITuple<[AccountId, Keys]>>>(),
api.derive.session.indexes()
]).pipe(
switchMap(([queuedKeys, { activeEra }]): Observable<DeriveStakingQuery[]> => {
? api.derive.session.indexes().pipe(
switchMap(({ activeEra }): Observable<DeriveStakingQuery[]> => {
const stashIds = accountIds.map((accountId) => api.registry.createType('AccountId', accountId));
return (
@@ -132,7 +111,7 @@ export function queryMulti (api: ApiInterfaceRx): (accountIds: (Uint8Array | str
switchMap((results): Observable<DeriveStakingQuery[]> =>
retrieveControllers(api, results.map(([optController]) => optController)).pipe(
map((stakingLedgerOpts) =>
stashIds.map((stashId, index) => parseController(stashId, queuedKeys, results[index], stakingLedgerOpts[index]))
stashIds.map((stashId, index) => parseController(stashId, results[index], stakingLedgerOpts[index]))
)
)
)
@@ -11,8 +11,8 @@ import { map, switchMap } from 'rxjs/operators';
import { memo } from '../util';
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[]> => {
export function _stakerExposure (instanceId: string, api: ApiInterfaceRx): (accountId: Uint8Array | string, eras: EraIndex[], withActive: boolean) => Observable<DeriveStakerExposure[]> {
return memo(instanceId, (accountId: Uint8Array | string, eras: EraIndex[], withActive: boolean): Observable<DeriveStakerExposure[]> => {
const stakerId = api.registry.createType('AccountId', accountId).toString();
return api.derive.staking._erasExposure(eras, withActive).pipe(
@@ -37,8 +37,8 @@ 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 = false): Observable<DeriveStakerExposure[]> =>
export function stakerExposure (instanceId: string, api: ApiInterfaceRx): (accountId: Uint8Array | string, withActive?: boolean) => Observable<DeriveStakerExposure[]> {
return memo(instanceId, (accountId: Uint8Array | string, withActive = false): Observable<DeriveStakerExposure[]> =>
api.derive.staking.erasHistoric(withActive).pipe(
switchMap((eras) => api.derive.staking._stakerExposure(accountId, eras, withActive))
)
@@ -11,8 +11,8 @@ import { map, switchMap } from 'rxjs/operators';
import { memo } from '../util';
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[]> => {
export function _stakerPoints (instanceId: string, api: ApiInterfaceRx): (accountId: Uint8Array | string, eras: EraIndex[], withActive: boolean) => Observable<DeriveStakerPoints[]> {
return memo(instanceId, (accountId: Uint8Array | string, eras: EraIndex[], withActive: boolean): Observable<DeriveStakerPoints[]> => {
const stakerId = api.registry.createType('AccountId', accountId).toString();
return api.derive.staking._erasPoints(eras, withActive).pipe(
@@ -27,8 +27,8 @@ 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 = false): Observable<DeriveStakerPoints[]> =>
export function stakerPoints (instanceId: string, api: ApiInterfaceRx): (accountId: Uint8Array | string, withActive?: boolean) => Observable<DeriveStakerPoints[]> {
return memo(instanceId, (accountId: Uint8Array | string, withActive = false): Observable<DeriveStakerPoints[]> =>
api.derive.staking.erasHistoric(withActive).pipe(
switchMap((eras) => api.derive.staking._stakerPoints(accountId, eras, withActive))
)
@@ -158,8 +158,8 @@ function filterRewards (api: ApiInterfaceRx, eras: EraIndex[], migrateEra: BN, r
);
}
export function _stakerRewardsEras (api: ApiInterfaceRx): (eras: EraIndex[], withActive: boolean) => Observable<ErasResult> {
return memo((eras: EraIndex[], withActive: boolean): Observable<ErasResult> =>
export function _stakerRewardsEras (instanceId: string, api: ApiInterfaceRx): (eras: EraIndex[], withActive: boolean) => Observable<ErasResult> {
return memo(instanceId, (eras: EraIndex[], withActive: boolean): Observable<ErasResult> =>
combineLatest([
isFunction(api.query.staking.migrateEra)
? api.query.staking.migrateEra<Option<EraIndex>>()
@@ -171,8 +171,8 @@ export function _stakerRewardsEras (api: ApiInterfaceRx): (eras: EraIndex[], wit
);
}
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[]> =>
export function _stakerRewards (instanceId: string, api: ApiInterfaceRx): (accountId: Uint8Array | string, eras: EraIndex[], withActive: boolean) => Observable<DeriveStakerReward[]> {
return memo(instanceId, (accountId: Uint8Array | string, eras: EraIndex[], withActive: boolean): Observable<DeriveStakerReward[]> =>
combineLatest([
api.derive.staking.query(accountId),
api.derive.staking._stakerExposure(accountId, eras, withActive),
@@ -191,24 +191,24 @@ export function _stakerRewards (api: ApiInterfaceRx): (accountId: Uint8Array | s
);
}
export function stakerRewards (api: ApiInterfaceRx): (accountId: Uint8Array | string, withActive?: boolean) => Observable<DeriveStakerReward[]> {
return memo((accountId: Uint8Array | string, withActive = false): Observable<DeriveStakerReward[]> =>
export function stakerRewards (instanceId: string, api: ApiInterfaceRx): (accountId: Uint8Array | string, withActive?: boolean) => Observable<DeriveStakerReward[]> {
return memo(instanceId, (accountId: Uint8Array | string, withActive = false): Observable<DeriveStakerReward[]> =>
api.derive.staking.erasHistoric(withActive).pipe(
switchMap((eras) => api.derive.staking._stakerRewards(accountId, eras, withActive))
)
);
}
export function stakerRewardsMultiEras (api: ApiInterfaceRx): (accountIds: (Uint8Array | string)[], eras: EraIndex[]) => Observable<DeriveStakerReward[][]> {
return memo((accountIds: (Uint8Array | string)[], eras: EraIndex[]): Observable<DeriveStakerReward[][]> =>
export function stakerRewardsMultiEras (instanceId: string, api: ApiInterfaceRx): (accountIds: (Uint8Array | string)[], eras: EraIndex[]) => Observable<DeriveStakerReward[][]> {
return memo(instanceId, (accountIds: (Uint8Array | string)[], eras: EraIndex[]): Observable<DeriveStakerReward[][]> =>
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[][]> =>
export function stakerRewardsMulti (instanceId: string, api: ApiInterfaceRx): (accountIds: (Uint8Array | string)[], withActive?: boolean) => Observable<DeriveStakerReward[][]> {
return memo(instanceId, (accountIds: (Uint8Array | string)[], withActive = false): Observable<DeriveStakerReward[][]> =>
api.derive.staking.erasHistoric(withActive).pipe(
switchMap((eras) => api.derive.staking.stakerRewardsMultiEras(accountIds, eras))
)
@@ -11,8 +11,8 @@ import { map, switchMap } from 'rxjs/operators';
import { memo } from '../util';
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[]> => {
export function _stakerSlashes (instanceId: string, api: ApiInterfaceRx): (accountId: Uint8Array | string, eras: EraIndex[], withActive: boolean) => Observable<DeriveStakerSlashes[]> {
return memo(instanceId, (accountId: Uint8Array | string, eras: EraIndex[], withActive: boolean): Observable<DeriveStakerSlashes[]> => {
const stakerId = api.registry.createType('AccountId', accountId).toString();
return api.derive.staking._erasSlashes(eras, withActive).pipe(
@@ -26,8 +26,8 @@ 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 = false): Observable<DeriveStakerSlashes[]> =>
export function stakerSlashes (instanceId: string, api: ApiInterfaceRx): (accountId: Uint8Array | string, withActive?: boolean) => Observable<DeriveStakerSlashes[]> {
return memo(instanceId, (accountId: Uint8Array | string, withActive = false): Observable<DeriveStakerSlashes[]> =>
api.derive.staking.erasHistoric(withActive).pipe(
switchMap((eras) => api.derive.staking._stakerSlashes(accountId, eras, withActive))
)
+2 -2
View File
@@ -15,8 +15,8 @@ import { memo } from '../util';
/**
* @description Retrieve the list of all validator stashes
*/
export function stashes (api: ApiInterfaceRx): () => Observable<AccountId[]> {
return memo((): Observable<AccountId[]> =>
export function stashes (instanceId: string, api: ApiInterfaceRx): () => Observable<AccountId[]> {
return memo(instanceId, (): Observable<AccountId[]> =>
api.query.staking.validators.creator.meta.type.asMap.linked.isTrue
? api.query.staking.validators<ITuple<[Vec<AccountId>, Vec<ValidatorPrefs>]>>().pipe(
map(([stashIds]) => stashIds)
+42 -41
View File
@@ -3,7 +3,7 @@
// of the Apache-2.0 license. See the LICENSE file for details.
import type BN from 'bn.js';
import { AccountId, Balance, EraIndex, Exposure, Keys, RewardDestination, RewardPoint, StakingLedger, ValidatorPrefs } from '@polkadot/types/interfaces';
import { AccountId, Balance, EraIndex, Exposure, RewardDestination, RewardPoint, StakingLedger, ValidatorPrefs } from '@polkadot/types/interfaces';
import { DeriveSessionIndexes } from '../session/types';
export type DeriveEraValPoints = Record<string, RewardPoint>;
@@ -40,6 +40,17 @@ export interface DeriveStakerPoints {
points: RewardPoint;
}
export interface DeriveOwnExposure {
clipped: Exposure;
era: EraIndex;
exposure: Exposure;
}
export interface DeriveEraExposureNominating {
validatorId: string;
validatorIndex: number;
}
export type DeriveEraNominatorExposure = Record<string, DeriveEraExposureNominating[]>;
export type DeriveEraValidatorExposure = Record<string, Exposure>;
@@ -50,19 +61,6 @@ export interface DeriveEraExposure {
validators: DeriveEraValidatorExposure;
}
export interface DeriveOwnExposure {
clipped: Exposure;
era: EraIndex;
exposure: Exposure;
}
export type DeriveOwnSlashes = DeriveStakerSlashes;
export interface DeriveEraExposureNominating {
validatorId: string;
validatorIndex: number;
}
export interface DeriveStakerExposure {
era: EraIndex;
isEmpty: boolean;
@@ -91,6 +89,32 @@ export interface DeriveStakerSlashes {
total: Balance;
}
export type DeriveOwnSlashes = DeriveStakerSlashes;
export interface DeriveStakingKeys {
nextSessionIds: AccountId[];
sessionIds: AccountId[];
}
export interface DeriveStakingValidators {
nextElected: AccountId[];
validators: AccountId[];
}
export interface DeriveStakingStash {
controllerId: AccountId | null;
exposure: Exposure;
nominators: AccountId[];
rewardDestination: RewardDestination;
stashId: AccountId;
validatorPrefs: ValidatorPrefs;
}
export interface DeriveStakingQuery extends DeriveStakingStash {
accountId: AccountId;
stakingLedger: StakingLedger;
}
export interface DeriveStakingElected {
nextElected: AccountId[];
info: DeriveStakingQuery[];
@@ -101,30 +125,12 @@ export interface DeriveStakingWaiting {
waiting: AccountId[];
}
export interface DeriveStakingValidators {
nextElected: AccountId[];
validators: AccountId[];
export interface DeriveUnlocking {
remainingEras: BN;
value: Balance;
}
export interface DeriveStakingStash {
controllerId?: AccountId;
exposure?: Exposure;
nominators?: AccountId[];
nominateAt?: EraIndex;
rewardDestination?: RewardDestination;
nextKeys?: Keys;
stashId?: AccountId;
validatorPrefs?: ValidatorPrefs;
}
export interface DeriveStakingQuery extends DeriveStakingStash {
accountId: AccountId;
nextSessionIds: AccountId[];
sessionIds: AccountId[];
stakingLedger?: StakingLedger;
}
export interface DeriveStakingAccount extends DeriveStakingQuery {
export interface DeriveStakingAccount extends DeriveStakingQuery, DeriveStakingKeys {
redeemable?: Balance;
unlocking?: DeriveUnlocking[];
}
@@ -133,8 +139,3 @@ export interface DeriveStakingOverview extends DeriveSessionIndexes {
nextElected: AccountId[];
validators: AccountId[];
}
export type DeriveUnlocking = {
remainingEras: BN;
value: Balance;
};

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