Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
19510c1ede | ||
|
|
97b5c699b1 | ||
|
|
d2befda86e | ||
|
|
740348b48f | ||
|
|
9e2a5cf532 | ||
|
|
6df466d9ea | ||
|
|
e2a2ac2842 | ||
|
|
5adc846e45 | ||
|
|
75aa310837 | ||
|
|
ce0523eb1c | ||
|
|
eb0370bb66 | ||
|
|
5eb491dc67 | ||
|
|
b50294ab0f | ||
|
|
e1cb62d2d2 | ||
|
|
8ed0ef2295 | ||
|
|
956e173323 | ||
|
|
b8a37ba438 | ||
|
|
e7669c2b00 | ||
|
|
6c309a503d | ||
|
|
3cf67c975a | ||
|
|
077914364c | ||
|
|
56e4cbdb27 | ||
|
|
60bfdae734 | ||
|
|
1cf4d6b9b8 | ||
|
|
40cd9ff51f | ||
|
|
c7e6e40030 | ||
|
|
97d0bcbfd4 | ||
|
|
6ca84425d1 | ||
|
|
8481647d2c | ||
|
|
658dda66a4 | ||
|
|
87f18efe72 | ||
|
|
bcdfcce89c | ||
|
|
9418f1de56 | ||
|
|
37c8b8e592 | ||
|
|
4f8db79a40 | ||
|
|
54cf086a89 | ||
|
|
37ddcaa32d | ||
|
|
6a2baf8352 | ||
|
|
ecca91dffd | ||
|
|
42576d74ac | ||
|
|
26a6f20dbf | ||
|
|
c3ee8393b2 | ||
|
|
b6f0b9f262 | ||
|
|
991dc48020 | ||
|
|
e4a82f9a1d | ||
|
|
c8b6012553 | ||
|
|
d0fe862605 | ||
|
|
61a0198695 | ||
|
|
345a97dc9f | ||
|
|
f821ab8ecd | ||
|
|
f9e2bf332d | ||
|
|
ad69430980 | ||
|
|
d25743016c | ||
|
|
ee0a46adc4 | ||
|
|
f516abfc3f | ||
|
|
1a96ca5c0e | ||
|
|
8c73cd7d6e | ||
|
|
36232c0289 | ||
|
|
50d4e0397f | ||
|
|
539a8c4cb5 | ||
|
|
b849976b3b | ||
|
|
2395401a2b | ||
|
|
0e1bbd5cac | ||
|
|
e9489d41cb | ||
|
|
63483b9db7 | ||
|
|
b26c7f9f0a | ||
|
|
a165c9375c | ||
|
|
28631f7180 | ||
|
|
6489251b47 | ||
|
|
66884febea | ||
|
|
8058dc350f | ||
|
|
63096cc238 | ||
|
|
05600c0cd0 | ||
|
|
eed5e23e65 | ||
|
|
cdf5b15673 | ||
|
|
1922676bd7 | ||
|
|
b6c427e985 | ||
|
|
0327aedf8e | ||
|
|
d7035cebb1 | ||
|
|
8b492021af | ||
|
|
6a01fc7c8c | ||
|
|
bbc30ec9dc | ||
|
|
f07c0628bc | ||
|
|
023c7588e5 | ||
|
|
7dfc8625cc | ||
|
|
8643b5da87 | ||
|
|
afa0e63ae8 | ||
|
|
534303ff45 | ||
|
|
f1ebcddec6 | ||
|
|
657a2006dd | ||
|
|
219e928c01 | ||
|
|
43183118d5 | ||
|
|
76e15d465d | ||
|
|
4c0387e1a3 | ||
|
|
bbbd82eb4a | ||
|
|
a34a7450aa | ||
|
|
bf472fdcf4 | ||
|
|
f428a58006 | ||
|
|
fcce2ab340 | ||
|
|
877eb11717 | ||
|
|
4b55f1be93 | ||
|
|
f2a677634e | ||
|
|
eea4c8775e | ||
|
|
792bf0ec36 | ||
|
|
e3d13107a9 | ||
|
|
e5c2c6a228 | ||
|
|
d2be79132c | ||
|
|
76da2638c1 | ||
|
|
daf3912920 | ||
|
|
6dfebbb9fe | ||
|
|
e55c5f77f7 | ||
|
|
c7315ffb74 | ||
|
|
84eb806f07 | ||
|
|
2493442a2e | ||
|
|
77df7907c7 | ||
|
|
f1b6268784 | ||
|
|
9aa9380251 | ||
|
|
b4306cb60a | ||
|
|
1e83daf797 | ||
|
|
d46d32d9bc | ||
|
|
032a0a595c | ||
|
|
34101ec12b | ||
|
|
4e02b982d3 | ||
|
|
5b96d52fa6 | ||
|
|
735f2b835e | ||
|
|
646e64c286 | ||
|
|
fc9060caa8 | ||
|
|
503c2b3c63 | ||
|
|
168abc130f | ||
|
|
5c5db2709b | ||
|
|
5a4ff5420f | ||
|
|
a1655508ba | ||
|
|
64827a6114 | ||
|
|
2eb09374bc | ||
|
|
ddf67d5564 | ||
|
|
ad6b8280a2 | ||
|
|
682c6b6fb2 | ||
|
|
6a281211b4 | ||
|
|
6ef94b3c3b | ||
|
|
e900d1d657 | ||
|
|
7f1a3fa636 | ||
|
|
21802664b8 | ||
|
|
1492df11a7 | ||
|
|
00fed90da2 | ||
|
|
e6beb6554d | ||
|
|
099cf5a351 | ||
|
|
55e762a348 | ||
|
|
0ad146c607 | ||
|
|
4e7f3f5268 | ||
|
|
6a9e3d80f1 | ||
|
|
dee98fae55 | ||
|
|
ff52876920 | ||
|
|
4d01a09c54 | ||
|
|
7310ea825e | ||
|
|
15b80a47c3 | ||
|
|
622682b4ef | ||
|
|
56415df4ab | ||
|
|
8bea5e5a3b | ||
|
|
d6372ade44 | ||
|
|
f501994df8 | ||
|
|
b787a7d5a0 | ||
|
|
11d162a10d | ||
|
|
e2564dea17 | ||
|
|
2b9152871e | ||
|
|
70ecb03d14 | ||
|
|
a2f179acb1 | ||
|
|
c8cb97edef | ||
|
|
69d344c6c3 | ||
|
|
44cdf49b2c | ||
|
|
daaf4654a1 | ||
|
|
f8d4fcaf04 | ||
|
|
eb19a39d82 | ||
|
|
7ed958fb2d | ||
|
|
bbe9b94f26 | ||
|
|
6e83e6aaef | ||
|
|
1545bbf7c5 | ||
|
|
5bfc2cd534 | ||
|
|
b22d0a196f | ||
|
|
b174864804 | ||
|
|
e6834d60c5 | ||
|
|
97438bb2e8 | ||
|
|
f630d43a25 | ||
|
|
0187f1ff19 | ||
|
|
d8db866316 | ||
|
|
28aa9e18a7 | ||
|
|
3eaea97b8f | ||
|
|
ea0e5e4547 | ||
|
|
1256317b65 | ||
|
|
e0c3ed1b96 | ||
|
|
9f2c3016d7 | ||
|
|
938ace2342 | ||
|
|
e5d2607dff | ||
|
|
50b8db2263 | ||
|
|
91766a6885 | ||
|
|
4b1a9ab9e1 | ||
|
|
9a14c65336 | ||
|
|
4aa66fd4c6 | ||
|
|
3d9c62d538 | ||
|
|
4156eb44ab | ||
|
|
4b2d33693c | ||
|
|
e8b127e177 | ||
|
|
b052b03f31 | ||
|
|
6727e12468 | ||
|
|
c130285651 | ||
|
|
47fc4a2b3c | ||
|
|
97cb408f36 | ||
|
|
dde7c8085a | ||
|
|
8b02fafb99 | ||
|
|
393f46ba4a | ||
|
|
455f5ad834 | ||
|
|
674324e7f9 | ||
|
|
b0dc7cf451 | ||
|
|
cbe1b2b1ce | ||
|
|
4bd2f2fc32 | ||
|
|
053112470d | ||
|
|
acdf27a272 | ||
|
|
f70b32ba76 | ||
|
|
67a3376ef8 | ||
|
|
eb06bb6e93 | ||
|
|
f8f7e92da4 | ||
|
|
d0fd3eca25 | ||
|
|
dac1df35de | ||
|
|
597563d2bb | ||
|
|
f825c7f187 | ||
|
|
2e71a6160e | ||
|
|
c076c37119 | ||
|
|
0e18fdbccc | ||
|
|
c3eebd8fbe | ||
|
|
45786b31da | ||
|
|
f348e34de7 | ||
|
|
337de79bef | ||
|
|
a13b51b985 | ||
|
|
c5c77c9b52 | ||
|
|
2a033e5634 | ||
|
|
00ffb358cb | ||
|
|
66d1bbe4cb | ||
|
|
3baf36e9e6 | ||
|
|
e3abb95111 | ||
|
|
da281c9531 | ||
|
|
c0e3026772 | ||
|
|
757da68675 | ||
|
|
f145488314 | ||
|
|
0ce10d2938 | ||
|
|
6f2d62bb3b | ||
|
|
fc7c8310ae | ||
|
|
c9921f002f | ||
|
|
6b8a65eb31 | ||
|
|
0cf29719b3 | ||
|
|
abecabdaed | ||
|
|
0c5b69bea1 | ||
|
|
7b3f24b1f5 | ||
|
|
d1f8f8b5e8 | ||
|
|
3f060b9e0d | ||
|
|
fe69f70539 | ||
|
|
578c4ffb69 | ||
|
|
66aa38000b | ||
|
|
50ddff6907 | ||
|
|
14874f41f7 | ||
|
|
5a11b0c701 | ||
|
|
8491ab8ca6 | ||
|
|
4f5cb0f35e | ||
|
|
53d081df65 | ||
|
|
6b5dbb6948 | ||
|
|
3879986a75 | ||
|
|
378ca10580 | ||
|
|
d75d8bec0e | ||
|
|
6f6a32a7a2 | ||
|
|
226426e67e | ||
|
|
66e2a4d298 | ||
|
|
664151f829 | ||
|
|
49b00524b1 | ||
|
|
401784b7e6 | ||
|
|
99873e901a | ||
|
|
72d131f62f | ||
|
|
c412f7fa11 | ||
|
|
a1ad90c2b4 | ||
|
|
92f62bfa15 | ||
|
|
fa9c5778be | ||
|
|
e6f877621a | ||
|
|
5c35a70e9d | ||
|
|
a287096cc3 | ||
|
|
c35f31bfbd | ||
|
|
718afa91e3 | ||
|
|
102a06b0f2 | ||
|
|
58f0df1ef0 | ||
|
|
a458589222 | ||
|
|
deef4ce4c7 | ||
|
|
f5d2449407 | ||
|
|
8bb1d1259e | ||
|
|
abd860d548 | ||
|
|
25936d882f | ||
|
|
9deaff54e4 | ||
|
|
bc479a995b | ||
|
|
458b7fa7e4 | ||
|
|
2fc17a66e1 | ||
|
|
94f81db568 | ||
|
|
e83d97c849 | ||
|
|
4a497fa970 | ||
|
|
cb40d459b5 | ||
|
|
c70cdb351f | ||
|
|
001aa0d011 | ||
|
|
961d27ad46 | ||
|
|
1c09bb69dd | ||
|
|
174510a928 | ||
|
|
39ed76f2de | ||
|
|
7d1c93db59 | ||
|
|
e9b1b4ee77 | ||
|
|
2367978f6e | ||
|
|
e77050b9f5 | ||
|
|
844d1a2928 | ||
|
|
6a70beda0f | ||
|
|
05a834b822 | ||
|
|
6a3af506a4 | ||
|
|
c82b85ef79 | ||
|
|
91ab81ef60 | ||
|
|
3665690444 | ||
|
|
03dcefceb5 | ||
|
|
e84be032f4 |
+3
-1
@@ -1,4 +1,6 @@
|
||||
24
|
||||
25
|
||||
1.4.2
|
||||
1.6.2
|
||||
1.11.2
|
||||
1.12.2
|
||||
1.17.2
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
.eslintrc.js
|
||||
**/build/*
|
||||
**/coverage/*
|
||||
**/node_modules/*
|
||||
|
||||
@@ -10,7 +10,7 @@ jobs:
|
||||
matrix:
|
||||
step: ['build:release', 'docs:release']
|
||||
name: ${{ matrix.step }}
|
||||
if: "! contains(github.event.head_commit.message, '[CI Skip]') && github.repository == 'polkadot-js/api'"
|
||||
if: "! startsWith(github.event.head_commit.message, '[CI Skip]') && github.repository == 'polkadot-js/api'"
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v1
|
||||
@@ -21,16 +21,13 @@ jobs:
|
||||
CC_TEST_REPORTER_ID: ${{ secrets.CC_TEST_REPORTER_ID }}
|
||||
GH_PAGES_SRC: build-docs
|
||||
GH_PAT: ${{ secrets.GH_PAT }}
|
||||
GH_TOKEN: ${{ secrets.GH_PAT }}
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
GH_RELEASE_GITHUB_API_TOKEN: ${{ secrets.GH_PAT }}
|
||||
NPM_TOKEN: ${{ secrets.NPM_TOKEN }}
|
||||
run: |
|
||||
yarn install --immutable | grep -v 'YN0013'
|
||||
yarn ${{ matrix.step }}
|
||||
|
||||
dummy:
|
||||
name: Dummy
|
||||
if: "contains(github.event.head_commit.message, '[CI Skip]')"
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: dummy
|
||||
|
||||
Vendored
+14
-8
File diff suppressed because one or more lines are too long
+240
-76
@@ -1,4 +1,168 @@
|
||||
# 1.12.1 Apr 29, 2020
|
||||
# CHANGELOG
|
||||
|
||||
## 1.27.1 Aug 3, 2020
|
||||
|
||||
- Remove outdated example poc-3 RPC reference (Thanks to https://github.com/swswsw)
|
||||
- Raw/Bytes `toHuman` detects ASCII sequence for text output
|
||||
- Add know types for the Rococo chain
|
||||
|
||||
## 1.26.1 Jul 27, 2020
|
||||
|
||||
- Update docs for the new `system.accountNextIndex` (Thanks to https://github.com/shawntabrizi)
|
||||
- Update contracts call parameter typing (Thanks to https://github.com/kwingram25)
|
||||
- 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
|
||||
|
||||
- **Important** Contract RPC result updated on Substrate, on older chains supply `ContractExecResult: 'ContractExecResultTo255'`
|
||||
- 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)
|
||||
- Raw/Bytes `toHuman()` displays utf-8 as available
|
||||
- Add fallback for `setImmediate` when not polyfilled
|
||||
- Update `NetworkState` reputation type for `system_networkState` RPC
|
||||
- Update session progress calcs for Aura (cater for negative)
|
||||
- Fix class prototype for (basically-deprecated) Linkage type
|
||||
- Add Polkadot types for `purchase` pallet
|
||||
|
||||
## 1.24.1 Jul 13, 2020
|
||||
|
||||
- Added `isAscii` & `isUtf8` getters to `Bytes` & `Raw` types
|
||||
- Added `toUtf8()` helper to `Bytes` & `Raw` types
|
||||
- `@polkadot/util` 2.18
|
||||
|
||||
## 1.23.1 Jul 6, 2020
|
||||
|
||||
- Small README typo fix (Thanks to https://github.com/woss)
|
||||
- Add latest Substrate master types
|
||||
- Adjust `<Codec>.toRawType()` to use registry name as available
|
||||
- Update `ProxyType` for Kusama, Polkadot & Westend with `IdentityJudgement`
|
||||
- Validate number format (signed/unsigned) for number types
|
||||
- Remove core codec dependencies on Base class (with proper TS encapsulation)
|
||||
- `@polkadot/util` 2.17
|
||||
|
||||
## 1.22.1 Jun 30, 2020
|
||||
|
||||
- **Important** Substrate changed the treasury tip structure, on older chains supply `OpenTip: 'OpenTipTo225'`
|
||||
- Allow for `[u8; 33]` in U8aFixed (Thanks to https://github.com/akru)
|
||||
- Improve derive accountId -> accountIndex lookups (optimize entries queries)
|
||||
- Vesting balance calculations via `derive.balances.all` has been updated for locks
|
||||
- Add derive for multi staking rewards with specified eras
|
||||
- `@polkadot/util` 2.16
|
||||
|
||||
## 1.21.1 Jun 23, 2020
|
||||
|
||||
- Fix subscriptions never unsubscribing after the id swap in 1.18.1 (Thanks to https://github.com/dillu24 for testing iterations)
|
||||
- Add support for `CheckMortality` signed extension (old `CheckEra` is now an alias)
|
||||
- Promise API will default to using `getStorage` on non-subscription calls, reducing RPC overhead
|
||||
- Optimize derive BN allocations, using in-place operators as applicable
|
||||
- Add new Substrate types for Babe `EquivocationProof`
|
||||
- Adjust `Releases` enum to use a shared instance
|
||||
|
||||
## 1.20.1 Jun 22, 2020
|
||||
|
||||
- **Important** RPC for `account_nextIndex` has been moved to `system_accountNextIndex` (Aligning with Substrate as a primary alias)
|
||||
- Cleanup map entries support with only Substrate 2.0-era RPCs (when introduced)
|
||||
- Add `system_dryRun` RPC
|
||||
- Optimize `derive.staking.queryMulti` retrievals with additional per-type batching
|
||||
- Add `derive.staking.waitingInfo` (same as `electedInfo` for waiting validators)
|
||||
- Adjust types & metadata for latest Substrate
|
||||
- `@polkadot/util` 2.15
|
||||
|
||||
## 1.19.1 Jun 16, 2020
|
||||
|
||||
- Improve typing on `.entries()` queries (Thanks to https://github.com/monitz87)
|
||||
- Align metadata and types with latest Substrate
|
||||
- Update Polkadot types for current evolution of parachains
|
||||
- Allow for type aliasing on events (aligning with calls & queries)
|
||||
- `@polkadot/util` 2.14
|
||||
|
||||
## 1.18.1 Jun 8, 2020
|
||||
|
||||
- Expand docs on node-template types (Thanks to https://github.com/g2udevelopment)
|
||||
- Update contract fees to current impl. (Thanks to https://github.com/djuanit0x)
|
||||
- Allow `Option` types in enum/Result type generation (Thanks to http://github.com/xlc)
|
||||
- Add `.entriesPaged` and `.keysPaged` methods for state maps (https://github.com/monitz87)
|
||||
- Add types for new Substrate proxy module
|
||||
- Adjust types for new Substrate (renamed) npos-elections module
|
||||
- `Call` now exposes `method` & `section` fields (aligned with `toHuman()` representation)
|
||||
- Cater for new Substrate string subscription ids (with backwards compatibility)
|
||||
- `@polkadot/util` 2.13
|
||||
|
||||
## 1.17.2 Jun 2, 2020
|
||||
|
||||
- Ensure subscription promise resolves before first result
|
||||
|
||||
## 1.17.1 Jun 2, 2020
|
||||
|
||||
- Fix `ElectionSize` type (Thanks to https://github.com/arjanz)
|
||||
- Allow `BTreeSet` decoding from Array/JSON inputs
|
||||
- Adjust Call-only metadata output to trim documentation to first full line
|
||||
- Safeguard against divide-by-zero for total era points (expired reward eras)
|
||||
- Internal derive optimizations with combining calls
|
||||
- Support for latest Substrate types & metadata
|
||||
- `@polkadot/util` 2.12
|
||||
|
||||
## 1.16.1 May 26, 2020
|
||||
|
||||
- Support for Polkadot CC1 types & signed extensions
|
||||
- Add support for Babe VRF secondary digests (author extraction)
|
||||
- Adjust `Perbill/Permill` `toHuman()` formatting to output percentage
|
||||
- Support for latest Substrate types & metadata
|
||||
- Update to latest TypeScript, eslint & typescript-eslint
|
||||
- `@polkadot/util` 2.11
|
||||
|
||||
## 1.15.1 May 23, 2020
|
||||
|
||||
- Adjust `keyPrefix()` with DoubleMap args (Thanks to https://github.com/KiChjang)
|
||||
- Added `WeightToFeeCoefficient` type (Thanks to https://github.com/danforbes)
|
||||
- Spelling fixes for console logs (Thanks to https://github.com/JoshOrndorff)
|
||||
- Spelling fixes in cookbook (Thanks to https://github.com/pawelnguyen)
|
||||
- Add `transactionVersion` getter in payloads (Thanks to https://github.com/amaurymartiny)
|
||||
- Adjust `stakerRewards` derive ordering for improved on-payout refreshes
|
||||
- Baseline implementation for derive caching infrastructure
|
||||
- Adjust `Multiplier` type to `Fixed128` (as per latest Substrate)
|
||||
- Updated to latest Substrate metadata & add new types
|
||||
|
||||
## 1.14.1 May 14, 2020
|
||||
|
||||
- **Important** `DispatchInfo` changed `paysFee` to an enum, if using an older version use, `DispatchInfo: 'DispatchInfoTo244'`
|
||||
- Align imOnline `Heartbeat` with Substrate (Thanks to https://github.com/arjanz)
|
||||
- Adust EVM types to include `Vicinity` (Thanks to https://github.com/drewstone)
|
||||
- Add `derive.democracy.locks` to return extended lock info based on votes
|
||||
- Ensure metadata is only requested once upon startup (bypass on upgrade subscriptions)
|
||||
- Expand testing around `ExtrinsicEra` construction
|
||||
- Expand `Registry` to direct access to available signed extensions (in addition to exposed types)
|
||||
- Cater for new `CheckSpecVersion` and `CheckTxVersion` signed extensions (with `SignerPayload` adjustments)
|
||||
- Cater for new `PrevalidateAttests` signed extensions (Polkadot claims)
|
||||
- Don't re-calculate submittable extrinsic hash on status checks (optimization)
|
||||
- Support for both old/new Tuples in `democracy.depositOf` in derives
|
||||
- Fix democracy `ProxyState` types
|
||||
- Extends types for Polkadot claims
|
||||
- Update `@polkadot/util` to 2.10
|
||||
|
||||
## 1.13.1 May 6, 2020
|
||||
|
||||
- Add support for ECDSA keypairs in extrinsic signers (Thanks to https://github.com/akru)
|
||||
- Rework type generation to use templating for better maintenance (Thanks to https://github.com/xlc)
|
||||
- Adjust extrinsic `sign/signAsync` signature to optional options (Thanks to https://github.com/KiChjang)
|
||||
- Support round-robin endpoints in the `WsProvider` with array of urls (Thanks to https://github.com/hoani)
|
||||
- Remove static test-only metadata for Polkadot dev chains (not updated regularly, Substrate dev to remain)
|
||||
- Revert error swallow for wrong preimage data (temp. override for Kusama upgrade with no migration)
|
||||
- Fix `.encodedLength` calculation on `[Type; N]` types
|
||||
- Add new `rpc.grandpa.roundState` RPC
|
||||
- Update types & metadata as per latest Substrate master
|
||||
- Adjust Centrifuge starting version
|
||||
|
||||
## 1.12.2 Apr 30, 2020
|
||||
|
||||
- Update `@polkadot/util` to stable 2.9.1 (sadly missed in the previous version, stable should match to stable)
|
||||
|
||||
## 1.12.1 Apr 29, 2020
|
||||
|
||||
- Fix `CompactAssignments` types (Thanks to https://github.com/arjanz)
|
||||
- Provider ayo-connect now allows for interval config (Thanks to https://github.com/jnaviask)
|
||||
@@ -9,11 +173,11 @@
|
||||
- Allow generic types in ApiPromise.combineLatest
|
||||
- Update to latest substrate metadata
|
||||
|
||||
# 1.11.2 Apr 22, 2020
|
||||
## 1.11.2 Apr 22, 2020
|
||||
|
||||
- Small patch to add missing Polkadot master types (will be in next Kusama update)
|
||||
|
||||
# 1.11.1 Apr 21, 2020
|
||||
## 1.11.1 Apr 21, 2020
|
||||
|
||||
- **Important** Substrate master has an updated `Weight` (to `u64`), on older chains apply `Weight: 'u32'` (This does affect event decoding if wrongly set)
|
||||
- Allow user type augmentation to work with different versions of rxjs (Thanks to https://github.com/monitz87)
|
||||
@@ -32,7 +196,7 @@
|
||||
- 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
|
||||
## 1.10.1 Apr 13, 2020
|
||||
|
||||
- **Important** Substrate master has updated staking, on older chains apply `StakingLedger: 'StakingLedgerTo240'`
|
||||
- Add `rpc.system.chainType` to retrieve the chain type (Development. Local, Live & Custom)
|
||||
@@ -45,7 +209,7 @@
|
||||
- Internally all private/protected methods/variables are now `_` prefixed (Aligning with the `private/protected` indicators in the TS definitions)
|
||||
- Update metadata/docs-from-metadata to the latest Substrate
|
||||
|
||||
# 1.9.1 Apr 1, 2020
|
||||
## 1.9.1 Apr 1, 2020
|
||||
|
||||
- **Breaking change** (TypeScript with derives only) The return type names for `api.derive.*` have been adjusted for consistency, all starting with `Derive*` (previously a mixture of `Derived*` and `Derive*`)
|
||||
- **Breaking change** (derives only) Additional cleanups of democracy proposal & referenda derives, including support for new Polkadot/Substrate vote retrievals
|
||||
@@ -60,7 +224,7 @@
|
||||
- Fix encoding for `Vec<u8>`-related types as part of constants
|
||||
- Internal adjustment of interface type locations (no impact on imports via `@polkadot/types/interfaces`)
|
||||
|
||||
# 1.8.1 Mar 22, 2020
|
||||
## 1.8.1 Mar 22, 2020
|
||||
|
||||
- **Breaking change** The format for any custom RPCs have been changed (alongside API-internal changes) to allow for better RPC management. If you are currently using custom RPCs (or planning to do so), look at the [updated documentation](https://polkadot.js.org/api/start/rpc.custom.html)
|
||||
- **Breaking change** Alongside API RPC changes, the `@polkadot/jsonrpc` package has been removed. Since it was never documented and only used internally, this should not have adverse impacts. All RPC definitions itself has now been moved to the relevant modules inside `@polkadot/types/interfaces`
|
||||
@@ -72,7 +236,7 @@
|
||||
- Adjusted referendum derives to cater for bot new/old democracy. Derived `referendumInfo` now includes `status` field, not `info`
|
||||
- Add `initWasm` flag to API options. When set to `false` does not init the WASM portion (leaving it to the user elsewhere)
|
||||
|
||||
# 1.7.1 Mar 17, 2020
|
||||
## 1.7.1 Mar 17, 2020
|
||||
|
||||
- **Important** Current versions of Polkadot/Substrate have dropped support for linked maps on storage entries. If you are using these queries to retrieve all entries, for instance `staking.{nominators,validators}()` and using an upgraded chain, you need to swap to retrieving entries via `.entries()` or `.keys()` for the keys.
|
||||
- Pull in support and types for latest Polkadot/Substrate
|
||||
@@ -82,11 +246,11 @@
|
||||
- Expanded `derive.staking.*` derives, including addition of `derive.staking.own*`
|
||||
- Re-add fixed (with tests) checks for query args, previously disabled in 1.6.2
|
||||
|
||||
# 1.6.2 Mar 12, 2020
|
||||
## 1.6.2 Mar 12, 2020
|
||||
|
||||
- Revert checks for query args, not working on `.at()` queries (proper fix in next version)
|
||||
|
||||
# 1.6.1 Mar 12, 2020
|
||||
## 1.6.1 Mar 12, 2020
|
||||
|
||||
- **Breaking change** `api.rpc.state.queryStorage(...)` now fully decodes the `Vec<StorageChangeSet>` and returns a decoded `[Hash, Codec[]][]` when using this RPC.
|
||||
- `StorageKey` now has an `.args` property, decoded from meta where `twox64_concat` or `blake128_concat` are used on maps
|
||||
@@ -100,7 +264,7 @@
|
||||
- Add runtime validation for map arguments to `api.query.*`
|
||||
- TypeScript interfaces for linked maps now correctly generates as `[Type, Linkage<Next>]`
|
||||
|
||||
# 1.5.1 Mar 06, 2020
|
||||
## 1.5.1 Mar 06, 2020
|
||||
|
||||
- **Important** Substrate master has updated staking, on older chains supply `StakingLedger: 'StakingLedgerTo223'`
|
||||
- **Important** Substrate master has updated collective, on older chains supply `Votes: 'VotesTo230'`
|
||||
@@ -120,11 +284,11 @@
|
||||
- Add additional derives to `api.derive.staking` to handle lazy-payout retrievals
|
||||
- Update `@polkadot/{util, util-crypto, keyring}` to 1.6.1 & `@polkadot/wasm` to 1.2.1
|
||||
|
||||
# 1.4.2 Feb 27, 2020
|
||||
## 1.4.2 Feb 27, 2020
|
||||
|
||||
- Fix `api.tx(<extrinsic>): Submittable` decoration (non-working in 1.4.1, now with proper test)
|
||||
|
||||
# 1.4.1 Feb 26, 2020
|
||||
## 1.4.1 Feb 26, 2020
|
||||
|
||||
- **Breaking change** (TypeScript only) The `*.d.ts` files now contain TypeScript 3.8 features (specifically `#private`), which is not usable in TS versions < 3.8
|
||||
- **Breaking change** - `api.derive.staking.*` has updated result types and detects support for lazy payouts queries
|
||||
@@ -150,7 +314,7 @@
|
||||
- Cleanup augmentation and generation scripts for type definitions, aligning with api augmentation
|
||||
- Bump to `@polkadot/{util, util-crypto, keyring}` 2.5.1
|
||||
|
||||
# 1.3.1 Feb 18, 2020
|
||||
## 1.3.1 Feb 18, 2020
|
||||
|
||||
- Add `@types/bn.js` as a normal dependency, exposed in `*.d.ts` (Thanks to https://github.com/monitz87)
|
||||
- Type generation scripts (including `polkadot-types-from-{chain,defs}`) has been moved to the `@polkadot/typegen` package
|
||||
@@ -158,7 +322,7 @@
|
||||
- Expose chain properties on registry (and use for API type formatting)
|
||||
- Add `toHuman(isExtended?: boolean)` to all codec types, formatting into a human-readable structure
|
||||
|
||||
# 1.2.1 Feb 16, 2020
|
||||
## 1.2.1 Feb 16, 2020
|
||||
|
||||
- **Important** Update RPC status codes (latest Substrate 2), with the `isInBlock` (`isFinalized` now indicates finality)
|
||||
- Storage `.entries(arg?: any)` now has the correct argument type for DoubleMap (Thanks to https://github.com/monitz87)
|
||||
@@ -176,7 +340,7 @@
|
||||
- Cleanup `codec/Date` tests to make it run properly on all timezones
|
||||
- Add explicit dependencies to all packages and move TypeScript `@types/*` to dev deps
|
||||
|
||||
# 1.1.1 Feb 06, 2020
|
||||
## 1.1.1 Feb 06, 2020
|
||||
|
||||
- **Important** Chains without `balances.account` or `system.account` should supply `"BalanceLock": "BalanceLockTo212"` to their types to use the previous-generation `BalanceLock` (when querying locks)
|
||||
- Add support for `balances.account` in all applicable derives (incl. `vesting` module)
|
||||
@@ -190,7 +354,7 @@
|
||||
- Adjust balances fees derivation with optional transfer and creation fees (removed in Substrate)
|
||||
- Adjust enum `.toJSON()` to return type name as specified
|
||||
|
||||
# 1.0.1 Jan 30, 2020
|
||||
## 1.0.1 Jan 30, 2020
|
||||
|
||||
- **Breaking change** Drop support for Substrate v1 chain in all derives
|
||||
- Return unsub functions from provider .on emitters (Thanks to https://github.com/jak-pan)
|
||||
@@ -209,7 +373,7 @@
|
||||
- Remove support for un-deployed metadata
|
||||
- Remove old known types for Substrate V1
|
||||
|
||||
# 0.100.1 Jan 13, 2020
|
||||
## 0.100.1 Jan 13, 2020
|
||||
|
||||
- **Important** This will the the last API version with Substrate 1.x support. Although you will still be able to use subsequent versions with older chains, dependent libraries such as sr25519 may not be compatible.
|
||||
- Add support for the Substrate identity module
|
||||
@@ -220,7 +384,7 @@
|
||||
- Add support for latest Polkadot/Substrate types
|
||||
- Add `paymentInfo` to submittables to calculate fees
|
||||
|
||||
# 0.99.1 Dec 13, 2019
|
||||
## 0.99.1 Dec 13, 2019
|
||||
|
||||
- **Breaking change** The `Data` and `U8a` type has been renamed and just replaced with the `Raw` type
|
||||
- **Breaking change** The `api.derive.staking.info` has been split into 2 - `staking.query` for non-balance related information (more effective) and `staking.account` that enhances query for all the information previously found `.info`
|
||||
@@ -229,7 +393,7 @@
|
||||
- Add additional derives for both council & treasury
|
||||
- Alignment with latest Polkadot/Substrate master branch types
|
||||
|
||||
# 0.98.1 Dec 04, 2019
|
||||
## 0.98.1 Dec 04, 2019
|
||||
|
||||
- Make the TypeScript generation script mor re-usable (Thanks to https://github.com/xlc)
|
||||
- Add `.entries()` for all map-types, returning storage keys and values
|
||||
@@ -238,7 +402,7 @@
|
||||
- Support for new Substrate democracy with preimages in derive
|
||||
- Alignment of types with Substrate/Polkadot master branches
|
||||
|
||||
# 0.97.1 Nov 29, 2019
|
||||
## 0.97.1 Nov 29, 2019
|
||||
|
||||
- **Breaking change** Add the passing on an explicit `Registry` to all calls to `createType` as well as all codec classes. If you are upgrading form an older version, use the [migration guide](UPGRADING.md) to walk through the changes required.
|
||||
- **Breaking change** The metadata classes have been moved from `@polkadot/types` into `@polkadot/metadata`. If you explicitly create `Metadata` classes, you now would need to do so with the `import Metadata from '@polkadot/metadata';` This is a decorated class, where the previous metadata is now available on `Metadata.metadata`, alongside decorated `consts.*`', `tx.*` and `query.*`.
|
||||
@@ -250,7 +414,7 @@
|
||||
- Support for Metadata V9, which adjusts the hashing methods of storage entries
|
||||
- Support for Metadata V10 (still un-released), which includes prefixed map support
|
||||
|
||||
# 0.96.1 Nov 09, 2019
|
||||
## 0.96.1 Nov 09, 2019
|
||||
|
||||
- Updated types for latest Kusama
|
||||
- Add `filterRecords` (in addition to `findRecord`) on submittable results
|
||||
@@ -260,11 +424,11 @@
|
||||
- Update council derives for the latest Substrate master support (with constants)
|
||||
- Derive cleanups, including sharing of instances between the API and internal to derives
|
||||
|
||||
# 0.95.2 Oct 25, 2019
|
||||
## 0.95.2 Oct 25, 2019
|
||||
|
||||
- Temporary removal of `account_nextIndex` use, will be re-added in a future release
|
||||
|
||||
# 0.95.1 Oct 25, 2019
|
||||
## 0.95.1 Oct 25, 2019
|
||||
|
||||
- Support Extrinsic V4 with additional signature indicator (Latest Polkadot/Substrate/Kusama)
|
||||
- Adjust subscription update checks to avoid duplicated data updates
|
||||
@@ -274,7 +438,7 @@
|
||||
- All latest Polkadot & Substrate types (as per master branches)
|
||||
- **Breaking change** `Call.injectMethods` is moved to `Call.injectMetadata` to align with `Events` (This _should_ not be used externally, however mentioned as breaking here)
|
||||
|
||||
# 0.94.1 Oct 07, 2019
|
||||
## 0.94.1 Oct 07, 2019
|
||||
|
||||
- Add handling of `Result<Ok, Error>` definitions
|
||||
- Adjust API cloning now takes RPC filters from source into account
|
||||
@@ -286,7 +450,7 @@
|
||||
- Add documentation for custom extrinsic formats (advanced chains)
|
||||
- Update to latest substrate master metadata
|
||||
|
||||
# 0.93.1 Sep 26, 2019
|
||||
## 0.93.1 Sep 26, 2019
|
||||
|
||||
- Support for Kusama CC2
|
||||
- In extrinsic submission, use `rpc.account.nextIndex` to retrieve the nonce when available
|
||||
@@ -296,7 +460,7 @@
|
||||
- Support recursive type registration (self-referencing via `Box`) in addition to better sanitation of user-defined-types
|
||||
- Documentation and example updates (thanks mostly to contributions)
|
||||
|
||||
# 0.92.1 Sep 12, 2019
|
||||
## 0.92.1 Sep 12, 2019
|
||||
|
||||
- The API now correctly sets the ss58 prefix as retrieved from the chain properties via `ss58Format`
|
||||
- Bump to `@polkadot/util` 1.4.1, removing use of `ExtError`
|
||||
@@ -304,7 +468,7 @@
|
||||
- Support the latest Polkadot & Substrate master branches (incl. metadata updates)
|
||||
- Getting started documentation has been made available
|
||||
|
||||
# 0.91.1 Sep 09, 2019
|
||||
## 0.91.1 Sep 09, 2019
|
||||
|
||||
- This release was focussed on stability, with a number of cleanups and bug-fixes
|
||||
- Adjustments for Substrate 1.x chain detection (with auto-types) and Substrate 2.x support has been extended with all latest types
|
||||
@@ -318,7 +482,7 @@
|
||||
- **Breaking change** `SignerPayload` is renamed to `SignerPayloadJSON`
|
||||
- **Breaking change** `SignerPayloadJSON`, `SignerPayloadRawBase` and `SignerPayloadRaw` are all moved to `@polkadot/types`
|
||||
|
||||
# 0.90.1 Aug 24, 2019
|
||||
## 0.90.1 Aug 24, 2019
|
||||
|
||||
If you are upgrading form an older version, use the CHANGELOG hand-in-hand with the [migration guide](UPGRADING.md).
|
||||
|
||||
@@ -336,7 +500,7 @@ If you are upgrading form an older version, use the CHANGELOG hand-in-hand with
|
||||
- The `types/codec/createType` has been moved to `types/codec/create` with the same exports. If you explicitly imported from here (and not doing the suggested `import { createType } from '@polkadot/types`), the reference needs to be updated
|
||||
|
||||
|
||||
# 0.82.0-beta.x Jul 28, 2019
|
||||
## 0.82.0-beta.x Jul 28, 2019
|
||||
|
||||
- Support for substrate 2.x (master) has been extended,
|
||||
- Additional types have been addedd for the modules
|
||||
@@ -355,7 +519,7 @@ If you are upgrading form an older version, use the CHANGELOG hand-in-hand with
|
||||
- The `ContractsAbi` type has been moved from `@polkadot/types` to `import { Abi } from '@polkadot/api-contract`. This paves the way for an enhanced contracts interface, instead of dealing with low-level API calls.
|
||||
|
||||
|
||||
# 0.81.1 Jun 14, 2019
|
||||
## 0.81.1 Jun 14, 2019
|
||||
|
||||
- The dependency on `@polkadot/keyring` has been removed - if you relied on the API to provide this, you would now need to manually add it
|
||||
- `createType` allows for the creation of `[u8; <length>]` types (opening the door for contract support)
|
||||
@@ -375,7 +539,7 @@ If you are upgrading form an older version, use the CHANGELOG hand-in-hand with
|
||||
- Add `off` method to `Api` (Base, for both `ApiPromise` & `ApiRx`) to remove an event listener
|
||||
|
||||
|
||||
# 0.80.1 Jun 04, 2019
|
||||
## 0.80.1 Jun 04, 2019
|
||||
|
||||
- Support for mortal transactions
|
||||
- Better DoubleMap storage support
|
||||
@@ -385,7 +549,7 @@ If you are upgrading form an older version, use the CHANGELOG hand-in-hand with
|
||||
- Misc. cleanups and fixes
|
||||
|
||||
|
||||
# 0.79.1 May 22, 2019
|
||||
## 0.79.1 May 22, 2019
|
||||
|
||||
- DoubleMap query support
|
||||
- Support latest EventRecord metadata (substrate master)
|
||||
@@ -397,7 +561,7 @@ If you are upgrading form an older version, use the CHANGELOG hand-in-hand with
|
||||
- Add `toRawType` on all type classes (breakdown into primitive types)
|
||||
|
||||
|
||||
# 0.78.1 May 08, 2019
|
||||
## 0.78.1 May 08, 2019
|
||||
|
||||
- Fix linked-maps (not working since 0.77.1)
|
||||
- Convert Usize to U32 (as found in WASM environments)
|
||||
@@ -408,13 +572,13 @@ If you are upgrading form an older version, use the CHANGELOG hand-in-hand with
|
||||
- Metadata updates for substrate (WithdrawReasons, ContractInfo)
|
||||
|
||||
|
||||
# 0.77.1 Apr 25, 2019
|
||||
## 0.77.1 Apr 25, 2019
|
||||
|
||||
- Support Metadata v4, which introduces the use of a custom hasher to hash storage map keys.
|
||||
- Add TreasuryProposal (not the same as democracy, type aliased)
|
||||
|
||||
|
||||
# 0.76.1 Apr 03, 2019
|
||||
## 0.76.1 Apr 03, 2019
|
||||
|
||||
- Caching improvements (duplicate queries, no duplicate subscriptions)
|
||||
- Experimental contract API
|
||||
@@ -422,12 +586,12 @@ If you are upgrading form an older version, use the CHANGELOG hand-in-hand with
|
||||
- Update @polkadot/util-crypto with smaller footprint
|
||||
|
||||
|
||||
# 0.75.1 Mar 29, 2019
|
||||
## 0.75.1 Mar 29, 2019
|
||||
|
||||
- Start journey to 1.0
|
||||
|
||||
|
||||
# 0.53.1 Mar 29, 2019
|
||||
## 0.53.1 Mar 29, 2019
|
||||
|
||||
- Change spelling to US English as per substrate master (1.0-rc1). Breaking changes as a result:
|
||||
- For extrinsic status results, if you have checked the type returns, i.e. `result.type === 'Finalised'` now check on the status for `result.status.isFinalized` or `result.status.isBroadcast`, ... (the `type` property is now accessible only on `result.status.type`)
|
||||
@@ -438,7 +602,7 @@ If you are upgrading form an older version, use the CHANGELOG hand-in-hand with
|
||||
- All examples have been updated with sr25519 addresses (with the new checksums)
|
||||
|
||||
|
||||
# 0.52.1 Mar 28, 2019
|
||||
## 0.52.1 Mar 28, 2019
|
||||
|
||||
- Support queries to linked mapped storage (found in new staking interfaces)
|
||||
- Add `derive.staking.controllers` to retrieve all active staking controllers
|
||||
@@ -448,42 +612,42 @@ If you are upgrading form an older version, use the CHANGELOG hand-in-hand with
|
||||
- Check for single instances for api and types as they are loaded (assertSingletonPackage)
|
||||
|
||||
|
||||
# 0.51.1 Mar 25, 2019
|
||||
## 0.51.1 Mar 25, 2019
|
||||
|
||||
- Support metadata V2 as per latest substrate master
|
||||
- Update metadata with new types as per latest substrate master
|
||||
|
||||
|
||||
# 0.50.1 Mar 23, 2019
|
||||
## 0.50.1 Mar 23, 2019
|
||||
|
||||
- Latest util-crypto (usage of WASM with JS fallbacks if not available)
|
||||
- Update upstream @polkadot dependencies (for new crypto)
|
||||
|
||||
|
||||
# 0.49.1 Mar 20, 2019
|
||||
## 0.49.1 Mar 20, 2019
|
||||
|
||||
- Fix large message signing on non-known nodes (default is now hashing, there has been enough time between upgrades)
|
||||
|
||||
|
||||
# 0.48.1 Mar 18, 2019
|
||||
## 0.48.1 Mar 18, 2019
|
||||
|
||||
- Pull in new sr25519 capable keyring for dev nodes
|
||||
- When using dev mode, it assumes that the node is the latest with derived sr25519 keys
|
||||
|
||||
|
||||
# 0.47.1 Mar 14, 2019
|
||||
## 0.47.1 Mar 14, 2019
|
||||
|
||||
- Swap to publishing -beta.x on merge (non-breaking testing)
|
||||
|
||||
|
||||
# 0.46.1 Mar 01, 2019
|
||||
## 0.46.1 Mar 01, 2019
|
||||
|
||||
- Extended type registration to now handle internal types as well. Additionally the built-in Extrinsic type can now we overridden with a custom version.
|
||||
- Where `Extrinsic` and `Method` is used as types, consider importing `{ IMethod, IExtrinsic }` from `@polkadot/types/types`, especially in the cases where this is used from a `SubmittableExtrinsic`
|
||||
- The `typeRegistry` constant is now `getTypeRegistry()` as a function
|
||||
|
||||
|
||||
# 0.45.1 Feb 19, 2019
|
||||
## 0.45.1 Feb 19, 2019
|
||||
|
||||
- Storage with option values now correctly return `Option<Type>` and is indicated as such in the documentation
|
||||
|
||||
@@ -500,7 +664,7 @@ console.log('llo', llo.unwrapOr('not set') /* Option<BlockNumber> */)
|
||||
```
|
||||
|
||||
|
||||
# 0.44.1 Feb 19, 2019
|
||||
## 0.44.1 Feb 19, 2019
|
||||
|
||||
- Split primitives and types into separate folders. This should not affect external use since the exports remain the same, however does have an impact where classes are referenced directly. e.g.
|
||||
|
||||
@@ -518,45 +682,45 @@ import { Method, Signature } from '@polkadot/types';
|
||||
```
|
||||
|
||||
|
||||
# 0.43.1 Feb 14, 2019
|
||||
## 0.43.1 Feb 14, 2019
|
||||
|
||||
- Introduces support for the new keyring with sr25519 support in addition to ed25519. While this does not change the exposed API, it is considered breaking since @polkadot/keyring has interface changes. (Unless needed, don't rush the upgrade)
|
||||
|
||||
|
||||
# 0.42.1 Jan 31, 2019
|
||||
## 0.42.1 Jan 31, 2019
|
||||
|
||||
- Support for substrate hash signing with implVersion >= 18
|
||||
- Changed signatures for Extrinsic signing, this should not have (much) of an impact since it is generally not used directly. SubmittableExtrinsic (as exposed by the API), supports the old-style use.
|
||||
|
||||
|
||||
# 0.41.1 Jan 26, 2019
|
||||
## 0.41.1 Jan 26, 2019
|
||||
|
||||
- Support the V1 metadata specification from Substrate in addition to the currently testnet active V0 version
|
||||
|
||||
|
||||
# 0.40.1 Jan 16, 2019
|
||||
## 0.40.1 Jan 16, 2019
|
||||
|
||||
- The API interfaces now require a WS-compatible provider, e.g. subscription support is a must. Previously the HTTPProvider could be use (although it was very limited in the interactions).
|
||||
|
||||
|
||||
# 0.39.1 Jan 11, 2019
|
||||
## 0.39.1 Jan 11, 2019
|
||||
|
||||
- The Promise API now returns a `Promise<UnsubFunction>` instead of `UnsubFunction` when making subscriptions.
|
||||
|
||||
|
||||
# 0.38.1 Jan 08, 2019
|
||||
## 0.38.1 Jan 08, 2019
|
||||
|
||||
Substrate has been updated with a breaking new transaction format where the Index/Nonce is now encoded as a Compact. This change is being rolled out to both Alexander (Polkadot testnet) as well as Charred Cherry (Substrate testnet) - transactions between old and new are not compatible.
|
||||
|
||||
|
||||
# 0.37.1 Jan 04, 2019
|
||||
## 0.37.1 Jan 04, 2019
|
||||
|
||||
api-observable has been removed. This was only used in /apps and inconsistent with the api/rx and api/promise APIs. Future work will include derives like was included in api-observable into the base.
|
||||
|
||||
Tuples now return single types when only one type is available, i.e. `(AccountId)` would now resolve as `AccountId`. The extra type wrapper adds no benefit to users here.
|
||||
|
||||
|
||||
# 0.36.1 Jan 03, 2019
|
||||
## 0.36.1 Jan 03, 2019
|
||||
|
||||
Api Promise has been updated in the way we deal with subscriptions. Previously a subscription returned `Promise<number>` where the caller was to keep track of the id and use it in subsequent unsubscribes. Now any subscriptions return an unsubscribe/destroy function `(): void`, that is use for removing the subscriptions, e.g.
|
||||
|
||||
@@ -567,51 +731,51 @@ unsubscribe(); // here we destroy the subscription
|
||||
```
|
||||
|
||||
|
||||
# 0.35.1 Dec 20, 2018
|
||||
## 0.35.1 Dec 20, 2018
|
||||
|
||||
Swapped to new metadata structures from Substrate. If the API is not working with your node, update Substrate to latest master branch. (Or 0.9.1 for Charred Cherry). Dropped support for old metadata as found as far back as BBQ Birch.
|
||||
|
||||
|
||||
# 0.34.1 Dec 18, 2018
|
||||
## 0.34.1 Dec 18, 2018
|
||||
|
||||
Changed the send signature (for future expansion of eg. events) to return `result: { status: ExtrinsicStatus }` instead of `status: ExtrinsicStatus`. For most cases where only status `type` checks are used, i.e. `status.type === 'Finalised'` this should not be a breaking change. Deep inspection of the status object however will need to adapt.
|
||||
|
||||
# 0.33.1 Dec 06, 2018
|
||||
## 0.33.1 Dec 06, 2018
|
||||
|
||||
# 0.32.1 Nov 21, 2018
|
||||
## 0.32.1 Nov 21, 2018
|
||||
|
||||
# 0.31.1 Oct 10, 2018
|
||||
## 0.31.1 Oct 10, 2018
|
||||
|
||||
# 0.30.1 Sep 27, 2018
|
||||
## 0.30.1 Sep 27, 2018
|
||||
|
||||
# 0.29.1 Sep 14, 2018
|
||||
## 0.29.1 Sep 14, 2018
|
||||
|
||||
# 0.28.1 Aug 11, 2018
|
||||
## 0.28.1 Aug 11, 2018
|
||||
|
||||
# 0.15.1 Aug 07, 2018
|
||||
## 0.15.1 Aug 07, 2018
|
||||
|
||||
# 0.14.1 Jun 23, 2018
|
||||
## 0.14.1 Jun 23, 2018
|
||||
|
||||
# 0.13.1 May 29, 2018
|
||||
## 0.13.1 May 29, 2018
|
||||
|
||||
# 0.12.1 May 18, 2018
|
||||
## 0.12.1 May 18, 2018
|
||||
|
||||
# 0.11.1 May 16, 2018
|
||||
## 0.11.1 May 16, 2018
|
||||
|
||||
# 0.10.1 May 07, 2018
|
||||
## 0.10.1 May 07, 2018
|
||||
|
||||
# 0.9.1 Apr 24, 2018
|
||||
## 0.9.1 Apr 24, 2018
|
||||
|
||||
# 0.8.1 Mar 15, 2018
|
||||
## 0.8.1 Mar 15, 2018
|
||||
|
||||
# 0.7.1 Jan 25, 2018
|
||||
## 0.7.1 Jan 25, 2018
|
||||
|
||||
# 0.6.1 Dec 03, 2017
|
||||
## 0.6.1 Dec 03, 2017
|
||||
|
||||
# 0.5.1 Nov 28, 2017
|
||||
## 0.5.1 Nov 28, 2017
|
||||
|
||||
# 0.4.1 Nov 19, 2017
|
||||
## 0.4.1 Nov 19, 2017
|
||||
|
||||
# 0.3.1 Nov 19, 2017
|
||||
## 0.3.1 Nov 19, 2017
|
||||
|
||||
# 0.2.1 Nov 18, 2017
|
||||
## 0.2.1 Nov 18, 2017
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
|
||||
# @polkadot/api
|
||||
|
||||
This library provides a clean wrapper around all the methods exposed by a Polkadot/Subtrate network client and defines all the types exposed by a node. For complete documentation around the classes, interfaces and their use, visit the [documentation portal](https://polkadot.js.org/api/).
|
||||
This library provides a clean wrapper around all the methods exposed by a Polkadot/Substrate network client and defines all the types exposed by a node. For complete documentation around the classes, interfaces and their use, visit the [documentation portal](https://polkadot.js.org/api/).
|
||||
|
||||
If you are an existing user, please be sure to track the [CHANGELOG](CHANGELOG.md) and [UPGRADING](UPGRADING.md) guides when changing versions.
|
||||
|
||||
|
||||
@@ -20,7 +20,8 @@ module.exports = {
|
||||
},
|
||||
{ text: 'GitHub', link: 'https://github.com/polkadot-js/api' }
|
||||
],
|
||||
search: false,
|
||||
search: true,
|
||||
searchMaxSuggestions: 10,
|
||||
sidebar: [
|
||||
{
|
||||
title: 'Getting started',
|
||||
@@ -97,5 +98,10 @@ module.exports = {
|
||||
['/types/', '@polkadot/types'],
|
||||
'/CONTRIBUTING.md'
|
||||
]
|
||||
}
|
||||
},
|
||||
plugins: [
|
||||
['@vuepress/search', {
|
||||
searchMaxSuggestions: 10
|
||||
}]
|
||||
]
|
||||
};
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
$accentColor = #fd8824
|
||||
$textColor = #2c3e50
|
||||
$borderColor = #eaecef
|
||||
$codeBgColor = #282c34
|
||||
$arrowBgColor = #ccc
|
||||
|
||||
.home .hero .description,
|
||||
.home .feature h2,
|
||||
|
||||
@@ -25,7 +25,7 @@ signedBlock.block.extrinsics.forEach((ex, index) => {
|
||||
|
||||
## How do I extract the block author?
|
||||
|
||||
Th block author is encoded inside the consensus logs for the block. To extract, you need to decode the log (which the API does do) and then map the index of the validator to the list of session validators. This extraction is however available on the api derive for new head subscriptions, which returns an extended header with the author populated (assuming that the digest logs are known).
|
||||
The block author is encoded inside the consensus logs for the block. To extract, you need to decode the log (which the API does do) and then map the index of the validator to the list of session validators. This extraction is however available on the api derive for new head subscriptions, which returns an extended header with the author populated (assuming that the digest logs are known).
|
||||
|
||||
```js
|
||||
// subscribe to all new headers (with extended info)
|
||||
|
||||
+3
-3
@@ -97,12 +97,12 @@ api.tx.utility
|
||||
|
||||
## How do I take the pending tx pool into account in my nonce?
|
||||
|
||||
The `system.account` query will always contain the current state, i.e. it will reflect the nonce for the last known block. As such when sending multiple transactions in quick succession (see batching above), there may be transactions in the pool that has the same nonce that `signAndSend` would apply - this call doesn't do any magic, it simply reads the state for the nonce. Since we can specify options to the `signandSend` operation, we can override the nonce, either by manually incrementing it o querying it via `nextNonce`.
|
||||
The `system.account` query will always contain the current state, i.e. it will reflect the nonce for the last known block. As such when sending multiple transactions in quick succession (see batching above), there may be transactions in the pool that has the same nonce that `signAndSend` would apply - this call doesn't do any magic, it simply reads the state for the nonce. Since we can specify options to the `signAndSend` operation, we can override the nonce, either by manually incrementing it or querying it via `rpc.system.accountNextIndex`.
|
||||
|
||||
```js
|
||||
for (let i = 0; i < 10; i++) {
|
||||
// retrieve the nextNonce, taking txs in the pool into account
|
||||
const nonce = await api.rpc.account.nextNonce(sender);
|
||||
// retrieve sender's next index/nonce, taking txs in the pool into account
|
||||
const nonce = await api.rpc.system.accountNextIndex(sender);
|
||||
|
||||
// send, just retrieving the hash, not waiting on status
|
||||
const txhash = await api.tx.balances
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
/* eslint-disable header/header */
|
||||
/* eslint-disable @typescript-eslint/require-await */
|
||||
/* eslint-disable @typescript-eslint/unbound-method */
|
||||
/* eslint-disable @typescript-eslint/no-floating-promises */
|
||||
|
||||
// Import the API
|
||||
const { ApiPromise } = require('@polkadot/api');
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
/* eslint-disable header/header */
|
||||
/* eslint-disable @typescript-eslint/require-await */
|
||||
/* eslint-disable @typescript-eslint/unbound-method */
|
||||
/* eslint-disable @typescript-eslint/no-floating-promises */
|
||||
|
||||
// Import the API
|
||||
const { ApiPromise } = require('@polkadot/api');
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
/* eslint-disable header/header */
|
||||
/* eslint-disable @typescript-eslint/require-await */
|
||||
/* eslint-disable @typescript-eslint/unbound-method */
|
||||
/* eslint-disable @typescript-eslint/no-floating-promises */
|
||||
|
||||
// Import the API
|
||||
const { ApiPromise } = require('@polkadot/api');
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
/* eslint-disable header/header */
|
||||
/* eslint-disable @typescript-eslint/require-await */
|
||||
/* eslint-disable @typescript-eslint/no-var-requires */
|
||||
/* eslint-disable @typescript-eslint/no-floating-promises */
|
||||
|
||||
// Import the API & Provider and some utility functions
|
||||
const { ApiPromise } = require('@polkadot/api');
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
/* eslint-disable header/header */
|
||||
/* eslint-disable @typescript-eslint/require-await */
|
||||
/* eslint-disable @typescript-eslint/unbound-method */
|
||||
/* eslint-disable @typescript-eslint/no-floating-promises */
|
||||
|
||||
// Import the API & Provider and some utility functions
|
||||
const { ApiPromise, WsProvider } = require('@polkadot/api');
|
||||
|
||||
@@ -20,6 +20,9 @@ All data transferred between the API and the Node is in a SCALE-encoded binary f
|
||||
|
||||
To fix this, you should look at the specific `api.tx.*` params and adjust the type definitions for those param types to match what is found on the node side. In some rare cases the cause could be extrinsic formatting related, to track these make an `api.tx.system.remark(data: Bytes)` call, if it fails, the API and node cannot agree on [an extrinsic format and adjustments are required](types.extend.md#impact-on-extrinsics).
|
||||
|
||||
If you are using a node-template based version of substrate and you changed the specName you need to add these typings(In addition to other custom types) `{"Address": "AccountId","LookupSource": "AccountId"}`. This is also the case when you use [polkadot-js/apps](https://github.com/polkadot-js/apps) to connect to your node. When the specName stays node-template the API is smart enough to add the custom typings.
|
||||
|
||||
|
||||
## I would like to sign transactions offline
|
||||
|
||||
The API itself is independent on where the signature comes from and how it is injected. Additionally it implements a signer interface, that can be used for external signing - an example of this is the [polkadot-js/apps](https://github.com/polkadot-js/apps) support for signing via extensions and even the [polkadot-js/extension](https://github.com/polkadot-js/extension) support for tools such as the [Parity Signer](https://github.com/paritytech/parity-signer).
|
||||
@@ -63,3 +66,16 @@ Due to these customizations and differences that bleed through to the transactio
|
||||
Recently Substrate master updated the `Weight` type from `u32` -> `u64`. This type is used in the `DispatchInfo` struct in the `system.ExtrinsicSuccess` events, to return the applied call weights as well as the resulting fees. Since the API master branch tracks Substrate master, this means the change has been applied by default, with the default set to `u64`.
|
||||
|
||||
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
|
||||
|
||||
@@ -26,7 +26,7 @@ If we had a query with parameters, i.e. where we wish to perform a query for a s
|
||||
|
||||
// Subscribe to balance changes for our account
|
||||
const unsub = await api.query.system.account(ADDR, ({ nonce, data: balance }) => {
|
||||
console.log(`free balance is ${balance.freee} with ${balance.reserved} reserved and a nonce of ${nonce}`);
|
||||
console.log(`free balance is ${balance.free} with ${balance.reserved} reserved and a nonce of ${nonce}`);
|
||||
});
|
||||
```
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# Custom RPC
|
||||
|
||||
In previous sections we looked at the injection of types, as in use and defined in modules from the node. Another area that can be customized is RC definitions, and like with the types, the API provides the capability to add user-defined RPCs (in addition to the Polkadot/Substrate base) to allow use of these RPCs via the API.
|
||||
In previous sections we looked at the injection of types, as in use and defined in modules from the node. Another area that can be customized is RPC definitions, and like with the types, the API provides the capability to add user-defined RPCs (in addition to the Polkadot/Substrate base) to allow use of these RPCs via the API.
|
||||
|
||||
## Custom definitions
|
||||
|
||||
@@ -25,9 +25,14 @@ const api = await ApiPromise.create({
|
||||
}
|
||||
],
|
||||
type: 'Balance'
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
anotherMethod: { ... },
|
||||
...
|
||||
},
|
||||
anotherModule: { ... },
|
||||
...
|
||||
},
|
||||
...
|
||||
});
|
||||
```
|
||||
|
||||
|
||||
+1
-1
@@ -9,5 +9,5 @@
|
||||
"packages": [
|
||||
"packages/*"
|
||||
],
|
||||
"version": "1.12.1"
|
||||
"version": "1.27.1"
|
||||
}
|
||||
|
||||
+11
-9
@@ -7,7 +7,7 @@
|
||||
"packages/*"
|
||||
],
|
||||
"resolutions": {
|
||||
"typescript": "^3.8.3"
|
||||
"babel-core": "^7.0.0-bridge.0"
|
||||
},
|
||||
"scripts": {
|
||||
"build": "yarn build:interfaces && polkadot-dev-build-ts && (cd packages/typegen && copyfiles scripts/* build)",
|
||||
@@ -24,13 +24,15 @@
|
||||
"test:watch": "polkadot-dev-run-test --watch"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@babel/core": "^7.9.0",
|
||||
"@babel/register": "^7.9.0",
|
||||
"@babel/runtime": "^7.9.2",
|
||||
"@polkadot/dev": "^0.52.11",
|
||||
"@polkadot/ts": "^0.3.18",
|
||||
"@babel/core": "^7.11.0",
|
||||
"@babel/register": "^7.10.5",
|
||||
"@babel/runtime": "^7.11.0",
|
||||
"@polkadot/dev": "^0.55.30",
|
||||
"@polkadot/ts": "^0.3.31",
|
||||
"@polkadot/typegen": "workspace:packages/typegen",
|
||||
"@types/jest": "^25.2.1",
|
||||
"copyfiles": "^2.2.0"
|
||||
}
|
||||
"@types/jest": "^26.0.8",
|
||||
"@vuepress/plugin-search": "^1.5.2",
|
||||
"copyfiles": "^2.3.0"
|
||||
},
|
||||
"version": "1.27.1"
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@polkadot/api-contract",
|
||||
"version": "1.12.1",
|
||||
"version": "1.27.1",
|
||||
"description": "Interfaces for interacting with contracts and contract ABIs",
|
||||
"main": "index.js",
|
||||
"keywords": [
|
||||
@@ -26,12 +26,12 @@
|
||||
},
|
||||
"homepage": "https://github.com/polkadot-js/api/tree/master/packages/api-contract#readme",
|
||||
"dependencies": {
|
||||
"@babel/runtime": "^7.9.2",
|
||||
"@polkadot/api": "1.12.1",
|
||||
"@polkadot/rpc-core": "1.12.1",
|
||||
"@polkadot/types": "1.12.1",
|
||||
"@polkadot/util": "^2.9.0-beta.3",
|
||||
"bn.js": "^5.1.1",
|
||||
"rxjs": "^6.5.5"
|
||||
"@babel/runtime": "^7.11.0",
|
||||
"@polkadot/api": "1.27.1",
|
||||
"@polkadot/rpc-core": "1.27.1",
|
||||
"@polkadot/types": "1.27.1",
|
||||
"@polkadot/util": "^3.0.1",
|
||||
"bn.js": "^5.1.2",
|
||||
"rxjs": "^6.6.2"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -19,7 +19,7 @@ function parseSelector (registry: Registry, fnname: string, input: ContractABIMe
|
||||
return registry.createType('u32', hexToU8a(input));
|
||||
} else if (typeof input === 'string') {
|
||||
try {
|
||||
const array = JSON.parse(input);
|
||||
const array = JSON.parse(input) as unknown[];
|
||||
|
||||
assert(array.length === 4, `${fnname}: Invalid selector length`);
|
||||
|
||||
@@ -108,7 +108,7 @@ export default class ContractRegistry extends MetaRegistry {
|
||||
|
||||
public createMessage (name: string, message: Partial<ContractABIMessage> & ContractABIMessageBase): ContractABIFn {
|
||||
const args = message.args.map(({ name, type }): ContractABIFnArg => {
|
||||
assert(isObject(type), `Invalid type at index ${type}`);
|
||||
assert(isObject(type), `Invalid type at index ${type.toString()}`);
|
||||
|
||||
return {
|
||||
name: stringCamelCase(name),
|
||||
@@ -183,6 +183,7 @@ export default class ContractRegistry extends MetaRegistry {
|
||||
public convertMessage ({ args, name, return_type: returnType, ...message }: ContractABIMessagePre): ContractABIMessage {
|
||||
return {
|
||||
...message,
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
|
||||
args: this.convertArgs(args),
|
||||
name: this._stringAt(name),
|
||||
returnType: returnType ? this.convertType(returnType) : null
|
||||
@@ -191,6 +192,7 @@ export default class ContractRegistry extends MetaRegistry {
|
||||
|
||||
public convertEvent ({ args }: ContractABIEventPre): ContractABIEvent {
|
||||
return {
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
|
||||
args: this.convertArgs(args)
|
||||
};
|
||||
}
|
||||
|
||||
@@ -7,11 +7,11 @@ import { MetaRegistryItem, MetaRegistryJson, MetaTypeDefClikeEnum, MetaType, Met
|
||||
import { assert } from '@polkadot/util';
|
||||
import { displayType, withTypeString } from '@polkadot/types';
|
||||
|
||||
const builtinMap: [(id: any) => boolean, MetaTypeInfo][] = [
|
||||
[(id: any): boolean => typeof id === 'string', MetaTypeInfo.BuiltinPlain],
|
||||
[(id: any): boolean => Array.isArray(id), MetaTypeInfo.BuiltinTuple],
|
||||
[(id: any): boolean => !!(id['array.type']), MetaTypeInfo.BuiltinVecFixed],
|
||||
[(id: any): boolean => !!(id['slice.type']), MetaTypeInfo.BuiltinVec]
|
||||
const builtinMap: [(id: unknown | unknown[] | { 'array.type': unknown } | { 'slice.type': unknown }) => boolean, MetaTypeInfo][] = [
|
||||
[(id: any) => typeof id === 'string', MetaTypeInfo.BuiltinPlain],
|
||||
[(id: any) => Array.isArray(id), MetaTypeInfo.BuiltinTuple],
|
||||
[(id: any) => !!((id as { 'array.type': unknown })['array.type']), MetaTypeInfo.BuiltinVecFixed],
|
||||
[(id: any) => !!((id as { 'slice.type': unknown })['slice.type']), MetaTypeInfo.BuiltinVec]
|
||||
];
|
||||
|
||||
const typeMap: [string, MetaTypeInfo][] = [
|
||||
@@ -25,8 +25,8 @@ function detectedType ({ def, id }: MetaType): MetaTypeInfo {
|
||||
assert(!(def as MetaTypeDefUnion)['union.fields'], 'Invalid union type definition found');
|
||||
|
||||
const lookup = def === 'builtin'
|
||||
? builtinMap.find(([test]): boolean => test(id))
|
||||
: typeMap.find(([test]): boolean => !!(def as any)[test]);
|
||||
? builtinMap.find(([test]) => test(id))
|
||||
: typeMap.find(([test]) => !!(def as unknown as Record<string, unknown>)[test]);
|
||||
|
||||
return lookup
|
||||
? lookup[1]
|
||||
@@ -59,7 +59,7 @@ class MetadataRegistryLookup {
|
||||
}
|
||||
}
|
||||
|
||||
protected _itemAt (index: number, variant: MetaRegistryItem): any {
|
||||
protected _itemAt (index: number, variant: MetaRegistryItem): string | MetaType | TypeDef {
|
||||
assert(this._hasItemAt(index, variant), `MetaRegistry: Invalid ${variant} index ${index} found in metadata`);
|
||||
|
||||
switch (variant) {
|
||||
@@ -72,24 +72,24 @@ class MetadataRegistryLookup {
|
||||
}
|
||||
}
|
||||
|
||||
protected _itemsAt (indices: number[], variant: MetaRegistryItem): any[] {
|
||||
return indices.map((index: number): string => this._itemAt(index, variant));
|
||||
protected _itemsAt (indices: number[], variant: MetaRegistryItem): (string | MetaType | TypeDef)[] {
|
||||
return indices.map((index: number) => this._itemAt(index, variant));
|
||||
}
|
||||
|
||||
protected _stringAt (index: StringIndex): string {
|
||||
return this._itemAt(index, MetaRegistryItem.String);
|
||||
return this._itemAt(index, MetaRegistryItem.String) as string;
|
||||
}
|
||||
|
||||
public stringsAt (indices: StringIndex[]): string[] {
|
||||
return this._itemsAt(indices, MetaRegistryItem.String);
|
||||
return this._itemsAt(indices, MetaRegistryItem.String) as string[];
|
||||
}
|
||||
|
||||
public typeAt (index: TypeIndex): MetaType {
|
||||
return this._itemAt(index, MetaRegistryItem.Type);
|
||||
return this._itemAt(index, MetaRegistryItem.Type) as MetaType;
|
||||
}
|
||||
|
||||
public typesAt (indices: TypeIndex[]): MetaType[] {
|
||||
return this._itemsAt(indices, MetaRegistryItem.Type);
|
||||
return this._itemsAt(indices, MetaRegistryItem.Type) as MetaType[];
|
||||
}
|
||||
|
||||
public hasTypeDefAt (index: TypeIndex): boolean {
|
||||
@@ -98,7 +98,7 @@ class MetadataRegistryLookup {
|
||||
|
||||
public typeDefAt (index: TypeIndex, extra: Pick<TypeDef, never> = {}): TypeDef {
|
||||
return {
|
||||
...this._itemAt(index, MetaRegistryItem.TypeDef),
|
||||
...this._itemAt(index, MetaRegistryItem.TypeDef) as TypeDef,
|
||||
...extra
|
||||
};
|
||||
}
|
||||
@@ -136,7 +136,7 @@ export default class MetaRegistry extends MetadataRegistryLookup {
|
||||
};
|
||||
}
|
||||
|
||||
private _typeDefDefFields (metaType: MetaType, typeIndex?: TypeIndex): Pick<TypeDef, never> {
|
||||
private _typeDefDefFields (metaType: MetaType, typeIndex: TypeIndex = -1): Pick<TypeDef, never> {
|
||||
let typeDef;
|
||||
|
||||
switch (detectedType(metaType)) {
|
||||
@@ -234,7 +234,7 @@ export default class MetaRegistry extends MetadataRegistryLookup {
|
||||
};
|
||||
}
|
||||
|
||||
private _typeDefForBuiltinVec (id: MetaTypeIdVec, typeIndex?: TypeIndex): Pick<TypeDef, never> {
|
||||
private _typeDefForBuiltinVec (id: MetaTypeIdVec, typeIndex: TypeIndex = -1): Pick<TypeDef, never> {
|
||||
const { 'slice.type': vecTypeIndex } = id;
|
||||
|
||||
assert(!typeIndex || vecTypeIndex !== typeIndex, `MetaRegistry: self-referencing registry type at index ${typeIndex}`);
|
||||
@@ -250,7 +250,7 @@ export default class MetaRegistry extends MetadataRegistryLookup {
|
||||
};
|
||||
}
|
||||
|
||||
private _typeDefForBuiltinVecFixed (id: MetaTypeIdVecFixed, typeIndex?: TypeIndex): Pick<TypeDef, never> {
|
||||
private _typeDefForBuiltinVecFixed (id: MetaTypeIdVecFixed, typeIndex: TypeIndex = -1): Pick<TypeDef, never> {
|
||||
const { 'array.len': vecLength, 'array.type': vecTypeIndex } = id;
|
||||
|
||||
assert(!vecLength || vecLength <= 256, 'MetaRegistry: Only support for [Type; <length>], where length <= 256');
|
||||
@@ -301,7 +301,7 @@ export default class MetaRegistry extends MetadataRegistryLookup {
|
||||
};
|
||||
}
|
||||
|
||||
public typeDefForOption (id: MetaTypeIdCustom, typeIndex?: TypeIndex): Pick<TypeDef, any> {
|
||||
public typeDefForOption (id: MetaTypeIdCustom, typeIndex: TypeIndex = -1): Pick<TypeDef, any> {
|
||||
assert(id['custom.params'] && id['custom.params'][0], `Invalid Option type defined at index ${typeIndex}`);
|
||||
|
||||
return {
|
||||
@@ -310,7 +310,7 @@ export default class MetaRegistry extends MetadataRegistryLookup {
|
||||
};
|
||||
}
|
||||
|
||||
public typeDefForResult (id: MetaTypeIdCustom, typeIndex?: TypeIndex): Pick<TypeDef, any> {
|
||||
public typeDefForResult (id: MetaTypeIdCustom, typeIndex: TypeIndex = -1): Pick<TypeDef, any> {
|
||||
assert(id['custom.params'] && id['custom.params'][0] && id['custom.params'][1], `Invalid Result type defined at index ${typeIndex}`);
|
||||
|
||||
return {
|
||||
|
||||
@@ -47,6 +47,7 @@ export default class Blueprint<ApiType extends ApiTypes> extends BaseWithTx<ApiT
|
||||
assert(!!this.abi.constructors[constructorIndex], `Specified constructor index ${constructorIndex} does not exist`);
|
||||
|
||||
return {
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
|
||||
signAndSend: this.decorateMethod(
|
||||
(account: IKeyringPair | string | AccountId | Address): BlueprintCreateResultSubscription<ApiType> => {
|
||||
return this._apiContracts
|
||||
|
||||
@@ -19,7 +19,6 @@ import { BaseWithTx } from './util';
|
||||
|
||||
type CodePutCodeResultSubscription<ApiType extends ApiTypes> = Observable<CodePutCodeResult<ApiType>>;
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/interface-name-prefix
|
||||
export interface CodePutCode<ApiType extends ApiTypes> {
|
||||
signAndSend (account: IKeyringPair | string | AccountId | Address): CodePutCodeResultSubscription<ApiType>;
|
||||
}
|
||||
@@ -46,6 +45,7 @@ export default class Code<ApiType extends ApiTypes> extends BaseWithTx<ApiType>
|
||||
|
||||
public createBlueprint = (maxGas: number | BN): CodePutCode<ApiType> => {
|
||||
return {
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
|
||||
signAndSend: this.decorateMethod(
|
||||
(account: IKeyringPair | string | AccountId | Address): CodePutCodeResultSubscription<ApiType> =>
|
||||
this._apiContracts
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
|
||||
import { ApiTypes, DecorateMethod, ObsInnerType } from '@polkadot/api/types';
|
||||
import { AccountId, Address, ContractExecResult } from '@polkadot/types/interfaces';
|
||||
import { Codec, IKeyringPair } from '@polkadot/types/types';
|
||||
import { Codec, CodecArg, IKeyringPair } from '@polkadot/types/types';
|
||||
import { ApiObject, ContractABIMessage, ContractABIPre, ContractCallOutcome } from '../types';
|
||||
|
||||
import BN from 'bn.js';
|
||||
@@ -21,7 +21,6 @@ type ContractCallResultSubscription<ApiType extends ApiTypes, CallType extends C
|
||||
? Observable<ContractCallResult<CallType>>
|
||||
: Promise<ObsInnerType<ContractCallResult<CallType>>>;
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/interface-name-prefix
|
||||
export interface ContractCall<ApiType extends ApiTypes, CallType extends ContractCallTypes> {
|
||||
send (account: IKeyringPair | string | AccountId | Address): ContractCallResultSubscription<ApiType, CallType>;
|
||||
}
|
||||
@@ -39,12 +38,13 @@ export default class Contract<ApiType extends ApiTypes> extends BaseWithTxAndRpc
|
||||
this.address = this.registry.createType('Address', address);
|
||||
}
|
||||
|
||||
public call (as: 'rpc', message: string, value: BN | number, gasLimit: BN | number, ...params: any[]): ContractCall<ApiType, 'rpc'>;
|
||||
public call (as: 'tx', message: string, value: BN | number, gasLimit: BN | number, ...params: any[]): ContractCall<ApiType, 'tx'>;
|
||||
public call<CallType extends ContractCallTypes> (as: CallType, message: string, value: BN | number, gasLimit: BN | number, ...params: any[]): ContractCall<ApiType, CallType> {
|
||||
public call (as: 'rpc', message: string, value: BN | number, gasLimit: BN | number, ...params: CodecArg[]): ContractCall<ApiType, 'rpc'>;
|
||||
public call (as: 'tx', message: string, value: BN | number, gasLimit: BN | number, ...params: CodecArg[]): ContractCall<ApiType, 'tx'>;
|
||||
public call<CallType extends ContractCallTypes> (as: CallType, message: string, value: BN | number, gasLimit: BN | number, ...params: CodecArg[]): ContractCall<ApiType, CallType> {
|
||||
const { def, fn } = this.getMessage(message);
|
||||
|
||||
return {
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
|
||||
send: this.decorateMethod(
|
||||
as === 'rpc' && this.hasRpcContractsCall
|
||||
? (account: IKeyringPair | string | AccountId | Address): ContractCallResult<'rpc'> =>
|
||||
@@ -67,7 +67,7 @@ export default class Contract<ApiType extends ApiTypes> extends BaseWithTxAndRpc
|
||||
};
|
||||
}
|
||||
|
||||
private _createOutcome (result: ContractExecResult, origin: AccountId, message: ContractABIMessage, params: any[]): ContractCallOutcome {
|
||||
private _createOutcome (result: ContractExecResult, origin: AccountId, message: ContractABIMessage, params: CodecArg[]): ContractCallOutcome {
|
||||
let output: Codec | null = null;
|
||||
|
||||
if (result.isSuccess) {
|
||||
|
||||
@@ -46,7 +46,7 @@ export abstract class Base<ApiType extends ApiTypes> implements ContractBase<Api
|
||||
: 0;
|
||||
const def = this.abi.abi.contract.messages[index];
|
||||
|
||||
assert(!!def, `Attempted to access a contract message that does not exist: ${typeof nameOrIndex === 'number' ? `index ${nameOrIndex}` : nameOrIndex}`);
|
||||
assert(!!def, `Attempted to access a contract message that does not exist: ${typeof nameOrIndex === 'number' ? `index ${nameOrIndex}` : (nameOrIndex || 'unknown')}`);
|
||||
|
||||
const fn = this.abi.messages[def.name] || this.abi.messages[stringCamelCase(def.name)];
|
||||
|
||||
|
||||
@@ -23,6 +23,7 @@ export interface ContractBase<ApiType extends ApiTypes> {
|
||||
|
||||
export interface ContractABITypePre {
|
||||
ty: TypeIndex;
|
||||
// eslint-disable-next-line camelcase
|
||||
display_name: StringIndex[];
|
||||
}
|
||||
|
||||
@@ -56,6 +57,7 @@ export interface ContractABIMessageCommon {
|
||||
|
||||
export interface ContractABIMessagePre extends ContractABIMessageCommon, ContractABIMessageBasePre {
|
||||
name: StringIndex;
|
||||
// eslint-disable-next-line camelcase
|
||||
return_type: ContractABITypePre | null;
|
||||
}
|
||||
|
||||
@@ -187,6 +189,7 @@ export interface InterfaceAbi {
|
||||
}
|
||||
|
||||
export interface InterfaceContractCalls {
|
||||
// eslint-disable-next-line @typescript-eslint/ban-types
|
||||
[index: string]: Function;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@polkadot/api-derive",
|
||||
"version": "1.12.1",
|
||||
"version": "1.27.1",
|
||||
"description": "Common functions used across Polkadot, derived from RPC calls and storage queries.",
|
||||
"main": "index.js",
|
||||
"keywords": [
|
||||
@@ -27,18 +27,18 @@
|
||||
},
|
||||
"homepage": "https://github.com/polkadot-js/api/tree/master/packages/api-derive#readme",
|
||||
"dependencies": {
|
||||
"@babel/runtime": "^7.9.2",
|
||||
"@polkadot/api": "1.12.1",
|
||||
"@polkadot/rpc-core": "1.12.1",
|
||||
"@polkadot/rpc-provider": "1.12.1",
|
||||
"@polkadot/types": "1.12.1",
|
||||
"@polkadot/util": "^2.9.0-beta.3",
|
||||
"@polkadot/util-crypto": "^2.9.0-beta.3",
|
||||
"bn.js": "^5.1.1",
|
||||
"@babel/runtime": "^7.11.0",
|
||||
"@polkadot/api": "1.27.1",
|
||||
"@polkadot/rpc-core": "1.27.1",
|
||||
"@polkadot/rpc-provider": "1.27.1",
|
||||
"@polkadot/types": "1.27.1",
|
||||
"@polkadot/util": "^3.0.1",
|
||||
"@polkadot/util-crypto": "^3.0.1",
|
||||
"bn.js": "^5.1.2",
|
||||
"memoizee": "^0.4.14",
|
||||
"rxjs": "^6.5.5"
|
||||
"rxjs": "^6.6.2"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@polkadot/keyring": "^2.9.0-beta.3"
|
||||
"@polkadot/keyring": "^3.0.1"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -10,6 +10,7 @@ import { map, startWith } from 'rxjs/operators';
|
||||
import { ApiInterfaceRx } from '@polkadot/api/types';
|
||||
import { ENUMSET_SIZE } from '@polkadot/types/generic/AccountIndex';
|
||||
import { Option, Vec } from '@polkadot/types';
|
||||
import { isFunction } from '@polkadot/util';
|
||||
|
||||
import { memo } from '../util';
|
||||
|
||||
@@ -51,7 +52,7 @@ function query (api: ApiInterfaceRx, accountIndex: AccountIndex | string): Obser
|
||||
export function indexToId (api: ApiInterfaceRx): (accountIndex: AccountIndex | string) => Observable<AccountId | undefined> {
|
||||
return memo((accountIndex: AccountIndex | string): Observable<AccountId | undefined> =>
|
||||
api.query.indices
|
||||
? api.query.indices.accounts
|
||||
? isFunction(api.query.indices.accounts)
|
||||
? query(api, accountIndex)
|
||||
: queryEnumSet(api, accountIndex)
|
||||
: of(undefined)
|
||||
|
||||
@@ -10,11 +10,14 @@ import { Observable, of } from 'rxjs';
|
||||
import { map, startWith, switchMap } from 'rxjs/operators';
|
||||
import { ENUMSET_SIZE } from '@polkadot/types/generic/AccountIndex';
|
||||
import { Vec } from '@polkadot/types';
|
||||
import { isFunction } from '@polkadot/util';
|
||||
|
||||
import { memo } from '../util';
|
||||
|
||||
const enumsetSize = ENUMSET_SIZE.toNumber();
|
||||
|
||||
let indicesCache: AccountIndexes | null = null;
|
||||
|
||||
function queryEnumSet (api: ApiInterfaceRx): Observable<AccountIndexes> {
|
||||
return api.query.indices.nextEnumSet<AccountIndex>().pipe(
|
||||
// use the nextEnumSet (which is a counter of the number of sets) to construct
|
||||
@@ -71,11 +74,20 @@ function queryAccounts (api: ApiInterfaceRx): Observable<AccountIndexes> {
|
||||
*/
|
||||
export function indexes (api: ApiInterfaceRx): () => Observable<AccountIndexes> {
|
||||
return memo((): Observable<AccountIndexes> =>
|
||||
(api.query.indices
|
||||
? api.query.indices.accounts
|
||||
? queryAccounts(api)
|
||||
: queryEnumSet(api)
|
||||
: of({} as AccountIndexes)
|
||||
).pipe(startWith({}))
|
||||
indicesCache
|
||||
? of(indicesCache)
|
||||
: (
|
||||
api.query.indices
|
||||
? isFunction(api.query.indices.accounts)
|
||||
? queryAccounts(api).pipe(startWith({}))
|
||||
: queryEnumSet(api).pipe(startWith({}))
|
||||
: of({} as AccountIndexes)
|
||||
).pipe(
|
||||
map((indices): AccountIndexes => {
|
||||
indicesCache = indices;
|
||||
|
||||
return indices;
|
||||
})
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -9,6 +9,7 @@ import { DeriveBalancesAccount } from '../types';
|
||||
import { Observable, combineLatest, of } from 'rxjs';
|
||||
import { map, switchMap } from 'rxjs/operators';
|
||||
import { ApiInterfaceRx } from '@polkadot/api/types';
|
||||
import { isFunction } from '@polkadot/util';
|
||||
|
||||
import { memo } from '../util';
|
||||
|
||||
@@ -22,7 +23,7 @@ function calcBalances (api: ApiInterfaceRx, [accountId, [freeBalance, reservedBa
|
||||
frozenFee,
|
||||
frozenMisc,
|
||||
reservedBalance,
|
||||
votingBalance: api.registry.createType('Balance', freeBalance.add(reservedBalance))
|
||||
votingBalance: api.registry.createType('Balance', freeBalance.toBn())
|
||||
};
|
||||
}
|
||||
|
||||
@@ -86,9 +87,9 @@ export function account (api: ApiInterfaceRx): (address: AccountIndex | AccountI
|
||||
(accountId
|
||||
? combineLatest([
|
||||
of(accountId),
|
||||
api.query.system.account
|
||||
isFunction(api.query.system.account)
|
||||
? queryCurrent(api, accountId)
|
||||
: api.query.balances.account
|
||||
: isFunction(api.query.balances.account)
|
||||
? queryBalancesAccount(api, accountId)
|
||||
: queryBalancesFree(api, accountId)
|
||||
])
|
||||
|
||||
@@ -10,7 +10,7 @@ import { Observable, combineLatest, of } from 'rxjs';
|
||||
import { map, switchMap } from 'rxjs/operators';
|
||||
import { ApiInterfaceRx } from '@polkadot/api/types';
|
||||
import { Option, Vec } from '@polkadot/types';
|
||||
import { bnMax } from '@polkadot/util';
|
||||
import { bnMax, isFunction } from '@polkadot/util';
|
||||
|
||||
import { memo } from '../util';
|
||||
|
||||
@@ -20,15 +20,17 @@ type Result = [DeriveBalancesAccount, BlockNumber, ResultBalance];
|
||||
function calcBalances (api: ApiInterfaceRx, [{ accountId, accountNonce, freeBalance, frozenFee, frozenMisc, reservedBalance, votingBalance }, bestNumber, [vesting, locks]]: Result): DeriveBalancesAll {
|
||||
let lockedBalance = api.registry.createType('Balance');
|
||||
let lockedBreakdown: (BalanceLock | BalanceLockTo212)[] = [];
|
||||
let vestingLocked = api.registry.createType('Balance');
|
||||
let allLocked = false;
|
||||
|
||||
if (Array.isArray(locks)) {
|
||||
// only get the locks that are valid until passed the current block
|
||||
lockedBreakdown = (locks as BalanceLockTo212[]).filter(({ until }): boolean => !until || (bestNumber && until.gt(bestNumber)));
|
||||
|
||||
const notAll = lockedBreakdown.filter(({ amount }): boolean => !amount.isMax());
|
||||
const notAll = lockedBreakdown.filter(({ amount }) => !amount.isMax());
|
||||
|
||||
allLocked = lockedBreakdown.some(({ amount }): boolean => amount.isMax());
|
||||
allLocked = lockedBreakdown.some(({ amount }) => amount.isMax());
|
||||
vestingLocked = api.registry.createType('Balance', lockedBreakdown.filter(({ id }) => id.eq('0x76657374696e6720')).reduce((result: BN, { amount }) => result.iadd(amount), new BN(0)));
|
||||
|
||||
// get the maximum of the locks according to https://github.com/paritytech/substrate/blob/master/srml/balances/src/lib.rs#L699
|
||||
if (notAll.length) {
|
||||
@@ -41,19 +43,11 @@ function calcBalances (api: ApiInterfaceRx, [{ accountId, accountNonce, freeBala
|
||||
// - perBlock is the unlock amount
|
||||
const { locked: vestingTotal, perBlock, startingBlock } = vesting || api.registry.createType('VestingInfo');
|
||||
const isStarted = bestNumber.gt(startingBlock);
|
||||
const vestedBalance = api.registry.createType('Balance', isStarted ? perBlock.mul(bestNumber.sub(startingBlock)) : 0);
|
||||
const isVesting = isStarted && vestedBalance.lt(vestingTotal);
|
||||
|
||||
// The available balance & vested has an interplay here
|
||||
// "
|
||||
// vesting is a guarantee that the account's balance will never go below a certain amount. so it functions in the opposite way, a bit like a lock that is monotonically decreasing rather than a liquid amount that is monotonically increasing.
|
||||
// locks function as the same guarantee - that a balance will not be lower than a particular amount.
|
||||
// because of this you can see that if there is a "vesting lock" that guarantees the balance cannot go below 200, and a "staking lock" that guarantees the balance cannot drop below 300, then we just have two guarantees of which the first is irrelevant.
|
||||
// i.e. (balance >= 200 && balance >= 300) == (balance >= 300)
|
||||
// ""
|
||||
const floating = freeBalance.sub(lockedBalance);
|
||||
const extraReceived = isVesting ? freeBalance.sub(vestingTotal) : new BN(0);
|
||||
const availableBalance = api.registry.createType('Balance', allLocked ? 0 : bnMax(new BN(0), isVesting && floating.gt(vestedBalance) ? vestedBalance.add(extraReceived) : floating));
|
||||
const vestedNow = isStarted ? perBlock.mul(bestNumber.sub(startingBlock)) : new BN(0);
|
||||
const vestedBalance = vestedNow.gt(vestingTotal) ? vestingTotal : api.registry.createType('Balance', vestedNow);
|
||||
const isVesting = isStarted && !vestingLocked.isZero();
|
||||
const vestedClaimable = api.registry.createType('Balance', isVesting ? vestingLocked.sub(vestingTotal.sub(vestedBalance)) : 0);
|
||||
const availableBalance = api.registry.createType('Balance', allLocked ? 0 : bnMax(new BN(0), freeBalance.sub(lockedBalance)));
|
||||
|
||||
return {
|
||||
accountId,
|
||||
@@ -67,6 +61,8 @@ function calcBalances (api: ApiInterfaceRx, [{ accountId, accountNonce, freeBala
|
||||
lockedBreakdown,
|
||||
reservedBalance,
|
||||
vestedBalance,
|
||||
vestedClaimable,
|
||||
vestingLocked,
|
||||
vestingTotal,
|
||||
votingBalance
|
||||
};
|
||||
@@ -135,7 +131,7 @@ export function all (api: ApiInterfaceRx): (address: AccountIndex | AccountId |
|
||||
? combineLatest([
|
||||
of(account),
|
||||
api.derive.chain.bestNumber(),
|
||||
api.query.balances.account
|
||||
isFunction(api.query.balances.account)
|
||||
? queryCurrent(api, account.accountId)
|
||||
: queryOld(api, account.accountId)
|
||||
])
|
||||
|
||||
@@ -28,12 +28,12 @@ export function fees (api: ApiInterfaceRx): () => Observable<DeriveFees> {
|
||||
return memo((): Observable<DeriveFees> =>
|
||||
of([
|
||||
// deprecated - remove
|
||||
(api.consts.balances?.creationFee as Balance) || api.registry.createType('Balance'),
|
||||
(api.consts.balances?.transferFee as Balance) || api.registry.createType('Balance'),
|
||||
(api.consts.balances?.creationFee as unknown as Balance) || api.registry.createType('Balance'),
|
||||
(api.consts.balances?.transferFee as unknown as Balance) || api.registry.createType('Balance'),
|
||||
|
||||
// current
|
||||
(api.consts.balances?.existentialDeposit as Balance) || api.registry.createType('Balance'),
|
||||
(api.consts.transactionPayment?.transactionBaseFee as Balance) || api.registry.createType('Balance'),
|
||||
(api.consts.transactionPayment?.transactionBaseFee as unknown as Balance) || api.registry.createType('Balance'),
|
||||
(api.consts.transactionPayment?.transactionByteFee as Balance) || api.registry.createType('Balance')
|
||||
]).pipe(
|
||||
map(([creationFee, transferFee, existentialDeposit, transactionBaseFee, transactionByteFee]): DeriveFees => ({
|
||||
|
||||
@@ -9,6 +9,7 @@ import { DeriveCollectiveProposal } from '../types';
|
||||
import { Observable, combineLatest, of } from 'rxjs';
|
||||
import { map, switchMap } from 'rxjs/operators';
|
||||
import { Option } from '@polkadot/types';
|
||||
import { isFunction } from '@polkadot/util';
|
||||
|
||||
import { memo } from '../util';
|
||||
|
||||
@@ -30,7 +31,7 @@ function parse ([hashes, proposals, votes]: Result): DeriveCollectiveProposal[]
|
||||
|
||||
export function proposals (api: ApiInterfaceRx, section: 'council' | 'technicalCommittee'): () => Observable<DeriveCollectiveProposal[]> {
|
||||
return memo((): Observable<DeriveCollectiveProposal[]> =>
|
||||
api.query[section]?.proposals
|
||||
isFunction(api.query[section]?.proposals)
|
||||
? api.query[section].proposals().pipe(
|
||||
switchMap((hashes: Hash[]): Observable<Result> =>
|
||||
hashes.length
|
||||
|
||||
@@ -11,23 +11,24 @@ import { map } from 'rxjs/operators';
|
||||
|
||||
import { memo } from '../util';
|
||||
|
||||
type ResultV2 = [BN, BN, BN, BN, BN, BN, BN, BN, BN];
|
||||
type ResultV2 = [BN, BN, BN, BN, BN, BN, BN, BN, BN, BN];
|
||||
|
||||
// query via constants (current applicable path)
|
||||
function queryConstants (api: ApiInterfaceRx): Observable<ResultV2> {
|
||||
return of([
|
||||
// deprecated
|
||||
api.consts.contracts.callBaseFee || api.registry.createType('Balance'),
|
||||
api.consts.contracts.contractFee || api.registry.createType('Balance'),
|
||||
api.consts.contracts.creationFee || api.registry.createType('Balance'),
|
||||
api.consts.contracts.transactionBaseFee || api.registry.createType('Balance'),
|
||||
api.consts.contracts.transactionByteFee || api.registry.createType('Balance'),
|
||||
api.consts.contracts.transferFee || api.registry.createType('Balance'),
|
||||
|
||||
// current
|
||||
api.consts.contracts.callBaseFee,
|
||||
api.consts.contracts.contractFee,
|
||||
api.consts.contracts.rentByteFee,
|
||||
api.consts.contracts.rentDepositOffset,
|
||||
api.consts.contracts.tombstoneDeposit,
|
||||
api.consts.contracts.transactionBaseFee,
|
||||
api.consts.contracts.transactionByteFee
|
||||
api.consts.contracts.surchargeReward,
|
||||
api.consts.contracts.tombstoneDeposit
|
||||
]) as unknown as Observable<ResultV2>;
|
||||
}
|
||||
|
||||
@@ -47,12 +48,13 @@ function queryConstants (api: ApiInterfaceRx): Observable<ResultV2> {
|
||||
export function fees (api: ApiInterfaceRx): () => Observable<DeriveContractFees> {
|
||||
return memo((): Observable<DeriveContractFees> => {
|
||||
return queryConstants(api).pipe(
|
||||
map(([creationFee, transferFee, callBaseFee, contractFee, rentByteFee, rentDepositOffset, tombstoneDeposit, transactionBaseFee, transactionByteFee]): DeriveContractFees => ({
|
||||
map(([callBaseFee, contractFee, creationFee, transactionBaseFee, transactionByteFee, transferFee, rentByteFee, rentDepositOffset, surchargeReward, tombstoneDeposit]): DeriveContractFees => ({
|
||||
callBaseFee,
|
||||
contractFee,
|
||||
creationFee,
|
||||
rentByteFee,
|
||||
rentDepositOffset,
|
||||
surchargeReward,
|
||||
tombstoneDeposit,
|
||||
transactionBaseFee,
|
||||
transactionByteFee,
|
||||
|
||||
@@ -10,7 +10,7 @@ import { Observable, combineLatest, of } from 'rxjs';
|
||||
import { map, switchMap } from 'rxjs/operators';
|
||||
import { ApiInterfaceRx } from '@polkadot/api/types';
|
||||
import { Option, Vec, u64 } from '@polkadot/types';
|
||||
import { stringToHex } from '@polkadot/util';
|
||||
import { isFunction, stringToHex } from '@polkadot/util';
|
||||
|
||||
import { memo } from '../util';
|
||||
|
||||
@@ -96,7 +96,7 @@ function queryScheduler (api: ApiInterfaceRx): Observable<DeriveDispatch[]> {
|
||||
|
||||
export function dispatchQueue (api: ApiInterfaceRx): () => Observable<DeriveDispatch[]> {
|
||||
return memo((): Observable<DeriveDispatch[]> =>
|
||||
api.query.scheduler?.agenda
|
||||
isFunction(api.query.scheduler?.agenda)
|
||||
? queryScheduler(api)
|
||||
: api.query.democracy.dispatchQueue
|
||||
? queryQueue(api)
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
// of the Apache-2.0 license. See the LICENSE file for details.
|
||||
|
||||
export * from './dispatchQueue';
|
||||
export * from './locks';
|
||||
export * from './nextExternal';
|
||||
export * from './preimage';
|
||||
export * from './preimages';
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
// Copyright 2017-2020 @polkadot/api-derive authors & contributors
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the Apache-2.0 license. See the LICENSE file for details.
|
||||
|
||||
import { AccountId, ReferendumInfo, ReferendumInfoTo239, VotingDirect, VotingDirectVote } from '@polkadot/types/interfaces';
|
||||
import { ApiInterfaceRx } from '@polkadot/api/types';
|
||||
import { DeriveDemocracyLock } from '../types';
|
||||
|
||||
import BN from 'bn.js';
|
||||
import { Observable, of } from 'rxjs';
|
||||
import { map, switchMap } from 'rxjs/operators';
|
||||
import { Option } from '@polkadot/types';
|
||||
import { isUndefined } from '@polkadot/util';
|
||||
|
||||
import { memo } from '../util';
|
||||
|
||||
const LOCKUPS = [0, 1, 2, 4, 8, 16, 32];
|
||||
const ZERO = new BN(0);
|
||||
|
||||
function parseLock (api: ApiInterfaceRx, [referendumId, accountVote]: VotingDirectVote, referendum: ReferendumInfo): DeriveDemocracyLock {
|
||||
const { balance, vote } = accountVote.asStandard;
|
||||
let unlockAt = ZERO;
|
||||
|
||||
if (referendum.isFinished) {
|
||||
const { approved, end } = referendum.asFinished;
|
||||
|
||||
if ((approved.isTrue && vote.isAye) || (approved.isFalse && vote.isNay)) {
|
||||
unlockAt = end.add(api.consts.democracy.enactmentPeriod.muln(LOCKUPS[vote.conviction.index]));
|
||||
}
|
||||
}
|
||||
|
||||
return { balance, isFinished: referendum.isFinished, referendumId, unlockAt, vote };
|
||||
}
|
||||
|
||||
function directLocks (api: ApiInterfaceRx, { votes }: VotingDirect): Observable<DeriveDemocracyLock[]> {
|
||||
if (!votes.length) {
|
||||
return of([]);
|
||||
}
|
||||
|
||||
return api.query.democracy.referendumInfoOf.multi<Option<ReferendumInfo | ReferendumInfoTo239>>(votes.map(([referendumId]) => referendumId)).pipe(
|
||||
map((referendums) =>
|
||||
votes
|
||||
.map((vote, index): [VotingDirectVote, ReferendumInfo | ReferendumInfoTo239 | null] =>
|
||||
[vote, referendums[index].unwrapOr(null)]
|
||||
)
|
||||
.filter((item): item is [VotingDirectVote, ReferendumInfo] =>
|
||||
!!item[1] && isUndefined((item[1] as ReferendumInfoTo239).end) && item[0][1].isStandard
|
||||
)
|
||||
.map(([directVote, referendum]) =>
|
||||
parseLock(api, directVote, referendum)
|
||||
)
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
export function locks (api: ApiInterfaceRx): (accountId: string | AccountId) => Observable<DeriveDemocracyLock[]> {
|
||||
return memo((accountId: string | AccountId): Observable<DeriveDemocracyLock[]> =>
|
||||
api.query.democracy.votingOf(accountId).pipe(
|
||||
switchMap((voting): Observable<DeriveDemocracyLock[]> =>
|
||||
voting.isDirect
|
||||
? directLocks(api, voting.asDirect)
|
||||
: of([])
|
||||
)
|
||||
)
|
||||
);
|
||||
}
|
||||
@@ -10,27 +10,41 @@ import { Observable, combineLatest, of } from 'rxjs';
|
||||
import { map, switchMap } from 'rxjs/operators';
|
||||
import { ApiInterfaceRx } from '@polkadot/api/types';
|
||||
import { Option, Vec } from '@polkadot/types';
|
||||
import { isFunction } from '@polkadot/util';
|
||||
|
||||
import { memo } from '../util';
|
||||
|
||||
type Depositors = Option<ITuple<[Balance, Vec<AccountId>]>>;
|
||||
type DepositorsNew = Option<ITuple<[Vec<AccountId>, Balance]>>;
|
||||
type DepositorsOld = Option<ITuple<[Balance, Vec<AccountId>]>>;
|
||||
type Depositors = DepositorsNew | DepositorsOld;
|
||||
type Proposals = Vec<ITuple<[PropIndex, Hash, AccountId]>>;
|
||||
type Result = [Proposals, (DeriveProposalImage | undefined)[], Depositors[]];
|
||||
|
||||
function parse ([proposals, images, depositors]: [Proposals, (DeriveProposalImage | undefined)[], Depositors[]]): DeriveProposal[] {
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
function isNewDepositors (depositors: ITuple<[Vec<AccountId>, Balance]> | ITuple<[Balance, Vec<AccountId>]>): depositors is ITuple<[Vec<AccountId>, Balance]> {
|
||||
// Detect balance...
|
||||
// eslint-disable-next-line @typescript-eslint/unbound-method
|
||||
return isFunction((depositors[1] as Balance).mul);
|
||||
}
|
||||
|
||||
function parse ([proposals, images, optDepositors]: Result): DeriveProposal[] {
|
||||
return proposals
|
||||
.filter(([, , proposer], index): boolean =>
|
||||
!!(depositors[index]?.isSome) && !proposer.isEmpty
|
||||
!!(optDepositors[index]?.isSome) && !proposer.isEmpty
|
||||
)
|
||||
.map(([index, imageHash, proposer], proposalIndex): DeriveProposal => {
|
||||
const [balance, seconds] = depositors[proposalIndex].unwrap();
|
||||
const depositors = optDepositors[proposalIndex].unwrap();
|
||||
|
||||
return {
|
||||
balance,
|
||||
...(
|
||||
isNewDepositors(depositors)
|
||||
? { balance: depositors[1], seconds: depositors[0] }
|
||||
: { balance: depositors[0], seconds: depositors[1] }
|
||||
),
|
||||
image: images[proposalIndex],
|
||||
imageHash,
|
||||
index,
|
||||
proposer,
|
||||
seconds
|
||||
proposer
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
@@ -20,6 +20,7 @@ export function referendumIds (api: ApiInterfaceRx): () => Observable<BN[]> {
|
||||
]).pipe(
|
||||
map(([first, total]): BN[] =>
|
||||
total.gt(first)
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
|
||||
? [...Array(total.sub(first).toNumber())].map((_, i): BN => first.addn(i))
|
||||
: []
|
||||
)
|
||||
|
||||
@@ -10,6 +10,7 @@ import BN from 'bn.js';
|
||||
import { Observable, of, combineLatest } from 'rxjs';
|
||||
import { map, switchMap } from 'rxjs/operators';
|
||||
import { Option, Vec } from '@polkadot/types';
|
||||
import { isFunction } from '@polkadot/util';
|
||||
|
||||
import { memo } from '../util';
|
||||
import { calcVotes, getStatus, parseImage } from './util';
|
||||
@@ -95,7 +96,7 @@ export function _referendumVotes (api: ApiInterfaceRx): (referendum: DeriveRefer
|
||||
return memo((referendum: DeriveReferendum): Observable<DeriveReferendumVotes> =>
|
||||
combineLatest([
|
||||
api.derive.democracy.sqrtElectorate(),
|
||||
api.query.democracy.votingOf
|
||||
isFunction(api.query.democracy.votingOf)
|
||||
? votesCurr(api, referendum.index)
|
||||
: votesPrev(api, referendum.index)
|
||||
]).pipe(
|
||||
|
||||
@@ -2,11 +2,19 @@
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the Apache-2.0 license. See the LICENSE file for details.
|
||||
|
||||
import type BN from 'bn.js';
|
||||
import { AccountId, Balance, BlockNumber, Hash, Proposal, PropIndex, ReferendumInfoTo239, ReferendumStatus, Vote, ReferendumIndex, VoteThreshold } from '@polkadot/types/interfaces';
|
||||
|
||||
import BN from 'bn.js';
|
||||
import { Vec } from '@polkadot/types';
|
||||
|
||||
export interface DeriveDemocracyLock {
|
||||
balance: Balance;
|
||||
isFinished: boolean;
|
||||
referendumId: ReferendumIndex;
|
||||
unlockAt: BN;
|
||||
vote: Vote;
|
||||
}
|
||||
|
||||
export interface DeriveDispatch {
|
||||
at: BlockNumber;
|
||||
index: ReferendumIndex;
|
||||
|
||||
@@ -82,15 +82,15 @@ function calcVotesPrev (votesFor: DeriveReferendumVote[]): DeriveReferendumVoteS
|
||||
if (vote.isAye) {
|
||||
state.allAye.push(derived);
|
||||
state.voteCountAye++;
|
||||
state.votedAye = state.votedAye.add(counted);
|
||||
state.votedAye.iadd(counted);
|
||||
} else {
|
||||
state.allNay.push(derived);
|
||||
state.voteCountNay++;
|
||||
state.votedNay = state.votedNay.add(counted);
|
||||
state.votedNay.iadd(counted);
|
||||
}
|
||||
|
||||
state.voteCount++;
|
||||
state.votedTotal = state.votedTotal.add(counted);
|
||||
state.votedTotal.iadd(counted);
|
||||
|
||||
return state;
|
||||
}, {
|
||||
|
||||
@@ -2,6 +2,10 @@
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the Apache-2.0 license. See the LICENSE file for details.
|
||||
|
||||
/* eslint-disable @typescript-eslint/no-unsafe-return */
|
||||
/* eslint-disable @typescript-eslint/no-unsafe-call */
|
||||
/* eslint-disable @typescript-eslint/restrict-template-expressions */
|
||||
|
||||
import { Observable, from } from 'rxjs';
|
||||
import ApiRx from '@polkadot/api/rx/Api';
|
||||
import MockProvider from '@polkadot/rpc-provider/mock';
|
||||
@@ -33,7 +37,7 @@ describe('derive', (): void => {
|
||||
const api = new ApiRx({ provider: new MockProvider(registry), registry });
|
||||
|
||||
beforeAll((done): void => {
|
||||
api.isReady.subscribe((): void => done());
|
||||
api.isReady.subscribe(() => done());
|
||||
});
|
||||
|
||||
testFunction(api)('accounts', 'idAndIndex', []);
|
||||
|
||||
@@ -76,9 +76,11 @@ function injectFunctions<AllSections> (api: ApiInterfaceRx, allSections: AllSect
|
||||
.reduce((sectionAcc, _methodName): DeriveSection<typeof section> => {
|
||||
const methodName = _methodName as keyof typeof section;
|
||||
// Not sure what to do here, casting as any. Though the final types are good
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment,@typescript-eslint/no-unsafe-call
|
||||
const method = (section[methodName] as any)(api);
|
||||
|
||||
// idem
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment,@typescript-eslint/no-unsafe-member-access
|
||||
(sectionAcc as any)[methodName] = method;
|
||||
|
||||
return sectionAcc;
|
||||
|
||||
@@ -9,6 +9,7 @@ import { DeriveSessionIndexes } from '../types';
|
||||
import { Observable, of } from 'rxjs';
|
||||
import { map } from 'rxjs/operators';
|
||||
import { Option, u32 } from '@polkadot/types';
|
||||
import { isFunction } from '@polkadot/util';
|
||||
|
||||
import { memo } from '../util';
|
||||
|
||||
@@ -79,7 +80,7 @@ export function indexes (api: ApiInterfaceRx): () => Observable<DeriveSessionInd
|
||||
return memo((): Observable<DeriveSessionIndexes> =>
|
||||
(
|
||||
api.query.session && api.query.staking
|
||||
? api.query.staking.activeEra
|
||||
? isFunction(api.query.staking.activeEra)
|
||||
? query(api)
|
||||
: queryNoActive(api)
|
||||
: empty(api)
|
||||
|
||||
@@ -9,6 +9,7 @@ import { Observable, combineLatest, of } from 'rxjs';
|
||||
import { map, switchMap } from 'rxjs/operators';
|
||||
import { ApiInterfaceRx } from '@polkadot/api/types';
|
||||
import { Option, u64 } from '@polkadot/types';
|
||||
import { isFunction } from '@polkadot/util';
|
||||
|
||||
import { memo } from '../util';
|
||||
|
||||
@@ -16,9 +17,9 @@ type ResultSlots = [u64, u64, u64, Option<SessionIndex>];
|
||||
type ResultSlotsFlat = [u64, u64, u64, SessionIndex];
|
||||
|
||||
function createDerive (api: ApiInterfaceRx, info: DeriveSessionInfo, [currentSlot, epochIndex, epochOrGenesisStartSlot, activeEraStartSessionIndex]: ResultSlotsFlat): DeriveSessionProgress {
|
||||
const epochStartSlot = epochIndex.mul(info.sessionLength).add(epochOrGenesisStartSlot);
|
||||
const epochStartSlot = epochIndex.mul(info.sessionLength).iadd(epochOrGenesisStartSlot);
|
||||
const sessionProgress = currentSlot.sub(epochStartSlot);
|
||||
const eraProgress = info.currentIndex.sub(activeEraStartSessionIndex).mul(info.sessionLength).add(sessionProgress);
|
||||
const eraProgress = info.currentIndex.sub(activeEraStartSessionIndex).imul(info.sessionLength).iadd(sessionProgress);
|
||||
|
||||
return {
|
||||
...info,
|
||||
@@ -29,14 +30,11 @@ function createDerive (api: ApiInterfaceRx, info: DeriveSessionInfo, [currentSlo
|
||||
|
||||
function queryAura (api: ApiInterfaceRx): Observable<DeriveSessionProgress> {
|
||||
return api.derive.session.info().pipe(
|
||||
map((info): DeriveSessionProgress =>
|
||||
createDerive(api, info, [
|
||||
api.registry.createType('u64', 1),
|
||||
api.registry.createType('u64', 1),
|
||||
api.registry.createType('u64', 1),
|
||||
api.registry.createType('SessionIndex', 1)
|
||||
])
|
||||
)
|
||||
map((info): DeriveSessionProgress => ({
|
||||
...info,
|
||||
eraProgress: api.registry.createType('BlockNumber'),
|
||||
sessionProgress: api.registry.createType('BlockNumber')
|
||||
}))
|
||||
);
|
||||
}
|
||||
|
||||
@@ -77,9 +75,10 @@ function queryBabeNoHistory (api: ApiInterfaceRx): Observable<[DeriveSessionInfo
|
||||
export function progress (api: ApiInterfaceRx): () => Observable<DeriveSessionProgress> {
|
||||
return memo((): Observable<DeriveSessionProgress> =>
|
||||
api.consts.babe
|
||||
? (api.query.staking.erasStartSessionIndex
|
||||
? queryBabe(api) // 2.x with Babe
|
||||
: queryBabeNoHistory(api)
|
||||
? (
|
||||
isFunction(api.query.staking.erasStartSessionIndex)
|
||||
? queryBabe(api) // 2.x with Babe
|
||||
: queryBabeNoHistory(api)
|
||||
).pipe(
|
||||
map(([info, slots]: [DeriveSessionInfo, ResultSlotsFlat]): DeriveSessionProgress =>
|
||||
createDerive(api, info, slots)
|
||||
|
||||
@@ -7,7 +7,7 @@ import { Balance, StakingLedger, UnlockChunk } from '@polkadot/types/interfaces'
|
||||
import { DeriveSessionInfo, DeriveStakingAccount, DeriveStakingQuery, DeriveUnlocking } from '../types';
|
||||
|
||||
import BN from 'bn.js';
|
||||
import { Observable, combineLatest } from 'rxjs';
|
||||
import { Observable } from 'rxjs';
|
||||
import { map, switchMap } from 'rxjs/operators';
|
||||
|
||||
import { isUndefined } from '@polkadot/util';
|
||||
@@ -21,7 +21,7 @@ function groupByEra (list: UnlockChunk[]): Record<string, BN> {
|
||||
|
||||
map[key] = !map[key]
|
||||
? value.unwrap()
|
||||
: map[key].add(value.unwrap());
|
||||
: map[key].iadd(value.unwrap());
|
||||
|
||||
return map;
|
||||
}, {});
|
||||
@@ -32,8 +32,8 @@ function calculateUnlocking (api: ApiInterfaceRx, stakingLedger: StakingLedger |
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const unlockingChunks = stakingLedger.unlocking.filter(({ era }): boolean =>
|
||||
era.unwrap().sub(sessionInfo.activeEra).gtn(0)
|
||||
const unlockingChunks = stakingLedger.unlocking.filter(({ era }) =>
|
||||
era.unwrap().gt(sessionInfo.activeEra)
|
||||
);
|
||||
|
||||
if (!unlockingChunks.length) {
|
||||
@@ -43,11 +43,13 @@ function calculateUnlocking (api: ApiInterfaceRx, stakingLedger: StakingLedger |
|
||||
// group the unlock chunks that have the same era and sum their values
|
||||
const groupedResult = groupByEra(unlockingChunks);
|
||||
const results = Object.entries(groupedResult).map(([eraString, value]): DeriveUnlocking => ({
|
||||
remainingEras: new BN(eraString).sub(sessionInfo.activeEra),
|
||||
remainingEras: new BN(eraString).isub(sessionInfo.activeEra),
|
||||
value: api.registry.createType('Balance', value)
|
||||
}));
|
||||
|
||||
return results.length ? results : undefined;
|
||||
return results.length
|
||||
? results
|
||||
: undefined;
|
||||
}
|
||||
|
||||
function redeemableSum (api: ApiInterfaceRx, stakingLedger: StakingLedger | undefined, sessionInfo: DeriveSessionInfo): Balance {
|
||||
@@ -57,7 +59,7 @@ function redeemableSum (api: ApiInterfaceRx, stakingLedger: StakingLedger | unde
|
||||
|
||||
return api.registry.createType('Balance', stakingLedger.unlocking.reduce((total, { era, value }): BN => {
|
||||
return sessionInfo.activeEra.gte(era.unwrap())
|
||||
? total.add(value.unwrap())
|
||||
? total.iadd(value.unwrap())
|
||||
: total;
|
||||
}, new BN(0)));
|
||||
}
|
||||
@@ -70,23 +72,6 @@ function parseResult (api: ApiInterfaceRx, sessionInfo: DeriveSessionInfo, query
|
||||
};
|
||||
}
|
||||
|
||||
export function _account (api: ApiInterfaceRx): (sessionInfo: DeriveSessionInfo, accountId: Uint8Array | string) => Observable<DeriveStakingAccount> {
|
||||
return memo((sessionInfo: DeriveSessionInfo, accountId: Uint8Array | string): Observable<DeriveStakingAccount> =>
|
||||
api.derive.staking.query(accountId).pipe(
|
||||
map((query) => parseResult(api, sessionInfo, query))
|
||||
));
|
||||
}
|
||||
|
||||
/**
|
||||
* @description From a stash, retrieve the controllerId and fill in all the relevant staking details
|
||||
*/
|
||||
export function account (api: ApiInterfaceRx): (accountId: Uint8Array | string) => Observable<DeriveStakingAccount> {
|
||||
return memo((accountId: Uint8Array | string): Observable<DeriveStakingAccount> =>
|
||||
api.derive.session.info().pipe(
|
||||
switchMap((sessionInfo) => api.derive.staking._account(sessionInfo, accountId))
|
||||
));
|
||||
}
|
||||
|
||||
/**
|
||||
* @description From a list of stashes, fill in all the relevant staking details
|
||||
*/
|
||||
@@ -94,7 +79,21 @@ export function accounts (api: ApiInterfaceRx): (accountIds: (Uint8Array | strin
|
||||
return memo((accountIds: (Uint8Array | string)[]): Observable<DeriveStakingAccount[]> =>
|
||||
api.derive.session.info().pipe(
|
||||
switchMap((sessionInfo) =>
|
||||
combineLatest(accountIds.map((accountId) => api.derive.staking._account(sessionInfo, accountId)))
|
||||
api.derive.staking.queryMulti(accountIds).pipe(
|
||||
map((queries) => queries.map((query) => parseResult(api, sessionInfo, query)))
|
||||
)
|
||||
)
|
||||
));
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @description From a stash, retrieve the controllerId and fill in all the relevant staking details
|
||||
*/
|
||||
export function account (api: ApiInterfaceRx): (accountId: Uint8Array | string) => Observable<DeriveStakingAccount> {
|
||||
return memo((accountId: Uint8Array | string): Observable<DeriveStakingAccount> =>
|
||||
api.derive.staking.accounts([accountId]).pipe(
|
||||
map(([first]) => first)
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -3,10 +3,9 @@
|
||||
// of the Apache-2.0 license. See the LICENSE file for details.
|
||||
|
||||
import { ApiInterfaceRx } from '@polkadot/api/types';
|
||||
import { AccountId } from '@polkadot/types/interfaces';
|
||||
import { DeriveStakingQuery, DeriveStakingElected } from '../types';
|
||||
import { DeriveStakingElected } from '../types';
|
||||
|
||||
import { Observable, combineLatest, of } from 'rxjs';
|
||||
import { Observable } from 'rxjs';
|
||||
import { map, switchMap } from 'rxjs/operators';
|
||||
|
||||
import { memo } from '../util';
|
||||
@@ -14,18 +13,14 @@ import { memo } from '../util';
|
||||
export function electedInfo (api: ApiInterfaceRx): () => Observable<DeriveStakingElected> {
|
||||
return memo((): Observable<DeriveStakingElected> =>
|
||||
api.derive.staking.validators().pipe(
|
||||
switchMap(({ nextElected }): Observable<[AccountId[], DeriveStakingQuery[]]> =>
|
||||
combineLatest([
|
||||
of(nextElected),
|
||||
combineLatest(
|
||||
nextElected.map((accountId) => api.derive.staking.query(accountId))
|
||||
)
|
||||
])
|
||||
),
|
||||
map(([nextElected, info]): DeriveStakingElected => ({
|
||||
info,
|
||||
nextElected
|
||||
}))
|
||||
switchMap(({ nextElected }): Observable<DeriveStakingElected> =>
|
||||
api.derive.staking.queryMulti(nextElected).pipe(
|
||||
map((info): DeriveStakingElected => ({
|
||||
info,
|
||||
nextElected
|
||||
}))
|
||||
)
|
||||
)
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -10,10 +10,12 @@ import { Observable, combineLatest, of } from 'rxjs';
|
||||
import { map, switchMap } from 'rxjs/operators';
|
||||
import { StorageKey } from '@polkadot/types';
|
||||
|
||||
import { memo } from '../util';
|
||||
import { deriveCache, memo } from '../util';
|
||||
|
||||
type KeysAndExposures = [StorageKey, Exposure][];
|
||||
|
||||
const CACHE_KEY = 'eraExposure';
|
||||
|
||||
function mapStakers (era: EraIndex, stakers: KeysAndExposures): DeriveEraExposure {
|
||||
const nominators: DeriveEraNominatorExposure = {};
|
||||
const validators: DeriveEraValidatorExposure = {};
|
||||
@@ -34,26 +36,45 @@ function mapStakers (era: EraIndex, stakers: KeysAndExposures): DeriveEraExposur
|
||||
return { era, nominators, validators };
|
||||
}
|
||||
|
||||
export function _eraExposure (api: ApiInterfaceRx): (era: EraIndex, withActive: boolean) => Observable<DeriveEraExposure> {
|
||||
return memo((era: EraIndex, withActive: boolean): Observable<DeriveEraExposure> => {
|
||||
const cacheKey = `${CACHE_KEY}-${era.toString()}`;
|
||||
const cached = withActive
|
||||
? undefined
|
||||
: deriveCache.get<DeriveEraExposure>(cacheKey);
|
||||
|
||||
return cached
|
||||
? of(cached)
|
||||
: api.query.staking.erasStakersClipped.entries(era).pipe(
|
||||
map((stakers): DeriveEraExposure => {
|
||||
const value = mapStakers(era, stakers);
|
||||
|
||||
!withActive && deriveCache.set(cacheKey, value);
|
||||
|
||||
return value;
|
||||
})
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
export function eraExposure (api: ApiInterfaceRx): (era: EraIndex) => Observable<DeriveEraExposure> {
|
||||
return memo((era: EraIndex): Observable<DeriveEraExposure> =>
|
||||
api.query.staking.erasStakersClipped.entries(era).pipe(
|
||||
map((stakers) => mapStakers(era, stakers))
|
||||
)
|
||||
api.derive.staking._eraExposure(era, true)
|
||||
);
|
||||
}
|
||||
|
||||
export function _erasExposure (api: ApiInterfaceRx): (eras: EraIndex[]) => Observable<DeriveEraExposure[]> {
|
||||
return memo((eras: EraIndex[]): Observable<DeriveEraExposure[]> =>
|
||||
export function _erasExposure (api: ApiInterfaceRx): (eras: EraIndex[], withActive: boolean) => Observable<DeriveEraExposure[]> {
|
||||
return memo((eras: EraIndex[], withActive: boolean): Observable<DeriveEraExposure[]> =>
|
||||
eras.length
|
||||
? combineLatest(eras.map((era) => api.derive.staking.eraExposure(era)))
|
||||
? combineLatest(eras.map((era) => api.derive.staking._eraExposure(era, withActive)))
|
||||
: of([])
|
||||
);
|
||||
}
|
||||
|
||||
export function erasExposure (api: ApiInterfaceRx): (withActive?: boolean) => Observable<DeriveEraExposure[]> {
|
||||
return memo((withActive?: boolean): Observable<DeriveEraExposure[]> =>
|
||||
return memo((withActive = false): Observable<DeriveEraExposure[]> =>
|
||||
api.derive.staking.erasHistoric(withActive).pipe(
|
||||
switchMap((eras) => api.derive.staking._erasExposure(eras))
|
||||
switchMap((eras) => api.derive.staking._erasExposure(eras, withActive))
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -12,8 +12,8 @@ import { Option, u32 } from '@polkadot/types';
|
||||
|
||||
import { memo } from '../util';
|
||||
|
||||
export function erasHistoric (api: ApiInterfaceRx): (withActive?: boolean) => Observable<EraIndex[]> {
|
||||
return memo((withActive?: boolean): Observable<EraIndex[]> =>
|
||||
export function erasHistoric (api: ApiInterfaceRx): (withActive: boolean) => Observable<EraIndex[]> {
|
||||
return memo((withActive: boolean): Observable<EraIndex[]> =>
|
||||
api.query.staking?.activeEra
|
||||
? api.queryMulti<[Option<ActiveEraInfo>, u32]>([
|
||||
api.query.staking.activeEra,
|
||||
|
||||
@@ -9,7 +9,9 @@ import { DeriveEraPoints, DeriveEraValPoints } from '../types';
|
||||
import { Observable, of } from 'rxjs';
|
||||
import { map, switchMap } from 'rxjs/operators';
|
||||
|
||||
import { memo } from '../util';
|
||||
import { deriveCache, memo } from '../util';
|
||||
|
||||
const CACHE_KEY = 'eraPoints';
|
||||
|
||||
function mapValidators ({ individual }: EraRewardPoints): DeriveEraValPoints {
|
||||
return [...individual.entries()]
|
||||
@@ -21,26 +23,48 @@ function mapValidators ({ individual }: EraRewardPoints): DeriveEraValPoints {
|
||||
}, {});
|
||||
}
|
||||
|
||||
export function _erasPoints (api: ApiInterfaceRx): (eras: EraIndex[]) => Observable<DeriveEraPoints[]> {
|
||||
return memo((eras: EraIndex[]): Observable<DeriveEraPoints[]> =>
|
||||
eras.length
|
||||
? api.query.staking.erasRewardPoints.multi<EraRewardPoints>(eras).pipe(
|
||||
map((points) =>
|
||||
eras.map((era, index): DeriveEraPoints => ({
|
||||
era,
|
||||
eraPoints: points[index].total,
|
||||
validators: mapValidators(points[index])
|
||||
}))
|
||||
)
|
||||
)
|
||||
: of([])
|
||||
);
|
||||
function mapPoints (eras: EraIndex[], points: EraRewardPoints[]): DeriveEraPoints[] {
|
||||
return eras.map((era, index): DeriveEraPoints => ({
|
||||
era,
|
||||
eraPoints: points[index].total,
|
||||
validators: mapValidators(points[index])
|
||||
}));
|
||||
}
|
||||
|
||||
export function _erasPoints (api: ApiInterfaceRx): (eras: EraIndex[], withActive: boolean) => Observable<DeriveEraPoints[]> {
|
||||
return memo((eras: EraIndex[], withActive: boolean): Observable<DeriveEraPoints[]> => {
|
||||
if (!eras.length) {
|
||||
return of([]);
|
||||
}
|
||||
|
||||
const cached: DeriveEraPoints[] = withActive
|
||||
? []
|
||||
: eras
|
||||
.map((era) => deriveCache.get<DeriveEraPoints>(`${CACHE_KEY}-${era.toString()}`))
|
||||
.filter((value): value is DeriveEraPoints => !!value);
|
||||
const remaining = eras.filter((era) => !cached.some((cached) => era.eq(cached.era)));
|
||||
|
||||
return !remaining.length
|
||||
? of(cached)
|
||||
: api.query.staking.erasRewardPoints.multi<EraRewardPoints>(remaining).pipe(
|
||||
map((points): DeriveEraPoints[] => {
|
||||
const query = mapPoints(remaining, points);
|
||||
|
||||
!withActive && query.forEach((q) => deriveCache.set(`${CACHE_KEY}-${q.era.toString()}`, q));
|
||||
|
||||
return eras.map((era): DeriveEraPoints =>
|
||||
cached.find((cached) => era.eq(cached.era)) ||
|
||||
query.find((query) => era.eq(query.era)) as DeriveEraPoints
|
||||
);
|
||||
})
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
export function erasPoints (api: ApiInterfaceRx): (withActive?: boolean) => Observable<DeriveEraPoints[]> {
|
||||
return memo((withActive?: boolean): Observable<DeriveEraPoints[]> =>
|
||||
return memo((withActive = false): Observable<DeriveEraPoints[]> =>
|
||||
api.derive.staking.erasHistoric(withActive).pipe(
|
||||
switchMap((eras) => api.derive.staking._erasPoints(eras))
|
||||
switchMap((eras) => api.derive.staking._erasPoints(eras, withActive))
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -10,7 +10,9 @@ import { Observable, combineLatest, of } from 'rxjs';
|
||||
import { map, switchMap } from 'rxjs/operators';
|
||||
import { StorageKey } from '@polkadot/types';
|
||||
|
||||
import { memo } from '../util';
|
||||
import { deriveCache, memo } from '../util';
|
||||
|
||||
const CACHE_KEY = 'eraPrefs';
|
||||
|
||||
function mapPrefs (era: EraIndex, all: [StorageKey, ValidatorPrefs][]): DeriveEraPrefs {
|
||||
const validators: DeriveEraValPrefs = {};
|
||||
@@ -22,26 +24,45 @@ function mapPrefs (era: EraIndex, all: [StorageKey, ValidatorPrefs][]): DeriveEr
|
||||
return { era, validators };
|
||||
}
|
||||
|
||||
export function _eraPrefs (api: ApiInterfaceRx): (era: EraIndex, withActive: boolean) => Observable<DeriveEraPrefs> {
|
||||
return memo((era: EraIndex, withActive: boolean): Observable<DeriveEraPrefs> => {
|
||||
const cacheKey = `${CACHE_KEY}-${era.toString()}`;
|
||||
const cached = withActive
|
||||
? undefined
|
||||
: deriveCache.get<DeriveEraPrefs>(cacheKey);
|
||||
|
||||
return cached
|
||||
? of(cached)
|
||||
: api.query.staking.erasValidatorPrefs.entries(era).pipe(
|
||||
map((prefs): DeriveEraPrefs => {
|
||||
const value = mapPrefs(era, prefs);
|
||||
|
||||
!withActive && deriveCache.set(cacheKey, value);
|
||||
|
||||
return value;
|
||||
})
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
export function eraPrefs (api: ApiInterfaceRx): (era: EraIndex) => Observable<DeriveEraPrefs> {
|
||||
return memo((era: EraIndex): Observable<DeriveEraPrefs> =>
|
||||
api.query.staking.erasValidatorPrefs.entries(era).pipe(
|
||||
map((prefs) => mapPrefs(era, prefs))
|
||||
)
|
||||
api.derive.staking._eraPrefs(era, true)
|
||||
);
|
||||
}
|
||||
|
||||
export function _erasPrefs (api: ApiInterfaceRx): (eras: EraIndex[]) => Observable<DeriveEraPrefs[]> {
|
||||
return memo((eras: EraIndex[]): Observable<DeriveEraPrefs[]> =>
|
||||
export function _erasPrefs (api: ApiInterfaceRx): (eras: EraIndex[], withActive: boolean) => Observable<DeriveEraPrefs[]> {
|
||||
return memo((eras: EraIndex[], withActive: boolean): Observable<DeriveEraPrefs[]> =>
|
||||
eras.length
|
||||
? combineLatest(eras.map((era) => api.derive.staking.eraPrefs(era)))
|
||||
? combineLatest(eras.map((era) => api.derive.staking._eraPrefs(era, withActive)))
|
||||
: of([])
|
||||
);
|
||||
}
|
||||
|
||||
export function erasPrefs (api: ApiInterfaceRx): (withActive?: boolean) => Observable<DeriveEraPrefs[]> {
|
||||
return memo((withActive?: boolean): Observable<DeriveEraPrefs[]> =>
|
||||
return memo((withActive = false): Observable<DeriveEraPrefs[]> =>
|
||||
api.derive.staking.erasHistoric(withActive).pipe(
|
||||
switchMap((eras) => api.derive.staking._erasPrefs(eras))
|
||||
switchMap((eras) => api.derive.staking._erasPrefs(eras, withActive))
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -10,25 +10,53 @@ import { Observable, of } from 'rxjs';
|
||||
import { map, switchMap } from 'rxjs/operators';
|
||||
import { Option } from '@polkadot/types';
|
||||
|
||||
import { memo } from '../util';
|
||||
import { deriveCache, memo } from '../util';
|
||||
|
||||
export function _erasRewards (api: ApiInterfaceRx): (eras: EraIndex[]) => Observable<DeriveEraRewards[]> {
|
||||
return memo((eras: EraIndex[]): Observable<DeriveEraRewards[]> =>
|
||||
eras.length
|
||||
? api.query.staking.erasValidatorReward.multi<Option<Balance>>(eras).pipe(
|
||||
map((rewards) => eras.map((era, index): DeriveEraRewards => ({
|
||||
era,
|
||||
eraReward: rewards[index].unwrapOrDefault()
|
||||
})))
|
||||
)
|
||||
: of([])
|
||||
);
|
||||
const CACHE_KEY = 'eraRewards';
|
||||
|
||||
function mapRewards (eras: EraIndex[], optRewards: Option<Balance>[]): DeriveEraRewards[] {
|
||||
return eras.map((era, index): DeriveEraRewards => ({
|
||||
era,
|
||||
eraReward: optRewards[index].unwrapOrDefault()
|
||||
}));
|
||||
}
|
||||
|
||||
export function _erasRewards (api: ApiInterfaceRx): (eras: EraIndex[], withActive: boolean) => Observable<DeriveEraRewards[]> {
|
||||
return memo((eras: EraIndex[], withActive: boolean): Observable<DeriveEraRewards[]> => {
|
||||
if (!eras.length) {
|
||||
return of([]);
|
||||
}
|
||||
|
||||
const cached: DeriveEraRewards[] = withActive
|
||||
? []
|
||||
: eras
|
||||
.map((era) => deriveCache.get<DeriveEraRewards>(`${CACHE_KEY}-${era.toString()}`))
|
||||
.filter((value): value is DeriveEraRewards => !!value);
|
||||
const remaining = eras.filter((era) => !cached.some((cached) => era.eq(cached.era)));
|
||||
|
||||
if (!remaining.length) {
|
||||
return of(cached);
|
||||
}
|
||||
|
||||
return api.query.staking.erasValidatorReward.multi<Option<Balance>>(remaining).pipe(
|
||||
map((optRewards) => {
|
||||
const query = mapRewards(remaining, optRewards);
|
||||
|
||||
!withActive && query.forEach((q) => deriveCache.set(`${CACHE_KEY}-${q.era.toString()}`, q));
|
||||
|
||||
return eras.map((era): DeriveEraRewards =>
|
||||
cached.find((cached) => era.eq(cached.era)) ||
|
||||
query.find((query) => era.eq(query.era)) as DeriveEraRewards
|
||||
);
|
||||
})
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
export function erasRewards (api: ApiInterfaceRx): (withActive?: boolean) => Observable<DeriveEraRewards[]> {
|
||||
return memo((withActive?: boolean): Observable<DeriveEraRewards[]> =>
|
||||
return memo((withActive = false): Observable<DeriveEraRewards[]> =>
|
||||
api.derive.staking.erasHistoric(withActive).pipe(
|
||||
switchMap((eras) => api.derive.staking._erasRewards(eras))
|
||||
switchMap((eras) => api.derive.staking._erasRewards(eras, withActive))
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -11,7 +11,9 @@ import { Observable, combineLatest, of } from 'rxjs';
|
||||
import { map, switchMap } from 'rxjs/operators';
|
||||
import { Option, StorageKey } from '@polkadot/types';
|
||||
|
||||
import { memo } from '../util';
|
||||
import { deriveCache, memo } from '../util';
|
||||
|
||||
const CACHE_KEY = 'eraSlashes';
|
||||
|
||||
function mapSlashes (era: EraIndex, noms: [StorageKey, Option<BalanceOf>][], vals: [StorageKey, Option<ITuple<[Perbill, BalanceOf]>>][]): DeriveEraSlashes {
|
||||
const nominators: DeriveEraValSlash = {};
|
||||
@@ -28,31 +30,50 @@ function mapSlashes (era: EraIndex, noms: [StorageKey, Option<BalanceOf>][], val
|
||||
return { era, nominators, validators };
|
||||
}
|
||||
|
||||
export function _eraSlashes (api: ApiInterfaceRx): (era: EraIndex, withActive: boolean) => Observable<DeriveEraSlashes> {
|
||||
return memo((era: EraIndex, withActive: boolean): Observable<DeriveEraSlashes> => {
|
||||
const cacheKey = `${CACHE_KEY}-${era.toString()}`;
|
||||
const cached = withActive
|
||||
? undefined
|
||||
: deriveCache.get<DeriveEraSlashes>(cacheKey);
|
||||
|
||||
return cached
|
||||
? of(cached)
|
||||
: combineLatest([
|
||||
api.query.staking.nominatorSlashInEra.entries(era),
|
||||
api.query.staking.validatorSlashInEra.entries(era)
|
||||
]).pipe(
|
||||
map(([noms, vals]): DeriveEraSlashes => {
|
||||
const value = mapSlashes(era, noms, vals);
|
||||
|
||||
!withActive && deriveCache.set(cacheKey, value);
|
||||
|
||||
return value;
|
||||
})
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
export function eraSlashes (api: ApiInterfaceRx): (era: EraIndex) => Observable<DeriveEraSlashes> {
|
||||
return memo((era: EraIndex): Observable<DeriveEraSlashes> =>
|
||||
combineLatest([
|
||||
api.query.staking.nominatorSlashInEra.entries(era),
|
||||
api.query.staking.validatorSlashInEra.entries(era)
|
||||
]).pipe(
|
||||
map(([noms, vals]) => mapSlashes(era, noms, vals))
|
||||
)
|
||||
api.derive.staking._eraSlashes(era, true)
|
||||
);
|
||||
}
|
||||
|
||||
export function _erasSlashes (api: ApiInterfaceRx): (eras: EraIndex[]) => Observable<DeriveEraSlashes[]> {
|
||||
return memo((eras: EraIndex[]): Observable<DeriveEraSlashes[]> =>
|
||||
export function _erasSlashes (api: ApiInterfaceRx): (eras: EraIndex[], withActive: boolean) => Observable<DeriveEraSlashes[]> {
|
||||
return memo((eras: EraIndex[], withActive: boolean): Observable<DeriveEraSlashes[]> =>
|
||||
eras.length
|
||||
? combineLatest(
|
||||
eras.map((era) => api.derive.staking.eraSlashes(era))
|
||||
eras.map((era) => api.derive.staking._eraSlashes(era, withActive))
|
||||
)
|
||||
: of([])
|
||||
);
|
||||
}
|
||||
|
||||
export function erasSlashes (api: ApiInterfaceRx): (withActive?: boolean) => Observable<DeriveEraSlashes[]> {
|
||||
return memo((withActive?: boolean): Observable<DeriveEraSlashes[]> =>
|
||||
return memo((withActive = false): Observable<DeriveEraSlashes[]> =>
|
||||
api.derive.staking.erasHistoric(withActive).pipe(
|
||||
switchMap((eras) => api.derive.staking._erasSlashes(eras))
|
||||
switchMap((eras) => api.derive.staking._erasSlashes(eras, withActive))
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -21,3 +21,4 @@ export * from './stakerRewards';
|
||||
export * from './stakerSlashes';
|
||||
export * from './stashes';
|
||||
export * from './validators';
|
||||
export * from './waitingInfo';
|
||||
|
||||
@@ -2,34 +2,62 @@
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the Apache-2.0 license. See the LICENSE file for details.
|
||||
|
||||
import { EraIndex, Exposure } from '@polkadot/types/interfaces';
|
||||
import { ApiInterfaceRx } from '@polkadot/api/types';
|
||||
import { DeriveOwnExposure } from '../types';
|
||||
|
||||
import { Observable, combineLatest, of } from 'rxjs';
|
||||
import { map, switchMap } from 'rxjs/operators';
|
||||
|
||||
import { memo } from '../util';
|
||||
import { deriveCache, memo } from '../util';
|
||||
|
||||
export function ownExposure (api: ApiInterfaceRx): (accountId: Uint8Array | string, withActive?: boolean) => Observable<DeriveOwnExposure[]> {
|
||||
return memo((accountId: Uint8Array | string, withActive?: boolean): Observable<DeriveOwnExposure[]> => {
|
||||
const CACHE_KEY = 'ownExposure';
|
||||
|
||||
export function _ownExposure (api: ApiInterfaceRx): (accountId: Uint8Array | string, era: EraIndex, withActive: boolean) => Observable<DeriveOwnExposure> {
|
||||
return memo((accountId: Uint8Array | string, era: EraIndex, withActive: boolean): Observable<DeriveOwnExposure> => {
|
||||
const cacheKey = `${CACHE_KEY}-${era.toString()}-${accountId.toString()}`;
|
||||
const cached = withActive
|
||||
? undefined
|
||||
: deriveCache.get<DeriveOwnExposure>(cacheKey);
|
||||
|
||||
return cached
|
||||
? of(cached)
|
||||
: api.queryMulti<[Exposure, Exposure]>([
|
||||
[api.query.staking.erasStakersClipped, [era, accountId]],
|
||||
[api.query.staking.erasStakers, [era, accountId]]
|
||||
]).pipe(
|
||||
map(([clipped, exposure]): DeriveOwnExposure => {
|
||||
const value = { clipped, era, exposure };
|
||||
|
||||
!withActive && deriveCache.set(cacheKey, value);
|
||||
|
||||
return value;
|
||||
})
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
export function ownExposure (api: ApiInterfaceRx): (accountId: Uint8Array | string, era: EraIndex) => Observable<DeriveOwnExposure> {
|
||||
return memo((accountId: Uint8Array | string, era: EraIndex): Observable<DeriveOwnExposure> =>
|
||||
api.derive.staking._ownExposure(accountId, era, true)
|
||||
);
|
||||
}
|
||||
|
||||
export function _ownExposures (api: ApiInterfaceRx): (accountId: Uint8Array | string, eras: EraIndex[], withActive: boolean) => Observable<DeriveOwnExposure[]> {
|
||||
return memo((accountId: Uint8Array | string, eras: EraIndex[], withActive: boolean): Observable<DeriveOwnExposure[]> =>
|
||||
eras.length
|
||||
? combineLatest(
|
||||
eras.map((era) => api.derive.staking._ownExposure(accountId, era, withActive))
|
||||
)
|
||||
: of([])
|
||||
);
|
||||
}
|
||||
|
||||
export function ownExposures (api: ApiInterfaceRx): (accountId: Uint8Array | string, withActive?: boolean) => Observable<DeriveOwnExposure[]> {
|
||||
return memo((accountId: Uint8Array | string, withActive = false): Observable<DeriveOwnExposure[]> => {
|
||||
return api.derive.staking.erasHistoric(withActive).pipe(
|
||||
switchMap((eras) =>
|
||||
eras.length
|
||||
? combineLatest(
|
||||
eras.map((era) => combineLatest([
|
||||
of(era),
|
||||
api.query.staking.erasStakersClipped(era, accountId),
|
||||
api.query.staking.erasStakers(era, accountId)
|
||||
]))
|
||||
)
|
||||
: of([])
|
||||
),
|
||||
map((result): DeriveOwnExposure[] =>
|
||||
result.map(([era, clipped, exposure]): DeriveOwnExposure => ({
|
||||
clipped,
|
||||
era,
|
||||
exposure
|
||||
}))
|
||||
api.derive.staking._ownExposures(accountId, eras, withActive)
|
||||
)
|
||||
);
|
||||
});
|
||||
|
||||
@@ -3,34 +3,68 @@
|
||||
// of the Apache-2.0 license. See the LICENSE file for details.
|
||||
|
||||
import { ApiInterfaceRx } from '@polkadot/api/types';
|
||||
import { BalanceOf, EraIndex, Perbill } from '@polkadot/types/interfaces';
|
||||
import { ITuple } from '@polkadot/types/types';
|
||||
import { DeriveStakerSlashes } from '../types';
|
||||
|
||||
import { Observable, combineLatest, of } from 'rxjs';
|
||||
import { map, switchMap } from 'rxjs/operators';
|
||||
import { Option } from '@polkadot/types';
|
||||
|
||||
import { memo } from '../util';
|
||||
import { deriveCache, memo } from '../util';
|
||||
|
||||
const CACHE_KEY = 'ownSlash';
|
||||
|
||||
export function _ownSlash (api: ApiInterfaceRx): (accountId: Uint8Array | string, era: EraIndex, withActive: boolean) => Observable<DeriveStakerSlashes> {
|
||||
return memo((accountId: Uint8Array | string, era: EraIndex, withActive: boolean): Observable<DeriveStakerSlashes> => {
|
||||
const cacheKey = `${CACHE_KEY}-${era.toString()}-${accountId.toString()}`;
|
||||
const cached = withActive
|
||||
? undefined
|
||||
: deriveCache.get<DeriveStakerSlashes>(cacheKey);
|
||||
|
||||
return cached
|
||||
? of(cached)
|
||||
: api.queryMulti<[Option<BalanceOf>, Option<ITuple<[Perbill, BalanceOf]>>]>([
|
||||
[api.query.staking.nominatorSlashInEra, [era, accountId]],
|
||||
[api.query.staking.validatorSlashInEra, [era, accountId]]
|
||||
]).pipe(
|
||||
map(([optNom, optVal]): DeriveStakerSlashes => {
|
||||
const value = {
|
||||
era,
|
||||
total: optVal.isSome
|
||||
? optVal.unwrap()[1]
|
||||
: optNom.unwrapOrDefault()
|
||||
};
|
||||
|
||||
!withActive && deriveCache.set(cacheKey, value);
|
||||
|
||||
return value;
|
||||
})
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
export function ownSlash (api: ApiInterfaceRx): (accountId: Uint8Array | string, era: EraIndex) => Observable<DeriveStakerSlashes> {
|
||||
return memo((accountId: Uint8Array | string, era: EraIndex): Observable<DeriveStakerSlashes> =>
|
||||
api.derive.staking._ownSlash(accountId, era, true)
|
||||
);
|
||||
}
|
||||
|
||||
export function _ownSlashes (api: ApiInterfaceRx): (accountId: Uint8Array | string, eras: EraIndex[], withActive: boolean) => Observable<DeriveStakerSlashes[]> {
|
||||
return memo((accountId: Uint8Array | string, eras: EraIndex[], withActive: boolean): Observable<DeriveStakerSlashes[]> =>
|
||||
eras.length
|
||||
? combineLatest(
|
||||
eras.map((era) => api.derive.staking._ownSlash(accountId, era, withActive))
|
||||
)
|
||||
: of([])
|
||||
);
|
||||
}
|
||||
|
||||
export function ownSlashes (api: ApiInterfaceRx): (accountId: Uint8Array | string, withActive?: boolean) => Observable<DeriveStakerSlashes[]> {
|
||||
return memo((accountId: Uint8Array | string, withActive?: boolean): Observable<DeriveStakerSlashes[]> => {
|
||||
return memo((accountId: Uint8Array | string, withActive = false): Observable<DeriveStakerSlashes[]> => {
|
||||
return api.derive.staking.erasHistoric(withActive).pipe(
|
||||
switchMap((eras) =>
|
||||
eras.length
|
||||
? combineLatest(
|
||||
eras.map((era) => combineLatest([
|
||||
of(era),
|
||||
api.query.staking.nominatorSlashInEra(era, accountId),
|
||||
api.query.staking.validatorSlashInEra(era, accountId)
|
||||
]))
|
||||
)
|
||||
: of([])
|
||||
),
|
||||
map((result): DeriveStakerSlashes[] =>
|
||||
result.map(([era, optNom, optVal]): DeriveStakerSlashes => ({
|
||||
era,
|
||||
total: optVal.isSome
|
||||
? optVal.unwrap()[1]
|
||||
: optNom.unwrapOrDefault()
|
||||
}))
|
||||
api.derive.staking._ownSlashes(accountId, eras, withActive)
|
||||
)
|
||||
);
|
||||
});
|
||||
|
||||
@@ -3,19 +3,20 @@
|
||||
// of the Apache-2.0 license. See the LICENSE file for details.
|
||||
|
||||
import { ApiInterfaceRx } from '@polkadot/api/types';
|
||||
import { AccountId, Exposure, Keys, Nominations, RewardDestination, ValidatorPrefs } from '@polkadot/types/interfaces';
|
||||
import { AccountId, EraIndex, Exposure, Keys, Nominations, RewardDestination, StakingLedger, ValidatorPrefs } from '@polkadot/types/interfaces';
|
||||
import { ITuple } from '@polkadot/types/types';
|
||||
import { DeriveStakingQuery } from '../types';
|
||||
|
||||
import { Observable, combineLatest, of } from 'rxjs';
|
||||
import { map, switchMap } from 'rxjs/operators';
|
||||
import { Option, Vec } from '@polkadot/types';
|
||||
import { isFunction } from '@polkadot/util';
|
||||
|
||||
import { memo } from '../util';
|
||||
|
||||
type MultiResult = [Option<AccountId>, Option<ITuple<[Nominations]> | Nominations>, RewardDestination, ITuple<[ValidatorPrefs]> | ValidatorPrefs, Option<Keys>, Exposure];
|
||||
|
||||
function unwrapSessionIds (stashId: AccountId, queuedKeys: [AccountId, Keys][], nextKeys: Option<Keys>): { nextSessionIds: AccountId[]; sessionIds: AccountId[] } {
|
||||
function parseSessionIds (stashId: AccountId, queuedKeys: [AccountId, Keys][], nextKeys: Option<Keys>): { nextSessionIds: AccountId[]; sessionIds: AccountId[] } {
|
||||
const sessionIds = (queuedKeys.find(([currentId]): boolean =>
|
||||
currentId.eq(stashId)
|
||||
) || [undefined, [] as AccountId[]])[1];
|
||||
@@ -27,6 +28,31 @@ function unwrapSessionIds (stashId: AccountId, queuedKeys: [AccountId, Keys][],
|
||||
};
|
||||
}
|
||||
|
||||
function parseController (stashId: AccountId, queuedKeys: Vec<ITuple<[AccountId, Keys]>>, [controllerIdOpt, nominatorsOpt, rewardDestination, validatorPrefs, nextKeys, exposure]: MultiResult, stakingLedgerOpt: Option<StakingLedger>): DeriveStakingQuery {
|
||||
const controllerId = controllerIdOpt.unwrapOr(null);
|
||||
const nominators = nominatorsOpt.unwrapOr(null);
|
||||
|
||||
return controllerId && stakingLedgerOpt.isSome
|
||||
? {
|
||||
accountId: stashId,
|
||||
controllerId,
|
||||
exposure,
|
||||
nominators: nominators
|
||||
? Array.isArray(nominators)
|
||||
? nominators[0].targets
|
||||
: nominators.targets
|
||||
: [],
|
||||
rewardDestination,
|
||||
stakingLedger: stakingLedgerOpt.unwrapOr(undefined),
|
||||
stashId,
|
||||
validatorPrefs: Array.isArray(validatorPrefs)
|
||||
? validatorPrefs[0]
|
||||
: validatorPrefs,
|
||||
...parseSessionIds(stashId, queuedKeys, nextKeys)
|
||||
}
|
||||
: { accountId: stashId, nextSessionIds: [], sessionIds: [] };
|
||||
}
|
||||
|
||||
function retrievePrev (api: ApiInterfaceRx, stashId: AccountId): Observable<MultiResult> {
|
||||
return api.queryMulti<MultiResult>([
|
||||
[api.query.staking.bonded, stashId],
|
||||
@@ -38,64 +64,43 @@ function retrievePrev (api: ApiInterfaceRx, stashId: AccountId): Observable<Mult
|
||||
]);
|
||||
}
|
||||
|
||||
function retrieveCurr (api: ApiInterfaceRx, stashId: AccountId): Observable<MultiResult> {
|
||||
return api.derive.session.indexes().pipe(
|
||||
switchMap(({ activeEra }) =>
|
||||
api.queryMulti<MultiResult>([
|
||||
[api.query.staking.bonded, stashId],
|
||||
[api.query.staking.nominators, stashId],
|
||||
[api.query.staking.payee, stashId],
|
||||
[api.query.staking.validators, stashId],
|
||||
api.consts.session?.dedupKeyPrefix
|
||||
? [api.query.session.nextKeys, [api.consts.session.dedupKeyPrefix, stashId]]
|
||||
: [api.query.session.nextKeys, stashId],
|
||||
[api.query.staking.erasStakers, [activeEra, stashId]]
|
||||
])
|
||||
function retrieveCurr (api: ApiInterfaceRx, stashIds: AccountId[], activeEra: EraIndex): Observable<MultiResult[]> {
|
||||
return combineLatest([
|
||||
api.query.staking.bonded.multi<Option<AccountId>>(stashIds),
|
||||
api.query.staking.nominators.multi<Option<Nominations>>(stashIds),
|
||||
api.query.staking.payee.multi<RewardDestination>(stashIds),
|
||||
api.query.staking.validators.multi<ValidatorPrefs>(stashIds),
|
||||
api.consts.session?.dedupKeyPrefix
|
||||
? api.query.session.nextKeys.multi<Option<Keys>>(stashIds.map((stashId) => [api.consts.session.dedupKeyPrefix, stashId]))
|
||||
: api.query.session.nextKeys.multi<Option<Keys>>(stashIds),
|
||||
api.query.staking.erasStakers.multi<Exposure>(stashIds.map((stashId) => [activeEra, stashId]))
|
||||
]).pipe(
|
||||
map(([controllerIdOpt, nominatorsOpt, rewardDestination, validatorPrefs, nextKeys, exposure]): MultiResult[] =>
|
||||
controllerIdOpt.map((controllerIdOpt, index): MultiResult =>
|
||||
[controllerIdOpt, nominatorsOpt[index], rewardDestination[index], validatorPrefs[index], nextKeys[index], exposure[index]]
|
||||
)
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
function retrieveController (api: ApiInterfaceRx, stashId: AccountId, queuedKeys: Vec<ITuple<[AccountId, Keys]>>, [controllerIdOpt, nominatorsOpt, rewardDestination, validatorPrefs, nextKeys, exposure]: MultiResult): Observable<DeriveStakingQuery> {
|
||||
const controllerId = controllerIdOpt.unwrapOr(null);
|
||||
const nominators = nominatorsOpt.unwrapOr(null);
|
||||
function retrieveControllers (api: ApiInterfaceRx, optControllerIds: Option<AccountId>[]): Observable<Option<StakingLedger>[]> {
|
||||
const ids = optControllerIds.filter((opt) => opt.isSome).map((opt) => opt.unwrap());
|
||||
|
||||
return controllerId
|
||||
? api.query.staking.ledger(controllerId).pipe(
|
||||
map((stakingLedgerOpt): DeriveStakingQuery => ({
|
||||
accountId: stashId,
|
||||
controllerId,
|
||||
exposure,
|
||||
nominators: nominators
|
||||
? Array.isArray(nominators)
|
||||
? nominators[0].targets
|
||||
: nominators.targets
|
||||
: [],
|
||||
rewardDestination,
|
||||
stakingLedger: stakingLedgerOpt.unwrapOr(undefined),
|
||||
stashId,
|
||||
validatorPrefs: Array.isArray(validatorPrefs)
|
||||
? validatorPrefs[0]
|
||||
: validatorPrefs,
|
||||
...unwrapSessionIds(stashId, queuedKeys, nextKeys)
|
||||
}))
|
||||
)
|
||||
: of({ accountId: stashId, nextSessionIds: [], sessionIds: [] });
|
||||
}
|
||||
if (!ids.length) {
|
||||
return of(optControllerIds.map(() => api.registry.createType('Option<StakingLedger>')));
|
||||
}
|
||||
|
||||
export function queryWithQueued (api: ApiInterfaceRx): (accountId: Uint8Array | string, queuedKeys: Vec<ITuple<[AccountId, Keys]>>) => Observable<DeriveStakingQuery> {
|
||||
return memo((accountId: Uint8Array | string, queuedKeys: Vec<ITuple<[AccountId, Keys]>>): Observable<DeriveStakingQuery> => {
|
||||
const stashId = api.registry.createType('AccountId', accountId);
|
||||
return api.query.staking.ledger.multi<Option<StakingLedger>>(ids).pipe(
|
||||
map((optLedgers): Option<StakingLedger>[] => {
|
||||
let offset = -1;
|
||||
|
||||
return (
|
||||
api.query.staking.erasStakers
|
||||
? retrieveCurr(api, stashId)
|
||||
: retrievePrev(api, stashId)
|
||||
).pipe(
|
||||
switchMap((result): Observable<DeriveStakingQuery> =>
|
||||
retrieveController(api, stashId, queuedKeys, result)
|
||||
)
|
||||
);
|
||||
});
|
||||
return optControllerIds.map((opt): Option<StakingLedger> =>
|
||||
opt.isSome
|
||||
? optLedgers[++offset]
|
||||
: api.registry.createType('Option<StakingLedger>')
|
||||
);
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -103,8 +108,8 @@ export function queryWithQueued (api: ApiInterfaceRx): (accountId: Uint8Array |
|
||||
*/
|
||||
export function query (api: ApiInterfaceRx): (accountId: Uint8Array | string) => Observable<DeriveStakingQuery> {
|
||||
return memo((accountId: Uint8Array | string): Observable<DeriveStakingQuery> =>
|
||||
api.query.session.queuedKeys<Vec<ITuple<[AccountId, Keys]>>>().pipe(
|
||||
switchMap((queuedKeys) => api.derive.staking.queryWithQueued(accountId, queuedKeys))
|
||||
api.derive.staking.queryMulti([accountId]).pipe(
|
||||
map(([first]) => first)
|
||||
)
|
||||
);
|
||||
}
|
||||
@@ -112,10 +117,27 @@ export function query (api: ApiInterfaceRx): (accountId: Uint8Array | string) =>
|
||||
export function queryMulti (api: ApiInterfaceRx): (accountIds: (Uint8Array | string)[]) => Observable<DeriveStakingQuery[]> {
|
||||
return memo((accountIds: (Uint8Array | string)[]): Observable<DeriveStakingQuery[]> =>
|
||||
accountIds.length
|
||||
? api.query.session.queuedKeys<Vec<ITuple<[AccountId, Keys]>>>().pipe(
|
||||
switchMap((queuedKeys) => combineLatest(
|
||||
accountIds.map((acc) => api.derive.staking.queryWithQueued(acc, queuedKeys))
|
||||
))
|
||||
? combineLatest([
|
||||
api.query.session.queuedKeys<Vec<ITuple<[AccountId, Keys]>>>(),
|
||||
api.derive.session.indexes()
|
||||
]).pipe(
|
||||
switchMap(([queuedKeys, { activeEra }]): Observable<DeriveStakingQuery[]> => {
|
||||
const stashIds = accountIds.map((accountId) => api.registry.createType('AccountId', accountId));
|
||||
|
||||
return (
|
||||
isFunction(api.query.staking.erasStakers)
|
||||
? retrieveCurr(api, stashIds, activeEra)
|
||||
: combineLatest(stashIds.map((stashId) => retrievePrev(api, stashId)))
|
||||
).pipe(
|
||||
switchMap((results): Observable<DeriveStakingQuery[]> =>
|
||||
retrieveControllers(api, results.map(([optController]) => optController)).pipe(
|
||||
map((stakingLedgerOpts) =>
|
||||
stashIds.map((stashId, index) => parseController(stashId, queuedKeys, results[index], stakingLedgerOpts[index]))
|
||||
)
|
||||
)
|
||||
)
|
||||
);
|
||||
})
|
||||
)
|
||||
: of([])
|
||||
);
|
||||
|
||||
@@ -11,11 +11,11 @@ import { map, switchMap } from 'rxjs/operators';
|
||||
|
||||
import { memo } from '../util';
|
||||
|
||||
export function _stakerExposure (api: ApiInterfaceRx): (accountId: Uint8Array | string, eras: EraIndex[]) => Observable<DeriveStakerExposure[]> {
|
||||
return memo((accountId: Uint8Array | string, eras: EraIndex[]): Observable<DeriveStakerExposure[]> => {
|
||||
export function _stakerExposure (api: ApiInterfaceRx): (accountId: Uint8Array | string, eras: EraIndex[], withActive: boolean) => Observable<DeriveStakerExposure[]> {
|
||||
return memo((accountId: Uint8Array | string, eras: EraIndex[], withActive: boolean): Observable<DeriveStakerExposure[]> => {
|
||||
const stakerId = api.registry.createType('AccountId', accountId).toString();
|
||||
|
||||
return api.derive.staking._erasExposure(eras).pipe(
|
||||
return api.derive.staking._erasExposure(eras, withActive).pipe(
|
||||
map((exposures): DeriveStakerExposure[] =>
|
||||
exposures.map(({ era, nominators: allNominators, validators: allValidators }): DeriveStakerExposure => {
|
||||
const isValidator = !!allValidators[stakerId];
|
||||
@@ -38,9 +38,9 @@ export function _stakerExposure (api: ApiInterfaceRx): (accountId: Uint8Array |
|
||||
}
|
||||
|
||||
export function stakerExposure (api: ApiInterfaceRx): (accountId: Uint8Array | string, withActive?: boolean) => Observable<DeriveStakerExposure[]> {
|
||||
return memo((accountId: Uint8Array | string, withActive?: boolean): Observable<DeriveStakerExposure[]> =>
|
||||
return memo((accountId: Uint8Array | string, withActive = false): Observable<DeriveStakerExposure[]> =>
|
||||
api.derive.staking.erasHistoric(withActive).pipe(
|
||||
switchMap((eras) => api.derive.staking._stakerExposure(accountId, eras))
|
||||
switchMap((eras) => api.derive.staking._stakerExposure(accountId, eras, withActive))
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -11,11 +11,11 @@ import { map, switchMap } from 'rxjs/operators';
|
||||
|
||||
import { memo } from '../util';
|
||||
|
||||
export function _stakerPoints (api: ApiInterfaceRx): (accountId: Uint8Array | string, eras: EraIndex[]) => Observable<DeriveStakerPoints[]> {
|
||||
return memo((accountId: Uint8Array | string, eras: EraIndex[]): Observable<DeriveStakerPoints[]> => {
|
||||
export function _stakerPoints (api: ApiInterfaceRx): (accountId: Uint8Array | string, eras: EraIndex[], withActive: boolean) => Observable<DeriveStakerPoints[]> {
|
||||
return memo((accountId: Uint8Array | string, eras: EraIndex[], withActive: boolean): Observable<DeriveStakerPoints[]> => {
|
||||
const stakerId = api.registry.createType('AccountId', accountId).toString();
|
||||
|
||||
return api.derive.staking._erasPoints(eras).pipe(
|
||||
return api.derive.staking._erasPoints(eras, withActive).pipe(
|
||||
map((points): DeriveStakerPoints[] =>
|
||||
points.map(({ era, eraPoints, validators }): DeriveStakerPoints => ({
|
||||
era,
|
||||
@@ -28,9 +28,9 @@ export function _stakerPoints (api: ApiInterfaceRx): (accountId: Uint8Array | st
|
||||
}
|
||||
|
||||
export function stakerPoints (api: ApiInterfaceRx): (accountId: Uint8Array | string, withActive?: boolean) => Observable<DeriveStakerPoints[]> {
|
||||
return memo((accountId: Uint8Array | string, withActive?: boolean): Observable<DeriveStakerPoints[]> =>
|
||||
return memo((accountId: Uint8Array | string, withActive = false): Observable<DeriveStakerPoints[]> =>
|
||||
api.derive.staking.erasHistoric(withActive).pipe(
|
||||
switchMap((eras) => api.derive.staking._stakerPoints(accountId, eras))
|
||||
switchMap((eras) => api.derive.staking._stakerPoints(accountId, eras, withActive))
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -10,17 +10,18 @@ import BN from 'bn.js';
|
||||
import { Observable, combineLatest, of } from 'rxjs';
|
||||
import { map, switchMap } from 'rxjs/operators';
|
||||
import { Option } from '@polkadot/types';
|
||||
import { isFunction } from '@polkadot/util';
|
||||
|
||||
import { memo } from '../util';
|
||||
|
||||
type Result = [DeriveEraPoints[], DeriveEraPrefs[], DeriveEraRewards[], DeriveStakerExposure[]];
|
||||
type ErasResult = [{ unwrapOr: (value: BN) => BN }, DeriveEraPoints[], DeriveEraPrefs[], DeriveEraRewards[]];
|
||||
|
||||
const ZERO = new BN(0);
|
||||
const MIN_ONE = new BN(-1);
|
||||
const COMM_DIV = new BN(1_000_000_000);
|
||||
const MAX_ERAS = new BN(1_000_000_000);
|
||||
|
||||
function parseRewards (api: ApiInterfaceRx, stashId: AccountId, [erasPoints, erasPrefs, erasRewards, exposures]: Result): DeriveStakerReward[] {
|
||||
function parseRewards (api: ApiInterfaceRx, stashId: AccountId, [, erasPoints, erasPrefs, erasRewards]: ErasResult, exposures: DeriveStakerExposure[]): DeriveStakerReward[] {
|
||||
return exposures.map(({ era, isEmpty, isValidator, nominating, validators: eraValidators }): DeriveStakerReward => {
|
||||
const { eraPoints, validators: allValPoints } = erasPoints.find((p) => p.era.eq(era)) || { eraPoints: ZERO, validators: {} };
|
||||
const { eraReward } = erasRewards.find((r) => r.era.eq(era)) || { eraReward: api.registry.createType('Balance') };
|
||||
@@ -31,25 +32,27 @@ function parseRewards (api: ApiInterfaceRx, stashId: AccountId, [erasPoints, era
|
||||
Object.entries(eraValidators).forEach(([validatorId, exposure]): void => {
|
||||
const valPoints = allValPoints[validatorId] || ZERO;
|
||||
const valComm = allValPrefs[validatorId]?.commission.unwrap() || ZERO;
|
||||
const avail = eraReward.mul(valPoints).div(eraPoints);
|
||||
const valCut = valComm.mul(avail).div(COMM_DIV);
|
||||
const expTotal = exposure.total.unwrap();
|
||||
let avail = ZERO;
|
||||
let value: BN | undefined;
|
||||
|
||||
if (!expTotal.isZero() && !valPoints.isZero()) {
|
||||
if (!(expTotal.isZero() || valPoints.isZero() || eraPoints.isZero())) {
|
||||
avail = eraReward.mul(valPoints).div(eraPoints);
|
||||
|
||||
const valCut = valComm.mul(avail).div(COMM_DIV);
|
||||
let staked: BN;
|
||||
|
||||
if (validatorId === stakerId) {
|
||||
staked = exposure.own.unwrap();
|
||||
} else {
|
||||
const stakerExp = exposure.others.find(({ who }): boolean => who.eq(stakerId));
|
||||
const stakerExp = exposure.others.find(({ who }) => who.eq(stakerId));
|
||||
|
||||
staked = stakerExp
|
||||
? stakerExp.value.unwrap()
|
||||
: ZERO;
|
||||
}
|
||||
|
||||
value = avail.sub(valCut).mul(staked).div(expTotal).add(validatorId === stakerId ? valCut : ZERO);
|
||||
value = avail.sub(valCut).imul(staked).div(expTotal).iadd(validatorId === stakerId ? valCut : ZERO);
|
||||
}
|
||||
|
||||
validators[validatorId] = {
|
||||
@@ -97,28 +100,29 @@ function filterEras (eras: EraIndex[], stakingLedger: StakingLedger): EraIndex[]
|
||||
return eras.filter((era) => filterEra(era, stakingLedger));
|
||||
}
|
||||
|
||||
function filterRewards (api: ApiInterfaceRx, rewards: DeriveStakerReward[], stakingLedger: StakingLedger, withActive?: boolean): Observable<DeriveStakerReward[]> {
|
||||
function filterRewards (api: ApiInterfaceRx, eras: EraIndex[], migrateEra: BN, rewards: DeriveStakerReward[], stakingLedger: StakingLedger, withActive: boolean): Observable<DeriveStakerReward[]> {
|
||||
if (withActive) {
|
||||
return of(rewards);
|
||||
}
|
||||
|
||||
const validators = uniqValidators(rewards);
|
||||
|
||||
return combineLatest([
|
||||
api.query.staking.migrateEra
|
||||
? api.query.staking.migrateEra<Option<EraIndex>>()
|
||||
: of({ unwrapOr: () => api.tx.staking.payoutStakers ? ZERO : MAX_ERAS }),
|
||||
api.tx.staking.payoutStakers
|
||||
return (
|
||||
isFunction(api.tx.staking.payoutStakers)
|
||||
? api.derive.staking.queryMulti(validators)
|
||||
: of([])
|
||||
]).pipe(
|
||||
map(([optMigrate, queryValidators]): DeriveStakerReward[] => {
|
||||
const migrateEra: BN = optMigrate.unwrapOr(ZERO);
|
||||
).pipe(
|
||||
map((queryValidators): DeriveStakerReward[] => {
|
||||
const filter = withActive
|
||||
? eras
|
||||
: filterEras(eras, stakingLedger);
|
||||
|
||||
return rewards
|
||||
.filter(({ isEmpty }) => !isEmpty)
|
||||
.filter((reward): boolean => {
|
||||
if (reward.era.lt(migrateEra)) {
|
||||
if (!filter.some((filter) => reward.era.eq(filter))) {
|
||||
return false;
|
||||
} else if (reward.era.lt(migrateEra)) {
|
||||
// we filter again here, the actual ledger may have changed, e.g. something has been claimed
|
||||
return filterEra(reward.era, stakingLedger);
|
||||
}
|
||||
@@ -154,49 +158,59 @@ function filterRewards (api: ApiInterfaceRx, rewards: DeriveStakerReward[], stak
|
||||
);
|
||||
}
|
||||
|
||||
export function _stakerRewards (api: ApiInterfaceRx): (accountId: Uint8Array | string, eras: EraIndex[], withActive?: boolean) => Observable<DeriveStakerReward[]> {
|
||||
return memo((accountId: Uint8Array | string, _eras: EraIndex[], withActive?: boolean): Observable<DeriveStakerReward[]> =>
|
||||
api.derive.staking.query(accountId).pipe(
|
||||
switchMap(({ stakingLedger, stashId }): Observable<DeriveStakerReward[]> => {
|
||||
export function _stakerRewardsEras (api: ApiInterfaceRx): (eras: EraIndex[], withActive: boolean) => Observable<ErasResult> {
|
||||
return memo((eras: EraIndex[], withActive: boolean): Observable<ErasResult> =>
|
||||
combineLatest([
|
||||
isFunction(api.query.staking.migrateEra)
|
||||
? api.query.staking.migrateEra<Option<EraIndex>>()
|
||||
: of({ unwrapOr: () => isFunction(api.tx.staking.payoutStakers) ? ZERO : MAX_ERAS }),
|
||||
api.derive.staking._erasPoints(eras, withActive),
|
||||
api.derive.staking._erasPrefs(eras, withActive),
|
||||
api.derive.staking._erasRewards(eras, withActive)
|
||||
])
|
||||
);
|
||||
}
|
||||
|
||||
export function _stakerRewards (api: ApiInterfaceRx): (accountId: Uint8Array | string, eras: EraIndex[], withActive: boolean) => Observable<DeriveStakerReward[]> {
|
||||
return memo((accountId: Uint8Array | string, eras: EraIndex[], withActive: boolean): Observable<DeriveStakerReward[]> =>
|
||||
combineLatest([
|
||||
api.derive.staking.query(accountId),
|
||||
api.derive.staking._stakerExposure(accountId, eras, withActive),
|
||||
api.derive.staking._stakerRewardsEras(eras, withActive)
|
||||
]).pipe(
|
||||
switchMap(([{ stakingLedger, stashId }, exposures, erasResult]): Observable<DeriveStakerReward[]> => {
|
||||
const migrateEra: BN = erasResult[0].unwrapOr(ZERO);
|
||||
|
||||
if (!stashId || !stakingLedger) {
|
||||
return of([]);
|
||||
}
|
||||
|
||||
const eras = withActive
|
||||
? _eras
|
||||
: filterEras(_eras, stakingLedger);
|
||||
|
||||
return combineLatest([
|
||||
api.derive.staking._erasPoints(eras),
|
||||
api.derive.staking._erasPrefs(eras),
|
||||
api.derive.staking._erasRewards(eras),
|
||||
api.derive.staking._stakerExposure(stashId, eras)
|
||||
]).pipe(
|
||||
switchMap((result): Observable<DeriveStakerReward[]> =>
|
||||
filterRewards(api, parseRewards(api, stashId, result), stakingLedger, withActive)
|
||||
)
|
||||
);
|
||||
return filterRewards(api, eras, migrateEra, parseRewards(api, stashId, erasResult, exposures), stakingLedger, withActive);
|
||||
})
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
export function stakerRewards (api: ApiInterfaceRx): (accountId: Uint8Array | string, withActive?: boolean) => Observable<DeriveStakerReward[]> {
|
||||
return memo((accountId: Uint8Array | string, withActive?: boolean): Observable<DeriveStakerReward[]> =>
|
||||
return memo((accountId: Uint8Array | string, withActive = false): Observable<DeriveStakerReward[]> =>
|
||||
api.derive.staking.erasHistoric(withActive).pipe(
|
||||
switchMap((eras) => api.derive.staking._stakerRewards(accountId, eras, withActive))
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
export function stakerRewardsMulti (api: ApiInterfaceRx): (accountIds: (Uint8Array | string)[], withActive?: boolean) => Observable<DeriveStakerReward[][]> {
|
||||
return memo((accountIds: (Uint8Array | string)[], withActive?: boolean): Observable<DeriveStakerReward[][]> =>
|
||||
accountIds.length
|
||||
? api.derive.staking.erasHistoric(withActive).pipe(
|
||||
switchMap((eras) =>
|
||||
combineLatest(accountIds.map((acc) => api.derive.staking._stakerRewards(acc, eras, withActive)))
|
||||
)
|
||||
)
|
||||
export function stakerRewardsMultiEras (api: ApiInterfaceRx): (accountIds: (Uint8Array | string)[], eras: EraIndex[]) => Observable<DeriveStakerReward[][]> {
|
||||
return memo((accountIds: (Uint8Array | string)[], eras: EraIndex[]): Observable<DeriveStakerReward[][]> =>
|
||||
accountIds.length && eras.length
|
||||
? combineLatest(accountIds.map((acc) => api.derive.staking._stakerRewards(acc, eras, false)))
|
||||
: of([])
|
||||
);
|
||||
}
|
||||
|
||||
export function stakerRewardsMulti (api: ApiInterfaceRx): (accountIds: (Uint8Array | string)[], withActive?: boolean) => Observable<DeriveStakerReward[][]> {
|
||||
return memo((accountIds: (Uint8Array | string)[], withActive = false): Observable<DeriveStakerReward[][]> =>
|
||||
api.derive.staking.erasHistoric(withActive).pipe(
|
||||
switchMap((eras) => api.derive.staking.stakerRewardsMultiEras(accountIds, eras))
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -11,11 +11,11 @@ import { map, switchMap } from 'rxjs/operators';
|
||||
|
||||
import { memo } from '../util';
|
||||
|
||||
export function _stakerSlashes (api: ApiInterfaceRx): (accountId: Uint8Array | string, eras: EraIndex[]) => Observable<DeriveStakerSlashes[]> {
|
||||
return memo((accountId: Uint8Array | string, eras: EraIndex[]): Observable<DeriveStakerSlashes[]> => {
|
||||
export function _stakerSlashes (api: ApiInterfaceRx): (accountId: Uint8Array | string, eras: EraIndex[], withActive: boolean) => Observable<DeriveStakerSlashes[]> {
|
||||
return memo((accountId: Uint8Array | string, eras: EraIndex[], withActive: boolean): Observable<DeriveStakerSlashes[]> => {
|
||||
const stakerId = api.registry.createType('AccountId', accountId).toString();
|
||||
|
||||
return api.derive.staking._erasSlashes(eras).pipe(
|
||||
return api.derive.staking._erasSlashes(eras, withActive).pipe(
|
||||
map((slashes): DeriveStakerSlashes[] =>
|
||||
slashes.map(({ era, nominators, validators }): DeriveStakerSlashes => ({
|
||||
era,
|
||||
@@ -27,9 +27,9 @@ export function _stakerSlashes (api: ApiInterfaceRx): (accountId: Uint8Array | s
|
||||
}
|
||||
|
||||
export function stakerSlashes (api: ApiInterfaceRx): (accountId: Uint8Array | string, withActive?: boolean) => Observable<DeriveStakerSlashes[]> {
|
||||
return memo((accountId: Uint8Array | string, withActive?: boolean): Observable<DeriveStakerSlashes[]> =>
|
||||
return memo((accountId: Uint8Array | string, withActive = false): Observable<DeriveStakerSlashes[]> =>
|
||||
api.derive.staking.erasHistoric(withActive).pipe(
|
||||
switchMap((eras) => api.derive.staking._stakerSlashes(accountId, eras))
|
||||
switchMap((eras) => api.derive.staking._stakerSlashes(accountId, eras, withActive))
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -2,11 +2,10 @@
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the Apache-2.0 license. See the LICENSE file for details.
|
||||
|
||||
import type BN from 'bn.js';
|
||||
import { AccountId, Balance, EraIndex, Exposure, Keys, RewardDestination, RewardPoint, StakingLedger, ValidatorPrefs } from '@polkadot/types/interfaces';
|
||||
import { DeriveSessionIndexes } from '../session/types';
|
||||
|
||||
import BN from 'bn.js';
|
||||
|
||||
export type DeriveEraValPoints = Record<string, RewardPoint>;
|
||||
|
||||
export type DeriveEraValPrefs = Record<string, ValidatorPrefs>;
|
||||
@@ -97,6 +96,11 @@ export interface DeriveStakingElected {
|
||||
info: DeriveStakingQuery[];
|
||||
}
|
||||
|
||||
export interface DeriveStakingWaiting {
|
||||
info: DeriveStakingQuery[];
|
||||
waiting: AccountId[];
|
||||
}
|
||||
|
||||
export interface DeriveStakingValidators {
|
||||
nextElected: AccountId[];
|
||||
validators: AccountId[];
|
||||
|
||||
@@ -18,9 +18,7 @@ export function nextElected (api: ApiInterfaceRx): () => Observable<AccountId[]>
|
||||
// only populate for next era in the last session, so track both here - entries are not
|
||||
// subscriptions, so we need a trigger - currentIndex acts as that trigger to refresh
|
||||
switchMap(({ currentEra }) => api.query.staking.erasStakers.keys(currentEra)),
|
||||
map((keys): AccountId[] =>
|
||||
keys.map((key): AccountId => key.args[1] as AccountId)
|
||||
)
|
||||
map((keys) => keys.map((key) => key.args[1] as AccountId))
|
||||
)
|
||||
: api.query.staking.currentElected<AccountId[]>()
|
||||
);
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
// Copyright 2017-2020 @polkadot/api-derive authors & contributors
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the Apache-2.0 license. See the LICENSE file for details.
|
||||
|
||||
import { ApiInterfaceRx } from '@polkadot/api/types';
|
||||
import { DeriveStakingWaiting } from '../types';
|
||||
|
||||
import { Observable, combineLatest } from 'rxjs';
|
||||
import { map, switchMap } from 'rxjs/operators';
|
||||
|
||||
import { memo } from '../util';
|
||||
|
||||
export function waitingInfo (api: ApiInterfaceRx): () => Observable<DeriveStakingWaiting> {
|
||||
return memo((): Observable<DeriveStakingWaiting> =>
|
||||
combineLatest([
|
||||
api.derive.staking.validators(),
|
||||
api.derive.staking.stashes()
|
||||
]).pipe(
|
||||
switchMap(([{ nextElected }, stashes]): Observable<DeriveStakingWaiting> => {
|
||||
const elected = nextElected.map((a) => a.toString());
|
||||
const waiting = stashes.filter((v) => !elected.includes(v.toString()));
|
||||
|
||||
return api.derive.staking.queryMulti(waiting).pipe(
|
||||
map((info): DeriveStakingWaiting => ({
|
||||
info,
|
||||
waiting
|
||||
}))
|
||||
);
|
||||
})
|
||||
)
|
||||
);
|
||||
}
|
||||
@@ -4,4 +4,11 @@
|
||||
|
||||
import BN from 'bn.js';
|
||||
|
||||
export const FALLBACK_MAX_HASH_COUNT = 250;
|
||||
|
||||
// default here to 5 min eras, adjusted based on the actual blocktime
|
||||
export const FALLBACK_PERIOD = new BN(6 * 1000);
|
||||
|
||||
export const MAX_FINALITY_LAG = new BN(5);
|
||||
|
||||
export const MORTAL_PERIOD = new BN(5 * 60 * 1000);
|
||||
|
||||
@@ -5,26 +5,22 @@
|
||||
import { Header, Index } from '@polkadot/types/interfaces';
|
||||
import { AnyNumber, Codec, IExtrinsicEra } from '@polkadot/types/types';
|
||||
|
||||
import BN from 'bn.js';
|
||||
import { Observable, combineLatest, of } from 'rxjs';
|
||||
import { map, switchMap } from 'rxjs/operators';
|
||||
import { ApiInterfaceRx } from '@polkadot/api/types';
|
||||
import { isNumber, isUndefined } from '@polkadot/util';
|
||||
|
||||
import { FALLBACK_PERIOD, MAX_FINALITY_LAG, MORTAL_PERIOD } from './constants';
|
||||
|
||||
interface Result {
|
||||
header: Header | null;
|
||||
mortalLength: number;
|
||||
nonce: Index;
|
||||
}
|
||||
|
||||
// default here to 5 min eras, adjusted based on the actual blocktime
|
||||
const FALLBACK_PERIOD = new BN(6 * 1000);
|
||||
const MAX_FINALITY_LAG = new BN(5);
|
||||
const MORTAL_PERIOD = new BN(5 * 60 * 1000);
|
||||
|
||||
function latestNonce (api: ApiInterfaceRx, address: string): Observable<Index> {
|
||||
return api.derive.balances.account(address).pipe(
|
||||
map(({ accountNonce }): Index => accountNonce)
|
||||
map(({ accountNonce }) => accountNonce)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -35,7 +31,7 @@ function signingHeader (api: ApiInterfaceRx): Observable<Header> {
|
||||
switchMap((hash) => api.rpc.chain.getHeader(hash))
|
||||
)
|
||||
]).pipe(
|
||||
map(([current, finalized]): Header =>
|
||||
map(([current, finalized]) =>
|
||||
// determine the hash to use, current when lag > max, else finalized
|
||||
current.number.unwrap().sub(finalized.number.unwrap()).gt(MAX_FINALITY_LAG)
|
||||
? current
|
||||
@@ -61,7 +57,7 @@ export function signingInfo (api: ApiInterfaceRx): (address: string, nonce?: Any
|
||||
header,
|
||||
mortalLength: MORTAL_PERIOD
|
||||
.div(api.consts.babe?.expectedBlockTime || api.consts.timestamp?.minimumPeriod.muln(2) || FALLBACK_PERIOD)
|
||||
.add(MAX_FINALITY_LAG)
|
||||
.iadd(MAX_FINALITY_LAG)
|
||||
.toNumber(),
|
||||
nonce
|
||||
}))
|
||||
|
||||
@@ -9,7 +9,7 @@ import runtimeTypes from '@polkadot/types/interfaces/runtime/definitions';
|
||||
import { Struct } from '@polkadot/types';
|
||||
|
||||
// We can ignore the properties, added via Struct.with
|
||||
const _Header: Constructor<Header> = Struct.with(runtimeTypes.types.Header as any) as any;
|
||||
const _Header = Struct.with(runtimeTypes.types.Header as any) as Constructor<Header>;
|
||||
|
||||
/**
|
||||
* @name HeaderExtended
|
||||
|
||||
@@ -2,9 +2,9 @@
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the Apache-2.0 license. See the LICENSE file for details.
|
||||
|
||||
import type BN from 'bn.js';
|
||||
import { AccountId, Balance, BalanceLock, BalanceLockTo212, BalanceOf, Bid, BidKind, BlockNumber, Hash, Index, Proposal, ProposalIndex, SetIndex, SocietyVote, StrikeCount, TreasuryProposal, Votes, VoteIndex, VouchingStatus } from '@polkadot/types/interfaces';
|
||||
|
||||
import BN from 'bn.js';
|
||||
import { u32 } from '@polkadot/types';
|
||||
|
||||
export * from './accounts/types';
|
||||
@@ -31,6 +31,8 @@ export interface DeriveBalancesAll extends DeriveBalancesAccount {
|
||||
availableBalance: Balance;
|
||||
votingBalance: Balance;
|
||||
vestedBalance: Balance;
|
||||
vestedClaimable: Balance;
|
||||
vestingLocked: Balance;
|
||||
vestingTotal: Balance;
|
||||
}
|
||||
|
||||
@@ -42,6 +44,7 @@ export interface DeriveContractFees {
|
||||
creationFee: BN;
|
||||
rentByteFee: BN;
|
||||
rentDepositOffset: BN;
|
||||
surchargeReward: BN;
|
||||
tombstoneDeposit: BN;
|
||||
transactionBaseFee: BN;
|
||||
transactionByteFee: BN;
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
// Copyright 2017-2020 @polkadot/api-derive authors & contributors
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the Apache-2.0 license. See the LICENSE file for details.
|
||||
|
||||
import { DeriveCache } from './types';
|
||||
|
||||
import { deriveNoopCache } from './cacheImpl';
|
||||
|
||||
interface CacheValue<T> {
|
||||
v: T;
|
||||
x: number;
|
||||
}
|
||||
|
||||
const CHACHE_EXPIRY = 7 * (24 * 60) * (60 * 1000);
|
||||
|
||||
let deriveCache: DeriveCache;
|
||||
|
||||
function wrapCache (keyStart: string, cache: DeriveCache): DeriveCache {
|
||||
return {
|
||||
del: (partial: string): void => cache.del(`${keyStart}${partial}`),
|
||||
forEach: cache.forEach,
|
||||
get: <T = any> (partial: string): T | undefined => {
|
||||
const key = `${keyStart}${partial}`;
|
||||
const cached = cache.get<CacheValue<T>>(key);
|
||||
|
||||
if (cached) {
|
||||
cached.x = Date.now();
|
||||
cache.set(key, cached);
|
||||
|
||||
return cached.v;
|
||||
}
|
||||
|
||||
return undefined;
|
||||
},
|
||||
set: (partial: string, v: unknown): void => {
|
||||
cache.set(`${keyStart}${partial}`, { v, x: Date.now() });
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
function clearCache (cache: DeriveCache): void {
|
||||
// clear all expired values
|
||||
const now = Date.now();
|
||||
const all: any[] = [];
|
||||
|
||||
cache.forEach((key: string, { x }: CacheValue<any>): void => {
|
||||
((now - x) > CHACHE_EXPIRY) && all.push(key);
|
||||
});
|
||||
|
||||
// don't do delete inside loop, just in-case
|
||||
all.forEach((key) => cache.del(key));
|
||||
}
|
||||
|
||||
export function setDeriveCache (prefix = '', cache?: DeriveCache): void {
|
||||
deriveCache = cache
|
||||
? wrapCache(`derive:${prefix}:`, cache)
|
||||
: deriveNoopCache;
|
||||
|
||||
if (cache) {
|
||||
clearCache(cache);
|
||||
}
|
||||
}
|
||||
|
||||
setDeriveCache();
|
||||
|
||||
export { deriveCache };
|
||||
@@ -0,0 +1,35 @@
|
||||
// Copyright 2017-2020 @polkadot/api-derive authors & contributors
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the Apache-2.0 license. See the LICENSE file for details.
|
||||
|
||||
import { DeriveCache } from './types';
|
||||
|
||||
const mapCache = new Map<string, any>();
|
||||
|
||||
const deriveMapCache: DeriveCache = {
|
||||
del: (key: string): void => {
|
||||
mapCache.delete(key);
|
||||
},
|
||||
forEach: (cb: (key: string, value: any) => void): void => {
|
||||
const entries = mapCache.entries();
|
||||
|
||||
for (const entry in entries) {
|
||||
cb(entry[0], entry[1]);
|
||||
}
|
||||
},
|
||||
get: <T = any> (key: string): T | undefined => {
|
||||
return mapCache.get(key) as T;
|
||||
},
|
||||
set: (key: string, value: any): void => {
|
||||
mapCache.set(key, value);
|
||||
}
|
||||
};
|
||||
|
||||
const deriveNoopCache: DeriveCache = {
|
||||
del: (): void => undefined,
|
||||
forEach: () => undefined,
|
||||
get: (): undefined => undefined,
|
||||
set: (_: string, value: unknown): unknown => value
|
||||
};
|
||||
|
||||
export { deriveMapCache, deriveNoopCache };
|
||||
@@ -5,6 +5,8 @@
|
||||
import { drr } from '@polkadot/rpc-core/rxjs';
|
||||
|
||||
export * from './approvalFlagsToBools';
|
||||
export * from './cache';
|
||||
export * from './cacheImpl';
|
||||
export * from './memo';
|
||||
|
||||
export { drr };
|
||||
|
||||
@@ -3,15 +3,11 @@
|
||||
// of the Apache-2.0 license. See the LICENSE file for details.v
|
||||
|
||||
import createMemo from 'memoizee';
|
||||
import { Observable, Observer } from 'rxjs';
|
||||
import { Observable, Observer, TeardownLogic } from 'rxjs';
|
||||
import { drr } from '@polkadot/rpc-core/rxjs';
|
||||
|
||||
type ObsFn <T> = (...params: any[]) => Observable<T>;
|
||||
|
||||
// Normalize via JSON.stringify, allow e.g. AccountId -> ss58
|
||||
// eslint-disable-next-line @typescript-eslint/unbound-method
|
||||
const normalizer = JSON.stringify;
|
||||
|
||||
// Wraps a derive, doing 2 things to optimize calls -
|
||||
// 1. creates a memo of the inner fn -> Observable, removing when unsubscribed
|
||||
// 2. wraps the observable in a drr() (which includes an unsub delay)
|
||||
@@ -19,15 +15,19 @@ const normalizer = JSON.stringify;
|
||||
export function memo <T> (inner: ObsFn<T>): ObsFn<T> {
|
||||
const cached = createMemo(
|
||||
(...params: any[]): Observable<T> =>
|
||||
new Observable((observer: Observer<T>): VoidCallback => {
|
||||
const sub = inner(...params).subscribe(observer);
|
||||
new Observable((observer: Observer<T>): TeardownLogic => {
|
||||
const subscription = inner(...params).subscribe(observer);
|
||||
|
||||
return (): void => {
|
||||
cached.delete(...params);
|
||||
sub.unsubscribe();
|
||||
subscription.unsubscribe();
|
||||
};
|
||||
}).pipe(drr()),
|
||||
{ normalizer }
|
||||
{
|
||||
// Normalize via JSON.stringify, allow e.g. AccountId -> ss58
|
||||
// eslint-disable-next-line @typescript-eslint/unbound-method
|
||||
normalizer: JSON.stringify
|
||||
}
|
||||
);
|
||||
|
||||
return cached;
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
// Copyright 2017-2020 @polkadot/api-derive authors & contributors
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the Apache-2.0 license. See the LICENSE file for details.
|
||||
|
||||
export interface DeriveCache {
|
||||
del: (key: string) => void;
|
||||
forEach: (cb: (key: string, value: any) => void) => void;
|
||||
get: <T = any> (key: string) => T | undefined;
|
||||
set: (key: string, value: any) => void;
|
||||
}
|
||||
@@ -97,7 +97,7 @@ Some of the users of the API (let us know if you are missing from the list), inc
|
||||
- [Polkawallet.io](https://polkawallet.io) and [Polkawallet (Github)](https://github.com/polkawallet-io/polkawallet-RN/) A mobile wallet for the Polkadot network to manage funds and make transactions, available on both Androind and iOS
|
||||
- [PolkaStats.io](https://polkastats.io), [PolkaStats frontend GitHub repository](https://github.com/Colm3na/polkastats-v2) and [PolkaStats backend GitHub repository](https://github.com/Colm3na/polkastats-backend-v2) Polkadot network statistics (currently Kusama and Alexander). Shows network information and staking details from validators and intentions.
|
||||
- [Polkadot API Server (GitHub)](https://github.com/SimplyVC/polkadot_api_server) A lightweight server for querying Polkadot nodes from any language, built primarily as a backend for [PANIC for Polkadot (GitHub)](https://github.com/SimplyVC/panic_polkadot/), a validator monitoring and alerting tool.
|
||||
|
||||
- [Identity Registrar #1 from Chevdor on Westend, Kusama and Polkadot](https://www.chevdor.com/tags/registrar/)
|
||||
## Classes
|
||||
|
||||
[Classes](SUMMARY.md)
|
||||
|
||||
+15
-15
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@polkadot/api",
|
||||
"version": "1.12.1",
|
||||
"version": "1.27.1",
|
||||
"description": "Promise and RxJS wrappers around the Polkadot JS RPC",
|
||||
"main": "index.js",
|
||||
"keywords": [
|
||||
@@ -26,21 +26,21 @@
|
||||
},
|
||||
"homepage": "https://github.com/polkadot-js/api/tree/master/packages/api#readme",
|
||||
"dependencies": {
|
||||
"@babel/runtime": "^7.9.2",
|
||||
"@polkadot/api-derive": "1.12.1",
|
||||
"@polkadot/keyring": "^2.9.0-beta.3",
|
||||
"@polkadot/metadata": "1.12.1",
|
||||
"@polkadot/rpc-core": "1.12.1",
|
||||
"@polkadot/rpc-provider": "1.12.1",
|
||||
"@polkadot/types": "1.12.1",
|
||||
"@polkadot/types-known": "1.12.1",
|
||||
"@polkadot/util": "^2.9.0-beta.3",
|
||||
"@polkadot/util-crypto": "^2.9.0-beta.3",
|
||||
"bn.js": "^5.1.1",
|
||||
"eventemitter3": "^4.0.0",
|
||||
"rxjs": "^6.5.5"
|
||||
"@babel/runtime": "^7.11.0",
|
||||
"@polkadot/api-derive": "1.27.1",
|
||||
"@polkadot/keyring": "^3.0.1",
|
||||
"@polkadot/metadata": "1.27.1",
|
||||
"@polkadot/rpc-core": "1.27.1",
|
||||
"@polkadot/rpc-provider": "1.27.1",
|
||||
"@polkadot/types": "1.27.1",
|
||||
"@polkadot/types-known": "1.27.1",
|
||||
"@polkadot/util": "^3.0.1",
|
||||
"@polkadot/util-crypto": "^3.0.1",
|
||||
"bn.js": "^5.1.2",
|
||||
"eventemitter3": "^4.0.4",
|
||||
"rxjs": "^6.6.2"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@polkadot/keyring": "^2.9.0-beta.3"
|
||||
"@polkadot/keyring": "^3.0.1"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,10 +2,12 @@
|
||||
/* eslint-disable */
|
||||
|
||||
import { Codec } from '@polkadot/types/types';
|
||||
import { u32, u64 } from '@polkadot/types/primitive';
|
||||
import { Balance, BalanceOf, BlockNumber, LockIdentifier, ModuleId, Moment, Percent, Permill, RuntimeDbWeight, Weight } from '@polkadot/types/interfaces/runtime';
|
||||
import { Vec } from '@polkadot/types/codec';
|
||||
import { u16, u32, u64 } from '@polkadot/types/primitive';
|
||||
import { Balance, BalanceOf, BlockNumber, LockIdentifier, ModuleId, Moment, Perbill, Percent, Permill, RuntimeDbWeight, Weight } from '@polkadot/types/interfaces/runtime';
|
||||
import { SessionIndex } from '@polkadot/types/interfaces/session';
|
||||
import { EraIndex } from '@polkadot/types/interfaces/staking';
|
||||
import { WeightToFeeCoefficient } from '@polkadot/types/interfaces/support';
|
||||
|
||||
declare module '@polkadot/metadata/Decorated/consts/types' {
|
||||
export interface Constants {
|
||||
@@ -51,6 +53,7 @@ declare module '@polkadot/metadata/Decorated/consts/types' {
|
||||
/**
|
||||
* The amount of funds a contract should deposit in order to offset
|
||||
* the cost of one byte.
|
||||
*
|
||||
* Let's suppose the deposit is 1,000 BU (balance units)/byte and the rent is 1 BU/byte/day,
|
||||
* then a contract with 1,000,000 BU that uses 1,000 bytes of storage would pay no rent.
|
||||
* But if the balance reduced to 500,000 BU and the storage stayed the same at 1,000,
|
||||
@@ -59,13 +62,18 @@ declare module '@polkadot/metadata/Decorated/consts/types' {
|
||||
rentDepositOffset: AugmentedConst<BalanceOf>;
|
||||
/**
|
||||
* Number of block delay an extrinsic claim surcharge has.
|
||||
*
|
||||
* When claim surcharge is called by an extrinsic the rent is checked
|
||||
* for current_block - delay
|
||||
**/
|
||||
signedClaimHandicap: AugmentedConst<BlockNumber>;
|
||||
/**
|
||||
* Size of a contract at the time of instantiation. This is a simple way to ensure that
|
||||
* empty contracts eventually gets deleted.
|
||||
* A size offset for an contract. A just created account with untouched storage will have that
|
||||
* much of storage from the perspective of the state rent.
|
||||
*
|
||||
* This is a simple way to ensure that contracts with empty storage eventually get deleted
|
||||
* by making them pay rent. This creates an incentive to remove them early in order to save
|
||||
* rent.
|
||||
**/
|
||||
storageSizeOffset: AugmentedConst<u32>;
|
||||
/**
|
||||
@@ -86,6 +94,7 @@ declare module '@polkadot/metadata/Decorated/consts/types' {
|
||||
cooloffPeriod: AugmentedConst<BlockNumber>;
|
||||
/**
|
||||
* The minimum period of locking and the period between a proposal being approved and enacted.
|
||||
*
|
||||
* It should generally be a little more than the unstake period to ensure that
|
||||
* voting stakers have an opportunity to remove themselves from the system in the case where
|
||||
* they are on the losing side of a vote.
|
||||
@@ -99,6 +108,10 @@ declare module '@polkadot/metadata/Decorated/consts/types' {
|
||||
* How often (in blocks) new public referenda are launched.
|
||||
**/
|
||||
launchPeriod: AugmentedConst<BlockNumber>;
|
||||
/**
|
||||
* The maximum number of votes for an account.
|
||||
**/
|
||||
maxVotes: AugmentedConst<u32>;
|
||||
/**
|
||||
* The minimum amount to be used as a deposit for a public referendum proposal.
|
||||
**/
|
||||
@@ -163,6 +176,40 @@ declare module '@polkadot/metadata/Decorated/consts/types' {
|
||||
**/
|
||||
subAccountDeposit: AugmentedConst<BalanceOf>;
|
||||
};
|
||||
proxy: {
|
||||
[index: string]: AugmentedConst<object & Codec>;
|
||||
/**
|
||||
* The maximum amount of proxies allowed for a single account.
|
||||
**/
|
||||
maxProxies: AugmentedConst<u16>;
|
||||
/**
|
||||
* The base amount of currency needed to reserve for creating a proxy.
|
||||
**/
|
||||
proxyDepositBase: AugmentedConst<BalanceOf>;
|
||||
/**
|
||||
* The amount of currency needed per proxy added.
|
||||
**/
|
||||
proxyDepositFactor: AugmentedConst<BalanceOf>;
|
||||
};
|
||||
recovery: {
|
||||
[index: string]: AugmentedConst<object & Codec>;
|
||||
/**
|
||||
* The base amount of currency needed to reserve for creating a recovery configuration.
|
||||
**/
|
||||
configDepositBase: AugmentedConst<BalanceOf>;
|
||||
/**
|
||||
* The amount of currency needed per additional user when creating a recovery configuration.
|
||||
**/
|
||||
friendDepositFactor: AugmentedConst<BalanceOf>;
|
||||
/**
|
||||
* The maximum amount of friends allowed in a recovery configuration.
|
||||
**/
|
||||
maxFriends: AugmentedConst<u16>;
|
||||
/**
|
||||
* The base amount of currency needed to reserve for starting a recovery.
|
||||
**/
|
||||
recoveryDeposit: AugmentedConst<BalanceOf>;
|
||||
};
|
||||
society: {
|
||||
[index: string]: AugmentedConst<object & Codec>;
|
||||
/**
|
||||
@@ -202,10 +249,45 @@ declare module '@polkadot/metadata/Decorated/consts/types' {
|
||||
* Number of eras that staked funds must remain bonded for.
|
||||
**/
|
||||
bondingDuration: AugmentedConst<EraIndex>;
|
||||
/**
|
||||
* The number of blocks before the end of the era from which election submissions are allowed.
|
||||
*
|
||||
* Setting this to zero will disable the offchain compute and only on-chain seq-phragmen will
|
||||
* be used.
|
||||
*
|
||||
* This is bounded by being within the last session. Hence, setting it to a value more than the
|
||||
* length of a session will be pointless.
|
||||
**/
|
||||
electionLookahead: AugmentedConst<BlockNumber>;
|
||||
/**
|
||||
* Maximum number of balancing iterations to run in the offchain submission.
|
||||
*
|
||||
* If set to 0, balance_solution will not be executed at all.
|
||||
**/
|
||||
maxIterations: AugmentedConst<u32>;
|
||||
/**
|
||||
* The maximum number of nominators rewarded for each validator.
|
||||
*
|
||||
* For each validator only the `$MaxNominatorRewardedPerValidator` biggest stakers can claim
|
||||
* their reward. This used to limit the i/o cost for the nominator payout.
|
||||
**/
|
||||
maxNominatorRewardedPerValidator: AugmentedConst<u32>;
|
||||
/**
|
||||
* The threshold of improvement that should be provided for a new solution to be accepted.
|
||||
**/
|
||||
minSolutionScoreBump: AugmentedConst<Perbill>;
|
||||
/**
|
||||
* Number of sessions per era.
|
||||
**/
|
||||
sessionsPerEra: AugmentedConst<SessionIndex>;
|
||||
/**
|
||||
* Number of eras that slashes are deferred by, after computation.
|
||||
*
|
||||
* This should be less than the bonding duration.
|
||||
* Set to 0 if slashes should be applied immediately, without opportunity for
|
||||
* intervention.
|
||||
**/
|
||||
slashDeferDuration: AugmentedConst<EraIndex>;
|
||||
};
|
||||
system: {
|
||||
[index: string]: AugmentedConst<object & Codec>;
|
||||
@@ -213,6 +295,10 @@ declare module '@polkadot/metadata/Decorated/consts/types' {
|
||||
* The base weight of executing a block, independent of the transactions in the block.
|
||||
**/
|
||||
blockExecutionWeight: AugmentedConst<Weight>;
|
||||
/**
|
||||
* The maximum number of blocks to allow in mortal eras.
|
||||
**/
|
||||
blockHashCount: AugmentedConst<BlockNumber>;
|
||||
/**
|
||||
* The weight of runtime database operations the runtime can invoke.
|
||||
**/
|
||||
@@ -246,6 +332,10 @@ declare module '@polkadot/metadata/Decorated/consts/types' {
|
||||
* The fee to be paid for making a transaction; the per-byte portion.
|
||||
**/
|
||||
transactionByteFee: AugmentedConst<BalanceOf>;
|
||||
/**
|
||||
* The polynomial that is applied in order to derive fee from weight.
|
||||
**/
|
||||
weightToFee: AugmentedConst<Vec<WeightToFeeCoefficient>>;
|
||||
};
|
||||
treasury: {
|
||||
[index: string]: AugmentedConst<object & Codec>;
|
||||
|
||||
@@ -5,23 +5,23 @@ import { AnyNumber, ITuple, Observable } from '@polkadot/types/types';
|
||||
import { Option, U8aFixed, Vec } from '@polkadot/types/codec';
|
||||
import { Bytes, Data, bool, u32, u64 } from '@polkadot/types/primitive';
|
||||
import { UncleEntryItem } from '@polkadot/types/interfaces/authorship';
|
||||
import { BabeAuthorityWeight, MaybeVrf, Randomness } from '@polkadot/types/interfaces/babe';
|
||||
import { AccountData, BalanceLock, ReleasesBalances } from '@polkadot/types/interfaces/balances';
|
||||
import { BabeAuthorityWeight, MaybeRandomness, NextConfigDescriptor, Randomness } from '@polkadot/types/interfaces/babe';
|
||||
import { AccountData, BalanceLock } from '@polkadot/types/interfaces/balances';
|
||||
import { ProposalIndex, Votes } from '@polkadot/types/interfaces/collective';
|
||||
import { AuthorityId, RawVRFOutput } from '@polkadot/types/interfaces/consensus';
|
||||
import { AuthorityId } from '@polkadot/types/interfaces/consensus';
|
||||
import { CodeHash, ContractInfo, PrefabWasmModule, Schedule } from '@polkadot/types/interfaces/contracts';
|
||||
import { PreimageStatus, PropIndex, Proposal, ProxyState, ReferendumIndex, ReferendumInfo, Voting } from '@polkadot/types/interfaces/democracy';
|
||||
import { PreimageStatus, PropIndex, Proposal, ReferendumIndex, ReferendumInfo, Voting } from '@polkadot/types/interfaces/democracy';
|
||||
import { VoteThreshold } from '@polkadot/types/interfaces/elections';
|
||||
import { SetId, StoredPendingChange, StoredState } from '@polkadot/types/interfaces/grandpa';
|
||||
import { RegistrarInfo, Registration } from '@polkadot/types/interfaces/identity';
|
||||
import { AuthIndex } from '@polkadot/types/interfaces/imOnline';
|
||||
import { DeferredOffenceOf, Kind, OffenceDetails, OpaqueTimeSlot, ReportIdOf } from '@polkadot/types/interfaces/offences';
|
||||
import { ActiveRecovery, RecoveryConfig } from '@polkadot/types/interfaces/recovery';
|
||||
import { AccountId, AccountIndex, Balance, BalanceOf, BlockNumber, Hash, KeyTypeId, Moment, Perbill, ValidatorId, Weight } from '@polkadot/types/interfaces/runtime';
|
||||
import { AccountId, AccountIndex, Balance, BalanceOf, BlockNumber, ExtrinsicsWeight, Hash, KeyTypeId, Moment, OpaqueCall, Perbill, ProxyType, Releases, ValidatorId } from '@polkadot/types/interfaces/runtime';
|
||||
import { Scheduled, TaskAddress } from '@polkadot/types/interfaces/scheduler';
|
||||
import { Keys, SessionIndex } from '@polkadot/types/interfaces/session';
|
||||
import { Bid, BidKind, SocietyVote, StrikeCount, VouchingStatus } from '@polkadot/types/interfaces/society';
|
||||
import { ActiveEraInfo, ElectionResult, ElectionStatus, EraIndex, EraRewardPoints, Exposure, Forcing, Nominations, PhragmenScore, ReleasesStaking, RewardDestination, SlashingSpans, SpanIndex, SpanRecord, StakingLedger, UnappliedSlash, ValidatorPrefs } from '@polkadot/types/interfaces/staking';
|
||||
import { ActiveEraInfo, ElectionResult, ElectionScore, ElectionStatus, EraIndex, EraRewardPoints, Exposure, Forcing, Nominations, RewardDestination, SlashingSpans, SpanIndex, SpanRecord, StakingLedger, UnappliedSlash, ValidatorPrefs } from '@polkadot/types/interfaces/staking';
|
||||
import { AccountInfo, DigestOf, EventIndex, EventRecord, LastRuntimeUpgradeInfo, Phase } from '@polkadot/types/interfaces/system';
|
||||
import { OpenTip, TreasuryProposal } from '@polkadot/types/interfaces/treasury';
|
||||
import { Multiplier } from '@polkadot/types/interfaces/txpayment';
|
||||
@@ -69,21 +69,28 @@ declare module '@polkadot/api/types/storage' {
|
||||
* Temporary value (cleared at block finalization) which is `Some`
|
||||
* if per-block initialization has already been called for current block.
|
||||
**/
|
||||
initialized: AugmentedQuery<ApiType, () => Observable<Option<MaybeVrf>>> & QueryableStorageEntry<ApiType>;
|
||||
initialized: AugmentedQuery<ApiType, () => Observable<Option<MaybeRandomness>>> & QueryableStorageEntry<ApiType>;
|
||||
/**
|
||||
* How late the current block is compared to its parent.
|
||||
*
|
||||
* This entry is populated as part of block execution and is cleaned up
|
||||
* on block finalization. Querying this storage entry outside of block
|
||||
* execution context should always yield zero.
|
||||
**/
|
||||
lateness: AugmentedQuery<ApiType, () => Observable<BlockNumber>> & QueryableStorageEntry<ApiType>;
|
||||
/**
|
||||
* Next epoch configuration, if changed.
|
||||
**/
|
||||
nextEpochConfig: AugmentedQuery<ApiType, () => Observable<Option<NextConfigDescriptor>>> & QueryableStorageEntry<ApiType>;
|
||||
/**
|
||||
* Next epoch randomness.
|
||||
**/
|
||||
nextRandomness: AugmentedQuery<ApiType, () => Observable<Randomness>> & QueryableStorageEntry<ApiType>;
|
||||
/**
|
||||
* The epoch randomness for the *current* epoch.
|
||||
*
|
||||
* # Security
|
||||
*
|
||||
* This MUST NOT be used for gambling, as it can be influenced by a
|
||||
* malicious validator in the short term. It MAY be used in many
|
||||
* cryptographic protocols, however, so long as one remembers that this
|
||||
@@ -94,22 +101,26 @@ declare module '@polkadot/api/types/storage' {
|
||||
randomness: AugmentedQuery<ApiType, () => Observable<Randomness>> & QueryableStorageEntry<ApiType>;
|
||||
/**
|
||||
* Randomness under construction.
|
||||
*
|
||||
* We make a tradeoff between storage accesses and list length.
|
||||
* We store the under-construction randomness in segments of up to
|
||||
* `UNDER_CONSTRUCTION_SEGMENT_LENGTH`.
|
||||
*
|
||||
* Once a segment reaches this length, we begin the next one.
|
||||
* We reset all segments and return to `0` at the beginning of every
|
||||
* epoch.
|
||||
**/
|
||||
segmentIndex: AugmentedQuery<ApiType, () => Observable<u32>> & QueryableStorageEntry<ApiType>;
|
||||
underConstruction: AugmentedQuery<ApiType, (arg: u32 | AnyNumber | Uint8Array) => Observable<Vec<RawVRFOutput>>> & QueryableStorageEntry<ApiType>;
|
||||
/**
|
||||
* TWOX-NOTE: `SegmentIndex` is an increasing integer, so this is okay.
|
||||
**/
|
||||
underConstruction: AugmentedQuery<ApiType, (arg: u32 | AnyNumber | Uint8Array) => Observable<Vec<Randomness>>> & QueryableStorageEntry<ApiType>;
|
||||
};
|
||||
balances: {
|
||||
[index: string]: QueryableStorageEntry<ApiType>;
|
||||
/**
|
||||
* The balance of an account.
|
||||
* NOTE: THIS MAY NEVER BE IN EXISTENCE AND YET HAVE A `total().is_zero()`. If the total
|
||||
* is ever zero, then the entry *MUST* be removed.
|
||||
*
|
||||
* NOTE: This is only used in the case that this module is used to store balances.
|
||||
**/
|
||||
account: AugmentedQuery<ApiType, (arg: AccountId | string | Uint8Array) => Observable<AccountData>> & QueryableStorageEntry<ApiType>;
|
||||
@@ -120,9 +131,10 @@ declare module '@polkadot/api/types/storage' {
|
||||
locks: AugmentedQuery<ApiType, (arg: AccountId | string | Uint8Array) => Observable<Vec<BalanceLock>>> & QueryableStorageEntry<ApiType>;
|
||||
/**
|
||||
* Storage version of the pallet.
|
||||
*
|
||||
* This is set to v2.0.0 for new networks.
|
||||
**/
|
||||
storageVersion: AugmentedQuery<ApiType, () => Observable<ReleasesBalances>> & QueryableStorageEntry<ApiType>;
|
||||
storageVersion: AugmentedQuery<ApiType, () => Observable<Releases>> & QueryableStorageEntry<ApiType>;
|
||||
/**
|
||||
* The total units issued in the system.
|
||||
**/
|
||||
@@ -140,6 +152,8 @@ declare module '@polkadot/api/types/storage' {
|
||||
codeStorage: AugmentedQuery<ApiType, (arg: CodeHash | string | Uint8Array) => Observable<Option<PrefabWasmModule>>> & QueryableStorageEntry<ApiType>;
|
||||
/**
|
||||
* The code associated with a given account.
|
||||
*
|
||||
* TWOX-NOTE: SAFE since `AccountId` is a secure hash.
|
||||
**/
|
||||
contractInfoOf: AugmentedQuery<ApiType, (arg: AccountId | string | Uint8Array) => Observable<Option<ContractInfo>>> & QueryableStorageEntry<ApiType>;
|
||||
/**
|
||||
@@ -192,8 +206,10 @@ declare module '@polkadot/api/types/storage' {
|
||||
cancellations: AugmentedQuery<ApiType, (arg: Hash | string | Uint8Array) => Observable<bool>> & QueryableStorageEntry<ApiType>;
|
||||
/**
|
||||
* Those who have locked a deposit.
|
||||
*
|
||||
* TWOX-NOTE: Safe, as increasing integer keys are safe.
|
||||
**/
|
||||
depositOf: AugmentedQuery<ApiType, (arg: PropIndex | AnyNumber | Uint8Array) => Observable<Option<ITuple<[BalanceOf, Vec<AccountId>]>>>> & QueryableStorageEntry<ApiType>;
|
||||
depositOf: AugmentedQuery<ApiType, (arg: PropIndex | AnyNumber | Uint8Array) => Observable<Option<ITuple<[Vec<AccountId>, BalanceOf]>>>> & QueryableStorageEntry<ApiType>;
|
||||
/**
|
||||
* True if the last referendum tabled was submitted externally. False if it was a public
|
||||
* proposal.
|
||||
@@ -202,6 +218,8 @@ declare module '@polkadot/api/types/storage' {
|
||||
/**
|
||||
* Accounts for which there are locks in action which may be removed at some point in the
|
||||
* future. The value is the block number at which the lock expires and may be removed.
|
||||
*
|
||||
* TWOX-NOTE: OK ― `AccountId` is a secure hash.
|
||||
**/
|
||||
locks: AugmentedQuery<ApiType, (arg: AccountId | string | Uint8Array) => Observable<Option<BlockNumber>>> & QueryableStorageEntry<ApiType>;
|
||||
/**
|
||||
@@ -221,11 +239,6 @@ declare module '@polkadot/api/types/storage' {
|
||||
* The block number is the block at which it was deposited.
|
||||
**/
|
||||
preimages: AugmentedQuery<ApiType, (arg: Hash | string | Uint8Array) => Observable<Option<PreimageStatus>>> & QueryableStorageEntry<ApiType>;
|
||||
/**
|
||||
* Who is able to vote for whom. Value is the fund-holding account, key is the
|
||||
* vote-transaction-sending account.
|
||||
**/
|
||||
proxy: AugmentedQuery<ApiType, (arg: AccountId | string | Uint8Array) => Observable<Option<ProxyState>>> & QueryableStorageEntry<ApiType>;
|
||||
/**
|
||||
* The number of (public) proposals that have been made so far.
|
||||
**/
|
||||
@@ -240,11 +253,21 @@ declare module '@polkadot/api/types/storage' {
|
||||
referendumCount: AugmentedQuery<ApiType, () => Observable<ReferendumIndex>> & QueryableStorageEntry<ApiType>;
|
||||
/**
|
||||
* Information concerning any given referendum.
|
||||
*
|
||||
* TWOX-NOTE: SAFE as indexes are not under an attacker’s control.
|
||||
**/
|
||||
referendumInfoOf: AugmentedQuery<ApiType, (arg: ReferendumIndex | AnyNumber | Uint8Array) => Observable<Option<ReferendumInfo>>> & QueryableStorageEntry<ApiType>;
|
||||
/**
|
||||
* Storage version of the pallet.
|
||||
*
|
||||
* New networks start with last version.
|
||||
**/
|
||||
storageVersion: AugmentedQuery<ApiType, () => Observable<Option<Releases>>> & QueryableStorageEntry<ApiType>;
|
||||
/**
|
||||
* All votes for a particular voter. We store the balance for the number of votes that we
|
||||
* have recorded. The second item is the total amount of delegations, that will be added.
|
||||
*
|
||||
* TWOX-NOTE: SAFE as `AccountId`s are crypto hashes anyway.
|
||||
**/
|
||||
votingOf: AugmentedQuery<ApiType, (arg: AccountId | string | Uint8Array) => Observable<Voting>> & QueryableStorageEntry<ApiType>;
|
||||
};
|
||||
@@ -269,6 +292,8 @@ declare module '@polkadot/api/types/storage' {
|
||||
runnersUp: AugmentedQuery<ApiType, () => Observable<Vec<ITuple<[AccountId, BalanceOf]>>>> & QueryableStorageEntry<ApiType>;
|
||||
/**
|
||||
* Votes and locked stake of a particular voter.
|
||||
*
|
||||
* TWOX-NOTE: SAFE as `AccountId` is a crypto hash
|
||||
**/
|
||||
voting: AugmentedQuery<ApiType, (arg: AccountId | string | Uint8Array) => Observable<ITuple<[BalanceOf, Vec<AccountId>]>>> & QueryableStorageEntry<ApiType>;
|
||||
};
|
||||
@@ -290,6 +315,8 @@ declare module '@polkadot/api/types/storage' {
|
||||
/**
|
||||
* A mapping from grandpa set ID to the index of the *most recent* session for which its
|
||||
* members were responsible.
|
||||
*
|
||||
* TWOX-NOTE: `SetId` is not under user control.
|
||||
**/
|
||||
setIdSession: AugmentedQuery<ApiType, (arg: SetId | AnyNumber | Uint8Array) => Observable<Option<SessionIndex>>> & QueryableStorageEntry<ApiType>;
|
||||
/**
|
||||
@@ -305,17 +332,23 @@ declare module '@polkadot/api/types/storage' {
|
||||
[index: string]: QueryableStorageEntry<ApiType>;
|
||||
/**
|
||||
* Information that is pertinent to identify the entity behind an account.
|
||||
*
|
||||
* TWOX-NOTE: OK ― `AccountId` is a secure hash.
|
||||
**/
|
||||
identityOf: AugmentedQuery<ApiType, (arg: AccountId | string | Uint8Array) => Observable<Option<Registration>>> & QueryableStorageEntry<ApiType>;
|
||||
/**
|
||||
* The set of registrars. Not expected to get very big as can only be added through a
|
||||
* special origin (likely a council motion).
|
||||
*
|
||||
* The index into this can be cast to `RegistrarIndex` to get a valid value.
|
||||
**/
|
||||
registrars: AugmentedQuery<ApiType, () => Observable<Vec<Option<RegistrarInfo>>>> & QueryableStorageEntry<ApiType>;
|
||||
/**
|
||||
* Alternative "sub" identities of this account.
|
||||
*
|
||||
* The first item is the deposit, the second is a vector of the accounts.
|
||||
*
|
||||
* TWOX-NOTE: OK ― `AccountId` is a secure hash.
|
||||
**/
|
||||
subsOf: AugmentedQuery<ApiType, (arg: AccountId | string | Uint8Array) => Observable<ITuple<[BalanceOf, Vec<AccountId>]>>> & QueryableStorageEntry<ApiType>;
|
||||
/**
|
||||
@@ -333,6 +366,7 @@ declare module '@polkadot/api/types/storage' {
|
||||
authoredBlocks: AugmentedQueryDoubleMap<ApiType, (key1: SessionIndex | AnyNumber | Uint8Array, key2: ValidatorId | string | Uint8Array) => Observable<u32>> & QueryableStorageEntry<ApiType>;
|
||||
/**
|
||||
* The block number after which it's ok to send heartbeats in current session.
|
||||
*
|
||||
* At the beginning of each session we set this to a value that should
|
||||
* fall roughly in the middle of the session duration.
|
||||
* The idea is to first wait for the validators to produce a block
|
||||
@@ -354,7 +388,15 @@ declare module '@polkadot/api/types/storage' {
|
||||
/**
|
||||
* The lookup from index to account.
|
||||
**/
|
||||
accounts: AugmentedQuery<ApiType, (arg: AccountIndex | AnyNumber | Uint8Array) => Observable<Option<ITuple<[AccountId, BalanceOf]>>>> & QueryableStorageEntry<ApiType>;
|
||||
accounts: AugmentedQuery<ApiType, (arg: AccountIndex | AnyNumber | Uint8Array) => Observable<Option<ITuple<[AccountId, BalanceOf, bool]>>>> & QueryableStorageEntry<ApiType>;
|
||||
};
|
||||
multisig: {
|
||||
[index: string]: QueryableStorageEntry<ApiType>;
|
||||
calls: AugmentedQuery<ApiType, (arg: U8aFixed | string | Uint8Array) => Observable<Option<ITuple<[OpaqueCall, AccountId, BalanceOf]>>>> & QueryableStorageEntry<ApiType>;
|
||||
/**
|
||||
* The set of open multisig operations.
|
||||
**/
|
||||
multisigs: AugmentedQueryDoubleMap<ApiType, (key1: AccountId | string | Uint8Array, key2: U8aFixed | string | Uint8Array) => Observable<Option<Multisig>>> & QueryableStorageEntry<ApiType>;
|
||||
};
|
||||
offences: {
|
||||
[index: string]: QueryableStorageEntry<ApiType>;
|
||||
@@ -373,12 +415,22 @@ declare module '@polkadot/api/types/storage' {
|
||||
reports: AugmentedQuery<ApiType, (arg: ReportIdOf | string | Uint8Array) => Observable<Option<OffenceDetails>>> & QueryableStorageEntry<ApiType>;
|
||||
/**
|
||||
* Enumerates all reports of a kind along with the time they happened.
|
||||
*
|
||||
* All reports are sorted by the time of offence.
|
||||
*
|
||||
* Note that the actual type of this mapping is `Vec<u8>`, this is because values of
|
||||
* different types are not supported at the moment so we are doing the manual serialization.
|
||||
**/
|
||||
reportsByKindIndex: AugmentedQuery<ApiType, (arg: Kind | string | Uint8Array) => Observable<Bytes>> & QueryableStorageEntry<ApiType>;
|
||||
};
|
||||
proxy: {
|
||||
[index: string]: QueryableStorageEntry<ApiType>;
|
||||
/**
|
||||
* The set of account proxies. Maps the account which has delegated to the accounts
|
||||
* which are being delegated to, together with the amount held on deposit.
|
||||
**/
|
||||
proxies: AugmentedQuery<ApiType, (arg: AccountId | string | Uint8Array) => Observable<ITuple<[Vec<ITuple<[AccountId, ProxyType]>>, BalanceOf]>>> & QueryableStorageEntry<ApiType>;
|
||||
};
|
||||
randomnessCollectiveFlip: {
|
||||
[index: string]: QueryableStorageEntry<ApiType>;
|
||||
/**
|
||||
@@ -392,12 +444,14 @@ declare module '@polkadot/api/types/storage' {
|
||||
[index: string]: QueryableStorageEntry<ApiType>;
|
||||
/**
|
||||
* Active recovery attempts.
|
||||
*
|
||||
* First account is the account to be recovered, and the second account
|
||||
* is the user trying to recover the account.
|
||||
**/
|
||||
activeRecoveries: AugmentedQueryDoubleMap<ApiType, (key1: AccountId | string | Uint8Array, key2: AccountId | string | Uint8Array) => Observable<Option<ActiveRecovery>>> & QueryableStorageEntry<ApiType>;
|
||||
/**
|
||||
* The list of allowed proxy accounts.
|
||||
*
|
||||
* Map from the user who can access it to the recovered account.
|
||||
**/
|
||||
proxy: AugmentedQuery<ApiType, (arg: AccountId | string | Uint8Array) => Observable<Option<AccountId>>> & QueryableStorageEntry<ApiType>;
|
||||
@@ -416,6 +470,12 @@ declare module '@polkadot/api/types/storage' {
|
||||
* Lookup from identity to the block number and index of the task.
|
||||
**/
|
||||
lookup: AugmentedQuery<ApiType, (arg: Bytes | string | Uint8Array) => Observable<Option<TaskAddress>>> & QueryableStorageEntry<ApiType>;
|
||||
/**
|
||||
* Storage version of the pallet.
|
||||
*
|
||||
* New networks start with last version.
|
||||
**/
|
||||
storageVersion: AugmentedQuery<ApiType, () => Observable<Releases>> & QueryableStorageEntry<ApiType>;
|
||||
};
|
||||
session: {
|
||||
[index: string]: QueryableStorageEntry<ApiType>;
|
||||
@@ -425,6 +485,7 @@ declare module '@polkadot/api/types/storage' {
|
||||
currentIndex: AugmentedQuery<ApiType, () => Observable<SessionIndex>> & QueryableStorageEntry<ApiType>;
|
||||
/**
|
||||
* Indices of disabled validators.
|
||||
*
|
||||
* The set is cleared when `on_session_ending` returns a new set of identities.
|
||||
**/
|
||||
disabledValidators: AugmentedQuery<ApiType, () => Observable<Vec<u32>>> & QueryableStorageEntry<ApiType>;
|
||||
@@ -523,6 +584,7 @@ declare module '@polkadot/api/types/storage' {
|
||||
[index: string]: QueryableStorageEntry<ApiType>;
|
||||
/**
|
||||
* The active era information, it holds index and start.
|
||||
*
|
||||
* The active era is the era currently rewarded.
|
||||
* Validator set of this era must be equal to `SessionInterface::validators`.
|
||||
**/
|
||||
@@ -533,6 +595,7 @@ declare module '@polkadot/api/types/storage' {
|
||||
bonded: AugmentedQuery<ApiType, (arg: AccountId | string | Uint8Array) => Observable<Option<AccountId>>> & QueryableStorageEntry<ApiType>;
|
||||
/**
|
||||
* A mapping from still-bonded eras to the first session index of that era.
|
||||
*
|
||||
* Must contains information for eras for the range:
|
||||
* `[active_era - bounding_duration; active_era]`
|
||||
**/
|
||||
@@ -544,6 +607,7 @@ declare module '@polkadot/api/types/storage' {
|
||||
canceledSlashPayout: AugmentedQuery<ApiType, () => Observable<BalanceOf>> & QueryableStorageEntry<ApiType>;
|
||||
/**
|
||||
* The current era index.
|
||||
*
|
||||
* This is the latest planned era, depending on how the Session pallet queues the validator
|
||||
* set, it might be active or not.
|
||||
**/
|
||||
@@ -564,18 +628,23 @@ declare module '@polkadot/api/types/storage' {
|
||||
erasRewardPoints: AugmentedQuery<ApiType, (arg: EraIndex | AnyNumber | Uint8Array) => Observable<EraRewardPoints>> & QueryableStorageEntry<ApiType>;
|
||||
/**
|
||||
* Exposure of validator at era.
|
||||
*
|
||||
* This is keyed first by the era index to allow bulk deletion and then the stash account.
|
||||
*
|
||||
* Is it removed after `HISTORY_DEPTH` eras.
|
||||
* If stakers hasn't been set or has been removed then empty exposure is returned.
|
||||
**/
|
||||
erasStakers: AugmentedQueryDoubleMap<ApiType, (key1: EraIndex | AnyNumber | Uint8Array, key2: AccountId | string | Uint8Array) => Observable<Exposure>> & QueryableStorageEntry<ApiType>;
|
||||
/**
|
||||
* Clipped Exposure of validator at era.
|
||||
*
|
||||
* This is similar to [`ErasStakers`] but number of nominators exposed is reduced to the
|
||||
* `T::MaxNominatorRewardedPerValidator` biggest stakers.
|
||||
* (Note: the field `total` and `own` of the exposure remains unchanged).
|
||||
* This is used to limit the i/o cost for the nominator payout.
|
||||
*
|
||||
* This is keyed fist by the era index to allow bulk deletion and then the stash account.
|
||||
*
|
||||
* Is it removed after `HISTORY_DEPTH` eras.
|
||||
* If stakers hasn't been set or has been removed then empty exposure is returned.
|
||||
**/
|
||||
@@ -591,12 +660,15 @@ declare module '@polkadot/api/types/storage' {
|
||||
erasTotalStake: AugmentedQuery<ApiType, (arg: EraIndex | AnyNumber | Uint8Array) => Observable<BalanceOf>> & QueryableStorageEntry<ApiType>;
|
||||
/**
|
||||
* Similar to `ErasStakers`, this holds the preferences of validators.
|
||||
*
|
||||
* This is keyed first by the era index to allow bulk deletion and then the stash account.
|
||||
*
|
||||
* Is it removed after `HISTORY_DEPTH` eras.
|
||||
**/
|
||||
erasValidatorPrefs: AugmentedQueryDoubleMap<ApiType, (key1: EraIndex | AnyNumber | Uint8Array, key2: AccountId | string | Uint8Array) => Observable<ValidatorPrefs>> & QueryableStorageEntry<ApiType>;
|
||||
/**
|
||||
* The total validator era payout for the last `HISTORY_DEPTH` eras.
|
||||
*
|
||||
* Eras that haven't finished yet or has been removed doesn't have reward.
|
||||
**/
|
||||
erasValidatorReward: AugmentedQuery<ApiType, (arg: EraIndex | AnyNumber | Uint8Array) => Observable<Option<BalanceOf>>> & QueryableStorageEntry<ApiType>;
|
||||
@@ -606,10 +678,12 @@ declare module '@polkadot/api/types/storage' {
|
||||
forceEra: AugmentedQuery<ApiType, () => Observable<Forcing>> & QueryableStorageEntry<ApiType>;
|
||||
/**
|
||||
* Number of eras to keep in history.
|
||||
*
|
||||
* Information is kept for eras in `[current_era - history_depth; current_era]`.
|
||||
* Must be more than the number of eras delayed by session otherwise.
|
||||
* I.e. active era must always be in history.
|
||||
* I.e. `active_era > current_era - history_depth` must be guaranteed.
|
||||
*
|
||||
* Must be more than the number of eras delayed by session otherwise. I.e. active era must
|
||||
* always be in history. I.e. `active_era > current_era - history_depth` must be
|
||||
* guaranteed.
|
||||
**/
|
||||
historyDepth: AugmentedQuery<ApiType, () => Observable<u32>> & QueryableStorageEntry<ApiType>;
|
||||
/**
|
||||
@@ -627,10 +701,6 @@ declare module '@polkadot/api/types/storage' {
|
||||
* Map from all (unlocked) "controller" accounts to the info regarding the staking.
|
||||
**/
|
||||
ledger: AugmentedQuery<ApiType, (arg: AccountId | string | Uint8Array) => Observable<Option<StakingLedger>>> & QueryableStorageEntry<ApiType>;
|
||||
/**
|
||||
* The era where we migrated from Lazy Payouts to Simple Payouts
|
||||
**/
|
||||
migrateEra: AugmentedQuery<ApiType, () => Observable<Option<EraIndex>>> & QueryableStorageEntry<ApiType>;
|
||||
/**
|
||||
* Minimum number of staking participants before emergency conditions are imposed.
|
||||
**/
|
||||
@@ -656,13 +726,14 @@ declare module '@polkadot/api/types/storage' {
|
||||
/**
|
||||
* The score of the current [`QueuedElected`].
|
||||
**/
|
||||
queuedScore: AugmentedQuery<ApiType, () => Observable<Option<PhragmenScore>>> & QueryableStorageEntry<ApiType>;
|
||||
queuedScore: AugmentedQuery<ApiType, () => Observable<Option<ElectionScore>>> & QueryableStorageEntry<ApiType>;
|
||||
/**
|
||||
* Slashing spans for stash accounts.
|
||||
**/
|
||||
slashingSpans: AugmentedQuery<ApiType, (arg: AccountId | string | Uint8Array) => Observable<Option<SlashingSpans>>> & QueryableStorageEntry<ApiType>;
|
||||
/**
|
||||
* The percentage of the slash that is distributed to reporters.
|
||||
*
|
||||
* The rest of the slashed value is handled by the `Slash`.
|
||||
**/
|
||||
slashRewardFraction: AugmentedQuery<ApiType, () => Observable<Perbill>> & QueryableStorageEntry<ApiType>;
|
||||
@@ -684,9 +755,10 @@ declare module '@polkadot/api/types/storage' {
|
||||
/**
|
||||
* True if network has been upgraded to this version.
|
||||
* Storage version of the pallet.
|
||||
*
|
||||
* This is set to v3.0.0 for new networks.
|
||||
**/
|
||||
storageVersion: AugmentedQuery<ApiType, () => Observable<ReleasesStaking>> & QueryableStorageEntry<ApiType>;
|
||||
storageVersion: AugmentedQuery<ApiType, () => Observable<Releases>> & QueryableStorageEntry<ApiType>;
|
||||
/**
|
||||
* All unapplied slashes that are queued for later.
|
||||
**/
|
||||
@@ -722,14 +794,14 @@ declare module '@polkadot/api/types/storage' {
|
||||
* Total length (in bytes) for all extrinsics put together, for the current block.
|
||||
**/
|
||||
allExtrinsicsLen: AugmentedQuery<ApiType, () => Observable<Option<u32>>> & QueryableStorageEntry<ApiType>;
|
||||
/**
|
||||
* Total weight for all extrinsics put together, for the current block.
|
||||
**/
|
||||
allExtrinsicsWeight: AugmentedQuery<ApiType, () => Observable<Option<Weight>>> & QueryableStorageEntry<ApiType>;
|
||||
/**
|
||||
* Map of block numbers to block hashes.
|
||||
**/
|
||||
blockHash: AugmentedQuery<ApiType, (arg: BlockNumber | AnyNumber | Uint8Array) => Observable<Hash>> & QueryableStorageEntry<ApiType>;
|
||||
/**
|
||||
* The current weight for the block.
|
||||
**/
|
||||
blockWeight: AugmentedQuery<ApiType, () => Observable<ExtrinsicsWeight>> & QueryableStorageEntry<ApiType>;
|
||||
/**
|
||||
* Digest of the current block, also part of the block header.
|
||||
**/
|
||||
@@ -745,9 +817,11 @@ declare module '@polkadot/api/types/storage' {
|
||||
/**
|
||||
* Mapping between a topic (represented by T::Hash) and a vector of indexes
|
||||
* of events in the `<Events<T>>` list.
|
||||
*
|
||||
* All topic vectors have deterministic storage locations depending on the topic. This
|
||||
* allows light-clients to leverage the changes trie storage tracking mechanism and
|
||||
* in case of changes fetch the list of events of interest.
|
||||
*
|
||||
* The value has the type `(T::BlockNumber, EventIndex)` because if we used only just
|
||||
* the `EventIndex` then in case if the topic has the same contents on the next block
|
||||
* no notification will be triggered thus the event might be lost.
|
||||
@@ -835,6 +909,7 @@ declare module '@polkadot/api/types/storage' {
|
||||
transactionPayment: {
|
||||
[index: string]: QueryableStorageEntry<ApiType>;
|
||||
nextFeeMultiplier: AugmentedQuery<ApiType, () => Observable<Multiplier>> & QueryableStorageEntry<ApiType>;
|
||||
storageVersion: AugmentedQuery<ApiType, () => Observable<Releases>> & QueryableStorageEntry<ApiType>;
|
||||
};
|
||||
treasury: {
|
||||
[index: string]: QueryableStorageEntry<ApiType>;
|
||||
@@ -862,13 +937,6 @@ declare module '@polkadot/api/types/storage' {
|
||||
**/
|
||||
tips: AugmentedQuery<ApiType, (arg: Hash | string | Uint8Array) => Observable<Option<OpenTip>>> & QueryableStorageEntry<ApiType>;
|
||||
};
|
||||
utility: {
|
||||
[index: string]: QueryableStorageEntry<ApiType>;
|
||||
/**
|
||||
* The set of open multisig operations.
|
||||
**/
|
||||
multisigs: AugmentedQueryDoubleMap<ApiType, (key1: AccountId | string | Uint8Array, key2: U8aFixed | string | Uint8Array) => Observable<Option<Multisig>>> & QueryableStorageEntry<ApiType>;
|
||||
};
|
||||
vesting: {
|
||||
[index: string]: QueryableStorageEntry<ApiType>;
|
||||
/**
|
||||
|
||||
@@ -13,21 +13,16 @@ import { AuthorityId } from '@polkadot/types/interfaces/consensus';
|
||||
import { ContractCallRequest, ContractExecResult } from '@polkadot/types/interfaces/contracts';
|
||||
import { CreatedBlock } from '@polkadot/types/interfaces/engine';
|
||||
import { Extrinsic } from '@polkadot/types/interfaces/extrinsics';
|
||||
import { ReportedRoundStates } from '@polkadot/types/interfaces/grandpa';
|
||||
import { StorageKind } from '@polkadot/types/interfaces/offchain';
|
||||
import { RuntimeDispatchInfo } from '@polkadot/types/interfaces/payment';
|
||||
import { RpcMethods } from '@polkadot/types/interfaces/rpc';
|
||||
import { AccountId, BlockNumber, H256, Hash, Header, Index, Justification, KeyValue, SignedBlock, StorageData } from '@polkadot/types/interfaces/runtime';
|
||||
import { ReadProof, RuntimeVersion } from '@polkadot/types/interfaces/state';
|
||||
import { ChainProperties, ChainType, Health, NetworkState, NodeRole, PeerInfo } from '@polkadot/types/interfaces/system';
|
||||
import { ApplyExtrinsicResult, ChainProperties, ChainType, Health, NetworkState, NodeRole, PeerInfo } from '@polkadot/types/interfaces/system';
|
||||
|
||||
declare module '@polkadot/rpc-core/types.jsonrpc' {
|
||||
export interface RpcInterface {
|
||||
account: {
|
||||
/**
|
||||
* Retrieves the next accountIndex as available on the node
|
||||
**/
|
||||
nextIndex: AugmentedRpc<(accountId: AccountId | string | Uint8Array) => Observable<Index>>;
|
||||
};
|
||||
author: {
|
||||
/**
|
||||
* Returns true if the keystore has private keys for the given public key and key type.
|
||||
@@ -140,6 +135,12 @@ declare module '@polkadot/rpc-core/types.jsonrpc' {
|
||||
**/
|
||||
finalizeBlock: AugmentedRpc<(hash: BlockHash | string | Uint8Array, justification?: Justification | string | Uint8Array) => Observable<bool>>;
|
||||
};
|
||||
grandpa: {
|
||||
/**
|
||||
* Returns the state of the current best round state as well as the ongoing background rounds
|
||||
**/
|
||||
roundState: AugmentedRpc<() => Observable<ReportedRoundStates>>;
|
||||
};
|
||||
offchain: {
|
||||
/**
|
||||
* Get offchain local storage under given key and prefix
|
||||
@@ -237,6 +238,10 @@ declare module '@polkadot/rpc-core/types.jsonrpc' {
|
||||
subscribeStorage: AugmentedRpc<<T = Codec[]>(keys?: Vec<StorageKey> | (StorageKey | string | Uint8Array | any)[]) => Observable<T>>;
|
||||
};
|
||||
system: {
|
||||
/**
|
||||
* Retrieves the next accountIndex as available on the node
|
||||
**/
|
||||
accountNextIndex: AugmentedRpc<(accountId: AccountId | string | Uint8Array) => Observable<Index>>;
|
||||
/**
|
||||
* Adds a reserved peer
|
||||
**/
|
||||
@@ -249,6 +254,10 @@ declare module '@polkadot/rpc-core/types.jsonrpc' {
|
||||
* Retrieves the chain type
|
||||
**/
|
||||
chainType: AugmentedRpc<() => Observable<ChainType>>;
|
||||
/**
|
||||
* Dry run an extrinsic at a given block
|
||||
**/
|
||||
dryRun: AugmentedRpc<(extrinsic: Bytes | string | Uint8Array, at?: BlockHash | string | Uint8Array) => Observable<ApplyExtrinsicResult>>;
|
||||
/**
|
||||
* Return health status of the node
|
||||
**/
|
||||
|
||||
+1679
-477
File diff suppressed because it is too large
Load Diff
@@ -7,22 +7,21 @@ import { RpcInterface } from '@polkadot/rpc-core/types';
|
||||
import { Call, Hash, RuntimeVersion } from '@polkadot/types/interfaces';
|
||||
import { AnyFunction, CallFunction, Codec, CodecArg as Arg, ITuple, InterfaceTypes, ModulesWithCalls, Registry, RegistryTypes } from '@polkadot/types/types';
|
||||
import { SubmittableExtrinsic } from '../submittable/types';
|
||||
import { ApiInterfaceRx, ApiOptions, ApiTypes, DecorateMethod, DecoratedRpc, DecoratedRpcSection, QueryableModuleStorage, QueryableStorage, QueryableStorageEntry, QueryableStorageMulti, QueryableStorageMultiArg, SubmittableExtrinsicFunction, SubmittableExtrinsics, SubmittableModuleExtrinsics } from '../types';
|
||||
import { ApiInterfaceRx, ApiOptions, ApiTypes, DecorateMethod, DecoratedRpc, DecoratedRpcSection, PaginationOptions, QueryableModuleStorage, QueryableStorage, QueryableStorageEntry, QueryableStorageMulti, QueryableStorageMultiArg, SubmittableExtrinsicFunction, SubmittableExtrinsics, SubmittableModuleExtrinsics } from '../types';
|
||||
|
||||
import BN from 'bn.js';
|
||||
import { BehaviorSubject, Observable, combineLatest, of } from 'rxjs';
|
||||
import { map, switchMap, take, tap, toArray } from 'rxjs/operators';
|
||||
import { map, switchMap, tap, toArray } from 'rxjs/operators';
|
||||
import decorateDerive, { ExactDerive } from '@polkadot/api-derive';
|
||||
import { memo } from '@polkadot/api-derive/util';
|
||||
import DecoratedMeta from '@polkadot/metadata/Decorated';
|
||||
import getHasher from '@polkadot/metadata/Decorated/storage/fromMetadata/getHasher';
|
||||
import RpcCore from '@polkadot/rpc-core';
|
||||
import { WsProvider } from '@polkadot/rpc-provider';
|
||||
import { Metadata, Null, Option, Raw, Text, TypeRegistry, u64 } from '@polkadot/types';
|
||||
import Linkage, { LinkageResult } from '@polkadot/types/codec/Linkage';
|
||||
import { DEFAULT_VERSION as EXTRINSIC_DEFAULT_VERSION } from '@polkadot/types/extrinsic/constants';
|
||||
import StorageKey, { StorageEntry, unwrapStorageType } from '@polkadot/types/primitive/StorageKey';
|
||||
import { assert, compactStripLength, isNull, isUndefined, logger, u8aConcat, u8aToHex } from '@polkadot/util';
|
||||
import { assert, compactStripLength, logger, u8aToHex } from '@polkadot/util';
|
||||
|
||||
import { createSubmittable } from '../submittable';
|
||||
import augmentObject from '../util/augmentObject';
|
||||
@@ -32,7 +31,7 @@ import Events from './Events';
|
||||
|
||||
interface MetaDecoration {
|
||||
callIndex?: Uint8Array;
|
||||
meta: any;
|
||||
meta: Record<string, unknown>;
|
||||
method: string;
|
||||
section: string;
|
||||
toJSON: () => any;
|
||||
@@ -146,7 +145,7 @@ export default abstract class Decorate<ApiType extends ApiTypes> extends Events
|
||||
/**
|
||||
* @description Creates an instance of a type as registered
|
||||
*/
|
||||
public createType <K extends keyof InterfaceTypes> (type: K, ...params: any[]): InterfaceTypes[K] {
|
||||
public createType <K extends keyof InterfaceTypes> (type: K, ...params: unknown[]): InterfaceTypes[K] {
|
||||
return this.registry.createType(type, ...params);
|
||||
}
|
||||
|
||||
@@ -247,9 +246,9 @@ export default abstract class Decorate<ApiType extends ApiTypes> extends Events
|
||||
)
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
.forEach(([_, { method, section }]): void => {
|
||||
delete (this._rpc as any)[section][method];
|
||||
delete (this._rpcCore as any)[section][method];
|
||||
delete (this._rx.rpc as any)[section][method];
|
||||
delete (this._rpc as Record<string, Record<string, unknown>>)[section][method];
|
||||
delete (this._rpcCore as unknown as Record<string, Record<string, unknown>>)[section][method];
|
||||
delete (this._rx.rpc as Record<string, Record<string, unknown>>)[section][method];
|
||||
});
|
||||
}
|
||||
|
||||
@@ -258,11 +257,12 @@ export default abstract class Decorate<ApiType extends ApiTypes> extends Events
|
||||
const sectionName = _sectionName as keyof DecoratedRpc<ApiType, RpcInterface>;
|
||||
|
||||
// out and section here are horrors to get right from a typing perspective :(
|
||||
(out as any)[sectionName] = Object.entries(rpc[sectionName]).reduce((section, [methodName, method]): DecoratedRpcSection<ApiType, RpcInterface[typeof sectionName]> => {
|
||||
(out as Record<string, unknown>)[sectionName] = Object.entries(rpc[sectionName]).reduce((section, [methodName, method]): DecoratedRpcSection<ApiType, RpcInterface[typeof sectionName]> => {
|
||||
// skip subscriptions where we have a non-subscribe interface
|
||||
if (this.hasSubscriptions || !(methodName.startsWith('subscribe') || methodName.startsWith('unsubscribe'))) {
|
||||
(section as any)[methodName] = decorateMethod(method, { methodName });
|
||||
(section as any)[methodName].raw = decorateMethod(method.raw, { methodName });
|
||||
(section as Record<string, unknown>)[methodName] = decorateMethod(method, { methodName }) as unknown;
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
|
||||
(section as Record<string, { raw: unknown }>)[methodName].raw = decorateMethod(method.raw, { methodName }) as unknown;
|
||||
}
|
||||
|
||||
return section;
|
||||
@@ -273,10 +273,12 @@ export default abstract class Decorate<ApiType extends ApiTypes> extends Events
|
||||
}
|
||||
|
||||
protected _decorateMulti<ApiType extends ApiTypes> (decorateMethod: DecorateMethod<ApiType>): QueryableStorageMulti<ApiType> {
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-return
|
||||
return decorateMethod((calls: QueryableStorageMultiArg<ApiType>[]): Observable<Codec[]> =>
|
||||
this._rpcCore.state.subscribeStorage(
|
||||
calls.map((arg: QueryableStorageMultiArg<ApiType>): [QueryableStorageEntry<ApiType>, ...Arg[]] =>
|
||||
// the input is a QueryableStorageEntry, convert to StorageEntry
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-return
|
||||
Array.isArray(arg)
|
||||
? [arg[0].creator, ...arg.slice(1)]
|
||||
: [arg.creator] as any)));
|
||||
@@ -300,7 +302,8 @@ export default abstract class Decorate<ApiType extends ApiTypes> extends Events
|
||||
const decorated = (...params: Arg[]): SubmittableExtrinsic<ApiType> =>
|
||||
creator(method(...params));
|
||||
|
||||
return this._decorateFunctionMeta(method, decorated as any) as SubmittableExtrinsicFunction<ApiType>;
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-return
|
||||
return this._decorateFunctionMeta(method as any, decorated as any) as unknown as SubmittableExtrinsicFunction<ApiType>;
|
||||
}
|
||||
|
||||
protected _decorateStorage<ApiType extends ApiTypes> (storage: Storage, decorateMethod: DecorateMethod<ApiType>): QueryableStorage<ApiType> {
|
||||
@@ -317,21 +320,15 @@ export default abstract class Decorate<ApiType extends ApiTypes> extends Events
|
||||
|
||||
private _decorateStorageEntry<ApiType extends ApiTypes> (creator: StorageEntry, decorateMethod: DecorateMethod<ApiType>): QueryableStorageEntry<ApiType> {
|
||||
// get the storage arguments, with DoubleMap as an array entry, otherwise spread
|
||||
const getArgs = (...args: any[]): any[] => extractStorageArgs(creator, args);
|
||||
const getArgs = (...args: unknown[]): unknown[] => extractStorageArgs(creator, args);
|
||||
|
||||
// Disable this where it occurs for each field we are decorating
|
||||
/* eslint-disable @typescript-eslint/no-unsafe-member-access,@typescript-eslint/no-unsafe-assignment */
|
||||
|
||||
// FIXME We probably want to be able to query the full list with non-subs as well
|
||||
const decorated = this.hasSubscriptions && creator.iterKey && creator.meta.type.isMap && creator.meta.type.asMap.linked.isTrue
|
||||
? this._decorateStorageLinked(creator, decorateMethod)
|
||||
: decorateMethod((...args: any[]): Observable<Codec> => (
|
||||
this.hasSubscriptions
|
||||
? this._rpcCore.state
|
||||
// Unfortunately for one-shot calls we also use .subscribeStorage here
|
||||
.subscribeStorage<[Codec]>([getArgs(...args)])
|
||||
// state_storage returns an array of values, since we have just subscribed to
|
||||
// a single entry, we pull that from the array and return it as-is
|
||||
.pipe(map(([data]): Codec => data))
|
||||
: this._rpcCore.state.getStorage(getArgs(...args))
|
||||
), { methodName: creator.method });
|
||||
: this._decorateStorageCall(creator, decorateMethod);
|
||||
|
||||
decorated.creator = creator;
|
||||
|
||||
@@ -344,8 +341,8 @@ export default abstract class Decorate<ApiType extends ApiTypes> extends Events
|
||||
decorated.key = (arg1?: Arg, arg2?: Arg): string =>
|
||||
u8aToHex(compactStripLength(creator(creator.meta.type.isDoubleMap ? [arg1, arg2] : arg1))[1]);
|
||||
|
||||
decorated.keyPrefix = (): string =>
|
||||
u8aToHex(creator.keyPrefix);
|
||||
decorated.keyPrefix = (key1?: Arg): string =>
|
||||
u8aToHex(creator.keyPrefix(key1));
|
||||
|
||||
decorated.range = decorateMethod((range: [Hash, Hash?], arg1?: Arg, arg2?: Arg): Observable<[Hash, Codec][]> =>
|
||||
this._decorateStorageRange(decorated, [arg1, arg2], range));
|
||||
@@ -359,9 +356,17 @@ export default abstract class Decorate<ApiType extends ApiTypes> extends Events
|
||||
memo((doubleMapArg?: Arg): Observable<[StorageKey, Codec][]> =>
|
||||
this._retrieveMapEntries(creator, doubleMapArg)));
|
||||
|
||||
decorated.entriesPaged = decorateMethod(
|
||||
memo((opts: PaginationOptions): Observable<[StorageKey, Codec][]> =>
|
||||
this._retrieveMapEntriesPaged(creator, opts)));
|
||||
|
||||
decorated.keys = decorateMethod(
|
||||
memo((doubleMapArg?: Arg): Observable<StorageKey[]> =>
|
||||
this._retrieveMapKeys(creator, doubleMapArg)));
|
||||
|
||||
decorated.keysPaged = decorateMethod(
|
||||
memo((opts: PaginationOptions): Observable<StorageKey[]> =>
|
||||
this._retrieveMapKeysPaged(creator, opts)));
|
||||
}
|
||||
|
||||
// only support multi where subs are available
|
||||
@@ -372,7 +377,25 @@ export default abstract class Decorate<ApiType extends ApiTypes> extends Events
|
||||
args.map((arg: Arg[] | Arg): [StorageEntry, Arg | Arg[]] => [creator, arg])));
|
||||
}
|
||||
|
||||
return this._decorateFunctionMeta(creator, decorated) as unknown as QueryableStorageEntry<ApiType>;
|
||||
/* eslint-enable @typescript-eslint/no-unsafe-member-access,@typescript-eslint/no-unsafe-assignment */
|
||||
|
||||
return this._decorateFunctionMeta(creator as any, decorated) as unknown as QueryableStorageEntry<ApiType>;
|
||||
}
|
||||
|
||||
// Decorate the base storage call. In the case or rxjs or promise-without-callback (await)
|
||||
// we make a subscription, alternatively we push this through a single-shot query
|
||||
private _decorateStorageCall<ApiType extends ApiTypes> (creator: StorageEntry, decorateMethod: DecorateMethod<ApiType>): ReturnType<DecorateMethod<ApiType>> {
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-return
|
||||
return decorateMethod((...args: unknown[]): Observable<Codec> => {
|
||||
return this.hasSubscriptions
|
||||
? this._rpcCore.state.subscribeStorage<[Codec]>([extractStorageArgs(creator, args)]).pipe(
|
||||
map(([data]) => data) // extract first/only result from list
|
||||
)
|
||||
: this._rpcCore.state.getStorage(extractStorageArgs(creator, args));
|
||||
}, {
|
||||
methodName: creator.method,
|
||||
overrideNoSub: (...args: unknown[]) => this._rpcCore.state.getStorage(extractStorageArgs(creator, args))
|
||||
});
|
||||
}
|
||||
|
||||
private _decorateStorageRange<ApiType extends ApiTypes> (decorated: QueryableStorageEntry<ApiType>, args: [Arg?, Arg?], range: [Hash, Hash?]): Observable<[Hash, Codec][]> {
|
||||
@@ -388,10 +411,15 @@ export default abstract class Decorate<ApiType extends ApiTypes> extends Events
|
||||
));
|
||||
}
|
||||
|
||||
// This is deprecated/removed on substrate - we still have some live chains, eg. Edgeware needing it, so it
|
||||
// has not been dropped yet. Slated for removal in API 2.0
|
||||
private _decorateStorageLinked<ApiType extends ApiTypes> (creator: StorageEntry, decorateMethod: DecorateMethod<ApiType>): ReturnType<DecorateMethod<ApiType>> {
|
||||
const result: Map<Codec, ITuple<[Codec, Linkage<Codec>]> | null> = new Map();
|
||||
const result = new Map<Codec, ITuple<[Codec, Linkage<Codec>]> | null>();
|
||||
let subject: BehaviorSubject<LinkageResult>;
|
||||
let head: Codec | null = null;
|
||||
const iterKey = creator.iterKey;
|
||||
|
||||
assert(iterKey, 'iterKey field is missing');
|
||||
|
||||
// retrieve a value based on the key, iterating if it has a next entry. Since
|
||||
// entries can be re-linked in the middle of a list, we subscribe here to make
|
||||
@@ -449,48 +477,49 @@ export default abstract class Decorate<ApiType extends ApiTypes> extends Events
|
||||
|
||||
// this handles the case where the head changes effectively, i.e. a new entry
|
||||
// appears at the top of the list, the new getNext gets kicked off
|
||||
return decorateMethod((...args: any[]): Observable<LinkageResult | [Codec, Linkage<Codec>]> =>
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-return
|
||||
return decorateMethod((...args: unknown[]): Observable<LinkageResult | [Codec, Linkage<Codec>]> =>
|
||||
args.length
|
||||
? this._rpcCore.state
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
|
||||
.subscribeStorage<[[Codec, Linkage<Codec>]]>([[creator, ...args]])
|
||||
.pipe(map(([data]): [Codec, Linkage<Codec>] => data))
|
||||
.pipe(map(([data]) => data))
|
||||
: this._rpcCore.state
|
||||
.subscribeStorage<[LinkageResult]>([creator.iterKey])
|
||||
.pipe(switchMap(([key]): Observable<LinkageResult> => getNext(head = key)))
|
||||
.subscribeStorage<[LinkageResult]>([iterKey()])
|
||||
.pipe(switchMap(([key]) => getNext(head = key)))
|
||||
);
|
||||
}
|
||||
|
||||
private _retrieveMapKeys ({ iterKey, meta }: StorageEntry, arg?: Arg): Observable<StorageKey[]> {
|
||||
assert(iterKey && (meta.type.isMap || meta.type.isDoubleMap), 'keys can only be retrieved on maps, linked maps and double maps');
|
||||
|
||||
const headKey = this.createType('Raw', u8aConcat(
|
||||
iterKey,
|
||||
meta.type.isDoubleMap && !isUndefined(arg) && !isNull(arg)
|
||||
? getHasher(meta.type.asDoubleMap.hasher)(
|
||||
this.createType(meta.type.asDoubleMap.key1.toString() as 'Raw', arg).toU8a()
|
||||
)
|
||||
: new Uint8Array([])
|
||||
)).toHex();
|
||||
const headKey = iterKey(arg).toHex();
|
||||
const startSubject = new BehaviorSubject<string>(headKey);
|
||||
|
||||
return this._rpcCore.state.getKeysPaged
|
||||
? startSubject.pipe(
|
||||
switchMap((startKey) =>
|
||||
this._rpcCore.state.getKeysPaged(headKey, PAGE_SIZE_KEYS, startKey).pipe(
|
||||
map((keys) => keys.map((key) => key.setMeta(meta)))
|
||||
)
|
||||
),
|
||||
tap((keys): void => {
|
||||
keys.length === PAGE_SIZE_KEYS
|
||||
? startSubject.next(keys[PAGE_SIZE_KEYS - 1].toHex())
|
||||
: startSubject.complete();
|
||||
}),
|
||||
toArray(), // toArray since we want to startSubject to be completed
|
||||
map((keysArr: StorageKey[][]) => keysArr.reduce((result: StorageKey[], keys) => result.concat(keys), []))
|
||||
)
|
||||
: this._rpcCore.state.getKeys(headKey).pipe(
|
||||
map((keys) => keys.map((key) => key.setMeta(meta)))
|
||||
);
|
||||
return startSubject.pipe(
|
||||
switchMap((startKey) =>
|
||||
this._rpcCore.state.getKeysPaged(headKey, PAGE_SIZE_KEYS, startKey).pipe(
|
||||
map((keys) => keys.map((key) => key.setMeta(meta)))
|
||||
)
|
||||
),
|
||||
tap((keys): void => {
|
||||
keys.length === PAGE_SIZE_KEYS
|
||||
? startSubject.next(keys[PAGE_SIZE_KEYS - 1].toHex())
|
||||
: startSubject.complete();
|
||||
}),
|
||||
toArray(), // toArray since we want to startSubject to be completed
|
||||
map((keysArr: StorageKey[][]) => keysArr.reduce((result: StorageKey[], keys) => result.concat(keys), []))
|
||||
);
|
||||
}
|
||||
|
||||
private _retrieveMapKeysPaged ({ iterKey, meta }: StorageEntry, opts: PaginationOptions): Observable<StorageKey[]> {
|
||||
assert(iterKey && (meta.type.isMap || meta.type.isDoubleMap), 'keys can only be retrieved on maps, linked maps and double maps');
|
||||
|
||||
const headKey = iterKey(opts.arg).toHex();
|
||||
|
||||
return this._rpcCore.state.getKeysPaged(headKey, opts.pageSize, opts.startKey || headKey).pipe(
|
||||
map((keys) => keys.map((key) => key.setMeta(meta)))
|
||||
);
|
||||
}
|
||||
|
||||
private _retrieveMapEntries (entry: StorageEntry, arg?: Arg): Observable<[StorageKey, Codec][]> {
|
||||
@@ -500,13 +529,27 @@ export default abstract class Decorate<ApiType extends ApiTypes> extends Events
|
||||
of(keys),
|
||||
...Array(Math.ceil(keys.length / PAGE_SIZE_VALS))
|
||||
.fill(0)
|
||||
.map((_, index): Observable<Codec[]> => {
|
||||
const keyset = keys.slice(index * PAGE_SIZE_VALS, (index * PAGE_SIZE_VALS) + PAGE_SIZE_VALS);
|
||||
.map((_, index): Observable<Codec[]> =>
|
||||
this._rpcCore.state.queryStorageAt<Codec[]>(
|
||||
keys.slice(index * PAGE_SIZE_VALS, (index * PAGE_SIZE_VALS) + PAGE_SIZE_VALS)
|
||||
)
|
||||
)
|
||||
])
|
||||
),
|
||||
map(([keys, ...valsArr]): [StorageKey, Codec][] =>
|
||||
valsArr
|
||||
.reduce((result: Codec[], vals) => result.concat(vals), [])
|
||||
.map((value, index) => [keys[index], value])
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
return this._rpcCore.state.queryStorageAt
|
||||
? this._rpcCore.state.queryStorageAt<Codec[]>(keyset)
|
||||
: this._rpcCore.state.subscribeStorage<Codec[]>(keyset).pipe(take(1));
|
||||
})
|
||||
private _retrieveMapEntriesPaged (entry: StorageEntry, opts: PaginationOptions): Observable<[StorageKey, Codec][]> {
|
||||
return this._retrieveMapKeysPaged(entry, opts).pipe(
|
||||
switchMap((keys) =>
|
||||
combineLatest<[StorageKey[], ...Codec[][]]>([
|
||||
of(keys),
|
||||
this._rpcCore.state.queryStorageAt<Codec[]>(keys)
|
||||
])
|
||||
),
|
||||
map(([keys, ...valsArr]): [StorageKey, Codec][] =>
|
||||
|
||||
@@ -5,11 +5,11 @@
|
||||
import { SignedBlock, RuntimeVersion } from '@polkadot/types/interfaces';
|
||||
import { ApiBase, ApiOptions, ApiTypes, DecorateMethod } from '../types';
|
||||
|
||||
import { Subscription, combineLatest, of } from 'rxjs';
|
||||
import { Observable, Subscription, of } from 'rxjs';
|
||||
import { map, switchMap } from 'rxjs/operators';
|
||||
import { Metadata, Text } from '@polkadot/types';
|
||||
import { LATEST_EXTRINSIC_VERSION } from '@polkadot/types/extrinsic/Extrinsic';
|
||||
import { getMetadataTypes, getSpecTypes } from '@polkadot/types-known';
|
||||
import { getMetadataTypes, getSpecAlias, getSpecTypes } from '@polkadot/types-known';
|
||||
import { logger } from '@polkadot/util';
|
||||
import { cryptoWaitReady } from '@polkadot/util-crypto';
|
||||
|
||||
@@ -35,6 +35,7 @@ export default abstract class Init<ApiType extends ApiTypes> extends Decorate<Ap
|
||||
this.registry.setKnownTypes({
|
||||
types: options.types,
|
||||
typesAlias: options.typesAlias,
|
||||
typesBundle: options.typesBundle,
|
||||
typesChain: options.typesChain,
|
||||
typesSpec: options.typesSpec
|
||||
});
|
||||
@@ -62,6 +63,7 @@ export default abstract class Init<ApiType extends ApiTypes> extends Decorate<Ap
|
||||
// 'connected' event, then the `on('connected')` won't fire anymore. To
|
||||
// cater for this case, we call manually `this._onProviderConnect`.
|
||||
if (this._rpcCore.provider.isConnected()) {
|
||||
// eslint-disable-next-line @typescript-eslint/no-floating-promises
|
||||
this.#onProviderConnect();
|
||||
}
|
||||
}
|
||||
@@ -107,7 +109,7 @@ export default abstract class Init<ApiType extends ApiTypes> extends Decorate<Ap
|
||||
// manually build a list of all available methods in this RPC, we are
|
||||
// going to filter on it to align the cloned RPC without making a call
|
||||
Object.keys(source.rpc).forEach((section): void => {
|
||||
Object.keys((source.rpc as any)[section]).forEach((method): void => {
|
||||
Object.keys((source.rpc as Record<string, Record<string, unknown>>)[section]).forEach((method): void => {
|
||||
methods.push(`${section}_${method}`);
|
||||
});
|
||||
});
|
||||
@@ -124,31 +126,55 @@ export default abstract class Init<ApiType extends ApiTypes> extends Decorate<Ap
|
||||
}
|
||||
|
||||
this.#updateSub = this._rpcCore.state.subscribeRuntimeVersion().pipe(
|
||||
switchMap((version: RuntimeVersion) =>
|
||||
combineLatest(
|
||||
of(version),
|
||||
this._rpcCore.state.getMetadata()
|
||||
)
|
||||
),
|
||||
map(([version, metadata]: [RuntimeVersion, Metadata]): boolean => {
|
||||
if (this._runtimeVersion?.specVersion.eq(version.specVersion)) {
|
||||
return false;
|
||||
}
|
||||
switchMap((version: RuntimeVersion): Observable<boolean> =>
|
||||
// only retrieve the metadata when the on-chain version has been changed
|
||||
this._runtimeVersion?.specVersion.eq(version.specVersion)
|
||||
? of(false)
|
||||
: this._rpcCore.state.getMetadata().pipe(
|
||||
map((metadata: Metadata): boolean => {
|
||||
l.log(`Runtime version updated to spec=${version.specVersion.toString()}, tx=${version.transactionVersion.toString()}`);
|
||||
|
||||
l.log(`Runtime version updated to ${version.specVersion}`);
|
||||
this._runtimeMetadata = metadata;
|
||||
this._runtimeVersion = version;
|
||||
this._rx.runtimeVersion = version;
|
||||
|
||||
this._runtimeMetadata = metadata;
|
||||
this._runtimeVersion = version;
|
||||
this._rx.runtimeVersion = version;
|
||||
this.registerTypes(getSpecTypes(this.registry, this._runtimeChain as Text, version.specName, version.specVersion));
|
||||
this.injectMetadata(metadata, false);
|
||||
|
||||
this.registerTypes(getSpecTypes(this.registry, this._runtimeChain as Text, version.specName, version.specVersion));
|
||||
this.injectMetadata(metadata, false);
|
||||
|
||||
return true;
|
||||
})
|
||||
return true;
|
||||
})
|
||||
)
|
||||
)
|
||||
).subscribe();
|
||||
}
|
||||
|
||||
private _adjustBundleTypes (chain: Text, specName: Text): void {
|
||||
// adjust known type aliases
|
||||
this.registry.knownTypes.typesAlias = getSpecAlias(this.registry, chain, specName);
|
||||
|
||||
// FIXME For the first round, we are not adjusting the user-injected RPCs
|
||||
// inject any user-level RPCs now that we have the chain/spec
|
||||
// this._rpcCore.addUserInterfaces(getSpecRpc(this.registry, chain, specName));
|
||||
|
||||
// const extraRpc = this._decorateRpc(this._rpcCore, this._decorateMethod);
|
||||
|
||||
// // FIXME this is a mess
|
||||
// Object.entries(extraRpc).forEach(([section, value]): void => {
|
||||
// if (this._rpc) {
|
||||
// if (!this._rpc[section as 'author']) {
|
||||
// this._rpc[section as 'author'] = {} as DecoratedRpcSection<ApiType, RpcInterface['author']>;
|
||||
// }
|
||||
|
||||
// Object.entries(value).forEach(([name, method]): void => {
|
||||
// if (this._rpc && !this._rpc[section as 'author'][name as 'hasKey']) {
|
||||
// // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
|
||||
// this._rpc[section as 'author'][name as 'hasKey'] = method;
|
||||
// }
|
||||
// });
|
||||
// }
|
||||
// });
|
||||
}
|
||||
|
||||
private async _metaFromChain (optMetadata: Record<string, string>): Promise<Metadata> {
|
||||
const [runtimeVersion, chain, chainProps] = await Promise.all([
|
||||
this._rpcCore.state.getRuntimeVersion().toPromise(),
|
||||
@@ -159,6 +185,12 @@ export default abstract class Init<ApiType extends ApiTypes> extends Decorate<Ap
|
||||
// set our chain version & genesisHash as returned
|
||||
this._runtimeChain = chain;
|
||||
this._runtimeVersion = runtimeVersion;
|
||||
this._rx.runtimeVersion = runtimeVersion;
|
||||
|
||||
// adjust types based on bundled info
|
||||
if (this.registry.knownTypes.typesBundle) {
|
||||
this._adjustBundleTypes(chain, runtimeVersion.specName);
|
||||
}
|
||||
|
||||
// do the setup for the specific chain
|
||||
this.registry.setChainProperties(chainProps);
|
||||
@@ -169,7 +201,7 @@ export default abstract class Init<ApiType extends ApiTypes> extends Decorate<Ap
|
||||
await this._filterRpc();
|
||||
|
||||
// retrieve metadata, either from chain or as pass-in via options
|
||||
const metadataKey = `${this._genesisHash}-${runtimeVersion.specVersion}`;
|
||||
const metadataKey = `${this._genesisHash?.toHex() || '0x'}-${runtimeVersion.specVersion.toString()}`;
|
||||
const metadata = metadataKey in optMetadata
|
||||
? new Metadata(this.registry, optMetadata[metadataKey])
|
||||
: await this._rpcCore.state.getMetadata().toPromise();
|
||||
@@ -234,7 +266,7 @@ export default abstract class Init<ApiType extends ApiTypes> extends Decorate<Ap
|
||||
});
|
||||
}, KEEPALIVE_INTERVAL);
|
||||
} catch (_error) {
|
||||
const error = new Error(`FATAL: Unable to initialize the API: ${_error.message}`);
|
||||
const error = new Error(`FATAL: Unable to initialize the API: ${(_error as Error).message}`);
|
||||
|
||||
l.error(error);
|
||||
|
||||
|
||||
@@ -29,8 +29,8 @@ interface PkgJson {
|
||||
let pkgJson: PkgJson = { name: '@polkadot/api', version: '-' };
|
||||
|
||||
import('../package.json')
|
||||
.then((_pkgJson: any): void => {
|
||||
pkgJson = _pkgJson;
|
||||
.then((_pkgJson: unknown): void => {
|
||||
pkgJson = _pkgJson as PkgJson;
|
||||
})
|
||||
.catch((): void => {
|
||||
// ignore
|
||||
|
||||
@@ -87,7 +87,7 @@ async function query (api: ApiPromise, keyring: TestKeyringMap): Promise<void> {
|
||||
// check range types
|
||||
const entries = await api.query.system.events.range(['0x12345', '0x7890']);
|
||||
|
||||
console.log(`Received ${entries.length} entries, ${entries.map(([hash, events]) => `${hash.toHex()}: ${events.length} events`)}`);
|
||||
console.log(`Received ${entries.length} entries, ${entries.map(([hash, events]) => `${hash.toHex()}: ${events.length} events`).join(', ')}`);
|
||||
}
|
||||
|
||||
async function rpc (api: ApiPromise): Promise<void> {
|
||||
@@ -105,6 +105,7 @@ async function rpc (api: ApiPromise): Promise<void> {
|
||||
await api.rpc.chain.getBlock.raw('0x123456');
|
||||
|
||||
// using raw subs
|
||||
// eslint-disable-next-line @typescript-eslint/no-floating-promises
|
||||
api.rpc.chain.subscribeNewHeads.raw((result: Uint8Array): void => {
|
||||
console.log(result);
|
||||
});
|
||||
@@ -125,7 +126,7 @@ function types (api: ApiPromise): void {
|
||||
|
||||
async function tx (api: ApiPromise, keyring: TestKeyringMap): Promise<void> {
|
||||
// transfer, also allows for BigInt inputs here
|
||||
const transfer = api.tx.balances.transfer(keyring.bob.address, 123_456_789n);
|
||||
const transfer = api.tx.balances.transfer(keyring.bob.address, 123456789n);
|
||||
|
||||
console.log('transfer as Call', transfer as IMethod);
|
||||
console.log('transfer as Extrinsic', transfer as IExtrinsic);
|
||||
@@ -159,8 +160,9 @@ async function tx (api: ApiPromise, keyring: TestKeyringMap): Promise<void> {
|
||||
});
|
||||
|
||||
// it allows for query & then using the submittable
|
||||
const second = api.tx.democracy.second(123);
|
||||
const second = api.tx.democracy.second(123, 5);
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-floating-promises
|
||||
second.signAndSend('123', (result): void => {
|
||||
console.log(result);
|
||||
});
|
||||
@@ -173,12 +175,15 @@ async function main (): Promise<void> {
|
||||
const api = await ApiPromise.create();
|
||||
const keyring = testKeyring();
|
||||
|
||||
consts(api);
|
||||
derive(api);
|
||||
query(api, keyring);
|
||||
rpc(api);
|
||||
types(api);
|
||||
tx(api, keyring);
|
||||
// eslint-disable-next-line @typescript-eslint/no-floating-promises
|
||||
Promise.all([
|
||||
consts(api),
|
||||
derive(api),
|
||||
query(api, keyring),
|
||||
rpc(api),
|
||||
types(api),
|
||||
tx(api, keyring)
|
||||
]);
|
||||
}
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/unbound-method
|
||||
|
||||
@@ -13,7 +13,7 @@ import { hexToU8a } from '@polkadot/util';
|
||||
import { SingleAccountSigner } from '../../test/util';
|
||||
import ApiPromise from './Api';
|
||||
|
||||
const TRANSFER_SIG = '0xa1d493ab6b74550da434fbc153a739429be68c9d30e59e631fb5d08f348504deefb5577f4824e138741ad102f479109827e8fa9552812a3e5f505a24d10e820f';
|
||||
const TRANSFER_SIG = '0x7a10e5ed9a14284eca7bea53f81631981dddda5a3d2dee973b136475947264801465726e4829ae3994d9058df638d959d4e043c7f1924299546790dda1dea20a';
|
||||
|
||||
describe('ApiPromise', (): void => {
|
||||
const registry = new TypeRegistry();
|
||||
@@ -39,7 +39,7 @@ describe('ApiPromise', (): void => {
|
||||
|
||||
const signer = new SingleAccountSigner(registry, aliceEd);
|
||||
const api = await ApiPromise.create({ provider, registry, signer });
|
||||
const transfer = api.tx.balances.transfer(keyring.getPair('0xe659a7a1628cdd93febc04a4e0646ea20e9f5f0ce097d9a05290d4a9e054df4e').address, 321_564_789_876_512_345n);
|
||||
const transfer = api.tx.balances.transfer(keyring.getPair('0xe659a7a1628cdd93febc04a4e0646ea20e9f5f0ce097d9a05290d4a9e054df4e').address, 321564789876512345n);
|
||||
|
||||
return { api, transfer: await transfer.signAsync(aliceEd.address, {}) };
|
||||
}
|
||||
@@ -57,8 +57,10 @@ describe('ApiPromise', (): void => {
|
||||
const metadata: any = {};
|
||||
const key = `${genesisHash}-${specVersion}`;
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
|
||||
metadata[key] = rpcData;
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
|
||||
const api = await ApiPromise.create({ metadata, provider, registry } as ApiOptions);
|
||||
|
||||
expect(api.genesisHash).toBeDefined();
|
||||
|
||||
@@ -2,30 +2,30 @@
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the Apache-2.0 license. See the LICENSE file for details.
|
||||
|
||||
import { AnyFunction, Callback, Codec } from '@polkadot/types/types';
|
||||
import { ApiOptions, DecorateMethodOptions, ObsInnerType, StorageEntryPromiseOverloads, UnsubscribePromise } from '../types';
|
||||
import { Callback, Codec } from '@polkadot/types/types';
|
||||
import { ApiOptions, DecorateFn, DecorateMethodOptions, ObsInnerType, StorageEntryPromiseOverloads, UnsubscribePromise, VoidFn } from '../types';
|
||||
|
||||
import { Observable, EMPTY } from 'rxjs';
|
||||
import { catchError, first, tap } from 'rxjs/operators';
|
||||
import { EMPTY, Observable, Subscription } from 'rxjs';
|
||||
import { catchError, tap } from 'rxjs/operators';
|
||||
import { isFunction, assert } from '@polkadot/util';
|
||||
|
||||
import ApiBase from '../base';
|
||||
import Combinator, { CombinatorCallback, CombinatorFunction } from './Combinator';
|
||||
|
||||
interface Tracker {
|
||||
interface Tracker<T> {
|
||||
reject: (value: Error) => Observable<never>;
|
||||
resolve: (value: () => void) => void;
|
||||
resolve: (value: T) => void;
|
||||
}
|
||||
|
||||
// extract the arguments and callback params from a value array possibly containing a callback
|
||||
function extractArgs (args: any[], needsCallback: boolean): [any[], Callback<Codec> | undefined] {
|
||||
function extractArgs (args: unknown[], needsCallback: boolean): [unknown[], Callback<Codec> | undefined] {
|
||||
let callback: Callback<Codec> | undefined;
|
||||
const actualArgs = args.slice();
|
||||
|
||||
// If the last arg is a function, we pop it, put it into callback.
|
||||
// actualArgs will then hold the actual arguments to be passed to `method`
|
||||
if (args.length && isFunction(args[args.length - 1])) {
|
||||
callback = actualArgs.pop();
|
||||
callback = actualArgs.pop() as Callback<Codec>;
|
||||
}
|
||||
|
||||
// When we need a subscription, ensure that a valid callback is actually passed
|
||||
@@ -35,57 +35,79 @@ function extractArgs (args: any[], needsCallback: boolean): [any[], Callback<Cod
|
||||
}
|
||||
|
||||
// a Promise completion tracker, wrapping an isComplete variable that ensures the promise only resolves once
|
||||
function promiseTracker (resolve: (value: () => void) => void, reject: (value: Error) => void): Tracker {
|
||||
function promiseTracker<T> (resolve: (value: T) => void, reject: (value: Error) => void): Tracker<T> {
|
||||
let isCompleted = false;
|
||||
|
||||
const complete = (fn: Function, value: any): void => {
|
||||
if (!isCompleted) {
|
||||
isCompleted = true;
|
||||
|
||||
fn(value);
|
||||
}
|
||||
};
|
||||
|
||||
return {
|
||||
reject: (error: Error): Observable<never> => {
|
||||
complete(reject, error);
|
||||
if (!isCompleted) {
|
||||
isCompleted = true;
|
||||
|
||||
reject(error);
|
||||
}
|
||||
|
||||
return EMPTY;
|
||||
},
|
||||
resolve: (value: any): void => {
|
||||
complete(resolve, value);
|
||||
resolve: (value: T): void => {
|
||||
if (!isCompleted) {
|
||||
isCompleted = true;
|
||||
|
||||
resolve(value);
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
// Decorate a call for a single-shot result - retrieve and then immediate unsubscribe
|
||||
function decorateCall<Method extends DecorateFn<ObsInnerType<ReturnType<Method>>>> (method: Method, actualArgs: unknown[]): Promise<ObsInnerType<ReturnType<Method>>> {
|
||||
return new Promise((resolve, reject): void => {
|
||||
// single result tracker - either reject with Error or resolve with Codec result
|
||||
const tracker = promiseTracker(resolve, reject);
|
||||
|
||||
// errors reject immediately, any result unsubscribes and resolves
|
||||
const subscription: Subscription = method(...actualArgs).pipe(
|
||||
catchError((error) => tracker.reject(error))
|
||||
).subscribe((result): void => {
|
||||
tracker.resolve(result);
|
||||
typeof setImmediate === 'undefined'
|
||||
? setTimeout(() => subscription.unsubscribe(), 0)
|
||||
: setImmediate(() => subscription.unsubscribe());
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
// Decorate a subscription where we have a result callback specified
|
||||
function decorateSubscribe<Method extends DecorateFn<ObsInnerType<ReturnType<Method>>>> (method: Method, actualArgs: unknown[], resultCb: Callback<Codec>): UnsubscribePromise {
|
||||
return new Promise<VoidFn>((resolve, reject): void => {
|
||||
// either reject with error or resolve with unsubscribe callback
|
||||
const tracker = promiseTracker(resolve, reject);
|
||||
|
||||
// errors reject immediately, the first result resolves with an unsubscribe promise, all results via callback
|
||||
const subscription: Subscription = method(...actualArgs).pipe(
|
||||
catchError((error) => tracker.reject(error)),
|
||||
tap(() => tracker.resolve(() => subscription.unsubscribe()))
|
||||
).subscribe((result): void => {
|
||||
// We use setImmediate here to ensure that the Promise above (tracker) has resolved, before returning
|
||||
// the first result. By putting is back in the queue, the promise above is guarded for first execution
|
||||
typeof setImmediate === 'undefined'
|
||||
? setTimeout(() => resultCb(result) as void, 0)
|
||||
: setImmediate(() => resultCb(result) as void);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Decorate method for ApiPromise, where the results are converted to the Promise equivalent
|
||||
*/
|
||||
export function decorateMethod<Method extends AnyFunction> (method: Method, options?: DecorateMethodOptions): StorageEntryPromiseOverloads {
|
||||
export function decorateMethod<Method extends DecorateFn<ObsInnerType<ReturnType<Method>>>> (method: Method, options?: DecorateMethodOptions): StorageEntryPromiseOverloads {
|
||||
const needsCallback = options && options.methodName && options.methodName.includes('subscribe');
|
||||
|
||||
return function (...args: any[]): Promise<ObsInnerType<ReturnType<Method>>> | UnsubscribePromise {
|
||||
const [actualArgs, callback] = extractArgs(args, !!needsCallback);
|
||||
return function (...args: unknown[]): Promise<ObsInnerType<ReturnType<Method>>> | UnsubscribePromise {
|
||||
const [actualArgs, resultCb] = extractArgs(args, !!needsCallback);
|
||||
|
||||
if (!callback) {
|
||||
return method(...actualArgs).pipe(first()).toPromise() as Promise<ObsInnerType<ReturnType<Method>>>;
|
||||
}
|
||||
|
||||
return new Promise((resolve, reject): void => {
|
||||
const tracker = promiseTracker(resolve, reject);
|
||||
const subscription = method(...actualArgs)
|
||||
.pipe(
|
||||
// if we find an error (invalid params, etc), reject the promise
|
||||
catchError((error): Observable<never> =>
|
||||
tracker.reject(error)
|
||||
),
|
||||
// upon the first result, resolve with the unsub function
|
||||
tap((): void =>
|
||||
tracker.resolve((): void => subscription.unsubscribe())
|
||||
)
|
||||
)
|
||||
.subscribe(callback);
|
||||
}) as any; // ???
|
||||
return resultCb
|
||||
? decorateSubscribe(method, actualArgs, resultCb)
|
||||
: decorateCall((options?.overrideNoSub as Method) || method, actualArgs);
|
||||
} as StorageEntryPromiseOverloads;
|
||||
}
|
||||
|
||||
|
||||
@@ -41,6 +41,7 @@ export default class Combinator<T extends any[] = any[]> {
|
||||
this.#fns.push(fn);
|
||||
|
||||
// Not quite 100% how to have a variable number at the front here
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-return,@typescript-eslint/ban-types
|
||||
return (fn as Function)(...args, this._createCallback(index));
|
||||
});
|
||||
}
|
||||
@@ -54,7 +55,7 @@ export default class Combinator<T extends any[] = any[]> {
|
||||
}
|
||||
|
||||
protected _createCallback (index: number): (value: any) => void {
|
||||
return (value: any): void => {
|
||||
return (value: unknown): void => {
|
||||
this.#fired[index] = true;
|
||||
this.#results[index] = value;
|
||||
|
||||
@@ -68,6 +69,7 @@ export default class Combinator<T extends any[] = any[]> {
|
||||
}
|
||||
|
||||
try {
|
||||
// eslint-disable-next-line @typescript-eslint/no-floating-promises
|
||||
this.#callback(this.#results as T);
|
||||
} catch (error) {
|
||||
// swallow, we don't want the handler to trip us up
|
||||
|
||||
@@ -49,5 +49,22 @@ describe('ApiRx', (): void => {
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
it('allows the second argument to signAsync to be omitted', () => {
|
||||
const signer = new SingleAccountSigner(registry, keyring.alice_session);
|
||||
|
||||
ApiRx.create({ provider, registry, signer }).pipe(
|
||||
switchMap((api: ApiRx): Observable<SubmittableExtrinsic<'rxjs'>> =>
|
||||
api.tx.balances
|
||||
.transfer(keyring.eve.address, 12345)
|
||||
.signAsync(keyring.alice_session)
|
||||
),
|
||||
map((tx: SubmittableExtrinsic<'rxjs'>): void => {
|
||||
expect(tx.signature.toHex()).toEqual(
|
||||
'0x97f3cfe5088fcd575313e983f45d02b0f630e7b94ff9a3ac50e20cd096a8f554fda73d42ead891b5a1d3ce5607d83f20b0c6570b555e949cfb5763d0abcd590b'
|
||||
);
|
||||
})
|
||||
);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -2,14 +2,14 @@
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the Apache-2.0 license. See the LICENSE file for details.
|
||||
|
||||
import { AnyFunction } from '@polkadot/types/types';
|
||||
import { ApiOptions } from '../types';
|
||||
import { Codec } from '@polkadot/types/types';
|
||||
import { ApiOptions, DecorateFn } from '../types';
|
||||
|
||||
import { from, Observable } from 'rxjs';
|
||||
|
||||
import ApiBase from '../base';
|
||||
|
||||
export function decorateMethod <Method extends AnyFunction> (method: Method): Method {
|
||||
export function decorateMethod <Method extends DecorateFn<Codec>> (method: Method): Method {
|
||||
return method;
|
||||
}
|
||||
|
||||
|
||||
@@ -41,6 +41,7 @@ export default function createClass <ApiType extends ApiTypes> ({ api, apiType,
|
||||
const [allOptions] = this.#makeSignAndSendOptions(options);
|
||||
const address = isKeyringPair(account) ? account.address : account.toString();
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-return,@typescript-eslint/no-unsafe-call
|
||||
return decorateMethod(
|
||||
(): Observable<RuntimeDispatchInfo> =>
|
||||
api.derive.tx.signingInfo(address, allOptions.nonce, allOptions.era).pipe(
|
||||
@@ -60,7 +61,7 @@ export default function createClass <ApiType extends ApiTypes> ({ api, apiType,
|
||||
}
|
||||
|
||||
// sign a transaction, returning the this to allow chaining, i.e. .sign(...).send()
|
||||
public sign (account: IKeyringPair, optionsOrNonce: Partial<SignerOptions>): this {
|
||||
public sign (account: IKeyringPair, optionsOrNonce?: Partial<SignerOptions>): this {
|
||||
super.sign(account, this.#makeSignOptions(this.#optionsOrNonce(optionsOrNonce), {}));
|
||||
|
||||
return this;
|
||||
@@ -69,7 +70,8 @@ export default function createClass <ApiType extends ApiTypes> ({ api, apiType,
|
||||
// signs a transaction, returning `this` to allow chaining. E.g.: `sign(...).send()`
|
||||
//
|
||||
// also supports signing through external signers
|
||||
public signAsync (account: AddressOrPair, optionsOrNonce: Partial<SignerOptions>): SubmittableThis<ApiType, this> {
|
||||
public signAsync (account: AddressOrPair, optionsOrNonce?: Partial<SignerOptions>): SubmittableThis<ApiType, this> {
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-return,@typescript-eslint/no-unsafe-call
|
||||
return decorateMethod(
|
||||
(): Observable<this> =>
|
||||
this.#observeSign(account, optionsOrNonce).pipe(mapTo(this))
|
||||
@@ -90,6 +92,7 @@ export default function createClass <ApiType extends ApiTypes> ({ api, apiType,
|
||||
const [options, statusCb] = this.#makeSignAndSendOptions(optionsOrStatus, optionalStatusCb);
|
||||
const isSubscription = api.hasSubscriptions && (this.#ignoreStatusCb || !!statusCb);
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-return,@typescript-eslint/no-unsafe-call
|
||||
return decorateMethod(
|
||||
(): Observable<Codec> => (
|
||||
this.#observeSign(account, options).pipe(
|
||||
@@ -112,6 +115,7 @@ export default function createClass <ApiType extends ApiTypes> ({ api, apiType,
|
||||
public send (statusCb?: Callback<ISubmittableResult>): SubmittableResultResult<ApiType> | SubmittableResultSubscription<ApiType> {
|
||||
const isSubscription = api.hasSubscriptions && (this.#ignoreStatusCb || !!statusCb);
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-return,@typescript-eslint/no-unsafe-call
|
||||
return decorateMethod(
|
||||
isSubscription
|
||||
? this.#observeSubscribe
|
||||
@@ -148,6 +152,7 @@ export default function createClass <ApiType extends ApiTypes> ({ api, apiType,
|
||||
...options,
|
||||
...extras,
|
||||
runtimeVersion: api.runtimeVersion,
|
||||
signedExtensions: api.registry.signedExtensions,
|
||||
version: api.extrinsicType
|
||||
} as SignatureOptions;
|
||||
}
|
||||
@@ -164,7 +169,7 @@ export default function createClass <ApiType extends ApiTypes> ({ api, apiType,
|
||||
return [options, statusCb];
|
||||
}
|
||||
|
||||
#observeSign = (account: AddressOrPair, optionsOrNonce: Partial<SignerOptions>): Observable<number | undefined> => {
|
||||
#observeSign = (account: AddressOrPair, optionsOrNonce?: Partial<SignerOptions>): Observable<number | undefined> => {
|
||||
const address = isKeyringPair(account) ? account.address : account.toString();
|
||||
const options = this.#optionsOrNonce(optionsOrNonce);
|
||||
let updateId: number | undefined;
|
||||
@@ -184,7 +189,7 @@ export default function createClass <ApiType extends ApiTypes> ({ api, apiType,
|
||||
);
|
||||
}
|
||||
|
||||
#observeStatus = (status: ExtrinsicStatus): Observable<ISubmittableResult> => {
|
||||
#observeStatus = (hash: Hash, status: ExtrinsicStatus): Observable<ISubmittableResult> => {
|
||||
if (!status.isFinalized && !status.isInBlock) {
|
||||
return of(new SubmittableResult({ status }));
|
||||
}
|
||||
@@ -196,7 +201,7 @@ export default function createClass <ApiType extends ApiTypes> ({ api, apiType,
|
||||
return api.derive.tx.events(blockHash).pipe(
|
||||
map(({ block, events }): ISubmittableResult =>
|
||||
new SubmittableResult({
|
||||
events: filterEvents(this.hash, block, events, status),
|
||||
events: filterEvents(hash, block, events, status),
|
||||
status
|
||||
})
|
||||
)
|
||||
@@ -212,9 +217,11 @@ export default function createClass <ApiType extends ApiTypes> ({ api, apiType,
|
||||
}
|
||||
|
||||
#observeSubscribe = (updateId = -1): Observable<ISubmittableResult> => {
|
||||
const hash = this.hash;
|
||||
|
||||
return api.rpc.author.submitAndWatchExtrinsic(this).pipe(
|
||||
switchMap((status): Observable<ISubmittableResult> =>
|
||||
this.#observeStatus(status)
|
||||
this.#observeStatus(hash, status)
|
||||
),
|
||||
tap((status): void => {
|
||||
this.#updateSigner(updateId, status);
|
||||
@@ -224,7 +231,7 @@ export default function createClass <ApiType extends ApiTypes> ({ api, apiType,
|
||||
|
||||
// NOTE here we actually override nonce if it was specified (backwards compat for
|
||||
// the previous signature - don't let userspace break, but allow then time to upgrade)
|
||||
#optionsOrNonce = (optionsOrNonce: Partial<SignerOptions>): Partial<SignerOptions> => {
|
||||
#optionsOrNonce = (optionsOrNonce: Partial<SignerOptions> = {}): Partial<SignerOptions> => {
|
||||
return isBn(optionsOrNonce) || isNumber(optionsOrNonce)
|
||||
? { nonce: optionsOrNonce }
|
||||
: optionsOrNonce;
|
||||
|
||||
@@ -22,6 +22,6 @@ export default function createSubmittable<ApiType extends ApiTypes> (apiType: Ap
|
||||
Submittable = createClass<ApiType>({ api, apiType, decorateMethod });
|
||||
}
|
||||
|
||||
return new Submittable(api.registry, extrinsic);
|
||||
return new Submittable(api.registry, extrinsic) as SubmittableExtrinsic<ApiType>;
|
||||
};
|
||||
}
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
// of the Apache-2.0 license. See the LICENSE file for details.
|
||||
|
||||
import { AccountId, Address, Extrinsic, ExtrinsicStatus, EventRecord, Hash, RuntimeDispatchInfo } from '@polkadot/types/interfaces';
|
||||
import { AnyNumber, AnyU8a, Callback, Codec, IExtrinsicEra, IKeyringPair, SignatureOptions, Signer, ISubmittableResult } from '@polkadot/types/types';
|
||||
import { AnyNumber, AnyU8a, Callback, Codec, IExtrinsicEra, IKeyringPair, Signer, ISubmittableResult } from '@polkadot/types/types';
|
||||
import { ApiTypes } from '../types';
|
||||
|
||||
import { Observable } from 'rxjs';
|
||||
@@ -50,9 +50,9 @@ export interface SubmittableExtrinsic<ApiType extends ApiTypes> extends Extrinsi
|
||||
|
||||
send(statusCb: Callback<ISubmittableResult>): SubmittableResultSubscription<ApiType>;
|
||||
|
||||
sign(account: IKeyringPair, _options: Partial<SignatureOptions>): this;
|
||||
sign(account: IKeyringPair, _options?: Partial<SignerOptions>): this;
|
||||
|
||||
signAsync(account: AddressOrPair, _options: Partial<SignatureOptions>): SubmittableThis<ApiType, this>;
|
||||
signAsync(account: AddressOrPair, _options?: Partial<SignerOptions>): SubmittableThis<ApiType, this>;
|
||||
|
||||
signAndSend(account: AddressOrPair, options?: Partial<SignerOptions>): SubmittableResultResult<ApiType>;
|
||||
|
||||
|
||||
@@ -2,8 +2,8 @@
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the Apache-2.0 license. See the LICENSE file for details.
|
||||
|
||||
import { Observable } from 'rxjs';
|
||||
import { AnyFunction, Callback, Codec } from '@polkadot/types/types';
|
||||
import type { Observable } from 'rxjs';
|
||||
import { AnyFunction, Callback, Codec, CodecArg } from '@polkadot/types/types';
|
||||
|
||||
// Prepend an element V onto the beginning of a tuple T.
|
||||
// Cons<1, [2,3,4]> is [1,2,3,4]
|
||||
@@ -30,7 +30,9 @@ export type ApiTypes = 'promise' | 'rxjs';
|
||||
// Returns the inner type of an Observable
|
||||
export type ObsInnerType<O extends Observable<any>> = O extends Observable<infer U> ? U : never;
|
||||
|
||||
export type UnsubscribePromise = Promise<() => void>;
|
||||
export type VoidFn = () => void;
|
||||
|
||||
export type UnsubscribePromise = Promise<VoidFn>;
|
||||
|
||||
// FIXME The day TS has higher-kinded types, we can remove this hardcoded stuff
|
||||
export type PromiseOrObs<ApiType extends ApiTypes, T> = ApiType extends 'rxjs'
|
||||
@@ -66,6 +68,15 @@ export type MethodResult<ApiType extends ApiTypes, F extends AnyFunction> = ApiT
|
||||
// information. This describes it.
|
||||
export interface DecorateMethodOptions {
|
||||
methodName?: string;
|
||||
overrideNoSub?: (...args: unknown[]) => Observable<Codec>;
|
||||
}
|
||||
|
||||
export type DecorateFn <T extends Codec> = (...args: any[]) => Observable<T>;
|
||||
|
||||
export interface PaginationOptions<ArgType = CodecArg> {
|
||||
arg?: ArgType;
|
||||
pageSize: number;
|
||||
startKey?: string;
|
||||
}
|
||||
|
||||
export type DecorateMethod<ApiType extends ApiTypes> = <Method extends (...args: any[]) => Observable<any>>(method: Method, options?: DecorateMethodOptions) => any;
|
||||
|
||||
@@ -5,10 +5,11 @@
|
||||
// Augment the modules
|
||||
import '@polkadot/api/augment';
|
||||
|
||||
import BN from 'bn.js';
|
||||
import type BN from 'bn.js';
|
||||
import { DeriveCustom, ExactDerive } from '@polkadot/api-derive';
|
||||
import { Constants } from '@polkadot/metadata/Decorated/types';
|
||||
import { RpcInterface } from '@polkadot/rpc-core/types';
|
||||
import { ProviderInterface, ProviderInterfaceEmitted } from '@polkadot/rpc-provider/types';
|
||||
import { Metadata } from '@polkadot/types';
|
||||
import { Hash, RuntimeVersion } from '@polkadot/types/interfaces';
|
||||
import { DefinitionRpc, DefinitionRpcSub, Signer, SignatureOptions, Registry, RegisteredTypes } from '@polkadot/types/types';
|
||||
@@ -18,7 +19,6 @@ import ApiBase from '../base';
|
||||
import { DecoratedRpc } from './rpc';
|
||||
import { QueryableStorage, QueryableStorageMulti } from './storage';
|
||||
import { SubmittableExtrinsics } from './submittable';
|
||||
import { ProviderInterface, ProviderInterfaceEmitted } from '@polkadot/rpc-provider/types';
|
||||
|
||||
export { Signer, SignerResult } from '@polkadot/types/types';
|
||||
export { default as ApiBase } from '../base';
|
||||
|
||||
@@ -8,7 +8,7 @@ import { Hash } from '@polkadot/types/interfaces';
|
||||
import { AnyFunction, Callback, Codec, CodecArg } from '@polkadot/types/types';
|
||||
import StorageKey, { StorageEntry } from '@polkadot/types/primitive/StorageKey';
|
||||
|
||||
import { ApiTypes, MethodResult, ObsInnerType, PromiseOrObs, UnsubscribePromise } from './base';
|
||||
import { ApiTypes, MethodResult, ObsInnerType, PaginationOptions, PromiseOrObs, UnsubscribePromise } from './base';
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-empty-interface
|
||||
export interface AugmentedQueries<ApiType extends ApiTypes> { }
|
||||
@@ -28,18 +28,20 @@ export type QueryableStorageEntry<ApiType extends ApiTypes> =
|
||||
export interface StorageEntryBase<ApiType extends ApiTypes, F extends AnyFunction> {
|
||||
at: <T extends Codec | any = ObsInnerType<ReturnType<F>>>(hash: Hash | Uint8Array | string, ...args: Parameters<F>) => PromiseOrObs<ApiType, T>;
|
||||
creator: StorageEntry;
|
||||
entries: <T extends Codec | any = ObsInnerType<ReturnType<F>>>(arg?: any) => PromiseOrObs<ApiType, [StorageKey, T][]>;
|
||||
entries: <T extends Codec | any = ObsInnerType<ReturnType<F>>>(arg?: Parameters<F>[0]) => PromiseOrObs<ApiType, [StorageKey, T][]>;
|
||||
entriesPaged: <T extends Codec | any = ObsInnerType<ReturnType<F>>>(opts: PaginationOptions<Parameters<F>[0]>) => PromiseOrObs<ApiType, [StorageKey, T][]>;
|
||||
hash: (...args: Parameters<F>) => PromiseOrObs<ApiType, Hash>;
|
||||
key: (...args: Parameters<F>) => string;
|
||||
keyPrefix: () => string;
|
||||
keys: (arg?: any) => PromiseOrObs<ApiType, StorageKey[]>;
|
||||
keysPaged: (opts: PaginationOptions<Parameters<F>[0]>) => PromiseOrObs<ApiType, StorageKey[]>;
|
||||
range: <T extends Codec | any = ObsInnerType<ReturnType<F>>>([from, to]: [Hash | Uint8Array | string, Hash | Uint8Array | string | undefined] | [Hash | Uint8Array | string], ...args: Parameters<F>) => PromiseOrObs<ApiType, [Hash, T][]>;
|
||||
size: (...args: Parameters<F>) => PromiseOrObs<ApiType, u64>;
|
||||
multi: ApiType extends 'rxjs' ? StorageEntryObservableMulti : StorageEntryPromiseMulti;
|
||||
}
|
||||
|
||||
export interface StorageEntryDoubleMap<ApiType extends ApiTypes, F extends AnyFunction> extends StorageEntryBase<ApiType, F> {
|
||||
entries: <T extends Codec | any = ObsInnerType<ReturnType<F>>>(arg?: Parameters<F>[0]) => PromiseOrObs<ApiType, [StorageKey, T][]>;
|
||||
keyPrefix: (key1?: Parameters<F>[0]) => string;
|
||||
}
|
||||
|
||||
interface StorageEntryObservableMulti {
|
||||
|
||||
@@ -12,6 +12,7 @@ describe('augmentObject', (): void => {
|
||||
});
|
||||
|
||||
afterEach((): void => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-call,@typescript-eslint/no-unsafe-member-access
|
||||
spy.mockClear();
|
||||
});
|
||||
|
||||
|
||||
@@ -32,7 +32,7 @@ function extractKeys (src: Record<string, Record<string, any>>, dst: Record<stri
|
||||
}
|
||||
|
||||
function findSectionExcludes (a: string[], b: string[]): string[] {
|
||||
return a.filter((section): boolean => !b.includes(section));
|
||||
return a.filter((section) => !b.includes(section));
|
||||
}
|
||||
|
||||
function extractSections (src: Record<string, Record<string, any>>, dst: Record<string, Record<string, any>>): StringsStrings {
|
||||
@@ -49,15 +49,15 @@ function findMethodExcludes (src: Record<string, Record<string, any>>, dst: Reco
|
||||
const dstSections = Object.keys(dst);
|
||||
|
||||
return dstSections
|
||||
.filter((section): boolean => srcSections.includes(section))
|
||||
.filter((section) => srcSections.includes(section))
|
||||
.reduce((rmMethods: string[], section): string[] => {
|
||||
const srcMethods = Object.keys(src[section]);
|
||||
|
||||
return rmMethods.concat(
|
||||
...Object
|
||||
.keys(dst[section])
|
||||
.filter((method): boolean => !srcMethods.includes(method))
|
||||
.map((method): string => `${section}.${method}`)
|
||||
.filter((method) => !srcMethods.includes(method))
|
||||
.map((method) => `${section}.${method}`)
|
||||
);
|
||||
}, []);
|
||||
}
|
||||
@@ -74,7 +74,7 @@ function extractMethods (src: Record<string, Record<string, any>>, dst: Record<s
|
||||
* already available, but rather just adds new missing ites into the result object.
|
||||
* @internal
|
||||
*/
|
||||
export default function augmentObject (prefix: string, src: Record<string, Record<string, any>>, dst: Record<string, Record<string, any>>, fromEmpty = false): Record<string, Record<string, any>> {
|
||||
export default function augmentObject (prefix: string, src: Record<string, Record<string, unknown>>, dst: Record<string, Record<string, unknown>>, fromEmpty = false): Record<string, Record<string, any>> {
|
||||
if (fromEmpty) {
|
||||
Object.keys(dst).forEach((key): void => {
|
||||
delete dst[key];
|
||||
@@ -88,12 +88,12 @@ export default function augmentObject (prefix: string, src: Record<string, Recor
|
||||
|
||||
return Object
|
||||
.keys(src)
|
||||
.reduce((newSection, sectionName): Record<string, Record<string, any>> => {
|
||||
.reduce((newSection, sectionName): Record<string, Record<string, unknown>> => {
|
||||
const section = src[sectionName];
|
||||
|
||||
newSection[sectionName] = Object
|
||||
.keys(section)
|
||||
.reduce((result, methodName): Record<string, any> => {
|
||||
.reduce((result, methodName): Record<string, unknown> => {
|
||||
// TODO When it does match, check the actual details and warn when there are differences
|
||||
if (!result[methodName]) {
|
||||
result[methodName] = section[methodName];
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user