Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d958ef8f15 | ||
|
|
97527871d6 | ||
|
|
0317f28e5a | ||
|
|
ebe6d03762 | ||
|
|
59e92fa344 | ||
|
|
cab338e26d | ||
|
|
743ea431b4 | ||
|
|
533f9ce249 | ||
|
|
797ee9c24a | ||
|
|
2f5e2537a3 | ||
|
|
dd52ea4b32 | ||
|
|
5e8ae793c3 | ||
|
|
8713a1f2b6 | ||
|
|
6e6fa4a97c | ||
|
|
ac2a0a34ca | ||
|
|
45fb6d44ad | ||
|
|
6d2265d4ff | ||
|
|
4ec42f1750 | ||
|
|
01166b9684 | ||
|
|
0075dce720 | ||
|
|
7fbb30066e | ||
|
|
637069d723 | ||
|
|
d639a7ee8c | ||
|
|
28ef291c40 | ||
|
|
48ddd0b0d4 | ||
|
|
e88ebf7b2e | ||
|
|
72700e6baf | ||
|
|
f748fcd46d | ||
|
|
7876bb9ced | ||
|
|
a83980b213 | ||
|
|
c4323d5e94 | ||
|
|
11694f1393 | ||
|
|
3989ae67b2 | ||
|
|
b78df57907 | ||
|
|
2f78329738 | ||
|
|
6063054712 | ||
|
|
e42af97928 | ||
|
|
d05ccdb5d7 | ||
|
|
c33334b72b | ||
|
|
94e9fd2b17 | ||
|
|
9c1327ea22 | ||
|
|
9f195e9402 | ||
|
|
3e5e089c68 | ||
|
|
35c37aa66c | ||
|
|
f1aeb564e3 | ||
|
|
c2ff1b32ae | ||
|
|
288427cbb8 | ||
|
|
d099ccedad | ||
|
|
79c7983199 | ||
|
|
80c578fe76 | ||
|
|
de90c048bf | ||
|
|
01a36a994d | ||
|
|
b1ce22d51d | ||
|
|
fe951c2645 | ||
|
|
5a17c542a7 | ||
|
|
59bb5f864f | ||
|
|
abcba20f90 | ||
|
|
014f08c7cc | ||
|
|
7ecd00a4e6 | ||
|
|
6239818c26 | ||
|
|
6af22f41c7 | ||
|
|
77c3a701d0 | ||
|
|
46b17a466c | ||
|
|
e592c6c878 | ||
|
|
ef37586dfc | ||
|
|
5856ce24cc | ||
|
|
8b79056bf9 | ||
|
|
70e0f19ade | ||
|
|
cf1e242c17 | ||
|
|
68856e9692 | ||
|
|
e0626c3dad | ||
|
|
277ea92fda | ||
|
|
aec6694028 | ||
|
|
533abb76f7 | ||
|
|
7660bab86b | ||
|
|
f7c1b6e81b | ||
|
|
b6e9b29570 | ||
|
|
519d9c8fa9 | ||
|
|
ad905db53b | ||
|
|
0a0aa742b4 | ||
|
|
dfbb06a4d6 | ||
|
|
82e71fd51e | ||
|
|
a8b88af97a | ||
|
|
eee36537de | ||
|
|
20a75eafb6 | ||
|
|
00d3a1174b | ||
|
|
e293c7c1cf | ||
|
|
3c8cd499c4 | ||
|
|
cb3816df78 | ||
|
|
fcfcbb2d97 | ||
|
|
321b80ed63 | ||
|
|
73eaa9fe17 | ||
|
|
4d8910f3da | ||
|
|
e6806ed7f9 | ||
|
|
218abf9568 | ||
|
|
a1df864681 | ||
|
|
45640edcff | ||
|
|
53655019b5 | ||
|
|
a1f8bedb6d | ||
|
|
9d1af1eaeb | ||
|
|
38bfd26511 | ||
|
|
1beaf9f208 | ||
|
|
29c29978dd | ||
|
|
a8d1dd0637 | ||
|
|
74571dcd26 | ||
|
|
54b4c2620a | ||
|
|
da05828e74 | ||
|
|
fa935156e1 | ||
|
|
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 |
+3
-2
@@ -1,5 +1,6 @@
|
||||
24
|
||||
25
|
||||
1.4.2
|
||||
1.6.2
|
||||
1.11.2
|
||||
1.12.2
|
||||
1.12.2
|
||||
1.17.2
|
||||
|
||||
+3
-1
@@ -13,6 +13,8 @@ module.exports = {
|
||||
// add override for any (a metric ton of them, initial conversion)
|
||||
'@typescript-eslint/no-explicit-any': 'off',
|
||||
// these should be removed, there are 8 of them as errors
|
||||
'@typescript-eslint/no-non-null-assertion': 'off'
|
||||
'@typescript-eslint/no-non-null-assertion': 'off',
|
||||
// this seems very broken atm, false positives
|
||||
'@typescript-eslint/unbound-method': 'off'
|
||||
}
|
||||
};
|
||||
|
||||
+86
File diff suppressed because one or more lines are too long
Vendored
-56
File diff suppressed because one or more lines are too long
+1
-1
@@ -8,4 +8,4 @@ plugins:
|
||||
- path: .yarn/plugins/@yarnpkg/plugin-interactive-tools.js
|
||||
spec: "@yarnpkg/plugin-interactive-tools"
|
||||
|
||||
yarnPath: .yarn/releases/yarn-rc.js
|
||||
yarnPath: .yarn/releases/yarn-2.1.1.cjs
|
||||
|
||||
+251
-2
@@ -1,8 +1,199 @@
|
||||
# CHANGELOG
|
||||
|
||||
## 1.31.1 Aug 31, 2020
|
||||
|
||||
Upgrade priority: Medium, especially for staking users on Polkadot, Kusama & Westend (type updates applied for v23 onwards) or if transparent `.at(hash)` queries are required/used
|
||||
|
||||
- **Important** Substrate changed the `RewardDestination` enum with an extra field for payout-to-any account for staking preferences. If on an older chain consider adding `RewardDestination: 'RewardDestinationTo257'`
|
||||
- **Important** Substrate changed the `CompactAssignment` type enhanced types for session solution submissions. If on an older chain consider adding `CompactAssignments: 'CompactAssignmentsTo257'`
|
||||
|
||||
- Fix documentation language and typos (Thanks to https://github.com/Meuko)
|
||||
- Add missing `TransactionPriority` type (Thanks to https://github.com/aniiantt)
|
||||
- Update definitions for new `CompactAssignments`, including tests (Thanks to https://github.com/kianenigma)
|
||||
|
||||
- Add transparent support for types/metadata, i.e. hash queries such as `rpc.chain.getBlock(<hash>)` & `query.system.events.at(<hash>)` now works out-of-the-box injecting the correct metadata & types.
|
||||
- Optimize RPC-layer calls with detection of short-term cacheable calls (in the same way subscriptions are done)
|
||||
- Additional checks on `AccountId` for valid sizes
|
||||
- Add `toBigInt()` (JS built-in `BigInt`) on `Int/Uint`, & `Compact<*>` types
|
||||
- Support for `.concat` on Codec arrays
|
||||
- Support for serialization with `isBare` flag on enums
|
||||
- Add `api.getBlockRegistry(blockHash?)` to create registry/types for a specific block
|
||||
- `derive.democracy.locks` now returns delegated locks for an account as well
|
||||
- Adjust unlocking derives with appropriate in-place additions (less object allocations)
|
||||
- `.sign` on submittables is marked deprecated (not due for removal, but rather use `.signAsync` for consistency with `.signAndSend`)
|
||||
- Adjust types for `CompactAssignments` & `RewardDestination` for Polkadot, Kusama & Westend
|
||||
- `@polkadot/util` 3.4
|
||||
- `@polkadot/wasm-crypto` 1.4
|
||||
|
||||
|
||||
## 1.30.1 Aug 24, 2020
|
||||
|
||||
Upgrade priority: Low, unless using the `proposeParachain` module.
|
||||
|
||||
- Adjust balance retrievals to check for `system.account` for new/old determination
|
||||
- Add types for the new `proposeParachain` module (as per Rococo)
|
||||
- Adjust `Address` <-> `LookupSource` definitions (no external impact, both in existence)
|
||||
- Add Ethereum-compatible `Ethereum{AccountId, LookupSource}` types, underlying `H160`
|
||||
- Allow for configurable hashers via `registry.setHasher(...)` (defaults to `blake2AsU8a`)
|
||||
- `@polkadot/util` 3.3
|
||||
|
||||
|
||||
## 1.29.1 Aug 17, 2020
|
||||
|
||||
Upgrade priority: Low, unless on bleeding-edge chain with new compact `CompactAssignments`.
|
||||
|
||||
- **Important** The Substrate `CompactAssignments` type has changed for better space utilization. On older chains, supply `CompactAssignments: 'CompactAssignmentsTo257'`
|
||||
|
||||
- Clean tx cookbook param expansion (Thanks to https://github.com/swswsw)
|
||||
|
||||
- Add additional `Fixed{I,U}{64,128}` and `{I,U}32F32` types
|
||||
- Add `desiredRunnersUp` to council derives
|
||||
- Cleanup indices/AccountId combination derive lookups
|
||||
- `@polkadot/util` 3.2
|
||||
|
||||
|
||||
## 1.28.1 Aug 10, 2020
|
||||
|
||||
Upgrade priority: Low, unless using Centrifuge or parachains
|
||||
|
||||
- Update Centrifuge types to latest (Thanks to https://github.com/mikiquantum)
|
||||
|
||||
- Add cookbook entry for viewing block extrinsics
|
||||
- Support types for time-delay proxies
|
||||
- Update types for parachains
|
||||
- `@polkadot/util` 3.1
|
||||
- `@polkadot/wasm-crypto` 1.3
|
||||
|
||||
|
||||
## 1.27.1 Aug 3, 2020
|
||||
|
||||
Upgrade priority: Low, unless using the Rococo chain
|
||||
|
||||
- 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
|
||||
|
||||
Upgrade priority: Low
|
||||
|
||||
- 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
|
||||
|
||||
Upgrade priority: Medium, especially if using contracts.
|
||||
|
||||
- **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)
|
||||
@@ -10,6 +201,7 @@
|
||||
- Support for latest Substrate types & metadata
|
||||
- `@polkadot/util` 2.12
|
||||
|
||||
|
||||
## 1.16.1 May 26, 2020
|
||||
|
||||
- Support for Polkadot CC1 types & signed extensions
|
||||
@@ -19,6 +211,7 @@
|
||||
- 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)
|
||||
@@ -26,17 +219,20 @@
|
||||
- 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)
|
||||
@@ -48,6 +244,7 @@
|
||||
- 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)
|
||||
@@ -55,38 +252,46 @@
|
||||
- Adjust extrinsic `sign/signAsync` signature to optional options (Thanks to https://github.com/KiChjang)
|
||||
- Support round-robin endpoints in the `WsProvider` with array of urls (Thanks to https://github.com/hoani)
|
||||
- Remove static test-only metadata for Polkadot dev chains (not updated regularly, Substrate dev to remain)
|
||||
|
||||
- Revert error swallow for wrong preimage data (temp. override for Kusama upgrade with no migration)
|
||||
- Fix `.encodedLength` calculation on `[Type; N]` types
|
||||
- Add new `rpc.grandpa.roundState` RPC
|
||||
- Update types & metadata as per latest Substrate master
|
||||
- Adjust Centrifuge starting version
|
||||
|
||||
|
||||
## 1.12.2 Apr 30, 2020
|
||||
|
||||
- Update `@polkadot/util` to stable 2.9.1 (sadly missed in the previous version, stable should match to stable)
|
||||
|
||||
|
||||
## 1.12.1 Apr 29, 2020
|
||||
|
||||
- Fix `CompactAssignments` types (Thanks to https://github.com/arjanz)
|
||||
- Provider ayo-connect now allows for interval config (Thanks to https://github.com/jnaviask)
|
||||
- Cleanup generation for c-like enums (Thanks to https://github.com/monitz87)
|
||||
- Allow subscription to all storage keys, alignment with Substrate (Thanks to https://github.com/xlc)
|
||||
|
||||
- Cater for vote delegations in democracy derives
|
||||
- Cleanup account derive flags where to allow for optional council modules
|
||||
- Allow generic types in ApiPromise.combineLatest
|
||||
- Update to latest substrate metadata
|
||||
|
||||
|
||||
## 1.11.2 Apr 22, 2020
|
||||
|
||||
- Small patch to add missing Polkadot master types (will be in next Kusama update)
|
||||
|
||||
|
||||
## 1.11.1 Apr 21, 2020
|
||||
|
||||
- **Important** Substrate master has an updated `Weight` (to `u64`), on older chains apply `Weight: 'u32'` (This does affect event decoding if wrongly set)
|
||||
|
||||
- Allow user type augmentation to work with different versions of rxjs (Thanks to https://github.com/monitz87)
|
||||
- Align augmented generation with camelCase (Thanks to https://github.com/monitz87)
|
||||
- Fix bitfield endian encoding (Thanks to investigation by https://github.com/xlc)
|
||||
- Add account flag derives via `accounts.flags(accountId)` (Thanks to https://github.com/kwingram25)
|
||||
|
||||
- Fix entries decoding for `Option<Number>` (& simplify, decoding correctly on rpc layer)
|
||||
- Add `system.{localPeerId, localListenAddresses}` & `state.getReadProof` RPCs
|
||||
- Ensure proper propagation of `api.runtimeVersion` (used for signing) after upgrade
|
||||
@@ -99,9 +304,11 @@
|
||||
- Enhance API support for non-subscription providers (skip subscription to runtimeVersion)
|
||||
- Adjust types for Kusama 1057 (notably the new `StakingLedger`)
|
||||
|
||||
|
||||
## 1.10.1 Apr 13, 2020
|
||||
|
||||
- **Important** Substrate master has updated staking, on older chains apply `StakingLedger: 'StakingLedgerTo240'`
|
||||
|
||||
- Add `rpc.system.chainType` to retrieve the chain type (Development. Local, Live & Custom)
|
||||
- Adjust types for Westend after the reset
|
||||
- Adjust democracy derives, including the support of the frame-scheduler for scheduled deployments
|
||||
@@ -112,10 +319,12 @@
|
||||
- Internally all private/protected methods/variables are now `_` prefixed (Aligning with the `private/protected` indicators in the TS definitions)
|
||||
- Update metadata/docs-from-metadata to the latest Substrate
|
||||
|
||||
|
||||
## 1.9.1 Apr 1, 2020
|
||||
|
||||
- **Breaking change** (TypeScript with derives only) The return type names for `api.derive.*` have been adjusted for consistency, all starting with `Derive*` (previously a mixture of `Derived*` and `Derive*`)
|
||||
- **Breaking change** (derives only) Additional cleanups of democracy proposal & referenda derives, including support for new Polkadot/Substrate vote retrievals
|
||||
|
||||
- Tx signing via `signAndSend` & `signAsync` now tries to use the last finalized block (depending on finalized drift)
|
||||
- Add support for `api.rpc.childstate.*` Substrate RPCs, older nodes with still populate `api.rpc.state.*` with the child methods
|
||||
- Adjust `Error.message` on RPC failures to not include the (already known) method signature
|
||||
@@ -127,11 +336,13 @@
|
||||
- Fix encoding for `Vec<u8>`-related types as part of constants
|
||||
- Internal adjustment of interface type locations (no impact on imports via `@polkadot/types/interfaces`)
|
||||
|
||||
|
||||
## 1.8.1 Mar 22, 2020
|
||||
|
||||
- **Breaking change** The format for any custom RPCs have been changed (alongside API-internal changes) to allow for better RPC management. If you are currently using custom RPCs (or planning to do so), look at the [updated documentation](https://polkadot.js.org/api/start/rpc.custom.html)
|
||||
- **Breaking change** Alongside API RPC changes, the `@polkadot/jsonrpc` package has been removed. Since it was never documented and only used internally, this should not have adverse impacts. All RPC definitions itself has now been moved to the relevant modules inside `@polkadot/types/interfaces`
|
||||
- **Important** Substrate has an updated democracy module. If using an older chain add the `ReferendumInfo: 'ReferendumInfoTo239'` type when using referendums
|
||||
|
||||
- The `isRetracted` Extrinsic status is now a warning, not a fatal error, correctly aligning with Polkadot/Substrate
|
||||
- The Substrate extrinsic phase definitions has been expanded with `Initialization` to align with the latest versions
|
||||
- Add support for all known substrate RPC methods
|
||||
@@ -139,9 +350,11 @@
|
||||
- Adjusted referendum derives to cater for bot new/old democracy. Derived `referendumInfo` now includes `status` field, not `info`
|
||||
- Add `initWasm` flag to API options. When set to `false` does not init the WASM portion (leaving it to the user elsewhere)
|
||||
|
||||
|
||||
## 1.7.1 Mar 17, 2020
|
||||
|
||||
- **Important** Current versions of Polkadot/Substrate have dropped support for linked maps on storage entries. If you are using these queries to retrieve all entries, for instance `staking.{nominators,validators}()` and using an upgraded chain, you need to swap to retrieving entries via `.entries()` or `.keys()` for the keys.
|
||||
|
||||
- Pull in support and types for latest Polkadot/Substrate
|
||||
- Add support for the new Substrate `state_getKeysPaged` RPC, including use in storage keys
|
||||
- Move `derive.staking.controllers` to `derive.staking.stashes`, reflecting actual content
|
||||
@@ -149,13 +362,16 @@
|
||||
- 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
|
||||
|
||||
- Revert checks for query args, not working on `.at()` queries (proper fix in next version)
|
||||
|
||||
|
||||
## 1.6.1 Mar 12, 2020
|
||||
|
||||
- **Breaking change** `api.rpc.state.queryStorage(...)` now fully decodes the `Vec<StorageChangeSet>` and returns a decoded `[Hash, Codec[]][]` when using this RPC.
|
||||
|
||||
- `StorageKey` now has an `.args` property, decoded from meta where `twox64_concat` or `blake128_concat` are used on maps
|
||||
- Fix `api.query.*.*.entries` type conversions to return exact types (not `Option` in some cases)
|
||||
- Add `api.query.*.*.keys` to retrieve only the storage keys, similar to `.entries`
|
||||
@@ -167,13 +383,16 @@
|
||||
- Add runtime validation for map arguments to `api.query.*`
|
||||
- TypeScript interfaces for linked maps now correctly generates as `[Type, Linkage<Next>]`
|
||||
|
||||
|
||||
## 1.5.1 Mar 06, 2020
|
||||
|
||||
- **Important** Substrate master has updated staking, on older chains supply `StakingLedger: 'StakingLedgerTo223'`
|
||||
- **Important** Substrate master has updated collective, on older chains supply `Votes: 'VotesTo230'`
|
||||
|
||||
- Add proper support for type generation with an Enum containing an Tuple (Thanks to https://github.com/monitz87)
|
||||
- Fix storage parsing not resulting in rejected Promises (Fix from https://github.com/aniiantt applied)
|
||||
- Remove use of deprecated `Observable.create` (Thanks to https://github.com/Himself65)
|
||||
|
||||
- Add types & metadata for the latest Polkadot/Substrate runtime versions (master branches)
|
||||
- Type extraction will now allow the same sub-module name across packages, i.e. `@polkadot/types/interfaces/runtime` & `@mine/interfaces/runtime` will be valid
|
||||
- Add `.range([from, to]: [Hash, Hash?], ...args: any[]): [Hash, Codec][]` on all storage entries
|
||||
@@ -187,17 +406,21 @@
|
||||
- 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
|
||||
|
||||
- Fix `api.tx(<extrinsic>): Submittable` decoration (non-working in 1.4.1, now with proper test)
|
||||
|
||||
|
||||
## 1.4.1 Feb 26, 2020
|
||||
|
||||
- **Breaking change** (TypeScript only) The `*.d.ts` files now contain TypeScript 3.8 features (specifically `#private`), which is not usable in TS versions < 3.8
|
||||
- **Breaking change** - `api.derive.staking.*` has updated result types and detects support for lazy payouts queries
|
||||
|
||||
- Rework type generation for `api.{query, tx}` to properly handle complex type inputs (Thanks to https://github.com/monitz87)
|
||||
- Rework metadata `--strict` mode to effectively decorate chain metadata (Thanks to https://github.com/monitz87)
|
||||
- Add `api.rpc.chain.subscribeAllHeads` (not just best) (Thanks to https://github.com/jak-pan)
|
||||
|
||||
- Add `api.rpc.engine.*` for manual seal support
|
||||
- Add `api.injectMetadata(metadata)` to initialize API with a specific metadata version
|
||||
- The api now checks for runtime upgrades, augmenting the interfaces with new metadata when found
|
||||
@@ -217,18 +440,23 @@
|
||||
- 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
|
||||
|
||||
- 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
|
||||
- The `@polkadot/types/codec/create` has been moved to `@polkadot/types/create`, imports from `@polkadot/types` are unaffected
|
||||
- Expose chain properties on registry (and use for API type formatting)
|
||||
- Add `toHuman(isExtended?: boolean)` to all codec types, formatting into a human-readable structure
|
||||
|
||||
|
||||
## 1.2.1 Feb 16, 2020
|
||||
|
||||
- **Important** Update RPC status codes (latest Substrate 2), with the `isInBlock` (`isFinalized` now indicates finality)
|
||||
|
||||
- Storage `.entries(arg?: any)` now has the correct argument type for DoubleMap (Thanks to https://github.com/monitz87)
|
||||
|
||||
- Swap Kusama and Polkadot aliases for `Address` to `AccountId` (future update)
|
||||
- Add `LookupSource` and `LookupTarget` types instead of mapping these directly for aliasing
|
||||
- Add `BitVec` type primitive
|
||||
@@ -243,9 +471,11 @@
|
||||
- Cleanup `codec/Date` tests to make it run properly on all timezones
|
||||
- Add explicit dependencies to all packages and move TypeScript `@types/*` to dev deps
|
||||
|
||||
|
||||
## 1.1.1 Feb 06, 2020
|
||||
|
||||
- **Important** Chains without `balances.account` or `system.account` should supply `"BalanceLock": "BalanceLockTo212"` to their types to use the previous-generation `BalanceLock` (when querying locks)
|
||||
|
||||
- Add support for `balances.account` in all applicable derives (incl. `vesting` module)
|
||||
- Inject and use SignedExtensions by name from V11 metadata (V4 extrinsics only)
|
||||
- Add typings for `api.tx.*.*` - the `polkadot-types-from-chain` now also generates these
|
||||
@@ -257,11 +487,14 @@
|
||||
- Adjust balances fees derivation with optional transfer and creation fees (removed in Substrate)
|
||||
- Adjust enum `.toJSON()` to return type name as specified
|
||||
|
||||
|
||||
## 1.0.1 Jan 30, 2020
|
||||
|
||||
- **Breaking change** Drop support for Substrate v1 chain in all derives
|
||||
|
||||
- Return unsub functions from provider .on emitters (Thanks to https://github.com/jak-pan)
|
||||
- `ApiPromise.isReady` now rejects on unrecoverable errors (Thanks to https://github.com/laec)
|
||||
|
||||
- Add `polkadot-types-from-chain` & `polkadot-types-from-defs` TypeScript generators to `@polkadot/types`
|
||||
- Only decorate derives where relevant parent `api.query.*` is available
|
||||
- Support `.entries(arg?: any)` lookups on DoubleMaps (in addition to previously supported maps)
|
||||
@@ -276,9 +509,11 @@
|
||||
- Remove support for un-deployed metadata
|
||||
- Remove old known types for Substrate V1
|
||||
|
||||
|
||||
## 0.100.1 Jan 13, 2020
|
||||
|
||||
- **Important** This will the the last API version with Substrate 1.x support. Although you will still be able to use subsequent versions with older chains, dependent libraries such as sr25519 may not be compatible.
|
||||
|
||||
- Add support for the Substrate identity module
|
||||
- Remove the `codec/Data` type, to remove a conflict with Substrate. This type is now named `Raw`
|
||||
- Fix for linked maps using `Option`
|
||||
@@ -287,36 +522,43 @@
|
||||
- Add support for latest Polkadot/Substrate types
|
||||
- Add `paymentInfo` to submittables to calculate fees
|
||||
|
||||
|
||||
## 0.99.1 Dec 13, 2019
|
||||
|
||||
- **Breaking change** The `Data` and `U8a` type has been renamed and just replaced with the `Raw` type
|
||||
- **Breaking change** The `api.derive.staking.info` has been split into 2 - `staking.query` for non-balance related information (more effective) and `staking.account` that enhances query for all the information previously found `.info`
|
||||
|
||||
- Cleanup `DoubleMap` hashing to always hash over the full value (in the case of `Vec<T>`, this includes the length)
|
||||
- Update democracy derives to take care of nextTally and lowestUnbaked
|
||||
- Add additional derives for both council & treasury
|
||||
- Alignment with latest Polkadot/Substrate master branch types
|
||||
|
||||
|
||||
## 0.98.1 Dec 04, 2019
|
||||
|
||||
- Make the TypeScript generation script mor re-usable (Thanks to https://github.com/xlc)
|
||||
- Add `.entries()` for all map-types, returning storage keys and values
|
||||
- Add `.signAsync` to submittable extrinsics (Thanks to https://github.com/c410-f3r)
|
||||
|
||||
- Cleanup circular references between internal dependencies
|
||||
- Support for new Substrate democracy with preimages in derive
|
||||
- Alignment of types with Substrate/Polkadot master branches
|
||||
|
||||
|
||||
## 0.97.1 Nov 29, 2019
|
||||
|
||||
- **Breaking change** Add the passing on an explicit `Registry` to all calls to `createType` as well as all codec classes. If you are upgrading form an older version, use the [migration guide](UPGRADING.md) to walk through the changes required.
|
||||
- **Breaking change** The metadata classes have been moved from `@polkadot/types` into `@polkadot/metadata`. If you explicitly create `Metadata` classes, you now would need to do so with the `import Metadata from '@polkadot/metadata';` This is a decorated class, where the previous metadata is now available on `Metadata.metadata`, alongside decorated `consts.*`', `tx.*` and `query.*`.
|
||||
- **Breaking change** Session `Keys` defaults to 4 keys now (Substrate master), depending on your node config, you would want to override with e.g. `Keys: 'SessionKeys3'` (1, 2, 3, 4, 5 & 6)
|
||||
- **Breaking change** `ValidatorPrefs` now default to the new percentage commission model, to use the previous `validatorPayment`, you can override with `ValidatorPrefs: 'ValidatorPrefsTo196'`
|
||||
|
||||
- `api.derive.*` now has built-in memomization
|
||||
- Various fixes and cleanups to `api.derive.*` including era length progress and vesting calculations
|
||||
- Aligned all types with the latest Polkadot & Substrate, including Kusama CC3
|
||||
- Support for Metadata V9, which adjusts the hashing methods of storage entries
|
||||
- Support for Metadata V10 (still un-released), which includes prefixed map support
|
||||
|
||||
|
||||
## 0.96.1 Nov 09, 2019
|
||||
|
||||
- Updated types for latest Kusama
|
||||
@@ -327,10 +569,12 @@
|
||||
- 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
|
||||
|
||||
- Temporary removal of `account_nextIndex` use, will be re-added in a future release
|
||||
|
||||
|
||||
## 0.95.1 Oct 25, 2019
|
||||
|
||||
- Support Extrinsic V4 with additional signature indicator (Latest Polkadot/Substrate/Kusama)
|
||||
@@ -341,6 +585,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
|
||||
|
||||
- Add handling of `Result<Ok, Error>` definitions
|
||||
@@ -353,6 +598,7 @@
|
||||
- Add documentation for custom extrinsic formats (advanced chains)
|
||||
- Update to latest substrate master metadata
|
||||
|
||||
|
||||
## 0.93.1 Sep 26, 2019
|
||||
|
||||
- Support for Kusama CC2
|
||||
@@ -363,6 +609,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
|
||||
|
||||
- The API now correctly sets the ss58 prefix as retrieved from the chain properties via `ss58Format`
|
||||
@@ -371,6 +618,7 @@
|
||||
- Support the latest Polkadot & Substrate master branches (incl. metadata updates)
|
||||
- Getting started documentation has been made available
|
||||
|
||||
|
||||
## 0.91.1 Sep 09, 2019
|
||||
|
||||
- This release was focussed on stability, with a number of cleanups and bug-fixes
|
||||
@@ -385,6 +633,7 @@
|
||||
- **Breaking change** `SignerPayload` is renamed to `SignerPayloadJSON`
|
||||
- **Breaking change** `SignerPayloadJSON`, `SignerPayloadRawBase` and `SignerPayloadRaw` are all moved to `@polkadot/types`
|
||||
|
||||
|
||||
## 0.90.1 Aug 24, 2019
|
||||
|
||||
If you are upgrading form an older version, use the CHANGELOG hand-in-hand with the [migration guide](UPGRADING.md).
|
||||
@@ -398,6 +647,7 @@ If you are upgrading form an older version, use the CHANGELOG hand-in-hand with
|
||||
- For creation of types, it is recommended to use `createType(<TypeName>, <value>)` instead of e.g. `new Proposal(...)`. When passing these to methods/queries, construction should not be needed, the raw value can be passed.
|
||||
- For moved types, a previous import would have been from `@polkadot/types`, i.e. `import { SetIndex } from '@polkadot/types`, now just the interfaces (TypeScript) are available via `import { SetIndex } from '@polkadot/types/interfaces`
|
||||
- `usize` is now a blacklisted type that will throw on construction. Since it is platform-specific, it creates incompatibilities between native (generally `u64`) and WASM (always `u32`) code. Use one of the `u32` or `u64` types explicitly.
|
||||
|
||||
- Support substrate v7 metadata
|
||||
- The `Method.findFunction(callIndex)` (allowing decoding of raw data), is now available on `api.findCall(callIndex)`. To keep backwards compatibility, it is still available on `GenericCall.findMethod` but the `api.findCall` is recommended and suggested.
|
||||
- The `types/codec/createType` has been moved to `types/codec/create` with the same exports. If you explicitly imported from here (and not doing the suggested `import { createType } from '@polkadot/types`), the reference needs to be updated
|
||||
@@ -499,7 +749,6 @@ If you are upgrading form an older version, use the CHANGELOG hand-in-hand with
|
||||
- Change spelling to US English as per substrate master (1.0-rc1). Breaking changes as a result:
|
||||
- For extrinsic status results, if you have checked the type returns, i.e. `result.type === 'Finalised'` now check on the status for `result.status.isFinalized` or `result.status.isBroadcast`, ... (the `type` property is now accessible only on `result.status.type`)
|
||||
- If using `subscribeFinalisedHeads` update this to `subscribeFinalizedHeads` (likewise `getFinalisedHead` should be updated to `getFinalizedHead` and `derive.bestNumberFinalized`)
|
||||
|
||||
- The underlying ss58 address checksums have changed
|
||||
- The updated keyring with support for this has been made available
|
||||
- All examples have been updated with sr25519 addresses (with the new checksums)
|
||||
|
||||
@@ -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.
|
||||
|
||||
|
||||
Executable
+23
@@ -0,0 +1,23 @@
|
||||
#!/usr/bin/env bash
|
||||
|
||||
function copy_folder () {
|
||||
SRC="packages/$1/build"
|
||||
DST="../test/js-test/node_modules/@polkadot/$1"
|
||||
|
||||
echo "** Copying $SRC to $DST"
|
||||
|
||||
rm -rf $DST
|
||||
cp -r $SRC $DST
|
||||
}
|
||||
|
||||
yarn polkadot-dev-build-ts
|
||||
|
||||
copy_folder "api"
|
||||
copy_folder "api-contract"
|
||||
copy_folder "api-derive"
|
||||
copy_folder "metadata"
|
||||
copy_folder "rpc-core"
|
||||
copy_folder "rpc-provider"
|
||||
copy_folder "types"
|
||||
copy_folder "types-known"
|
||||
copy_folder "typegen"
|
||||
@@ -42,3 +42,20 @@ const header = await api.derive.chain.getHeader();
|
||||
|
||||
console.log(`#${header.number}: ${header.author}`);
|
||||
```
|
||||
|
||||
## How do I view block extrinsic information?
|
||||
|
||||
The transactions are included in a signed block as part of the extrinsics - some of these will be unsigned and generated by the block author and some of these may be submitted from external sources and be signed. (Some palettes do use unsigned transactions, so signed/unsigned is not an indication of origin). To retrieve the block and display the transaction information, we can do the following -
|
||||
|
||||
```js
|
||||
// no blockHash is specified, so we retrieve the latest
|
||||
const signedBlock = await this.api.rpc.chain.getBlock();
|
||||
|
||||
// the information for each of the contained extrinsics
|
||||
signedBlock.block.extrinsics.forEach((ex, index) => {
|
||||
// the extrinsics are decoded by the API
|
||||
console.log(index, ex.toHuman());
|
||||
});
|
||||
```
|
||||
|
||||
In the above `.toHuman()` is used to format into a human-readable representation. You can inspect/extract specific fields from the decoded extrinsic as required, for instance `ex.method.section` would return the pallete that executed this transaction.
|
||||
|
||||
+6
-6
@@ -16,9 +16,9 @@ const info = await api.tx.balances
|
||||
|
||||
// log relevant info, partialFee is Balance, estimated for current
|
||||
console.log(`
|
||||
class=${class.toString()},
|
||||
weight=${weight.toString()},
|
||||
partialFee=${partialFee.toHuman()}
|
||||
class=${info.class.toString()},
|
||||
weight=${info.weight.toString()},
|
||||
partialFee=${info.partialFee.toHuman()}
|
||||
`);
|
||||
```
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -90,7 +90,7 @@ Looking at the example in this repo, it also has `augment*`, `index.ts` and `typ
|
||||
|
||||
## Generating
|
||||
|
||||
Now that both the metadata nd types setup is completed, we just run the build command via `yarn build` and magically (assuming you didn't have the `augment*` and other generated files), these files will be added. When running this command, the console should display something like -
|
||||
Now that both the metadata and types setup is completed, we just run the build command via `yarn build` and magically (assuming you didn't have the `augment*` and other generated files), these files will be added. When running this command, the console should display something like -
|
||||
|
||||
```
|
||||
> yarn build
|
||||
@@ -166,7 +166,7 @@ As mentioned earlier, here you will notice the `import { VoteStage }`, the gener
|
||||
|
||||
## TypeScript config
|
||||
|
||||
Now that we have files generated, it is time to make TypeScript aware of the types and add an explicit override into out `tsconfig.json`. After some changes, the paths in the config looks as follow (comments are in teh actual config file here) -
|
||||
Now that we have files generated, it is time to make TypeScript aware of the types and add an explicit override into out `tsconfig.json`. After some changes, the paths in the config looks as follow (comments are in the actual config file here) -
|
||||
|
||||
```json
|
||||
{
|
||||
|
||||
+2
-13
@@ -20,6 +20,8 @@ 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,16 +65,3 @@ Due to these customizations and differences that bleed through to the transactio
|
||||
Recently Substrate master updated the `Weight` type from `u32` -> `u64`. This type is used in the `DispatchInfo` struct in the `system.ExtrinsicSuccess` events, to return the applied call weights as well as the resulting fees. Since the API master branch tracks Substrate master, this means the change has been applied by default, with the default set to `u64`.
|
||||
|
||||
If you are on a chain that has not been upgraded yet, you need to add `Weight: 'u32'` to your types to allow for successful parsing of all events. Without this override, parsing will fail. As soon as one event in the `Vec<EventRecord>` structure from `system.events` fails to parse, all subsequent events are affected and the decoding will return an error.
|
||||
|
||||
## When querying older blocks & events, it fails on parsing
|
||||
|
||||
Upon initialization, the API is decorated with the [current on-chain metadata](basics.md#metadata) and (if [available](https://github.com/polkadot-js/api/tree/master/packages/types-known/src)) the specific types for the runtime version is added. This allows the API to decode all current (as per the on-chain info) state and extrinsics.
|
||||
|
||||
When the chain is upgraded, new metadata (indicating new events, storage and extrinsics) is added on-chain. Additionally this generally goes hand in-hand with changes in types, i.e. fields may be addedd or removed or state that was used could now be migrated to new locations. In most cases, this would mean that the current chain information cannot be used to parse older entries pre-upgrade. A typical consequence of this is that any `.at(...)` or `.range(...)` queries pre-upgrade may fail.
|
||||
|
||||
As of the current time, there is no automatic injection of older metadata (based on the runtime version at a specific block) nor decoration of older types if they are available. It can be emulated with what the API will do to handle these cases when it adds a `.historic(...)` query type -
|
||||
|
||||
- querying the runtime version at the parent of older block you wish to retrieve
|
||||
- retrieving and injecting the metadata from the parent block (if the runtime version has changed)
|
||||
- inject any specific older types for the state at that point
|
||||
- finally retrieve the actual entry via an `.at(...)` query
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -42,7 +42,7 @@ Be aware that while defined, the method will only appear on the API if it is in
|
||||
|
||||
## Definition breakdown
|
||||
|
||||
While the above example should be self-explanatory, it is important to understand teh structure. The `rpc: { ... }` definitions are keyed first and foremost by the name of the module exposing the RPC. This means that when we have 2 modules `firstModule` & `testModule`, the first-level structure would follow the following pattern,
|
||||
While the above example should be self-explanatory, it is important to understand the structure. The `rpc: { ... }` definitions are keyed first and foremost by the name of the module exposing the RPC. This means that when we have 2 modules `firstModule` & `testModule`, the first-level structure would follow the following pattern,
|
||||
|
||||
```js
|
||||
...
|
||||
|
||||
@@ -20,7 +20,7 @@ With the conversions done in the API, there are limited reasons to create types
|
||||
import type { Balance } from '@polkadot/types/interfaces';
|
||||
|
||||
...
|
||||
// unwrap out option into a zero Balance whn not found
|
||||
// unwrap out option into a zero Balance when not found
|
||||
// (This can be done via `.unwrapOrDefault()`, which does the same underlying)
|
||||
const balance: Balance = balanceOpt.unwrapOr(api.createType('Balance'));
|
||||
```
|
||||
|
||||
@@ -6,7 +6,7 @@ Therefore to cater for all types, a mapping in done on the [@polkadot/types libr
|
||||
|
||||
Additionally, the API contains some logic for chain type detection, for instance in the case of Substrate 1.x based chains, it will define `BlockNumber` & `Index` (nonce) as a `u64`, while for current-generation chains, these will be defined as `u32`. Some of the work in maintaining the API for Polkadot/Substrate is the addition of types as they appear and gets used in the Rust codebase.
|
||||
|
||||
There is a the [recommendation](install.md#betas) to use a `@polkadot/api@beta` should you wish to track the master branches of Polkadot or Substrate, since master changes for the addition of new types do not make it into a stable release immediately.
|
||||
There is the [recommendation](install.md#betas) to use a `@polkadot/api@beta` should you wish to track the master branches of Polkadot or Substrate, since master changes for the addition of new types do not make it into a stable release immediately.
|
||||
|
||||
## Extension
|
||||
|
||||
@@ -87,7 +87,7 @@ Document: {
|
||||
|
||||
## User-defined enum
|
||||
|
||||
One form of types that appear regularly is enums, these can be defined as follow -
|
||||
One form of types that appear regularly is enums, these can be defined as follows -
|
||||
|
||||
```js
|
||||
...
|
||||
@@ -212,4 +212,4 @@ Always look at customization and understand the impacts, replicating these chang
|
||||
|
||||
## Custom RPC
|
||||
|
||||
In addition to customizing modules and types on your node, you can also add custom RPC definitions. Like the type definitions in ths section, [these can be defined and passed to the API](rpc.custom.md) for decoration.
|
||||
In addition to customizing your node's modules and types, you can also add custom RPC definitions. Like the type definitions in this section, [these can be defined and passed to the API](rpc.custom.md) for decoration.
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# TypeScript user generated
|
||||
|
||||
In the previous section we looked at the TypeScript definitions that are available and is generated from both the chain and definitions. Here we will expand upon the use of the infrastructure created to define types as part of the `@polkadot/types` library and see how to use them to generate your own definitions and chain types.
|
||||
In the previous section we looked at the TypeScript definitions that are available and are generated from both the chain and definitions. Here we will expand upon the use of the infrastructure created to define types as part of the `@polkadot/types` library and see how to use them to generate your own definitions and chain types.
|
||||
|
||||
## Definitions
|
||||
|
||||
@@ -17,7 +17,7 @@ In the root of your project (with the `@polkadot/typegen` package installed), yo
|
||||
|
||||
## Chain modules
|
||||
|
||||
In the same way as the type library provides defaults from a substrate-base chain, you can also, directly from chain from metadata, generate a complete `api.{consts,query}.*` definition for your specific chain. The command will create 2 files, `{consts, query}.types.ts` which you can either use to augment the TypeScript definitions, or replace those in `@polkadot/api/*` with your versions (copy, TypeScript replacement or browser/node aliasing).
|
||||
In the same way as the type library provides defaults from a substrate-base chain, you can also, directly from the chain's metadata, generate a complete `api.{consts,query}.*` definition for your specific chain. The command will create 2 files, `{consts, query}.types.ts` which you can either use to augment the TypeScript definitions, or replace those in `@polkadot/api/*` with your versions (copy, TypeScript replacement or browser/node aliasing).
|
||||
|
||||
In the root of your project, you can run `yarn polkadot-types-from-chain --endpoint wss://<url> --output ./stuff` and it will create the required output. (Here you can specify an optional `--package @MeInc/stuff` to read definitions for the targeted output folder with the specified package name.)
|
||||
|
||||
@@ -27,4 +27,4 @@ The [TypeScript augmentation example](../examples/promise/90_typegen/) example p
|
||||
|
||||
## And that's a wrap
|
||||
|
||||
This brings us to the end of our overview and jump through the API. While the documentation is still very much and ever evolving item, we can encourage you to try out what you have learned with some [examples](../examples). As we [indicated right at the start of this journey](README.md#help-us-help-others), if there are areas for improvement, let us know.
|
||||
This brings us to the end of our overview and jump through the API. While the documentation is still very much an ever evolving item, we can encourage you to try out what you have learned with some [examples](../examples). As we [indicated right at the start of this journey](README.md#help-us-help-others), if there are areas for improvement, let us know.
|
||||
|
||||
+1
-1
@@ -9,5 +9,5 @@
|
||||
"packages": [
|
||||
"packages/*"
|
||||
],
|
||||
"version": "1.17.1"
|
||||
"version": "1.31.1"
|
||||
}
|
||||
|
||||
+12
-9
@@ -24,15 +24,18 @@
|
||||
"test:watch": "polkadot-dev-run-test --watch"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@babel/core": "^7.10.2",
|
||||
"@babel/register": "^7.10.1",
|
||||
"@babel/runtime": "^7.10.2",
|
||||
"@polkadot/dev": "^0.55.7",
|
||||
"@polkadot/ts": "^0.3.25",
|
||||
"@babel/core": "^7.11.4",
|
||||
"@babel/register": "^7.10.5",
|
||||
"@babel/runtime": "^7.11.2",
|
||||
"@polkadot/dev": "^0.55.43",
|
||||
"@polkadot/ts": "^0.3.40",
|
||||
"@polkadot/typegen": "workspace:packages/typegen",
|
||||
"@types/jest": "^25.2.3",
|
||||
"@vuepress/plugin-search": "^1.5.0",
|
||||
"copyfiles": "^2.3.0"
|
||||
"@types/jest": "^26.0.10",
|
||||
"@vuepress/plugin-search": "^1.5.4",
|
||||
"copyfiles": "^2.3.0",
|
||||
"typedoc": "^0.18.0",
|
||||
"typedoc-plugin-markdown": "^2.4.2",
|
||||
"typedoc-plugin-no-inherit": "^1.1.10"
|
||||
},
|
||||
"version": "1.17.1"
|
||||
"version": "1.31.1"
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@polkadot/api-contract",
|
||||
"version": "1.17.1",
|
||||
"version": "1.31.1",
|
||||
"description": "Interfaces for interacting with contracts and contract ABIs",
|
||||
"main": "index.js",
|
||||
"keywords": [
|
||||
@@ -26,12 +26,12 @@
|
||||
},
|
||||
"homepage": "https://github.com/polkadot-js/api/tree/master/packages/api-contract#readme",
|
||||
"dependencies": {
|
||||
"@babel/runtime": "^7.10.2",
|
||||
"@polkadot/api": "1.17.1",
|
||||
"@polkadot/rpc-core": "1.17.1",
|
||||
"@polkadot/types": "1.17.1",
|
||||
"@polkadot/util": "^2.12.2",
|
||||
"bn.js": "^5.1.2",
|
||||
"rxjs": "^6.5.5"
|
||||
"@babel/runtime": "^7.11.2",
|
||||
"@polkadot/api": "1.31.1",
|
||||
"@polkadot/rpc-core": "1.31.1",
|
||||
"@polkadot/types": "1.31.1",
|
||||
"@polkadot/util": "^3.4.1",
|
||||
"bn.js": "^5.1.3",
|
||||
"rxjs": "^6.6.2"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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';
|
||||
@@ -38,9 +38,9 @@ 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 {
|
||||
@@ -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) {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@polkadot/api-derive",
|
||||
"version": "1.17.1",
|
||||
"version": "1.31.1",
|
||||
"description": "Common functions used across Polkadot, derived from RPC calls and storage queries.",
|
||||
"main": "index.js",
|
||||
"keywords": [
|
||||
@@ -27,18 +27,18 @@
|
||||
},
|
||||
"homepage": "https://github.com/polkadot-js/api/tree/master/packages/api-derive#readme",
|
||||
"dependencies": {
|
||||
"@babel/runtime": "^7.10.2",
|
||||
"@polkadot/api": "1.17.1",
|
||||
"@polkadot/rpc-core": "1.17.1",
|
||||
"@polkadot/rpc-provider": "1.17.1",
|
||||
"@polkadot/types": "1.17.1",
|
||||
"@polkadot/util": "^2.12.2",
|
||||
"@polkadot/util-crypto": "^2.12.2",
|
||||
"bn.js": "^5.1.2",
|
||||
"@babel/runtime": "^7.11.2",
|
||||
"@polkadot/api": "1.31.1",
|
||||
"@polkadot/rpc-core": "1.31.1",
|
||||
"@polkadot/rpc-provider": "1.31.1",
|
||||
"@polkadot/types": "1.31.1",
|
||||
"@polkadot/util": "^3.4.1",
|
||||
"@polkadot/util-crypto": "^3.4.1",
|
||||
"bn.js": "^5.1.3",
|
||||
"memoizee": "^0.4.14",
|
||||
"rxjs": "^6.5.5"
|
||||
"rxjs": "^6.6.2"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@polkadot/keyring": "^2.12.2"
|
||||
"@polkadot/keyring": "^3.4.1"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -30,7 +30,7 @@ function retrieve (api: ApiInterfaceRx, address: Address | AccountId | AccountIn
|
||||
|
||||
const accountIndex = api.registry.createType('AccountIndex', decoded);
|
||||
|
||||
return api.derive.accounts.indexToId(accountIndex).pipe(
|
||||
return api.derive.accounts.indexToId(accountIndex.toString()).pipe(
|
||||
map((accountId): AccountIdAndIndex => [accountId, accountIndex])
|
||||
);
|
||||
} catch (error) {
|
||||
|
||||
@@ -16,6 +16,8 @@ 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
|
||||
@@ -72,11 +74,20 @@ function queryAccounts (api: ApiInterfaceRx): Observable<AccountIndexes> {
|
||||
*/
|
||||
export function indexes (api: ApiInterfaceRx): () => Observable<AccountIndexes> {
|
||||
return memo((): Observable<AccountIndexes> =>
|
||||
(api.query.indices
|
||||
? isFunction(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;
|
||||
})
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -23,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())
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -17,18 +17,22 @@ import { memo } from '../util';
|
||||
type ResultBalance = [VestingInfo | null, (BalanceLock | BalanceLockTo212)[]];
|
||||
type Result = [DeriveBalancesAccount, BlockNumber, ResultBalance];
|
||||
|
||||
const VESTING_ID = '0x76657374696e6720';
|
||||
|
||||
function calcBalances (api: ApiInterfaceRx, [{ accountId, accountNonce, freeBalance, frozenFee, frozenMisc, reservedBalance, votingBalance }, bestNumber, [vesting, locks]]: Result): DeriveBalancesAll {
|
||||
let lockedBalance = api.registry.createType('Balance');
|
||||
let lockedBreakdown: (BalanceLock | BalanceLockTo212)[] = [];
|
||||
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(VESTING_ID)).reduce((result: BN, { amount }) => result.iadd(amount), new BN(0)));
|
||||
|
||||
// get the maximum of the locks according to https://github.com/paritytech/substrate/blob/master/srml/balances/src/lib.rs#L699
|
||||
if (notAll.length) {
|
||||
@@ -41,19 +45,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 +63,8 @@ function calcBalances (api: ApiInterfaceRx, [{ accountId, accountNonce, freeBala
|
||||
lockedBreakdown,
|
||||
reservedBalance,
|
||||
vestedBalance,
|
||||
vestedClaimable,
|
||||
vestingLocked,
|
||||
vestingTotal,
|
||||
votingBalance
|
||||
};
|
||||
@@ -135,7 +133,7 @@ export function all (api: ApiInterfaceRx): (address: AccountIndex | AccountId |
|
||||
? combineLatest([
|
||||
of(account),
|
||||
api.derive.chain.bestNumber(),
|
||||
isFunction(api.query.balances.account)
|
||||
isFunction(api.query.system.account) || isFunction(api.query.balances.account)
|
||||
? queryCurrent(api, account.accountId)
|
||||
: queryOld(api, account.accountId)
|
||||
])
|
||||
|
||||
@@ -11,7 +11,7 @@ import { HeaderExtended } from '../type';
|
||||
import { memo } from '../util';
|
||||
|
||||
/**
|
||||
* @name bestNumberFinalized
|
||||
* @name getHeader
|
||||
* @param {( Uint8Array | string )} hash - A block hash as U8 array or string.
|
||||
* @returns An array containing the block header and the block author
|
||||
* @description Get a specific block header and extend it with the author
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the Apache-2.0 license. See the LICENSE file for details.
|
||||
|
||||
import { AccountId, ReferendumInfo, ReferendumInfoTo239, VotingDirect, VotingDirectVote } from '@polkadot/types/interfaces';
|
||||
import { AccountId, ReferendumInfo, ReferendumInfoTo239, VotingDelegating, VotingDirect, VotingDirectVote } from '@polkadot/types/interfaces';
|
||||
import { ApiInterfaceRx } from '@polkadot/api/types';
|
||||
import { DeriveDemocracyLock } from '../types';
|
||||
|
||||
@@ -20,16 +20,37 @@ const ZERO = new BN(0);
|
||||
function parseLock (api: ApiInterfaceRx, [referendumId, accountVote]: VotingDirectVote, referendum: ReferendumInfo): DeriveDemocracyLock {
|
||||
const { balance, vote } = accountVote.asStandard;
|
||||
let unlockAt = ZERO;
|
||||
let referendumEnd = ZERO;
|
||||
|
||||
if (referendum.isFinished) {
|
||||
const { approved, end } = referendum.asFinished;
|
||||
|
||||
referendumEnd = end;
|
||||
|
||||
if ((approved.isTrue && vote.isAye) || (approved.isFalse && vote.isNay)) {
|
||||
unlockAt = end.add(api.consts.democracy.enactmentPeriod.muln(LOCKUPS[vote.conviction.index]));
|
||||
}
|
||||
}
|
||||
|
||||
return { balance, isFinished: referendum.isFinished, referendumId, unlockAt, vote };
|
||||
return { balance, isDelegated: false, isFinished: referendum.isFinished, referendumEnd, referendumId, unlockAt, vote };
|
||||
}
|
||||
|
||||
function delegateLocks (api: ApiInterfaceRx, { balance, conviction, target }: VotingDelegating): Observable<DeriveDemocracyLock[]> {
|
||||
return api.derive.democracy.locks(target).pipe(
|
||||
map((available): DeriveDemocracyLock[] =>
|
||||
available.map(({ isFinished, referendumEnd, referendumId, unlockAt, vote }): DeriveDemocracyLock => ({
|
||||
balance,
|
||||
isDelegated: true,
|
||||
isFinished,
|
||||
referendumEnd,
|
||||
referendumId,
|
||||
unlockAt: unlockAt.isZero()
|
||||
? unlockAt
|
||||
: referendumEnd.add(api.consts.democracy.enactmentPeriod.muln(LOCKUPS[conviction.index])),
|
||||
vote: api.registry.createType('Vote', { aye: vote.isAye, conviction })
|
||||
}))
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
function directLocks (api: ApiInterfaceRx, { votes }: VotingDirect): Observable<DeriveDemocracyLock[]> {
|
||||
@@ -59,7 +80,9 @@ export function locks (api: ApiInterfaceRx): (accountId: string | AccountId) =>
|
||||
switchMap((voting): Observable<DeriveDemocracyLock[]> =>
|
||||
voting.isDirect
|
||||
? directLocks(api, voting.asDirect)
|
||||
: of([])
|
||||
: voting.isDelegating
|
||||
? delegateLocks(api, voting.asDelegating)
|
||||
: of([])
|
||||
)
|
||||
)
|
||||
);
|
||||
|
||||
@@ -9,7 +9,9 @@ import { Vec } from '@polkadot/types';
|
||||
|
||||
export interface DeriveDemocracyLock {
|
||||
balance: Balance;
|
||||
isDelegated: boolean;
|
||||
isFinished: boolean;
|
||||
referendumEnd: BN;
|
||||
referendumId: ReferendumIndex;
|
||||
unlockAt: BN;
|
||||
vote: Vote;
|
||||
|
||||
@@ -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;
|
||||
}, {
|
||||
|
||||
@@ -4,13 +4,13 @@
|
||||
|
||||
import { AccountId, Balance, BlockNumber } from '@polkadot/types/interfaces';
|
||||
import { ITuple } from '@polkadot/types/types';
|
||||
import { DeriveElectionsInfo } from './types';
|
||||
|
||||
import { Observable } from 'rxjs';
|
||||
import { map } from 'rxjs/operators';
|
||||
import { ApiInterfaceRx } from '@polkadot/api/types';
|
||||
import { Vec, u32 } from '@polkadot/types';
|
||||
|
||||
import { DeriveElectionsInfo } from '../types';
|
||||
import { memo } from '../util';
|
||||
|
||||
function sortAccounts ([, balanceA]: ITuple<[AccountId, Balance]>, [, balanceB]: ITuple<[AccountId, Balance]>): number {
|
||||
@@ -30,6 +30,7 @@ function queryElections (api: ApiInterfaceRx): Observable<DeriveElectionsInfo> {
|
||||
candidacyBond: api.consts[section].candidacyBond as Balance,
|
||||
candidateCount: api.registry.createType('u32', candidates.length),
|
||||
candidates,
|
||||
desiredRunnersUp: api.consts[section].desiredRunnersUp as u32,
|
||||
desiredSeats: api.consts[section].desiredMembers as u32,
|
||||
members: members.length
|
||||
? members.sort(sortAccounts)
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
// Copyright 2017-2020 @polkadot/api-derive authors & contributors
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the Apache-2.0 license. See the LICENSE file for details.
|
||||
|
||||
import { AccountId, Balance, BlockNumber, SetIndex, VoteIndex } from '@polkadot/types/interfaces';
|
||||
|
||||
import { u32 } from '@polkadot/types';
|
||||
|
||||
export interface DeriveElectionsInfo {
|
||||
candidates: AccountId[];
|
||||
candidateCount: u32;
|
||||
candidacyBond?: Balance;
|
||||
desiredRunnersUp: u32;
|
||||
desiredSeats: u32;
|
||||
members: [AccountId, Balance][];
|
||||
nextVoterSet?: SetIndex;
|
||||
runnersUp: [AccountId, Balance][];
|
||||
termDuration: BlockNumber;
|
||||
voteCount?: VoteIndex;
|
||||
voterCount?: SetIndex;
|
||||
votingBond?: Balance;
|
||||
}
|
||||
@@ -9,6 +9,7 @@ import { Observable, of, combineLatest } from 'rxjs';
|
||||
import { map, switchMap } from 'rxjs/operators';
|
||||
import { ApiInterfaceRx } from '@polkadot/api/types';
|
||||
import { Bytes, Option, u32 } from '@polkadot/types';
|
||||
import { BN_ZERO } from '@polkadot/util';
|
||||
|
||||
import { memo } from '../util';
|
||||
|
||||
@@ -34,7 +35,7 @@ export function receivedHeartbeats (api: ApiInterfaceRx): () => Observable<Deriv
|
||||
[validator.toString()]: {
|
||||
blockCount: numBlocks[index],
|
||||
hasMessage: !heartbeats[index].isEmpty,
|
||||
isOnline: !heartbeats[index].isEmpty || numBlocks[index].gtn(0)
|
||||
isOnline: !heartbeats[index].isEmpty || numBlocks[index].gt(BN_ZERO)
|
||||
}
|
||||
}), {})
|
||||
)
|
||||
|
||||
@@ -17,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,
|
||||
@@ -30,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')
|
||||
}))
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -7,57 +7,41 @@ 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';
|
||||
import { BN_ZERO } from '@polkadot/util';
|
||||
|
||||
import { memo } from '../util';
|
||||
|
||||
// groups the supplied chunks by era, i.e. { [era]: BN(total of values) }
|
||||
function groupByEra (list: UnlockChunk[]): Record<string, BN> {
|
||||
return list.reduce((map: Record<string, BN>, { era, value }): Record<string, BN> => {
|
||||
const key = era.toString();
|
||||
|
||||
map[key] = !map[key]
|
||||
? value.unwrap()
|
||||
: map[key].add(value.unwrap());
|
||||
map[key] = (map[key] || BN_ZERO).add(value.unwrap());
|
||||
|
||||
return map;
|
||||
}, {});
|
||||
}
|
||||
|
||||
function calculateUnlocking (api: ApiInterfaceRx, stakingLedger: StakingLedger | undefined, sessionInfo: DeriveSessionInfo): DeriveUnlocking[] | undefined {
|
||||
if (isUndefined(stakingLedger)) {
|
||||
return undefined;
|
||||
}
|
||||
const results = Object
|
||||
.entries(groupByEra(
|
||||
(stakingLedger?.unlocking || []).filter(({ era }) => era.unwrap().gt(sessionInfo.activeEra))
|
||||
))
|
||||
.map(([eraString, value]): DeriveUnlocking => ({
|
||||
remainingEras: new BN(eraString).isub(sessionInfo.activeEra),
|
||||
value: api.registry.createType('Balance', value)
|
||||
}));
|
||||
|
||||
const unlockingChunks = stakingLedger.unlocking.filter(({ era }): boolean =>
|
||||
era.unwrap().sub(sessionInfo.activeEra).gtn(0)
|
||||
);
|
||||
|
||||
if (!unlockingChunks.length) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
// group the unlock chunks that have the same era and sum their values
|
||||
const groupedResult = groupByEra(unlockingChunks);
|
||||
const results = Object.entries(groupedResult).map(([eraString, value]): DeriveUnlocking => ({
|
||||
remainingEras: new BN(eraString).sub(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 {
|
||||
if (isUndefined(stakingLedger)) {
|
||||
return api.registry.createType('Balance');
|
||||
}
|
||||
|
||||
return api.registry.createType('Balance', stakingLedger.unlocking.reduce((total, { era, value }): BN => {
|
||||
return api.registry.createType('Balance', (stakingLedger?.unlocking || [] as UnlockChunk[]).reduce((total, { era, value }): BN => {
|
||||
return sessionInfo.activeEra.gte(era.unwrap())
|
||||
? total.add(value.unwrap())
|
||||
? total.iadd(value.unwrap())
|
||||
: total;
|
||||
}, new BN(0)));
|
||||
}
|
||||
@@ -70,23 +54,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 +61,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
|
||||
}))
|
||||
)
|
||||
)
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -8,6 +8,7 @@ import { DeriveEraPoints, DeriveEraValPoints } from '../types';
|
||||
|
||||
import { Observable, of } from 'rxjs';
|
||||
import { map, switchMap } from 'rxjs/operators';
|
||||
import { BN_ZERO } from '@polkadot/util';
|
||||
|
||||
import { deriveCache, memo } from '../util';
|
||||
|
||||
@@ -15,7 +16,7 @@ const CACHE_KEY = 'eraPoints';
|
||||
|
||||
function mapValidators ({ individual }: EraRewardPoints): DeriveEraValPoints {
|
||||
return [...individual.entries()]
|
||||
.filter(([, points]): boolean => points.gtn(0))
|
||||
.filter(([, points]) => points.gt(BN_ZERO))
|
||||
.reduce((result: DeriveEraValPoints, [validatorId, points]): DeriveEraValPoints => {
|
||||
result[validatorId.toString()] = points;
|
||||
|
||||
|
||||
@@ -21,3 +21,4 @@ export * from './stakerRewards';
|
||||
export * from './stakerSlashes';
|
||||
export * from './stashes';
|
||||
export * from './validators';
|
||||
export * from './waitingInfo';
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
// 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';
|
||||
|
||||
@@ -16,7 +16,7 @@ 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];
|
||||
@@ -28,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],
|
||||
@@ -39,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 (
|
||||
isFunction(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>')
|
||||
);
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -104,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)
|
||||
)
|
||||
);
|
||||
}
|
||||
@@ -113,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([])
|
||||
);
|
||||
|
||||
@@ -52,7 +52,7 @@ function parseRewards (api: ApiInterfaceRx, stashId: AccountId, [, erasPoints, e
|
||||
: 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] = {
|
||||
@@ -199,14 +199,18 @@ export function stakerRewards (api: ApiInterfaceRx): (accountId: Uint8Array | st
|
||||
);
|
||||
}
|
||||
|
||||
export function stakerRewardsMulti (api: ApiInterfaceRx): (accountIds: (Uint8Array | string)[], withActive?: boolean) => Observable<DeriveStakerReward[][]> {
|
||||
return memo((accountIds: (Uint8Array | string)[], withActive = false): 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))
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -96,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
|
||||
}))
|
||||
);
|
||||
})
|
||||
)
|
||||
);
|
||||
}
|
||||
@@ -20,7 +20,7 @@ interface Result {
|
||||
|
||||
function latestNonce (api: ApiInterfaceRx, address: string): Observable<Index> {
|
||||
return api.derive.balances.account(address).pipe(
|
||||
map(({ accountNonce }): Index => accountNonce)
|
||||
map(({ accountNonce }) => accountNonce)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -31,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
|
||||
@@ -57,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
|
||||
}))
|
||||
|
||||
@@ -3,13 +3,14 @@
|
||||
// of the Apache-2.0 license. See the LICENSE file for details.
|
||||
|
||||
import type BN from 'bn.js';
|
||||
import { AccountId, Balance, BalanceLock, BalanceLockTo212, BalanceOf, Bid, BidKind, BlockNumber, Hash, Index, Proposal, ProposalIndex, SetIndex, SocietyVote, StrikeCount, TreasuryProposal, Votes, VoteIndex, VouchingStatus } from '@polkadot/types/interfaces';
|
||||
import { AccountId, Balance, BalanceLock, BalanceLockTo212, BalanceOf, Bid, BidKind, BlockNumber, Hash, Index, Proposal, ProposalIndex, SetIndex, SocietyVote, StrikeCount, TreasuryProposal, Votes, VouchingStatus } from '@polkadot/types/interfaces';
|
||||
|
||||
import { u32 } from '@polkadot/types';
|
||||
|
||||
export * from './accounts/types';
|
||||
export * from './council/types';
|
||||
export * from './democracy/types';
|
||||
export * from './elections/types';
|
||||
export * from './parachains/types';
|
||||
export * from './session/types';
|
||||
export * from './staking/types';
|
||||
@@ -31,6 +32,8 @@ export interface DeriveBalancesAll extends DeriveBalancesAccount {
|
||||
availableBalance: Balance;
|
||||
votingBalance: Balance;
|
||||
vestedBalance: Balance;
|
||||
vestedClaimable: Balance;
|
||||
vestingLocked: Balance;
|
||||
vestingTotal: Balance;
|
||||
}
|
||||
|
||||
@@ -42,6 +45,7 @@ export interface DeriveContractFees {
|
||||
creationFee: BN;
|
||||
rentByteFee: BN;
|
||||
rentDepositOffset: BN;
|
||||
surchargeReward: BN;
|
||||
tombstoneDeposit: BN;
|
||||
transactionBaseFee: BN;
|
||||
transactionByteFee: BN;
|
||||
@@ -56,20 +60,6 @@ export interface DeriveCollectiveProposal {
|
||||
|
||||
export type DeriveCollectiveProposals = DeriveCollectiveProposal[];
|
||||
|
||||
export interface DeriveElectionsInfo {
|
||||
candidates: AccountId[];
|
||||
candidateCount: u32;
|
||||
candidacyBond?: Balance;
|
||||
desiredSeats: u32;
|
||||
members: [AccountId, Balance][];
|
||||
nextVoterSet?: SetIndex;
|
||||
runnersUp: [AccountId, Balance][];
|
||||
termDuration: BlockNumber;
|
||||
voteCount?: VoteIndex;
|
||||
voterCount?: SetIndex;
|
||||
votingBond?: Balance;
|
||||
}
|
||||
|
||||
export interface DeriveFees {
|
||||
creationFee: Balance;
|
||||
existentialDeposit: Balance;
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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.17.1",
|
||||
"version": "1.31.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.10.2",
|
||||
"@polkadot/api-derive": "1.17.1",
|
||||
"@polkadot/keyring": "^2.12.2",
|
||||
"@polkadot/metadata": "1.17.1",
|
||||
"@polkadot/rpc-core": "1.17.1",
|
||||
"@polkadot/rpc-provider": "1.17.1",
|
||||
"@polkadot/types": "1.17.1",
|
||||
"@polkadot/types-known": "1.17.1",
|
||||
"@polkadot/util": "^2.12.2",
|
||||
"@polkadot/util-crypto": "^2.12.2",
|
||||
"bn.js": "^5.1.2",
|
||||
"eventemitter3": "^4.0.4",
|
||||
"rxjs": "^6.5.5"
|
||||
"@babel/runtime": "^7.11.2",
|
||||
"@polkadot/api-derive": "1.31.1",
|
||||
"@polkadot/keyring": "^3.4.1",
|
||||
"@polkadot/metadata": "1.31.1",
|
||||
"@polkadot/rpc-core": "1.31.1",
|
||||
"@polkadot/rpc-provider": "1.31.1",
|
||||
"@polkadot/types": "1.31.1",
|
||||
"@polkadot/types-known": "1.31.1",
|
||||
"@polkadot/util": "^3.4.1",
|
||||
"@polkadot/util-crypto": "^3.4.1",
|
||||
"bn.js": "^5.1.3",
|
||||
"eventemitter3": "^4.0.6",
|
||||
"rxjs": "^6.6.2"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@polkadot/keyring": "^2.12.2"
|
||||
"@polkadot/keyring": "^3.4.1"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,8 +3,8 @@
|
||||
|
||||
import { Codec } from '@polkadot/types/types';
|
||||
import { Vec } from '@polkadot/types/codec';
|
||||
import { u32, u64 } from '@polkadot/types/primitive';
|
||||
import { Balance, BalanceOf, BlockNumber, LockIdentifier, ModuleId, Moment, Percent, Permill, RuntimeDbWeight, Weight } from '@polkadot/types/interfaces/runtime';
|
||||
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';
|
||||
@@ -176,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>;
|
||||
/**
|
||||
@@ -215,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>;
|
||||
|
||||
@@ -6,22 +6,23 @@ 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, MaybeRandomness, NextConfigDescriptor, Randomness } from '@polkadot/types/interfaces/babe';
|
||||
import { AccountData, BalanceLock, ReleasesBalances } from '@polkadot/types/interfaces/balances';
|
||||
import { AccountData, BalanceLock } from '@polkadot/types/interfaces/balances';
|
||||
import { ProposalIndex, Votes } from '@polkadot/types/interfaces/collective';
|
||||
import { AuthorityId } from '@polkadot/types/interfaces/consensus';
|
||||
import { CodeHash, ContractInfo, PrefabWasmModule, Schedule } from '@polkadot/types/interfaces/contracts';
|
||||
import { PreimageStatus, PropIndex, Proposal, ProxyState, ReferendumIndex, ReferendumInfo, ReleasesDemocracy, 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 { ProxyType } from '@polkadot/types/interfaces/proxy';
|
||||
import { ActiveRecovery, RecoveryConfig } from '@polkadot/types/interfaces/recovery';
|
||||
import { AccountId, AccountIndex, Balance, BalanceOf, BlockNumber, ExtrinsicsWeight, Hash, KeyTypeId, Moment, Perbill, ValidatorId } from '@polkadot/types/interfaces/runtime';
|
||||
import { AccountId, AccountIndex, Balance, BalanceOf, BlockNumber, ExtrinsicsWeight, Hash, KeyTypeId, Moment, OpaqueCall, Perbill, 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';
|
||||
@@ -121,9 +122,6 @@ declare module '@polkadot/api/types/storage' {
|
||||
/**
|
||||
* 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>;
|
||||
@@ -137,7 +135,7 @@ declare module '@polkadot/api/types/storage' {
|
||||
*
|
||||
* 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.
|
||||
**/
|
||||
@@ -242,13 +240,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.
|
||||
*
|
||||
* TWOX-NOTE: OK ― `AccountId` is a secure hash.
|
||||
**/
|
||||
proxy: AugmentedQuery<ApiType, (arg: AccountId | string | Uint8Array) => Observable<Option<ProxyState>>> & QueryableStorageEntry<ApiType>;
|
||||
/**
|
||||
* The number of (public) proposals that have been made so far.
|
||||
**/
|
||||
@@ -272,7 +263,7 @@ declare module '@polkadot/api/types/storage' {
|
||||
*
|
||||
* New networks start with last version.
|
||||
**/
|
||||
storageVersion: AugmentedQuery<ApiType, () => Observable<Option<ReleasesDemocracy>>> & QueryableStorageEntry<ApiType>;
|
||||
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.
|
||||
@@ -398,7 +389,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>;
|
||||
@@ -425,6 +424,14 @@ declare module '@polkadot/api/types/storage' {
|
||||
**/
|
||||
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>;
|
||||
/**
|
||||
@@ -464,6 +471,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>;
|
||||
@@ -669,9 +682,9 @@ declare module '@polkadot/api/types/storage' {
|
||||
*
|
||||
* 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>;
|
||||
/**
|
||||
@@ -689,10 +702,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.
|
||||
**/
|
||||
@@ -718,7 +727,7 @@ 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.
|
||||
**/
|
||||
@@ -750,7 +759,7 @@ declare module '@polkadot/api/types/storage' {
|
||||
*
|
||||
* 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.
|
||||
**/
|
||||
@@ -901,6 +910,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>;
|
||||
@@ -928,13 +938,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>;
|
||||
/**
|
||||
|
||||
@@ -19,16 +19,10 @@ 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.
|
||||
@@ -244,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
|
||||
**/
|
||||
@@ -256,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
|
||||
**/
|
||||
|
||||
+510
-385
File diff suppressed because it is too large
Load Diff
@@ -7,11 +7,11 @@ 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';
|
||||
@@ -45,7 +45,7 @@ const PAGE_SIZE_VALS = PAGE_SIZE_KEYS;
|
||||
const l = logger('api/init');
|
||||
|
||||
export default abstract class Decorate<ApiType extends ApiTypes> extends Events {
|
||||
public readonly registry: Registry;
|
||||
#registry: Registry;
|
||||
|
||||
// HACK Use BN import so decorateDerive works... yes, wtf.
|
||||
protected __phantom = new BN(0);
|
||||
@@ -127,7 +127,7 @@ export default abstract class Decorate<ApiType extends ApiTypes> extends Events
|
||||
constructor (options: ApiOptions, type: ApiTypes, decorateMethod: DecorateMethod<ApiType>) {
|
||||
super();
|
||||
|
||||
this.registry = options.registry || new TypeRegistry();
|
||||
this.#registry = options.registry || new TypeRegistry();
|
||||
|
||||
const thisProvider = options.source
|
||||
? options.source._rpcCore.provider.clone()
|
||||
@@ -136,24 +136,31 @@ export default abstract class Decorate<ApiType extends ApiTypes> extends Events
|
||||
this._decorateMethod = decorateMethod;
|
||||
this._options = options;
|
||||
this._type = type;
|
||||
this._rpcCore = new RpcCore(this.registry, thisProvider, this._options.rpc);
|
||||
this._rpcCore = new RpcCore(this.#registry, thisProvider, this._options.rpc);
|
||||
this._isConnected = new BehaviorSubject(this._rpcCore.provider.isConnected());
|
||||
this._rx.hasSubscriptions = this._rpcCore.provider.hasSubscriptions;
|
||||
this._rx.registry = this.registry;
|
||||
this._rx.registry = this.#registry;
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Return the current used registry
|
||||
*/
|
||||
public get registry (): Registry {
|
||||
return this.#registry;
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Creates an instance of a type as registered
|
||||
*/
|
||||
public createType <K extends keyof InterfaceTypes> (type: K, ...params: any[]): InterfaceTypes[K] {
|
||||
return this.registry.createType(type, ...params);
|
||||
public createType <K extends keyof InterfaceTypes> (type: K, ...params: unknown[]): InterfaceTypes[K] {
|
||||
return this.#registry.createType(type, ...params);
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Register additional user-defined of chain-specific types in the type registry
|
||||
*/
|
||||
public registerTypes (types?: RegistryTypes): void {
|
||||
types && this.registry.register(types);
|
||||
types && this.#registry.register(types);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -163,8 +170,8 @@ export default abstract class Decorate<ApiType extends ApiTypes> extends Events
|
||||
return this._rpcCore.provider.hasSubscriptions;
|
||||
}
|
||||
|
||||
public injectMetadata (metadata: Metadata, fromEmpty?: boolean): void {
|
||||
const decoratedMeta = new DecoratedMeta(this.registry, metadata);
|
||||
public injectMetadata (metadata: Metadata, fromEmpty?: boolean, registry?: Registry): void {
|
||||
const decoratedMeta = new DecoratedMeta(registry || this.#registry, metadata);
|
||||
|
||||
if (fromEmpty || !this._extrinsics) {
|
||||
this._extrinsics = this._decorateExtrinsics(decoratedMeta.tx, this._decorateMethod);
|
||||
@@ -320,75 +327,84 @@ 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
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
|
||||
const decorated = this.hasSubscriptions && creator.iterKey && creator.meta.type.isMap && creator.meta.type.asMap.linked.isTrue
|
||||
? 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);
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
|
||||
decorated.creator = creator;
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access,@typescript-eslint/no-unsafe-assignment
|
||||
decorated.at = decorateMethod((hash: Hash, arg1?: Arg, arg2?: Arg): Observable<Codec> =>
|
||||
this._rpcCore.state.getStorage(getArgs(arg1, arg2), hash));
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access,@typescript-eslint/no-unsafe-assignment
|
||||
decorated.hash = decorateMethod((arg1?: Arg, arg2?: Arg): Observable<Hash> =>
|
||||
this._rpcCore.state.getStorageHash(getArgs(arg1, arg2)));
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
|
||||
decorated.key = (arg1?: Arg, arg2?: Arg): string =>
|
||||
u8aToHex(compactStripLength(creator(creator.meta.type.isDoubleMap ? [arg1, arg2] : arg1))[1]);
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
|
||||
decorated.keyPrefix = (key1?: Arg): string =>
|
||||
u8aToHex(creator.keyPrefix(key1));
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access,@typescript-eslint/no-unsafe-assignment
|
||||
decorated.range = decorateMethod((range: [Hash, Hash?], arg1?: Arg, arg2?: Arg): Observable<[Hash, Codec][]> =>
|
||||
this._decorateStorageRange(decorated, [arg1, arg2], range));
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access,@typescript-eslint/no-unsafe-assignment
|
||||
decorated.size = decorateMethod((arg1?: Arg, arg2?: Arg): Observable<u64> =>
|
||||
this._rpcCore.state.getStorageSize(getArgs(arg1, arg2)));
|
||||
|
||||
// .keys() & .entries() only available on map types
|
||||
if (creator.iterKey && (creator.meta.type.isMap || creator.meta.type.isDoubleMap)) {
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access,@typescript-eslint/no-unsafe-assignment
|
||||
decorated.entries = decorateMethod(
|
||||
memo((doubleMapArg?: Arg): Observable<[StorageKey, Codec][]> =>
|
||||
this._retrieveMapEntries(creator, doubleMapArg)));
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access,@typescript-eslint/no-unsafe-assignment
|
||||
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
|
||||
if (this.hasSubscriptions) {
|
||||
// When using double map storage function, user need to pass double map key as an array
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access,@typescript-eslint/no-unsafe-assignment
|
||||
decorated.multi = decorateMethod((args: (Arg | Arg[])[]): Observable<Codec[]> =>
|
||||
this._rpcCore.state.subscribeStorage(
|
||||
args.map((arg: Arg[] | Arg): [StorageEntry, Arg | Arg[]] => [creator, arg])));
|
||||
}
|
||||
|
||||
/* 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][]> {
|
||||
const outputType = unwrapStorageType(decorated.creator.meta.type, decorated.creator.meta.modifier.isOptional);
|
||||
|
||||
@@ -402,6 +418,8 @@ 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 = new Map<Codec, ITuple<[Codec, Linkage<Codec>]> | null>();
|
||||
let subject: BehaviorSubject<LinkageResult>;
|
||||
@@ -450,8 +468,8 @@ export default abstract class Decorate<ApiType extends ApiTypes> extends Events
|
||||
}
|
||||
|
||||
const nextResult = vals.length
|
||||
? new LinkageResult(this.registry, [keys[0].constructor as any, keys], [vals[0].constructor as any, vals])
|
||||
: new LinkageResult(this.registry, [Null, []], [Null, []]);
|
||||
? new LinkageResult(this.#registry, [keys[0].constructor as any, keys], [vals[0].constructor as any, vals])
|
||||
: new LinkageResult(this.#registry, [Null, []], [Null, []]);
|
||||
|
||||
// we set our result into a subject so we have a single observable for
|
||||
// which the value changes over time. Initially create, follow-up next
|
||||
@@ -467,15 +485,15 @@ export default abstract class Decorate<ApiType extends ApiTypes> extends Events
|
||||
// this handles the case where the head changes effectively, i.e. a new entry
|
||||
// appears at the top of the list, the new getNext gets kicked off
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-return
|
||||
return decorateMethod((...args: any[]): Observable<LinkageResult | [Codec, Linkage<Codec>]> =>
|
||||
return decorateMethod((...args: 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]>([iterKey()])
|
||||
.pipe(switchMap(([key]): Observable<LinkageResult> => getNext(head = key)))
|
||||
.pipe(switchMap(([key]) => getNext(head = key)))
|
||||
);
|
||||
}
|
||||
|
||||
@@ -485,24 +503,30 @@ export default abstract class Decorate<ApiType extends ApiTypes> extends Events
|
||||
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][]> {
|
||||
@@ -512,13 +536,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][] =>
|
||||
|
||||
+128
-12
@@ -3,25 +3,37 @@
|
||||
// of the Apache-2.0 license. See the LICENSE file for details.
|
||||
|
||||
import { SignedBlock, RuntimeVersion } from '@polkadot/types/interfaces';
|
||||
import { Registry } from '@polkadot/types/types';
|
||||
import { ApiBase, ApiOptions, ApiTypes, DecorateMethod } from '../types';
|
||||
|
||||
import BN from 'bn.js';
|
||||
import { Observable, Subscription, of } from 'rxjs';
|
||||
import { map, switchMap } from 'rxjs/operators';
|
||||
import { Metadata, Text } from '@polkadot/types';
|
||||
import { Metadata, Text, TypeRegistry } from '@polkadot/types';
|
||||
import { LATEST_EXTRINSIC_VERSION } from '@polkadot/types/extrinsic/Extrinsic';
|
||||
import { getMetadataTypes, getSpecTypes } from '@polkadot/types-known';
|
||||
import { logger } from '@polkadot/util';
|
||||
import { getMetadataTypes, getSpecAlias, getSpecTypes, getUpgradeVersion } from '@polkadot/types-known';
|
||||
import { BN_ZERO, assert, logger, u8aEq, u8aToU8a } from '@polkadot/util';
|
||||
import { cryptoWaitReady } from '@polkadot/util-crypto';
|
||||
|
||||
import Decorate from './Decorate';
|
||||
|
||||
interface VersionedRegistry {
|
||||
isDefault: boolean;
|
||||
lastBlockHash: Uint8Array | null;
|
||||
registry: Registry;
|
||||
specVersion: BN;
|
||||
}
|
||||
|
||||
const KEEPALIVE_INTERVAL = 15000;
|
||||
const DEFAULT_BLOCKNUMBER = { unwrap: () => BN_ZERO };
|
||||
|
||||
const l = logger('api/init');
|
||||
|
||||
export default abstract class Init<ApiType extends ApiTypes> extends Decorate<ApiType> {
|
||||
#healthTimer: NodeJS.Timeout | null = null;
|
||||
|
||||
#registries: VersionedRegistry[] = [];
|
||||
|
||||
#updateSub?: Subscription;
|
||||
|
||||
constructor (options: ApiOptions, type: ApiTypes, decorateMethod: DecorateMethod<ApiType>) {
|
||||
@@ -32,12 +44,7 @@ export default abstract class Init<ApiType extends ApiTypes> extends Decorate<Ap
|
||||
}
|
||||
|
||||
// all injected types added to the registry for overrides
|
||||
this.registry.setKnownTypes({
|
||||
types: options.types,
|
||||
typesAlias: options.typesAlias,
|
||||
typesChain: options.typesChain,
|
||||
typesSpec: options.typesSpec
|
||||
});
|
||||
this.registry.setKnownTypes(options);
|
||||
|
||||
// We only register the types (global) if this is not a cloned instance.
|
||||
// Do right up-front, so we get in the user types before we are actually
|
||||
@@ -54,6 +61,7 @@ export default abstract class Init<ApiType extends ApiTypes> extends Decorate<Ap
|
||||
this._rx.queryMulti = this._decorateMulti(this._rxDecorateMethod);
|
||||
this._rx.signer = options.signer;
|
||||
|
||||
this._rpcCore.setRegistrySwap((hash?: string | Uint8Array | null) => this.getBlockRegistry(hash));
|
||||
this._rpcCore.provider.on('disconnected', this.#onProviderDisconnect);
|
||||
this._rpcCore.provider.on('error', this.#onProviderError);
|
||||
this._rpcCore.provider.on('connected', this.#onProviderConnect);
|
||||
@@ -67,6 +75,71 @@ export default abstract class Init<ApiType extends ApiTypes> extends Decorate<Ap
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Sets up a registry based on the block hash defined
|
||||
*/
|
||||
public async getBlockRegistry (blockHash?: string | Uint8Array | null): Promise<Registry> {
|
||||
if (!blockHash) {
|
||||
return this.registry;
|
||||
}
|
||||
|
||||
// shortcut in the case where we have an immediate-same request
|
||||
const lastBlockHash = u8aToU8a(blockHash);
|
||||
const existingViaHash = this.#registries.find((r) => r.lastBlockHash && u8aEq(lastBlockHash, r.lastBlockHash));
|
||||
|
||||
if (existingViaHash) {
|
||||
return existingViaHash.registry;
|
||||
}
|
||||
|
||||
// ensure we have everything required
|
||||
assert(this._genesisHash && this._runtimeVersion, 'Cannot retrieve data on an uninitialized chain');
|
||||
|
||||
// We have to assume that on the RPC layer the calls used here does not call back into
|
||||
// the registry swap, so getHeader & getRuntimeVersion should not be historic
|
||||
const header = this._genesisHash.eq(blockHash)
|
||||
? { number: DEFAULT_BLOCKNUMBER, parentHash: this._genesisHash }
|
||||
: await this._rpcCore.chain.getHeader(blockHash).toPromise();
|
||||
|
||||
assert(header?.parentHash && !header.parentHash.isEmpty, 'Unable to retrieve header and parent from supplied hash');
|
||||
|
||||
// get the runtime version, either on-chain or via an known upgrade history
|
||||
const [firstVersion, lastVersion] = getUpgradeVersion(this._genesisHash, header.number.unwrap());
|
||||
const version = (firstVersion && (lastVersion || firstVersion.specVersion.eq(this._runtimeVersion.specVersion)))
|
||||
? { specName: this._runtimeVersion.specName, specVersion: firstVersion.specVersion }
|
||||
: await this._rpcCore.state.getRuntimeVersion(header.parentHash).toPromise();
|
||||
|
||||
// check for pre-existing registries
|
||||
const existingViaVersion = this.#registries.find((r) => r.specVersion.eq(version.specVersion));
|
||||
|
||||
if (existingViaVersion) {
|
||||
existingViaVersion.lastBlockHash = lastBlockHash;
|
||||
|
||||
return existingViaVersion.registry;
|
||||
}
|
||||
|
||||
// nothing has been found, construct new
|
||||
const registry = new TypeRegistry();
|
||||
|
||||
registry.setChainProperties(this.registry.getChainProperties());
|
||||
registry.setKnownTypes(this._options);
|
||||
registry.register(getSpecTypes(registry, this._runtimeChain as Text, version.specName, version.specVersion));
|
||||
|
||||
if (registry.knownTypes.typesBundle) {
|
||||
this._adjustBundleTypes(registry, this._runtimeChain as Text, version.specName);
|
||||
}
|
||||
|
||||
// retrieve the metadata now that we have all types set
|
||||
const metadata = await this._rpcCore.state.getMetadata(header.parentHash).toPromise();
|
||||
|
||||
// TODO: Not convinced (yet) that we really want to re-decorate, keep on ice since it does muddle-up
|
||||
// this.injectMetadata(metadata, false);
|
||||
registry.setMetadata(metadata);
|
||||
|
||||
this.#registries.push({ isDefault: false, lastBlockHash, registry, specVersion: version.specVersion });
|
||||
|
||||
return registry;
|
||||
}
|
||||
|
||||
protected async _loadMeta (): Promise<boolean> {
|
||||
const genesisHash = await this._rpcCore.chain.getBlockHash(0).toPromise();
|
||||
|
||||
@@ -137,8 +210,14 @@ export default abstract class Init<ApiType extends ApiTypes> extends Decorate<Ap
|
||||
this._runtimeVersion = version;
|
||||
this._rx.runtimeVersion = version;
|
||||
|
||||
this.registerTypes(getSpecTypes(this.registry, this._runtimeChain as Text, version.specName, version.specVersion));
|
||||
this.injectMetadata(metadata, false);
|
||||
// update the default registry version
|
||||
const thisRegistry = this.#registries.find(({ isDefault }) => isDefault);
|
||||
|
||||
assert(thisRegistry, 'Initialization error, cannot find the default registry');
|
||||
|
||||
thisRegistry.specVersion = version.specVersion;
|
||||
thisRegistry.registry.register(getSpecTypes(thisRegistry.registry, this._runtimeChain as Text, version.specName, version.specVersion));
|
||||
this.injectMetadata(metadata, false, thisRegistry.registry);
|
||||
|
||||
return true;
|
||||
})
|
||||
@@ -147,6 +226,33 @@ export default abstract class Init<ApiType extends ApiTypes> extends Decorate<Ap
|
||||
).subscribe();
|
||||
}
|
||||
|
||||
private _adjustBundleTypes (registry: Registry, chain: Text, specName: Text): void {
|
||||
// adjust known type aliases
|
||||
registry.knownTypes.typesAlias = getSpecAlias(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 +265,16 @@ export default abstract class Init<ApiType extends ApiTypes> extends Decorate<Ap
|
||||
this._runtimeVersion = runtimeVersion;
|
||||
this._rx.runtimeVersion = runtimeVersion;
|
||||
|
||||
// setup the initial registry, when we have none
|
||||
if (!this.#registries.length) {
|
||||
this.#registries.push({ isDefault: true, lastBlockHash: null, registry: this.registry, specVersion: runtimeVersion.specVersion });
|
||||
}
|
||||
|
||||
// adjust types based on bundled info
|
||||
if (this.registry.knownTypes.typesBundle) {
|
||||
this._adjustBundleTypes(this.registry, chain, runtimeVersion.specName);
|
||||
}
|
||||
|
||||
// do the setup for the specific chain
|
||||
this.registry.setChainProperties(chainProps);
|
||||
this.registerTypes(getSpecTypes(this.registry, chain, runtimeVersion.specName, runtimeVersion.specVersion));
|
||||
@@ -186,7 +302,7 @@ export default abstract class Init<ApiType extends ApiTypes> extends Decorate<Ap
|
||||
const metaExtrinsic = metadata.asLatest.extrinsic;
|
||||
|
||||
// only inject if we are not a clone (global init)
|
||||
if (metaExtrinsic.version.gtn(0)) {
|
||||
if (metaExtrinsic.version.gt(BN_ZERO)) {
|
||||
this._extrinsicType = metaExtrinsic.version.toNumber();
|
||||
} else if (!this._options.source) {
|
||||
// detect the extrinsic version in-use based on the last block
|
||||
|
||||
@@ -2,31 +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])) {
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
|
||||
callback = actualArgs.pop();
|
||||
callback = actualArgs.pop() as Callback<Codec>;
|
||||
}
|
||||
|
||||
// When we need a subscription, ensure that a valid callback is actually passed
|
||||
@@ -36,56 +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;
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/ban-types
|
||||
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) {
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-call,@typescript-eslint/no-unsafe-member-access
|
||||
return method(...actualArgs).pipe(first()).toPromise() as Promise<ObsInnerType<ReturnType<Method>>>;
|
||||
}
|
||||
|
||||
return new Promise((resolve, reject): void => {
|
||||
const tracker = promiseTracker(resolve, reject);
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-call,@typescript-eslint/no-unsafe-member-access,@typescript-eslint/no-unsafe-assignment
|
||||
const subscription: { unsubscribe: () => void } = 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
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-call,@typescript-eslint/no-unsafe-member-access,@typescript-eslint/no-unsafe-return
|
||||
tap(() => tracker.resolve(() => subscription.unsubscribe()))
|
||||
).subscribe(callback);
|
||||
}) as UnsubscribePromise;
|
||||
return resultCb
|
||||
? decorateSubscribe(method, actualArgs, resultCb)
|
||||
: decorateCall((options?.overrideNoSub as Method) || method, actualArgs);
|
||||
} as StorageEntryPromiseOverloads;
|
||||
}
|
||||
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
|
||||
@@ -60,16 +60,19 @@ export default function createClass <ApiType extends ApiTypes> ({ api, apiType,
|
||||
)();
|
||||
}
|
||||
|
||||
// sign a transaction, returning the this to allow chaining, i.e. .sign(...).send()
|
||||
/**
|
||||
* @description Sign a transaction, returning the this to allow chaining, i.e. .sign(...).send(). When options, e.g. nonce/blockHash are not specified, it will be inferred. To retrieve eg. nonce use `signAsync` (the preferred interface, this is provided for backwards compatibility)
|
||||
* @deprecated
|
||||
*/
|
||||
public sign (account: IKeyringPair, optionsOrNonce?: Partial<SignerOptions>): this {
|
||||
super.sign(account, this.#makeSignOptions(this.#optionsOrNonce(optionsOrNonce), {}));
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
// signs a transaction, returning `this` to allow chaining. E.g.: `sign(...).send()`
|
||||
//
|
||||
// also supports signing through external signers
|
||||
/**
|
||||
* @description Signs a transaction, returning `this` to allow chaining. E.g.: `sign(...).send()`. Like `.signAndSend` this will retrieve the nonce and blockHash to send the tx with.
|
||||
*/
|
||||
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(
|
||||
|
||||
@@ -50,6 +50,9 @@ export interface SubmittableExtrinsic<ApiType extends ApiTypes> extends Extrinsi
|
||||
|
||||
send(statusCb: Callback<ISubmittableResult>): SubmittableResultSubscription<ApiType>;
|
||||
|
||||
/**
|
||||
* @deprecated
|
||||
*/
|
||||
sign(account: IKeyringPair, _options?: Partial<SignerOptions>): this;
|
||||
|
||||
signAsync(account: AddressOrPair, _options?: Partial<SignerOptions>): SubmittableThis<ApiType, this>;
|
||||
|
||||
@@ -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,19 @@ 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;
|
||||
}
|
||||
|
||||
|
||||
@@ -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}`)
|
||||
);
|
||||
}, []);
|
||||
}
|
||||
|
||||
@@ -24,7 +24,7 @@ export default function filterEvents (extHash: H256, { block: { extrinsics, head
|
||||
return;
|
||||
}
|
||||
|
||||
return allEvents.filter(({ phase }): boolean =>
|
||||
return allEvents.filter(({ phase }) =>
|
||||
// only ApplyExtrinsic has the extrinsic index
|
||||
phase.isApplyExtrinsic && phase.asApplyExtrinsic.eqn(index)
|
||||
);
|
||||
|
||||
@@ -11,7 +11,7 @@ function sig ({ method, section }: StorageEntry, ...args: Type[]): string {
|
||||
return `${section}.${method}(${args.join(', ')})`;
|
||||
}
|
||||
|
||||
function doDoubleMap (creator: StorageEntry, args: any[]): [StorageEntry, [any, any]] {
|
||||
function doDoubleMap (creator: StorageEntry, args: unknown[]): [StorageEntry, [any, any]] {
|
||||
const { key1, key2 } = creator.meta.type.asDoubleMap;
|
||||
|
||||
assert(args.length === 2, `${sig(creator, key1, key2)} is a doublemap, requiring 2 arguments, ${args.length} found`);
|
||||
@@ -20,7 +20,7 @@ function doDoubleMap (creator: StorageEntry, args: any[]): [StorageEntry, [any,
|
||||
return [creator, args as [any, any]];
|
||||
}
|
||||
|
||||
function doMap (creator: StorageEntry, args: any[]): [StorageEntry] | [StorageEntry, any] {
|
||||
function doMap (creator: StorageEntry, args: unknown[]): [StorageEntry] | [StorageEntry, any] {
|
||||
const { key, linked } = creator.meta.type.asMap;
|
||||
|
||||
linked.isTrue
|
||||
@@ -35,7 +35,7 @@ function doMap (creator: StorageEntry, args: any[]): [StorageEntry] | [StorageEn
|
||||
|
||||
// sets up the arguments in the form of [creator, args] ready to be used in a storage
|
||||
// call. Additionally, it verifies that the correct number of arguments have been passed
|
||||
export function extractStorageArgs (creator: StorageEntry, _args: any[]): [StorageEntry, [any, any]] | [StorageEntry] | [StorageEntry, any] {
|
||||
export function extractStorageArgs (creator: StorageEntry, _args: unknown[]): [StorageEntry, [any, any]] | [StorageEntry] | [StorageEntry, any] {
|
||||
const args = _args.filter((arg) => !isUndefined(arg));
|
||||
|
||||
if (creator.meta.type.isDoubleMap) {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@polkadot/metadata",
|
||||
"version": "1.17.1",
|
||||
"version": "1.31.1",
|
||||
"description": "Helpers to extract information from runtime metadata",
|
||||
"main": "index.js",
|
||||
"publishConfig": {
|
||||
@@ -26,14 +26,14 @@
|
||||
},
|
||||
"homepage": "https://github.com/polkadot-js/api/tree/master/packages/type-metadata#readme",
|
||||
"dependencies": {
|
||||
"@babel/runtime": "^7.10.2",
|
||||
"@polkadot/types": "1.17.1",
|
||||
"@polkadot/types-known": "1.17.1",
|
||||
"@polkadot/util": "^2.12.2",
|
||||
"@polkadot/util-crypto": "^2.12.2",
|
||||
"bn.js": "^5.1.2"
|
||||
"@babel/runtime": "^7.11.2",
|
||||
"@polkadot/types": "1.31.1",
|
||||
"@polkadot/types-known": "1.31.1",
|
||||
"@polkadot/util": "^3.4.1",
|
||||
"@polkadot/util-crypto": "^3.4.1",
|
||||
"bn.js": "^5.1.3"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@polkadot/keyring": "^2.12.2"
|
||||
"@polkadot/keyring": "^3.4.1"
|
||||
}
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because one or more lines are too long
@@ -2,7 +2,7 @@
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the Apache-2.0 license. See the LICENSE file for details.
|
||||
|
||||
import { FunctionMetadataV11, FunctionMetadataLatest, MetadataV11, MetadataLatest, ModuleMetadataLatest, StorageMetadataV11, StorageMetadataLatest, StorageEntryMetadataLatest } from '@polkadot/types/interfaces/metadata';
|
||||
import { EventMetadataV11, EventMetadataLatest, FunctionMetadataV11, FunctionMetadataLatest, MetadataV11, MetadataLatest, ModuleMetadataLatest, StorageMetadataV11, StorageMetadataLatest, StorageEntryMetadataLatest } from '@polkadot/types/interfaces/metadata';
|
||||
import { Registry, OverrideModuleType } from '@polkadot/types/types';
|
||||
|
||||
import { getModuleTypes } from '@polkadot/types-known';
|
||||
@@ -35,6 +35,18 @@ function convertCalls (registry: Registry, calls: FunctionMetadataV11[], section
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Apply module-specific type overrides (always be done as part of toLatest)
|
||||
* @internal
|
||||
**/
|
||||
function convertEvents (registry: Registry, events: EventMetadataV11[], sectionTypes: OverrideModuleType): EventMetadataLatest[] {
|
||||
return events.map(({ args, documentation, name }): EventMetadataLatest => {
|
||||
args.forEach((type): void => setTypeOverride(sectionTypes, type));
|
||||
|
||||
return registry.createType('EventMetadataLatest', { args, documentation, name });
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Apply module-specific storage type overrides (always part of toLatest)
|
||||
* @internal
|
||||
@@ -70,6 +82,7 @@ export default function toLatest (registry: Registry, { extrinsic, modules }: Me
|
||||
extrinsic,
|
||||
modules: modules.map((mod): ModuleMetadataLatest => {
|
||||
const calls = mod.calls.unwrapOr(null);
|
||||
const events = mod.events.unwrapOr(null);
|
||||
const storage = mod.storage.unwrapOr(null);
|
||||
const sectionTypes = getModuleTypes(registry, stringCamelCase(mod.name.toString()));
|
||||
|
||||
@@ -78,6 +91,9 @@ export default function toLatest (registry: Registry, { extrinsic, modules }: Me
|
||||
calls: calls
|
||||
? convertCalls(registry, calls, sectionTypes)
|
||||
: null,
|
||||
events: events
|
||||
? convertEvents(registry, events, sectionTypes)
|
||||
: null,
|
||||
storage: storage
|
||||
? convertStorage(registry, storage, sectionTypes)
|
||||
: null
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@polkadot/rpc-core",
|
||||
"version": "1.17.1",
|
||||
"version": "1.31.1",
|
||||
"description": "A JavaScript wrapper for the Polkadot JsonRPC interface",
|
||||
"main": "index.js",
|
||||
"keywords": [
|
||||
@@ -26,15 +26,15 @@
|
||||
},
|
||||
"homepage": "https://github.com/polkadot-js/api/tree/master/packages/rpc-core#readme",
|
||||
"dependencies": {
|
||||
"@babel/runtime": "^7.10.2",
|
||||
"@polkadot/metadata": "1.17.1",
|
||||
"@polkadot/rpc-provider": "1.17.1",
|
||||
"@polkadot/types": "1.17.1",
|
||||
"@polkadot/util": "^2.12.2",
|
||||
"@babel/runtime": "^7.11.2",
|
||||
"@polkadot/metadata": "1.31.1",
|
||||
"@polkadot/rpc-provider": "1.31.1",
|
||||
"@polkadot/types": "1.31.1",
|
||||
"@polkadot/util": "^3.4.1",
|
||||
"memoizee": "^0.4.14",
|
||||
"rxjs": "^6.5.5"
|
||||
"rxjs": "^6.6.2"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@polkadot/keyring": "^2.12.2"
|
||||
"@polkadot/keyring": "^3.4.1"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -91,10 +91,25 @@ describe('Cached Observables', (): void => {
|
||||
expect(observable2).not.toBe(observable1);
|
||||
});
|
||||
|
||||
it('creates multiple observables for one-shots', (): void => {
|
||||
it('creates single observables for subsequent one-shots', (): void => {
|
||||
const observable1 = rpc.chain.getBlockHash(123);
|
||||
const observable2 = rpc.chain.getBlockHash(123);
|
||||
|
||||
expect(observable2).not.toBe(observable1);
|
||||
expect(observable2).toBe(observable1);
|
||||
});
|
||||
|
||||
it('creates multiple observables for subsequent one-shots delayed', (done): void => {
|
||||
const observable1 = rpc.chain.getBlockHash(123);
|
||||
|
||||
const sub = observable1.subscribe((): void => {
|
||||
sub.unsubscribe();
|
||||
});
|
||||
|
||||
expect(rpc.chain.getBlockHash(123)).toBe(observable1);
|
||||
|
||||
setTimeout((): void => {
|
||||
expect(rpc.chain.getBlockHash(123)).not.toBe(observable1);
|
||||
done();
|
||||
}, 3500);
|
||||
});
|
||||
});
|
||||
|
||||
+131
-92
@@ -8,13 +8,18 @@ import { AnyJson, Codec, DefinitionRpc, DefinitionRpcExt, DefinitionRpcSub, Regi
|
||||
import { RpcInterface, RpcInterfaceMethod } from './types';
|
||||
|
||||
import memoizee from 'memoizee';
|
||||
import { combineLatest, from, Observable, Observer, of, throwError } from 'rxjs';
|
||||
import { catchError, map, publishReplay, refCount, switchMap } from 'rxjs/operators';
|
||||
import { Observable, Observer } from 'rxjs';
|
||||
import { publishReplay, refCount } from 'rxjs/operators';
|
||||
import jsonrpc from '@polkadot/types/interfaces/jsonrpc';
|
||||
import { Option, StorageKey, Vec, createClass, createTypeUnsafe } from '@polkadot/types';
|
||||
import { assert, hexToU8a, isFunction, isNull, isNumber, isUndefined, logger, u8aToU8a } from '@polkadot/util';
|
||||
import { assert, hexToU8a, isFunction, isNull, isUndefined, logger, u8aToU8a } from '@polkadot/util';
|
||||
|
||||
import { drr } from './rxjs';
|
||||
import { drr, refCountDelay } from './rxjs';
|
||||
|
||||
interface StorageChangeSetJSON {
|
||||
block: string;
|
||||
changes: [string, string | null][];
|
||||
}
|
||||
|
||||
const l = logger('rpc-core');
|
||||
|
||||
@@ -61,22 +66,22 @@ function logErrorMessage (method: string, { params, type }: DefinitionRpc, error
|
||||
* ```
|
||||
*/
|
||||
export default class Rpc implements RpcInterface {
|
||||
#registryDefault: Registry;
|
||||
|
||||
#getBlockRegistry?: (blockHash?: string | Uint8Array | null) => Promise<Registry>;
|
||||
|
||||
readonly #storageCache = new Map<string, string | null>();
|
||||
|
||||
public readonly mapping = new Map<string, DefinitionRpcExt>();
|
||||
|
||||
public readonly provider: ProviderInterface;
|
||||
|
||||
public readonly registry: Registry;
|
||||
|
||||
public readonly sections: string[] = [];
|
||||
|
||||
// Ok, this is quite horrible - we really should not be using the ! here, but we are actually assigning
|
||||
// these via the createInterfaces inside the constructor. However... this is not quite visible. The reason
|
||||
// why we don't do for individual assignments is to allow user-defined RPCs to also be defined
|
||||
|
||||
public readonly account!: RpcInterface['account'];
|
||||
|
||||
public readonly author!: RpcInterface['author'];
|
||||
|
||||
public readonly babe!: RpcInterface['babe'];
|
||||
@@ -110,10 +115,15 @@ export default class Rpc implements RpcInterface {
|
||||
// eslint-disable-next-line @typescript-eslint/unbound-method
|
||||
assert(provider && isFunction(provider.send), 'Expected Provider to API create');
|
||||
|
||||
this.registry = registry;
|
||||
this.#registryDefault = registry;
|
||||
this.provider = provider;
|
||||
|
||||
this._createInterfaces(userRpc);
|
||||
const sectionNames = Object.keys(jsonrpc);
|
||||
|
||||
// these are the base keys (i.e. part of jsonrpc)
|
||||
this.sections.push(...sectionNames);
|
||||
|
||||
this.addUserInterfaces(userRpc);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -123,27 +133,44 @@ export default class Rpc implements RpcInterface {
|
||||
this.provider.disconnect();
|
||||
}
|
||||
|
||||
private _createInterfaces<Section extends keyof RpcInterface> (userRpc: Record<string, Record<string, DefinitionRpc | DefinitionRpcSub>>): void {
|
||||
const sectionNames = Object.keys(jsonrpc);
|
||||
|
||||
// these are the base keys (i.e. part of jsonrpc)
|
||||
this.sections.push(...sectionNames);
|
||||
/**
|
||||
* @description Sets a registry swap (typically from Api)
|
||||
*/
|
||||
public setRegistrySwap (registrySwap: (blockHash?: string | Uint8Array | null) => Promise<Registry>): void {
|
||||
this.#getBlockRegistry = registrySwap;
|
||||
}
|
||||
|
||||
public addUserInterfaces<Section extends keyof RpcInterface> (userRpc: Record<string, Record<string, DefinitionRpc | DefinitionRpcSub>>): void {
|
||||
// add any extra user-defined sections
|
||||
this.sections.push(...Object.keys(userRpc).filter((key): boolean => !this.sections.includes(key)));
|
||||
this.sections.push(...Object.keys(userRpc).filter((key) => !this.sections.includes(key)));
|
||||
|
||||
// decorate the sections with base and user methods
|
||||
this.sections.forEach((sectionName): void => {
|
||||
(this as Record<string, unknown>)[sectionName as Section] = {
|
||||
...this._createInterface(sectionName, jsonrpc[sectionName as 'babe'] || {}),
|
||||
...this._createInterface(sectionName, userRpc[sectionName] || {})
|
||||
};
|
||||
if (!(this as Record<string, unknown>)[sectionName as Section]) {
|
||||
(this as Record<string, unknown>)[sectionName as Section] = {};
|
||||
}
|
||||
|
||||
const section = (this as Record<string, unknown>)[sectionName as Section] as Record<string, any>;
|
||||
|
||||
Object
|
||||
.entries({
|
||||
...this._createInterface(sectionName, jsonrpc[sectionName as 'babe'] || {}),
|
||||
...this._createInterface(sectionName, userRpc[sectionName] || {})
|
||||
})
|
||||
.forEach(([key, value]): void => {
|
||||
// we don't want to clobber existing, i.e. when this is called again after chain is determined
|
||||
if (!section[key]) {
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
|
||||
section[key] = value;
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
private _createInterface<Section extends keyof RpcInterface> (section: string, methods: Record<string, DefinitionRpc | DefinitionRpcSub>): RpcInterface[Section] {
|
||||
return Object
|
||||
.keys(methods)
|
||||
.filter((method) => !this.mapping.has(`${section}_${method}`))
|
||||
.reduce((exposed, method): RpcInterface[Section] => {
|
||||
const def = methods[method];
|
||||
const isSubscription = !!(def as DefinitionRpcSub).pubsub;
|
||||
@@ -174,45 +201,64 @@ export default class Rpc implements RpcInterface {
|
||||
|
||||
private _createMethodSend (section: string, method: string, def: DefinitionRpc): RpcInterfaceMethod {
|
||||
const rpcName = `${section}_${method}`;
|
||||
const hashIndex = def.params.findIndex(({ isHistoric }) => isHistoric);
|
||||
const cacheIndex = def.params.findIndex(({ isCached }) => isCached);
|
||||
let memoized: null | RpcInterfaceMethod & memoizee.Memoized<RpcInterfaceMethod> = null;
|
||||
|
||||
// execute the RPC call, doing a registry swap for historic as applicable
|
||||
const callWithRegistry = async (isRaw: boolean, values: any[]): Promise<Codec | Codec[]> => {
|
||||
const hash = hashIndex === -1
|
||||
? undefined
|
||||
: values[hashIndex] as Uint8Array;
|
||||
const registry = hash && this.#getBlockRegistry
|
||||
? await this.#getBlockRegistry(hash)
|
||||
: this.#registryDefault;
|
||||
const params = this._formatInputs(registry, def, values);
|
||||
const data = await this.provider.send(rpcName, params.map((param): AnyJson => param.toJSON())) as AnyJson;
|
||||
|
||||
return isRaw
|
||||
? registry.createType('Raw', data)
|
||||
: this._formatOutput(registry, method, def, params, data);
|
||||
};
|
||||
|
||||
const creator = (isRaw: boolean) => (...values: any[]): Observable<any> => {
|
||||
// Here, logically, it should be `of(this.formatInputs(method, values))`.
|
||||
// However, formatInputs can throw, and when it does, the above way
|
||||
// doesn't throw in the "Observable loop" (which is internally wrapped in
|
||||
// a try/catch block). So we:
|
||||
// - first do `of(1)` - won't throw
|
||||
// - then do `map(()=>this.formatInputs)` - might throw, but inside Observable.
|
||||
return of(1).pipe(
|
||||
map(() => this._formatInputs(def, values)),
|
||||
switchMap((params): Observable<[Codec[], any]> =>
|
||||
combineLatest([
|
||||
of(params),
|
||||
from(this.provider.send(rpcName, params.map((param): AnyJson => param.toJSON())))
|
||||
])
|
||||
),
|
||||
map(([params, result]) =>
|
||||
isRaw
|
||||
? this.registry.createType('Raw', result)
|
||||
: this._formatOutput(method, def, params, result)
|
||||
),
|
||||
catchError((error): any => {
|
||||
logErrorMessage(method, def, error);
|
||||
const isDelayed = (hashIndex !== -1 && !!values[hashIndex]) || (cacheIndex !== -1 && !!values[cacheIndex]);
|
||||
|
||||
return throwError(error);
|
||||
}),
|
||||
return new Observable((observer: Observer<any>): VoidCallback => {
|
||||
callWithRegistry(isRaw, values)
|
||||
.then((value): void => {
|
||||
observer.next(value);
|
||||
observer.complete();
|
||||
})
|
||||
.catch((error): void => {
|
||||
logErrorMessage(method, def, error);
|
||||
|
||||
observer.error(error);
|
||||
observer.complete();
|
||||
});
|
||||
|
||||
return (): void => {
|
||||
// delete old results from cache
|
||||
memoized?.delete(...values);
|
||||
};
|
||||
}).pipe(
|
||||
publishReplay(1), // create a Replay(1)
|
||||
refCount() // Unsubscribe WS when there are no more subscribers
|
||||
isDelayed
|
||||
? refCountDelay() // Unsubscribe after delay
|
||||
: refCount()
|
||||
);
|
||||
};
|
||||
|
||||
// We voluntarily don't cache the "one-shot" RPC calls. For example,
|
||||
// `getStorage('123')` returns the current value, but this value can change
|
||||
// over time, so we wouldn't want to cache the Observable.
|
||||
return this._createMethodWithRaw(creator);
|
||||
memoized = memoizee(this._createMethodWithRaw(creator), {
|
||||
length: false,
|
||||
normalizer: JSON.stringify
|
||||
});
|
||||
|
||||
return memoized;
|
||||
}
|
||||
|
||||
// create a subscriptor, it subscribes once and resolves with the id as subscribe
|
||||
private _createSubscriber ({ paramsJson, subName, subType, update }: { subType: string; subName: string; paramsJson: AnyJson[]; update: ProviderInterfaceCallback }, errorHandler: (error: Error) => void): Promise<number> {
|
||||
private _createSubscriber ({ paramsJson, subName, subType, update }: { subType: string; subName: string; paramsJson: AnyJson[]; update: ProviderInterfaceCallback }, errorHandler: (error: Error) => void): Promise<number | string> {
|
||||
return new Promise((resolve, reject): void => {
|
||||
this.provider
|
||||
.subscribe(subType, subName, paramsJson, update)
|
||||
@@ -229,11 +275,13 @@ export default class Rpc implements RpcInterface {
|
||||
const subName = `${section}_${subMethod}`;
|
||||
const unsubName = `${section}_${unsubMethod}`;
|
||||
const subType = `${section}_${updateType}`;
|
||||
let memoized: null | RpcInterfaceMethod & memoizee.Memoized<RpcInterfaceMethod> = null;
|
||||
|
||||
const creator = (isRaw: boolean) => (...values: any[]): Observable<any> => {
|
||||
const creator = (isRaw: boolean) => (...values: unknown[]): Observable<any> => {
|
||||
return new Observable((observer: Observer<any>): VoidCallback => {
|
||||
// Have at least an empty promise, as used in the unsubscribe
|
||||
let subscriptionPromise: Promise<number | void> = Promise.resolve();
|
||||
let subscriptionPromise: Promise<number | string | null> = Promise.resolve(null);
|
||||
const registry = this.#registryDefault;
|
||||
|
||||
const errorHandler = (error: Error): void => {
|
||||
logErrorMessage(method, def, error);
|
||||
@@ -242,7 +290,7 @@ export default class Rpc implements RpcInterface {
|
||||
};
|
||||
|
||||
try {
|
||||
const params = this._formatInputs(def, values);
|
||||
const params = this._formatInputs(registry, def, values);
|
||||
const paramsJson = params.map((param): AnyJson => param.toJSON());
|
||||
|
||||
const update = (error?: Error | null, result?: any): void => {
|
||||
@@ -255,8 +303,8 @@ export default class Rpc implements RpcInterface {
|
||||
try {
|
||||
observer.next(
|
||||
isRaw
|
||||
? this.registry.createType('Raw', result)
|
||||
: this._formatOutput(method, def, params, result)
|
||||
? registry.createType('Raw', result)
|
||||
: this._formatOutput(registry, method, def, params, result)
|
||||
);
|
||||
} catch (error) {
|
||||
observer.error(error);
|
||||
@@ -270,31 +318,22 @@ export default class Rpc implements RpcInterface {
|
||||
|
||||
// Teardown logic
|
||||
return (): void => {
|
||||
// Delete from cache
|
||||
// Reason:
|
||||
// ```
|
||||
// const s = api.query.system.account(addr1).subscribe(); // let's say it's 6
|
||||
// s.unsubscribe();
|
||||
// // wait a bit, for the nonce to increase to 7
|
||||
// api.query.system.account(addr1).subscribe(); // will output 6 instead of 7 if we don't clear cache
|
||||
// // that's because all our observables are replay(1)
|
||||
// ```
|
||||
// eslint-disable-next-line @typescript-eslint/no-use-before-define
|
||||
memoized.delete(...values);
|
||||
// Delete from cache, so old results don't hang around
|
||||
memoized?.delete(...values);
|
||||
|
||||
// Unsubscribe from provider
|
||||
subscriptionPromise
|
||||
.then((subscriptionId): Promise<boolean> =>
|
||||
isNumber(subscriptionId)
|
||||
? this.provider.unsubscribe(subType, unsubName, subscriptionId)
|
||||
: Promise.resolve(false)
|
||||
isNull(subscriptionId)
|
||||
? Promise.resolve(false)
|
||||
: this.provider.unsubscribe(subType, unsubName, subscriptionId)
|
||||
)
|
||||
.catch((error: Error): void => logErrorMessage(method, def, error));
|
||||
.catch((error: Error) => logErrorMessage(method, def, error));
|
||||
};
|
||||
}).pipe(drr());
|
||||
};
|
||||
|
||||
const memoized = memoizee(this._createMethodWithRaw(creator), {
|
||||
memoized = memoizee(this._createMethodWithRaw(creator), {
|
||||
// Dynamic length for argument
|
||||
length: false,
|
||||
// Normalize args so that different args that should be cached
|
||||
@@ -307,7 +346,7 @@ export default class Rpc implements RpcInterface {
|
||||
return memoized;
|
||||
}
|
||||
|
||||
private _formatInputs (def: DefinitionRpc, inputs: any[]): Codec[] {
|
||||
private _formatInputs (registry: Registry, def: DefinitionRpc, inputs: any[]): Codec[] {
|
||||
const reqArgCount = def.params.filter(({ isOptional }): boolean => !isOptional).length;
|
||||
const optText = reqArgCount === def.params.length
|
||||
? ''
|
||||
@@ -316,7 +355,7 @@ export default class Rpc implements RpcInterface {
|
||||
assert(inputs.length >= reqArgCount && inputs.length <= def.params.length, `Expected ${def.params.length} parameters${optText}, ${inputs.length} found instead`);
|
||||
|
||||
return inputs.map((input, index): Codec =>
|
||||
createTypeUnsafe(this.registry, def.params[index].type, [input])
|
||||
createTypeUnsafe(registry, def.params[index].type, [input])
|
||||
);
|
||||
}
|
||||
|
||||
@@ -326,12 +365,12 @@ export default class Rpc implements RpcInterface {
|
||||
return ['0x3a636f6465'].includes(key.toHex());
|
||||
}
|
||||
|
||||
private _formatOutput (method: string, rpc: DefinitionRpc, params: Codec[], result?: any): Codec | Codec[] {
|
||||
private _formatOutput (registry: Registry, method: string, rpc: DefinitionRpc, params: Codec[], result?: any): Codec | Codec[] {
|
||||
if (rpc.type === 'StorageData') {
|
||||
const key = params[0] as StorageKey;
|
||||
|
||||
try {
|
||||
return this._formatStorageData(key, result);
|
||||
return this._formatStorageData(registry, key, result);
|
||||
} catch (error) {
|
||||
console.error(`Unable to decode storage ${key.section || 'unknown'}.${key.method || 'unknown'}:`, (error as Error).message);
|
||||
|
||||
@@ -341,12 +380,12 @@ export default class Rpc implements RpcInterface {
|
||||
const keys = params[0] as Vec<StorageKey>;
|
||||
|
||||
return keys
|
||||
? this._formatStorageSet(keys, (result as { changes: [string, string | null][] }).changes)
|
||||
: this.registry.createType('StorageChangeSet', result);
|
||||
? this._formatStorageSet(registry, keys, (result as StorageChangeSetJSON).changes)
|
||||
: registry.createType('StorageChangeSet', result);
|
||||
} else if (rpc.type === 'Vec<StorageChangeSet>') {
|
||||
const mapped = (result as { block: string; changes: [string, string | null][] }[]).map(({ block, changes }): [Hash, Codec[]] => [
|
||||
this.registry.createType('Hash', block),
|
||||
this._formatStorageSet(params[0] as Vec<StorageKey>, changes)
|
||||
const mapped = (result as StorageChangeSetJSON[]).map(({ block, changes }): [Hash, Codec[]] => [
|
||||
registry.createType('Hash', block),
|
||||
this._formatStorageSet(registry, params[0] as Vec<StorageKey>, changes)
|
||||
]);
|
||||
|
||||
// we only query at a specific block, not a range - flatten
|
||||
@@ -355,10 +394,10 @@ export default class Rpc implements RpcInterface {
|
||||
: mapped as unknown as Codec[];
|
||||
}
|
||||
|
||||
return createTypeUnsafe(this.registry, rpc.type, [result]);
|
||||
return createTypeUnsafe(registry, rpc.type, [result]);
|
||||
}
|
||||
|
||||
private _formatStorageData (key: StorageKey, value: string | null): Codec {
|
||||
private _formatStorageData (registry: Registry, key: StorageKey, value: string | null): Codec {
|
||||
// single return value (via state.getStorage), decode the value based on the
|
||||
// outputType that we have specified. Fallback to Raw on nothing
|
||||
const type = key.outputType || 'Raw';
|
||||
@@ -375,15 +414,15 @@ export default class Rpc implements RpcInterface {
|
||||
|
||||
if (meta.modifier.isOptional) {
|
||||
return new Option(
|
||||
this.registry,
|
||||
createClass(this.registry, type),
|
||||
registry,
|
||||
createClass(registry, type),
|
||||
isEmpty
|
||||
? null
|
||||
: createTypeUnsafe(this.registry, type, [input], true)
|
||||
: createTypeUnsafe(registry, type, [input], true)
|
||||
);
|
||||
}
|
||||
|
||||
return createTypeUnsafe(this.registry, type, [
|
||||
return createTypeUnsafe(registry, type, [
|
||||
isEmpty
|
||||
? meta.fallback
|
||||
? hexToU8a(meta.fallback.toHex())
|
||||
@@ -392,7 +431,7 @@ export default class Rpc implements RpcInterface {
|
||||
], true);
|
||||
}
|
||||
|
||||
private _formatStorageSet (keys: Vec<StorageKey>, changes: [string, string | null][]): Codec[] {
|
||||
private _formatStorageSet (registry: Registry, keys: Vec<StorageKey>, changes: [string, string | null][]): Codec[] {
|
||||
// For StorageChangeSet, the changes has the [key, value] mappings
|
||||
const withCache = keys.length !== 1;
|
||||
|
||||
@@ -402,7 +441,7 @@ export default class Rpc implements RpcInterface {
|
||||
// - null - The storage key is empty
|
||||
return keys.reduce((results: Codec[], key: StorageKey): Codec[] => {
|
||||
try {
|
||||
results.push(this._formatStorageSetEntry(key, changes, withCache));
|
||||
results.push(this._formatStorageSetEntry(registry, key, changes, withCache));
|
||||
} catch (error) {
|
||||
console.error(`Unable to decode storage ${key.section || 'unknown'}.${key.method || 'unknown'}:`, (error as Error).message);
|
||||
|
||||
@@ -413,7 +452,7 @@ export default class Rpc implements RpcInterface {
|
||||
}, []);
|
||||
}
|
||||
|
||||
private _formatStorageSetEntry (key: StorageKey, changes: [string, string | null][], witCache: boolean): Codec {
|
||||
private _formatStorageSetEntry (registry: Registry, key: StorageKey, changes: [string, string | null][], witCache: boolean): Codec {
|
||||
// Fallback to Raw (i.e. just the encoding) if we don't have a specific type
|
||||
const type = key.outputType || 'Raw';
|
||||
const hexKey = key.toHex();
|
||||
@@ -439,15 +478,15 @@ export default class Rpc implements RpcInterface {
|
||||
|
||||
if (meta.modifier.isOptional) {
|
||||
return new Option(
|
||||
this.registry,
|
||||
createClass(this.registry, type),
|
||||
registry,
|
||||
createClass(registry, type),
|
||||
isEmpty
|
||||
? null
|
||||
: createTypeUnsafe(this.registry, type, [input], true)
|
||||
: createTypeUnsafe(registry, type, [input], true)
|
||||
);
|
||||
}
|
||||
|
||||
return createTypeUnsafe(this.registry, type, [
|
||||
return createTypeUnsafe(registry, type, [
|
||||
isEmpty
|
||||
? meta.fallback
|
||||
? hexToU8a(meta.fallback.toHex())
|
||||
|
||||
@@ -12,6 +12,7 @@ import { refCountDelay } from './refCountDelay';
|
||||
export type DrrResult = <T> (source$: Observable<T>) => Observable<T>;
|
||||
|
||||
interface Options {
|
||||
delay?: number;
|
||||
skipChange?: boolean;
|
||||
skipTimeout?: boolean;
|
||||
}
|
||||
@@ -35,7 +36,7 @@ const NOOP = (): void => undefined;
|
||||
* @ignore
|
||||
* @internal
|
||||
*/
|
||||
export const drr = ({ skipChange = false, skipTimeout = false }: Options = {}): DrrResult => <T> (source$: Observable<T>): Observable<T> =>
|
||||
export const drr = ({ delay, skipChange = false, skipTimeout = false }: Options = {}): DrrResult => <T> (source$: Observable<T>): Observable<T> =>
|
||||
source$.pipe(
|
||||
catchError(ERR),
|
||||
skipChange
|
||||
@@ -44,5 +45,5 @@ export const drr = ({ skipChange = false, skipTimeout = false }: Options = {}):
|
||||
publishReplay(1),
|
||||
skipTimeout
|
||||
? refCount()
|
||||
: refCountDelay()
|
||||
: refCountDelay(delay)
|
||||
);
|
||||
|
||||
@@ -2,45 +2,42 @@
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the Apache-2.0 license. See the LICENSE file for details.
|
||||
|
||||
import { asapScheduler, ConnectableObservable, MonoTypeOperatorFunction, Observable, Subscription } from 'rxjs';
|
||||
|
||||
const DELAY = 1750;
|
||||
import { asapScheduler, ConnectableObservable, MonoTypeOperatorFunction, Observable, Subscription, TeardownLogic } from 'rxjs';
|
||||
|
||||
/** @internal */
|
||||
function refCountDelayInner <T> (source: Observable<T>): Observable<T> {
|
||||
// state: 0 = disconnected, 1 = disconnecting, 2 = connecting, 3 = connected
|
||||
let [state, refCount, connection, scheduler] = [0, 0, Subscription.EMPTY, Subscription.EMPTY];
|
||||
export function refCountDelay <T> (delay = 1750): MonoTypeOperatorFunction<T> {
|
||||
return (source: Observable<T>): Observable<T> => {
|
||||
// state: 0 = disconnected, 1 = disconnecting, 2 = connecting, 3 = connected
|
||||
let [state, refCount, connection, scheduler] = [0, 0, Subscription.EMPTY, Subscription.EMPTY];
|
||||
|
||||
return new Observable((ob) => {
|
||||
source.subscribe(ob);
|
||||
return new Observable((ob): TeardownLogic => {
|
||||
source.subscribe(ob);
|
||||
|
||||
if (refCount++ === 0) {
|
||||
if (state === 1) {
|
||||
scheduler.unsubscribe();
|
||||
} else {
|
||||
connection = (source as ConnectableObservable<T>).connect();
|
||||
}
|
||||
|
||||
state = 3;
|
||||
}
|
||||
|
||||
return (): void => {
|
||||
if (--refCount === 0) {
|
||||
if (state === 2) {
|
||||
state = 0; scheduler.unsubscribe();
|
||||
if (refCount++ === 0) {
|
||||
if (state === 1) {
|
||||
scheduler.unsubscribe();
|
||||
} else {
|
||||
// state === 3
|
||||
state = 1;
|
||||
scheduler = asapScheduler.schedule((): void => {
|
||||
state = 0; connection.unsubscribe();
|
||||
}, DELAY);
|
||||
connection = (source as ConnectableObservable<T>).connect();
|
||||
}
|
||||
}
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
/** @internal */
|
||||
export function refCountDelay <T> (): MonoTypeOperatorFunction<T> {
|
||||
return refCountDelayInner;
|
||||
state = 3;
|
||||
}
|
||||
|
||||
return (): void => {
|
||||
if (--refCount === 0) {
|
||||
if (state === 2) {
|
||||
state = 0;
|
||||
scheduler.unsubscribe();
|
||||
} else {
|
||||
// state === 3
|
||||
state = 1;
|
||||
scheduler = asapScheduler.schedule((): void => {
|
||||
state = 0;
|
||||
connection.unsubscribe();
|
||||
}, delay);
|
||||
}
|
||||
}
|
||||
};
|
||||
});
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@polkadot/rpc-provider",
|
||||
"version": "1.17.1",
|
||||
"version": "1.31.1",
|
||||
"description": "Transport providers for the API",
|
||||
"main": "index.js",
|
||||
"keywords": [
|
||||
@@ -26,19 +26,19 @@
|
||||
},
|
||||
"homepage": "https://github.com/polkadot-js/api/tree/master/packages/rpc-provider#readme",
|
||||
"dependencies": {
|
||||
"@babel/runtime": "^7.10.2",
|
||||
"@polkadot/metadata": "1.17.1",
|
||||
"@polkadot/types": "1.17.1",
|
||||
"@polkadot/util": "^2.12.2",
|
||||
"@polkadot/util-crypto": "^2.12.2",
|
||||
"bn.js": "^5.1.2",
|
||||
"eventemitter3": "^4.0.4",
|
||||
"@babel/runtime": "^7.11.2",
|
||||
"@polkadot/metadata": "1.31.1",
|
||||
"@polkadot/types": "1.31.1",
|
||||
"@polkadot/util": "^3.4.1",
|
||||
"@polkadot/util-crypto": "^3.4.1",
|
||||
"bn.js": "^5.1.3",
|
||||
"eventemitter3": "^4.0.6",
|
||||
"isomorphic-fetch": "^2.2.1",
|
||||
"websocket": "^1.0.31"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@polkadot/keyring": "^2.12.2",
|
||||
"@polkadot/keyring": "^3.4.1",
|
||||
"mock-socket": "^9.0.3",
|
||||
"nock": "^12.0.3"
|
||||
"nock": "^13.0.4"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -48,6 +48,18 @@ describe('decodeResponse', (): void => {
|
||||
).toThrow(/123: test error: Some random error description/);
|
||||
});
|
||||
|
||||
it('allows for number subscription ids', (): void => {
|
||||
expect(
|
||||
coder.decodeResponse({ id: 1, jsonrpc: '2.0', method: 'test', params: { result: 'test result', subscription: 1 } } as JsonRpcResponse)
|
||||
).toEqual('test result');
|
||||
});
|
||||
|
||||
it('allows for string subscription ids', (): void => {
|
||||
expect(
|
||||
coder.decodeResponse({ id: 1, jsonrpc: '2.0', method: 'test', params: { result: 'test result', subscription: 'abc' } } as JsonRpcResponse)
|
||||
).toEqual('test result');
|
||||
});
|
||||
|
||||
it('returns the result', (): void => {
|
||||
expect(
|
||||
coder.decodeResponse({ id: 1, jsonrpc: '2.0', result: 'some result' } as JsonRpcResponse)
|
||||
|
||||
@@ -30,7 +30,7 @@ export default class RpcCoder {
|
||||
|
||||
const isSubscription = !isUndefined(response.params) && !isUndefined(response.method);
|
||||
|
||||
assert(isNumber(response.id) || (isSubscription && isNumber(response.params.subscription)), 'Invalid id field in decoded object');
|
||||
assert(isNumber(response.id) || (isSubscription && (isNumber(response.params.subscription) || isString(response.params.subscription))), 'Invalid id field in decoded object');
|
||||
|
||||
this._checkError(response.error);
|
||||
|
||||
|
||||
@@ -24,6 +24,12 @@ describe('Http', (): void => {
|
||||
).not.toThrow();
|
||||
});
|
||||
|
||||
it('allows custom headers', (): void => {
|
||||
expect(
|
||||
(): Http => new Http('https://', { foo: 'bar' })
|
||||
).not.toThrow();
|
||||
});
|
||||
|
||||
it('always returns isConnected true', (): void => {
|
||||
expect(http.isConnected()).toEqual(true);
|
||||
});
|
||||
|
||||
@@ -40,14 +40,17 @@ export default class HttpProvider implements ProviderInterface {
|
||||
|
||||
readonly #endpoint: string;
|
||||
|
||||
readonly #headers: Record<string, string>;
|
||||
|
||||
/**
|
||||
* @param {string} endpoint The endpoint url starting with http://
|
||||
*/
|
||||
constructor (endpoint: string = defaults.HTTP_URL) {
|
||||
constructor (endpoint: string = defaults.HTTP_URL, headers: Record<string, string> = {}) {
|
||||
assert(/^(https|http):\/\//.test(endpoint), `Endpoint should start with 'http://', received '${endpoint}'`);
|
||||
|
||||
this.#coder = new Coder();
|
||||
this.#endpoint = endpoint;
|
||||
this.#headers = headers;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -102,7 +105,8 @@ export default class HttpProvider implements ProviderInterface {
|
||||
headers: {
|
||||
Accept: 'application/json',
|
||||
'Content-Length': `${body.length}`,
|
||||
'Content-Type': 'application/json'
|
||||
'Content-Type': 'application/json',
|
||||
...this.#headers
|
||||
},
|
||||
method: 'POST'
|
||||
});
|
||||
|
||||
@@ -28,7 +28,7 @@ interface JsonRpcResponseSubscription {
|
||||
params: {
|
||||
error?: JsonRpcResponseBaseError;
|
||||
result: unknown;
|
||||
subscription: number;
|
||||
subscription: number | string;
|
||||
};
|
||||
}
|
||||
|
||||
@@ -49,6 +49,6 @@ export interface ProviderInterface {
|
||||
isConnected (): boolean;
|
||||
on (type: ProviderInterfaceEmitted, sub: ProviderInterfaceEmitCb): () => void;
|
||||
send (method: string, params: any[]): Promise<any>;
|
||||
subscribe (type: string, method: string, params: any[], cb: ProviderInterfaceCallback): Promise<number>;
|
||||
unsubscribe (type: string, method: string, id: number): Promise<boolean>;
|
||||
subscribe (type: string, method: string, params: any[], cb: ProviderInterfaceCallback): Promise<number | string>;
|
||||
unsubscribe (type: string, method: string, id: number | string): Promise<boolean>;
|
||||
}
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
import { JsonRpcResponse, ProviderInterface, ProviderInterfaceCallback, ProviderInterfaceEmitted, ProviderInterfaceEmitCb } from '../types';
|
||||
|
||||
import EventEmitter from 'eventemitter3';
|
||||
import { assert, isNull, isUndefined, logger } from '@polkadot/util';
|
||||
import { assert, isNull, isUndefined, isChildClass, logger } from '@polkadot/util';
|
||||
|
||||
import Coder from '../coder';
|
||||
import defaults from '../defaults';
|
||||
@@ -67,6 +67,8 @@ export default class WsProvider implements WSProviderInterface {
|
||||
|
||||
readonly #endpoints: string[];
|
||||
|
||||
readonly #headers: Record<string, string>;
|
||||
|
||||
readonly #eventemitter: EventEmitter;
|
||||
|
||||
readonly #handlers: Record<string, WsStateAwaiting> = {};
|
||||
@@ -89,7 +91,7 @@ export default class WsProvider implements WSProviderInterface {
|
||||
* @param {string | string[]} endpoint The endpoint url. Usually `ws://ip:9944` or `wss://ip:9944`, may provide an array of endpoint strings.
|
||||
* @param {boolean} autoConnect Whether to connect automatically or not.
|
||||
*/
|
||||
constructor (endpoint: string | string[] = defaults.WS_URL, autoConnectMs: number | false = 1000) {
|
||||
constructor (endpoint: string | string[] = defaults.WS_URL, autoConnectMs: number | false = 1000, headers: Record<string, string> = {}) {
|
||||
const endpoints = Array.isArray(endpoint)
|
||||
? endpoint
|
||||
: [endpoint];
|
||||
@@ -105,6 +107,7 @@ export default class WsProvider implements WSProviderInterface {
|
||||
this.#coder = new Coder();
|
||||
this.#endpointIndex = -1;
|
||||
this.#endpoints = endpoints;
|
||||
this.#headers = headers;
|
||||
this.#websocket = null;
|
||||
|
||||
if (autoConnectMs > 0) {
|
||||
@@ -138,7 +141,11 @@ export default class WsProvider implements WSProviderInterface {
|
||||
|
||||
const WS = await getWSClass();
|
||||
|
||||
this.#websocket = new WS(this.#endpoints[this.#endpointIndex]);
|
||||
this.#websocket = typeof WebSocket !== 'undefined' && isChildClass(WebSocket, WS)
|
||||
? new WS(this.#endpoints[this.#endpointIndex])
|
||||
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
||||
// @ts-ignore - WS may be an instance of w3cwebsocket, which supports headers
|
||||
: new WS(this.#endpoints[this.#endpointIndex], undefined, undefined, this.#headers);
|
||||
this.#websocket.onclose = this.#onSocketClose;
|
||||
this.#websocket.onerror = this.#onSocketError;
|
||||
this.#websocket.onmessage = this.#onSocketMessage;
|
||||
@@ -247,8 +254,8 @@ export default class WsProvider implements WSProviderInterface {
|
||||
* })
|
||||
* ```
|
||||
*/
|
||||
public async subscribe (type: string, method: string, params: any[], callback: ProviderInterfaceCallback): Promise<number> {
|
||||
const id = await this.send(method, params, { callback, type }) as Promise<number>;
|
||||
public async subscribe (type: string, method: string, params: any[], callback: ProviderInterfaceCallback): Promise<number | string> {
|
||||
const id = await this.send(method, params, { callback, type }) as Promise<number | string>;
|
||||
|
||||
return id;
|
||||
}
|
||||
@@ -256,7 +263,7 @@ export default class WsProvider implements WSProviderInterface {
|
||||
/**
|
||||
* @summary Allows unsubscribing to subscriptions made with [[subscribe]].
|
||||
*/
|
||||
public async unsubscribe (type: string, method: string, id: number): Promise<boolean> {
|
||||
public async unsubscribe (type: string, method: string, id: number | string): Promise<boolean> {
|
||||
const subscription = `${type}::${id}`;
|
||||
|
||||
// FIXME This now could happen with re-subscriptions. The issue is that with a re-sub
|
||||
|
||||
@@ -28,6 +28,12 @@ describe('Ws', (): void => {
|
||||
createWs([]).isConnected()
|
||||
).toEqual(false);
|
||||
});
|
||||
|
||||
it('allows you to initialize the provider with custom headers', (): void => {
|
||||
expect(
|
||||
(): WsProvider => new WsProvider(TEST_WS_URL, 1000, { foo: 'bar' })
|
||||
).not.toThrow();
|
||||
});
|
||||
});
|
||||
|
||||
describe('Endpoint Parsing', (): void => {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@polkadot/typegen",
|
||||
"version": "1.17.1",
|
||||
"version": "1.31.1",
|
||||
"description": "Type generation scripts",
|
||||
"main": "index.js",
|
||||
"bin": {
|
||||
@@ -33,20 +33,20 @@
|
||||
},
|
||||
"homepage": "https://github.com/polkadot-js/api/tree/master/packages/typegen#readme",
|
||||
"dependencies": {
|
||||
"@babel/core": "^7.10.2",
|
||||
"@babel/register": "^7.10.1",
|
||||
"@babel/runtime": "^7.10.2",
|
||||
"@polkadot/api": "1.17.1",
|
||||
"@polkadot/metadata": "1.17.1",
|
||||
"@polkadot/rpc-provider": "1.17.1",
|
||||
"@polkadot/types": "1.17.1",
|
||||
"@polkadot/util": "^2.12.2",
|
||||
"@babel/core": "^7.11.4",
|
||||
"@babel/register": "^7.10.5",
|
||||
"@babel/runtime": "^7.11.2",
|
||||
"@polkadot/api": "1.31.1",
|
||||
"@polkadot/metadata": "1.31.1",
|
||||
"@polkadot/rpc-provider": "1.31.1",
|
||||
"@polkadot/types": "1.31.1",
|
||||
"@polkadot/util": "^3.4.1",
|
||||
"handlebars": "^4.7.6",
|
||||
"websocket": "^1.0.31",
|
||||
"yargs": "^15.3.1"
|
||||
"yargs": "^15.4.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/websocket": "^1.0.0",
|
||||
"@types/websocket": "^1.0.1",
|
||||
"@types/yargs": "^15.0.5"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,9 +5,10 @@
|
||||
import Handlebars from 'handlebars';
|
||||
|
||||
import { TypeRegistry } from '@polkadot/types/create';
|
||||
import * as definitions from '@polkadot/types/interfaces/definitions';
|
||||
import { Definitions } from '@polkadot/types/types';
|
||||
import * as defaultDefinitions from '@polkadot/types/interfaces/definitions';
|
||||
|
||||
import { createImports, getSimilarTypes, readTemplate, setImports, writeFile } from '../util';
|
||||
import { createImports, getSimilarTypes, formatType, readTemplate, setImports, writeFile } from '../util';
|
||||
|
||||
const StorageKeyTye = 'StorageKey | string | Uint8Array | any';
|
||||
|
||||
@@ -15,21 +16,28 @@ const template = readTemplate('rpc');
|
||||
const generateRpcTypesTemplate = Handlebars.compile(template);
|
||||
|
||||
/** @internal */
|
||||
export default function generateRpcTypes (dest = 'packages/api/src/augment/rpc.ts'): void {
|
||||
export function generateRpcTypes (importDefinitions: { [importPath: string]: Record<string, Definitions> }, dest: string): void {
|
||||
writeFile(dest, (): string => {
|
||||
const registry = new TypeRegistry();
|
||||
const allTypes = { '@polkadot/types/interfaces': definitions };
|
||||
const imports = createImports(allTypes);
|
||||
const allDefs = Object.entries(allTypes).reduce((defs, [path, obj]) => {
|
||||
|
||||
const imports = createImports(importDefinitions);
|
||||
const definitions = imports.definitions as Record<string, Definitions>;
|
||||
|
||||
const allDefs = Object.entries(importDefinitions).reduce((defs, [path, obj]) => {
|
||||
return Object.entries(obj).reduce((defs, [key, value]) => ({ ...defs, [`${path}/${key}`]: value }), defs);
|
||||
}, {});
|
||||
|
||||
const rpcKeys = Object
|
||||
.keys(definitions)
|
||||
.filter((key) => Object.keys(definitions[key as 'babe'].rpc || {}).length !== 0)
|
||||
.filter((key) => Object.keys(definitions[key].rpc || {}).length !== 0)
|
||||
.sort();
|
||||
const modules = rpcKeys.map((section) => {
|
||||
const allMethods = Object.keys(definitions[section as 'babe'].rpc).sort().map((methodName) => {
|
||||
const def = definitions[section as 'babe'].rpc[methodName];
|
||||
|
||||
const modules = rpcKeys.map((sectionFullName) => {
|
||||
const rpc = definitions[sectionFullName].rpc;
|
||||
const section = sectionFullName.split('/').pop();
|
||||
|
||||
const allMethods = Object.keys(rpc).sort().map((methodName) => {
|
||||
const def = rpc[methodName];
|
||||
|
||||
let args;
|
||||
let type;
|
||||
@@ -69,7 +77,7 @@ export default function generateRpcTypes (dest = 'packages/api/src/augment/rpc.t
|
||||
return `${param.name}${param.isOptional ? '?' : ''}: ${similarTypes.join(' | ')}`;
|
||||
});
|
||||
|
||||
type = def.type;
|
||||
type = formatType(allDefs, def.type, imports);
|
||||
generic = '';
|
||||
}
|
||||
|
||||
@@ -105,3 +113,10 @@ export default function generateRpcTypes (dest = 'packages/api/src/augment/rpc.t
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
export default function generateDefaultRpcTypes (): void {
|
||||
generateRpcTypes(
|
||||
{ '@polkadot/types/interfaces': defaultDefinitions },
|
||||
'packages/api/src/augment/rpc.ts'
|
||||
);
|
||||
}
|
||||
|
||||
@@ -61,6 +61,7 @@ function tsEnum (definitions: Record<string, ModuleTypes>, { name: enumName, sub
|
||||
case TypeDefInfo.Plain:
|
||||
case TypeDefInfo.Tuple:
|
||||
case TypeDefInfo.Vec:
|
||||
case TypeDefInfo.Option:
|
||||
return `${isGetter}${asGetter}`;
|
||||
|
||||
default:
|
||||
@@ -89,6 +90,7 @@ function tsResultGetter (definitions: Record<string, ModuleTypes>, resultName =
|
||||
case TypeDefInfo.Plain:
|
||||
case TypeDefInfo.Tuple:
|
||||
case TypeDefInfo.Vec:
|
||||
case TypeDefInfo.Option:
|
||||
return `${isGetter}${asGetter}`;
|
||||
|
||||
default:
|
||||
|
||||
@@ -16,7 +16,7 @@ import Vec from '@polkadot/types/codec/Vec';
|
||||
import Tuple from '@polkadot/types/codec/Tuple';
|
||||
import { AllConvictions } from '@polkadot/types/interfaces/democracy/definitions';
|
||||
import GenericAccountId from '@polkadot/types/generic/AccountId';
|
||||
import GenericAddress from '@polkadot/types/generic/Address';
|
||||
import GenericLookupSource from '@polkadot/types/generic/LookupSource';
|
||||
import Vote from '@polkadot/types/generic/Vote';
|
||||
import Null from '@polkadot/types/primitive/Null';
|
||||
import * as primitiveClasses from '@polkadot/types/primitive';
|
||||
@@ -92,18 +92,22 @@ export function getSimilarTypes (definitions: Record<string, ModuleTypes>, regis
|
||||
const Clazz = ClassOfUnsafe(registry, type);
|
||||
|
||||
if (isChildClass(Vec, Clazz)) {
|
||||
const subDef = (getTypeDef(type).sub) as TypeDef;
|
||||
const vecDef = getTypeDef(type);
|
||||
const subDef = (vecDef.sub) as TypeDef;
|
||||
|
||||
if (subDef.info === TypeDefInfo.Plain) {
|
||||
possibleTypes.push(`(${getSimilarTypes(definitions, registry, subDef.type, imports).join(' | ')})[]`);
|
||||
} else if (subDef.info === TypeDefInfo.Tuple) {
|
||||
const subs = (subDef.sub as TypeDef[]).map(({ type }): string =>
|
||||
getSimilarTypes(definitions, registry, type, imports).join(' | ')
|
||||
);
|
||||
// this could be that we define a Vec type and refer to it by name
|
||||
if (subDef) {
|
||||
if (subDef.info === TypeDefInfo.Plain) {
|
||||
possibleTypes.push(`(${getSimilarTypes(definitions, registry, subDef.type, imports).join(' | ')})[]`);
|
||||
} else if (subDef.info === TypeDefInfo.Tuple) {
|
||||
const subs = (subDef.sub as TypeDef[]).map(({ type }): string =>
|
||||
getSimilarTypes(definitions, registry, type, imports).join(' | ')
|
||||
);
|
||||
|
||||
possibleTypes.push(`([${subs.join(', ')}])[]`);
|
||||
} else {
|
||||
throw new Error(`Unhandled subtype in Vec, ${JSON.stringify(subDef)}`);
|
||||
possibleTypes.push(`([${subs.join(', ')}])[]`);
|
||||
} else {
|
||||
throw new Error(`Unhandled subtype in Vec, ${JSON.stringify(subDef)}`);
|
||||
}
|
||||
}
|
||||
} else if (isChildClass(Enum, Clazz)) {
|
||||
const e = new (Clazz as Constructor)(registry) as Enum;
|
||||
@@ -118,8 +122,8 @@ export function getSimilarTypes (definitions: Record<string, ModuleTypes>, regis
|
||||
possibleTypes.push('Uint8Array');
|
||||
} else if (isChildClass(AbstractInt as unknown as Constructor<UInt>, Clazz) || isChildClass(Compact, Clazz)) {
|
||||
possibleTypes.push('AnyNumber', 'Uint8Array');
|
||||
} else if (isChildClass(GenericAddress, Clazz)) {
|
||||
possibleTypes.push('Address', 'AccountId', 'AccountIndex', 'string', 'Uint8Array');
|
||||
} else if (isChildClass(GenericLookupSource, Clazz)) {
|
||||
possibleTypes.push('Address', 'AccountId', 'AccountIndex', 'LookupSource', 'string', 'Uint8Array');
|
||||
} else if (isChildClass(GenericAccountId, Clazz)) {
|
||||
possibleTypes.push('string', 'Uint8Array');
|
||||
} else if (isChildClass(registry.createClass('bool'), Clazz)) {
|
||||
@@ -141,8 +145,10 @@ export function getSimilarTypes (definitions: Record<string, ModuleTypes>, regis
|
||||
} else if (isChildClass(String, Clazz)) {
|
||||
possibleTypes.push('string');
|
||||
} else if (isChildClass(Tuple, Clazz)) {
|
||||
const subDef = getTypeDef(type).sub;
|
||||
const tupDef = getTypeDef(type);
|
||||
const subDef = tupDef.sub;
|
||||
|
||||
// this could be that we define a Tuple type and refer to it by name
|
||||
if (Array.isArray(subDef)) {
|
||||
const subs = subDef.map(({ type }) => getSimilarTypes(definitions, registry, type, imports).join(' | '));
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@polkadot/types-known",
|
||||
"version": "1.17.1",
|
||||
"version": "1.31.1",
|
||||
"description": "A JavaScript wrapper for the Polkadot JsonRPC interface",
|
||||
"main": "index.js",
|
||||
"keywords": [
|
||||
@@ -26,10 +26,10 @@
|
||||
},
|
||||
"homepage": "https://github.com/polkadot-js/api/tree/master/packages/types-known#readme",
|
||||
"dependencies": {
|
||||
"@babel/runtime": "^7.10.2",
|
||||
"@polkadot/types": "1.17.1",
|
||||
"@polkadot/util": "^2.12.2",
|
||||
"bn.js": "^5.1.2"
|
||||
"@babel/runtime": "^7.11.2",
|
||||
"@polkadot/types": "1.31.1",
|
||||
"@polkadot/util": "^3.4.1",
|
||||
"bn.js": "^5.1.3"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/bn.js": "^4.11.6"
|
||||
|
||||
@@ -3,7 +3,8 @@
|
||||
// of the Apache-2.0 license. See the LICENSE file for details.
|
||||
|
||||
import type BN from 'bn.js';
|
||||
import { Registry, RegistryTypes, OverrideModuleType, OverrideVersionedType } from '@polkadot/types/types';
|
||||
import { Hash } from '@polkadot/types/interfaces';
|
||||
import { ChainUpgradeVersion, DefinitionRpc, DefinitionRpcSub, Registry, RegistryTypes, OverrideModuleType, OverrideVersionedType } from '@polkadot/types/types';
|
||||
|
||||
import { Text } from '@polkadot/types';
|
||||
import { bnToBn, isUndefined } from '@polkadot/util';
|
||||
@@ -12,6 +13,7 @@ import typesChain from './chain';
|
||||
import typesMeta from './metadata';
|
||||
import typesModules from './modules';
|
||||
import typesSpec from './spec';
|
||||
import upgrades from './upgrades';
|
||||
import warnings from './warnings';
|
||||
|
||||
// flatten a VersionedType[] into a Record<string, string>
|
||||
@@ -58,7 +60,54 @@ export function getSpecTypes ({ knownTypes }: Registry, chainName: Text | string
|
||||
return {
|
||||
...filterVersions(typesSpec[_specName], _specVersion),
|
||||
...filterVersions(typesChain[_chainName], _specVersion),
|
||||
...filterVersions(knownTypes.typesBundle?.spec?.[_specName]?.types, _specVersion),
|
||||
...filterVersions(knownTypes.typesBundle?.chain?.[_chainName]?.types, _specVersion),
|
||||
...(knownTypes.typesSpec?.[_specName] || {}),
|
||||
...(knownTypes.typesChain?.[_chainName] || {})
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Based on the chain and runtimeVersion, get the applicable rpc definitions (ready for registration)
|
||||
*/
|
||||
export function getSpecRpc ({ knownTypes }: Registry, chainName: Text | string, specName: Text | string): Record<string, Record<string, DefinitionRpc | DefinitionRpcSub>> {
|
||||
const _chainName = chainName.toString();
|
||||
const _specName = specName.toString();
|
||||
|
||||
return {
|
||||
...(knownTypes.typesBundle?.spec?.[_specName]?.rpc || {}),
|
||||
...(knownTypes.typesBundle?.chain?.[_chainName]?.rpc || {})
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Based on the chain and runtimeVersion, get the applicable alias definitions (ready for registration)
|
||||
*/
|
||||
export function getSpecAlias ({ knownTypes }: Registry, chainName: Text | string, specName: Text | string): Record<string, OverrideModuleType> {
|
||||
const _chainName = chainName.toString();
|
||||
const _specName = specName.toString();
|
||||
|
||||
return {
|
||||
...(knownTypes.typesAlias || {}),
|
||||
...(knownTypes.typesBundle?.spec?.[_specName]?.alias || {}),
|
||||
...(knownTypes.typesBundle?.chain?.[_chainName]?.alias || {})
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Returns a version record for known chains where upgrades are being tracked
|
||||
*/
|
||||
export function getUpgradeVersion (genesisHash: Hash, blockNumber: BN): [ChainUpgradeVersion | undefined, ChainUpgradeVersion | undefined] {
|
||||
const known = upgrades.find((u) => genesisHash.eq(u.genesisHash));
|
||||
|
||||
return known
|
||||
? [
|
||||
known.versions.reduce((last: ChainUpgradeVersion | undefined, version): ChainUpgradeVersion | undefined => {
|
||||
return blockNumber.gt(version.blockNumber)
|
||||
? version
|
||||
: last;
|
||||
}, undefined),
|
||||
known.versions.find((version) => blockNumber.lte(version.blockNumber))
|
||||
]
|
||||
: [undefined, undefined];
|
||||
}
|
||||
|
||||
@@ -6,8 +6,11 @@ import { OverrideModuleType } from '@polkadot/types/types';
|
||||
|
||||
// type overrides for modules (where duplication between modules exist)
|
||||
const typesModules: Record<string, OverrideModuleType> = {
|
||||
babe: {
|
||||
EquivocationProof: 'BabeEquivocationProof'
|
||||
},
|
||||
balances: {
|
||||
Releases: 'ReleasesBalances'
|
||||
Status: 'BalanceStatus'
|
||||
},
|
||||
contract: { // old metadata & naming
|
||||
// v2 & v3
|
||||
@@ -16,8 +19,9 @@ const typesModules: Record<string, OverrideModuleType> = {
|
||||
contracts: {
|
||||
StorageKey: 'ContractStorageKey'
|
||||
},
|
||||
democracy: {
|
||||
Releases: 'ReleasesDemocracy'
|
||||
grandpa: {
|
||||
Equivocation: 'GrandpaEquivocation',
|
||||
EquivocationProof: 'GrandpaEquivocationProof'
|
||||
},
|
||||
identity: {
|
||||
Judgement: 'IdentityJudgement'
|
||||
@@ -25,13 +29,18 @@ const typesModules: Record<string, OverrideModuleType> = {
|
||||
parachains: {
|
||||
Id: 'ParaId'
|
||||
},
|
||||
proposeParachain: {
|
||||
Proposal: 'ParachainProposal'
|
||||
},
|
||||
proxy: {
|
||||
Announcement: 'ProxyAnnouncement'
|
||||
},
|
||||
society: {
|
||||
Judgement: 'SocietyJudgement',
|
||||
Vote: 'SocietyVote'
|
||||
},
|
||||
staking: {
|
||||
Compact: 'CompactAssignments',
|
||||
Releases: 'ReleasesStaking'
|
||||
Compact: 'CompactAssignments'
|
||||
},
|
||||
treasury: {
|
||||
Proposal: 'TreasuryProposal'
|
||||
|
||||
@@ -4,17 +4,47 @@
|
||||
|
||||
import { OverrideVersionedType } from '@polkadot/types/types';
|
||||
|
||||
const sharedTypes = {
|
||||
Address: 'LookupSource',
|
||||
AnchorData: {
|
||||
anchoredBlock: 'u64',
|
||||
docRoot: 'H256',
|
||||
id: 'H256'
|
||||
},
|
||||
Fee: {
|
||||
key: 'Hash',
|
||||
price: 'Balance'
|
||||
},
|
||||
MultiAccountData: {
|
||||
deposit: 'Balance',
|
||||
depositor: 'AccountId',
|
||||
signatories: 'Vec<AccountId>',
|
||||
threshold: 'u16'
|
||||
},
|
||||
Multiplier: 'Fixed64',
|
||||
PreCommitData: {
|
||||
expirationBlock: 'u64',
|
||||
identity: 'H256',
|
||||
signingRoot: 'H256'
|
||||
},
|
||||
Proof: {
|
||||
leafHash: 'H256',
|
||||
sortedHashes: 'H256'
|
||||
},
|
||||
ReferendumInfo: 'ReferendumInfoTo239',
|
||||
StakingLedger: 'StakingLedgerTo240',
|
||||
Weight: 'u32'
|
||||
};
|
||||
|
||||
const versioned: OverrideVersionedType[] = [
|
||||
{
|
||||
// most chains started at 1000 (Fulvous at 224)
|
||||
minmax: [1, undefined],
|
||||
minmax: [229, undefined],
|
||||
types: {
|
||||
Address: 'AccountId',
|
||||
LookupSource: 'AccountId',
|
||||
Multiplier: 'Fixed64',
|
||||
ReferendumInfo: 'ReferendumInfoTo239',
|
||||
StakingLedger: 'StakingLedgerTo240',
|
||||
Weight: 'u32'
|
||||
...sharedTypes,
|
||||
ChainId: 'u8',
|
||||
DepositNonce: 'u64',
|
||||
ResourceId: '[u8; 32]',
|
||||
'chainbridge::ChainId': 'u8'
|
||||
}
|
||||
}
|
||||
];
|
||||
|
||||
@@ -7,6 +7,7 @@ import { OverrideVersionedType } from '@polkadot/types/types';
|
||||
import centrifugeChain from './centrifuge-chain';
|
||||
import kusama from './kusama';
|
||||
import polkadot from './polkadot';
|
||||
import rococo from './rococo';
|
||||
import westend from './westend';
|
||||
|
||||
// Type overrides for specific spec types & versions as given in runtimeVersion
|
||||
@@ -14,6 +15,7 @@ const typesSpec: Record<string, OverrideVersionedType[]> = {
|
||||
'centrifuge-chain': centrifugeChain,
|
||||
kusama,
|
||||
polkadot,
|
||||
rococo,
|
||||
westend
|
||||
};
|
||||
|
||||
|
||||
@@ -4,19 +4,30 @@
|
||||
|
||||
import { OverrideVersionedType } from '@polkadot/types/types';
|
||||
|
||||
const sharedTypes = {
|
||||
Address: 'AccountId',
|
||||
Keys: 'SessionKeys5',
|
||||
LookupSource: 'AccountId',
|
||||
ProxyType: {
|
||||
_enum: ['Any', 'NonTransfer', 'Governance', 'Staking', 'IdentityJudgement']
|
||||
}
|
||||
};
|
||||
|
||||
const versioned: OverrideVersionedType[] = [
|
||||
{
|
||||
// 1020 is first CC3
|
||||
minmax: [1019, 1031],
|
||||
types: {
|
||||
Address: 'GenericAddress',
|
||||
Address: 'LookupSource',
|
||||
BalanceLock: 'BalanceLockTo212',
|
||||
CompactAssignments: 'CompactAssignmentsTo257',
|
||||
DispatchError: 'DispatchErrorTo198',
|
||||
DispatchInfo: 'DispatchInfoTo244',
|
||||
Keys: 'SessionKeys5',
|
||||
LookupSource: 'Address',
|
||||
Multiplier: 'Fixed64',
|
||||
OpenTip: 'OpenTipTo225',
|
||||
ReferendumInfo: 'ReferendumInfoTo239',
|
||||
RewardDestination: 'RewardDestinationTo257',
|
||||
SlashingSpans: 'SlashingSpansTo204',
|
||||
StakingLedger: 'StakingLedgerTo223',
|
||||
Votes: 'VotesTo230',
|
||||
@@ -26,13 +37,15 @@ const versioned: OverrideVersionedType[] = [
|
||||
{
|
||||
minmax: [1032, 1042],
|
||||
types: {
|
||||
Address: 'GenericAddress',
|
||||
Address: 'LookupSource',
|
||||
BalanceLock: 'BalanceLockTo212',
|
||||
CompactAssignments: 'CompactAssignmentsTo257',
|
||||
DispatchInfo: 'DispatchInfoTo244',
|
||||
Keys: 'SessionKeys5',
|
||||
LookupSource: 'Address',
|
||||
Multiplier: 'Fixed64',
|
||||
OpenTip: 'OpenTipTo225',
|
||||
ReferendumInfo: 'ReferendumInfoTo239',
|
||||
RewardDestination: 'RewardDestinationTo257',
|
||||
SlashingSpans: 'SlashingSpansTo204',
|
||||
StakingLedger: 'StakingLedgerTo223',
|
||||
Votes: 'VotesTo230',
|
||||
@@ -43,13 +56,15 @@ const versioned: OverrideVersionedType[] = [
|
||||
// actual at 1045 (1043-1044 is dev)
|
||||
minmax: [1043, 1045],
|
||||
types: {
|
||||
Address: 'GenericAddress',
|
||||
Address: 'LookupSource',
|
||||
BalanceLock: 'BalanceLockTo212',
|
||||
CompactAssignments: 'CompactAssignmentsTo257',
|
||||
DispatchInfo: 'DispatchInfoTo244',
|
||||
Keys: 'SessionKeys5',
|
||||
LookupSource: 'Address',
|
||||
Multiplier: 'Fixed64',
|
||||
OpenTip: 'OpenTipTo225',
|
||||
ReferendumInfo: 'ReferendumInfoTo239',
|
||||
RewardDestination: 'RewardDestinationTo257',
|
||||
StakingLedger: 'StakingLedgerTo223',
|
||||
Votes: 'VotesTo230',
|
||||
Weight: 'u32'
|
||||
@@ -59,12 +74,13 @@ const versioned: OverrideVersionedType[] = [
|
||||
minmax: [1046, 1054],
|
||||
types: {
|
||||
// Indices optional, not in transaction
|
||||
Address: 'AccountId',
|
||||
...sharedTypes,
|
||||
CompactAssignments: 'CompactAssignmentsTo257',
|
||||
DispatchInfo: 'DispatchInfoTo244',
|
||||
Keys: 'SessionKeys5',
|
||||
LookupSource: 'AccountId',
|
||||
Multiplier: 'Fixed64',
|
||||
OpenTip: 'OpenTipTo225',
|
||||
ReferendumInfo: 'ReferendumInfoTo239',
|
||||
RewardDestination: 'RewardDestinationTo257',
|
||||
StakingLedger: 'StakingLedgerTo240',
|
||||
Weight: 'u32'
|
||||
}
|
||||
@@ -72,11 +88,12 @@ const versioned: OverrideVersionedType[] = [
|
||||
{
|
||||
minmax: [1055, 1056],
|
||||
types: {
|
||||
Address: 'AccountId',
|
||||
...sharedTypes,
|
||||
CompactAssignments: 'CompactAssignmentsTo257',
|
||||
DispatchInfo: 'DispatchInfoTo244',
|
||||
Keys: 'SessionKeys5',
|
||||
LookupSource: 'AccountId',
|
||||
Multiplier: 'Fixed64',
|
||||
OpenTip: 'OpenTipTo225',
|
||||
RewardDestination: 'RewardDestinationTo257',
|
||||
StakingLedger: 'StakingLedgerTo240',
|
||||
Weight: 'u32'
|
||||
}
|
||||
@@ -84,18 +101,34 @@ const versioned: OverrideVersionedType[] = [
|
||||
{
|
||||
minmax: [1057, 1061],
|
||||
types: {
|
||||
Address: 'AccountId',
|
||||
...sharedTypes,
|
||||
CompactAssignments: 'CompactAssignmentsTo257',
|
||||
DispatchInfo: 'DispatchInfoTo244',
|
||||
Keys: 'SessionKeys5',
|
||||
LookupSource: 'AccountId'
|
||||
OpenTip: 'OpenTipTo225',
|
||||
RewardDestination: 'RewardDestinationTo257'
|
||||
}
|
||||
},
|
||||
{
|
||||
minmax: [1062, undefined],
|
||||
minmax: [1062, 2012],
|
||||
types: {
|
||||
Address: 'AccountId',
|
||||
Keys: 'SessionKeys5',
|
||||
LookupSource: 'AccountId'
|
||||
...sharedTypes,
|
||||
CompactAssignments: 'CompactAssignmentsTo257',
|
||||
OpenTip: 'OpenTipTo225',
|
||||
RewardDestination: 'RewardDestinationTo257'
|
||||
}
|
||||
},
|
||||
{
|
||||
minmax: [2013, 2022],
|
||||
types: {
|
||||
...sharedTypes,
|
||||
CompactAssignments: 'CompactAssignmentsTo257',
|
||||
RewardDestination: 'RewardDestinationTo257'
|
||||
}
|
||||
},
|
||||
{
|
||||
minmax: [2023, undefined],
|
||||
types: {
|
||||
...sharedTypes
|
||||
}
|
||||
}
|
||||
];
|
||||
|
||||
@@ -4,14 +4,39 @@
|
||||
|
||||
import { OverrideVersionedType } from '@polkadot/types/types';
|
||||
|
||||
const sharedTypes = {
|
||||
Address: 'AccountId',
|
||||
Keys: 'SessionKeys5',
|
||||
LookupSource: 'AccountId',
|
||||
ProxyType: {
|
||||
// was: SudoBalances
|
||||
_enum: ['Any', 'NonTransfer', 'Governance', 'Staking', 'Unused', 'IdentityJudgement']
|
||||
}
|
||||
};
|
||||
|
||||
// these are override types for Polkadot
|
||||
const versioned: OverrideVersionedType[] = [
|
||||
{
|
||||
minmax: [0, undefined],
|
||||
minmax: [0, 12],
|
||||
types: {
|
||||
Address: 'AccountId',
|
||||
Keys: 'SessionKeys5',
|
||||
LookupSource: 'AccountId'
|
||||
...sharedTypes,
|
||||
CompactAssignments: 'CompactAssignmentsTo257',
|
||||
OpenTip: 'OpenTipTo225',
|
||||
RewardDestination: 'RewardDestinationTo257'
|
||||
}
|
||||
},
|
||||
{
|
||||
minmax: [13, 22],
|
||||
types: {
|
||||
...sharedTypes,
|
||||
CompactAssignments: 'CompactAssignmentsTo257',
|
||||
RewardDestination: 'RewardDestinationTo257'
|
||||
}
|
||||
},
|
||||
{
|
||||
minmax: [23, undefined],
|
||||
types: {
|
||||
...sharedTypes
|
||||
}
|
||||
}
|
||||
];
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
// Copyright 2017-2020 @polkadot/types-known 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 { OverrideVersionedType } from '@polkadot/types/types';
|
||||
|
||||
const sharedTypes = {
|
||||
Address: 'AccountId',
|
||||
Keys: 'SessionKeys5',
|
||||
LookupSource: 'AccountId',
|
||||
RewardDestination: 'RewardDestinationTo257'
|
||||
};
|
||||
|
||||
const versioned: OverrideVersionedType[] = [
|
||||
{
|
||||
minmax: [0, undefined],
|
||||
types: {
|
||||
...sharedTypes,
|
||||
CompactAssignments: 'CompactAssignmentsTo257'
|
||||
}
|
||||
}
|
||||
];
|
||||
|
||||
export default versioned;
|
||||
@@ -4,23 +4,49 @@
|
||||
|
||||
import { OverrideVersionedType } from '@polkadot/types/types';
|
||||
|
||||
const sharedTypes = {
|
||||
Address: 'AccountId',
|
||||
Keys: 'SessionKeys5',
|
||||
LookupSource: 'AccountId',
|
||||
ProxyType: {
|
||||
// was: SudoBalances
|
||||
_enum: ['Any', 'NonTransfer', 'Staking', 'Unused', 'IdentityJudgement']
|
||||
}
|
||||
};
|
||||
|
||||
const versioned: OverrideVersionedType[] = [
|
||||
{
|
||||
minmax: [1, 2],
|
||||
types: {
|
||||
Address: 'AccountId',
|
||||
Keys: 'SessionKeys5',
|
||||
LookupSource: 'AccountId',
|
||||
...sharedTypes,
|
||||
CompactAssignments: 'CompactAssignmentsTo257',
|
||||
Multiplier: 'Fixed64',
|
||||
OpenTip: 'OpenTipTo225',
|
||||
RewardDestination: 'RewardDestinationTo257',
|
||||
Weight: 'u32'
|
||||
}
|
||||
},
|
||||
{
|
||||
minmax: [3, undefined],
|
||||
minmax: [3, 22],
|
||||
types: {
|
||||
Address: 'AccountId',
|
||||
Keys: 'SessionKeys5',
|
||||
LookupSource: 'AccountId'
|
||||
...sharedTypes,
|
||||
CompactAssignments: 'CompactAssignmentsTo257',
|
||||
OpenTip: 'OpenTipTo225',
|
||||
RewardDestination: 'RewardDestinationTo257'
|
||||
}
|
||||
},
|
||||
{
|
||||
minmax: [23, 42],
|
||||
types: {
|
||||
...sharedTypes,
|
||||
CompactAssignments: 'CompactAssignmentsTo257',
|
||||
RewardDestination: 'RewardDestinationTo257'
|
||||
}
|
||||
},
|
||||
{
|
||||
minmax: [43, undefined],
|
||||
types: {
|
||||
...sharedTypes
|
||||
}
|
||||
}
|
||||
];
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
// Copyright 2017-2020 @polkadot/types-known 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 { ChainUpgrades } from '@polkadot/types/types';
|
||||
|
||||
import kusama from './kusama';
|
||||
import polkadot from './polkadot';
|
||||
import westend from './westend';
|
||||
|
||||
// Type overrides for specific spec types & versions as given in runtimeVersion
|
||||
const upgrades: ChainUpgrades[] = [
|
||||
kusama,
|
||||
polkadot,
|
||||
westend
|
||||
];
|
||||
|
||||
export default upgrades;
|
||||
@@ -0,0 +1,26 @@
|
||||
// Copyright 2017-2020 @polkadot/types-known 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 { ChainUpgrades } from '@polkadot/types/types';
|
||||
|
||||
import BN from 'bn.js';
|
||||
import { hexToU8a } from '@polkadot/util';
|
||||
|
||||
const upgrades: ChainUpgrades = {
|
||||
genesisHash: hexToU8a('0xb0a8d493285c2df73290dfb7e61f870f17b41801197a149ca93654499ea3dafe'),
|
||||
versions: [
|
||||
[0, 1020], [26669, 1021], [38245, 1022], [54248, 1023], [59659, 1024],
|
||||
[67651, 1025], [82191, 1027], [83238, 1028], [101503, 1029], [203466, 1030],
|
||||
[295787, 1031], [461692, 1032], [504329, 1033], [569327, 1038], [587687, 1039],
|
||||
[653183, 1040], [693488, 1042], [901442, 1045], [1375086, 1050], [1445458, 1051],
|
||||
[1472960, 1052], [1475648, 1053], [1491596, 1054], [1574408, 1055], [2064961, 1058],
|
||||
[2201991, 1062], [2671528, 2005], [2704202, 2007], [2728002, 2008], [2832534, 2011],
|
||||
[2962294, 2012], [3240000, 2013], [3274408, 2015], [3323565, 2019], [3534175, 2022]
|
||||
].map(([blockNumber, specVersion]) => ({
|
||||
blockNumber: new BN(blockNumber),
|
||||
specVersion: new BN(specVersion)
|
||||
}))
|
||||
};
|
||||
|
||||
export default upgrades;
|
||||
@@ -0,0 +1,23 @@
|
||||
// Copyright 2017-2020 @polkadot/types-known 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 { ChainUpgrades } from '@polkadot/types/types';
|
||||
|
||||
import BN from 'bn.js';
|
||||
import { hexToU8a } from '@polkadot/util';
|
||||
|
||||
const upgrades: ChainUpgrades = {
|
||||
genesisHash: hexToU8a('0x91b171bb158e2d3848fa23a9f1c25182fb8e20313b2c1eb49219da7a70ce90c3'),
|
||||
versions: [
|
||||
[0, 0], [29231, 1], [188836, 5], [199405, 6], [214264, 7],
|
||||
[244358, 8], [303079, 9], [314201, 10], [342400, 11], [443963, 12],
|
||||
[528470, 13], [687751, 14], [746085, 15], [787923, 16], [799302, 17],
|
||||
[1205128, 18]
|
||||
].map(([blockNumber, specVersion]) => ({
|
||||
blockNumber: new BN(blockNumber),
|
||||
specVersion: new BN(specVersion)
|
||||
}))
|
||||
};
|
||||
|
||||
export default upgrades;
|
||||
@@ -0,0 +1,23 @@
|
||||
// Copyright 2017-2020 @polkadot/types-known 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 { ChainUpgrades } from '@polkadot/types/types';
|
||||
|
||||
import BN from 'bn.js';
|
||||
import { hexToU8a } from '@polkadot/util';
|
||||
|
||||
const upgrades: ChainUpgrades = {
|
||||
genesisHash: hexToU8a('0xe143f23803ac50e8f6f8e62695d1ce9e4e1d68aa36c1cd2cfd15340213f3423e'),
|
||||
versions: [
|
||||
[214356, 4], [392764, 7], [409740, 8], [809976, 20], [877581, 24],
|
||||
[879238, 25], [889472, 26], [902937, 27], [932751, 28], [991142, 29],
|
||||
[1030162, 31], [1119657, 32], [1199282, 33], [1342534, 34], [1392263, 35],
|
||||
[1431703, 36], [1433369, 37], [1490972, 41]
|
||||
].map(([blockNumber, specVersion]) => ({
|
||||
blockNumber: new BN(blockNumber),
|
||||
specVersion: new BN(specVersion)
|
||||
}))
|
||||
};
|
||||
|
||||
export default upgrades;
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user