Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0dc121a796 | ||
|
|
a827131457 | ||
|
|
2174537f76 | ||
|
|
53fca2406a | ||
|
|
0eaba284ae | ||
|
|
378f359a76 | ||
|
|
5460d96b5d | ||
|
|
b1353edc84 | ||
|
|
9129fed6e5 | ||
|
|
7c4abacaca | ||
|
|
3664c7d81b | ||
|
|
f75b87c5a5 | ||
|
|
1c228216cd | ||
|
|
cec3c12795 | ||
|
|
0d0d12e85b | ||
|
|
3a16e69be5 | ||
|
|
4ae8e3909f | ||
|
|
6e18bb3b1d | ||
|
|
be153e13a6 | ||
|
|
4c01dfd0ab | ||
|
|
b57c7a1343 | ||
|
|
da62acdf50 | ||
|
|
cc95e4fc0a | ||
|
|
7f5647c6e1 | ||
|
|
c636d63bc0 | ||
|
|
30c98ef857 | ||
|
|
debecde50f | ||
|
|
cd2cdd1184 | ||
|
|
f5c25d75ff | ||
|
|
780cc62942 | ||
|
|
165568c905 | ||
|
|
976a48d8f9 | ||
|
|
35cbbbe0ed | ||
|
|
772769c981 | ||
|
|
1ba2bd1766 | ||
|
|
4afa345a7d | ||
|
|
5c03359f32 | ||
|
|
04120505f0 | ||
|
|
7bd9dd65f8 | ||
|
|
5f57ecb2e1 | ||
|
|
9123f1d805 | ||
|
|
7050c4a554 | ||
|
|
62afb0b534 | ||
|
|
5157ca5608 | ||
|
|
315617c027 | ||
|
|
7d33b4dec6 | ||
|
|
2345f69c71 | ||
|
|
3cef2fb4d5 | ||
|
|
2bbf5513b2 | ||
|
|
c146f06178 | ||
|
|
5903704b61 | ||
|
|
90d8db651b | ||
|
|
557283a3d1 | ||
|
|
88b84dcf75 | ||
|
|
45d190eaca | ||
|
|
6d32328509 | ||
|
|
ba470e7417 | ||
|
|
4a16e46f88 | ||
|
|
ada0d99a84 | ||
|
|
e486fc4316 | ||
|
|
6e5c6f4e0b | ||
|
|
21ddcaf173 | ||
|
|
6085b994f6 | ||
|
|
7c3bf05868 | ||
|
|
8bce5b4a09 | ||
|
|
7a6077301f | ||
|
|
3f2767462f | ||
|
|
ecc37d11df | ||
|
|
0589d151da | ||
|
|
47cd6c6410 | ||
|
|
65688f9e0e | ||
|
|
5eb2a95ef2 | ||
|
|
282b39d27a | ||
|
|
f21e3d317a | ||
|
|
c2af7cf8f2 | ||
|
|
0958a4c693 | ||
|
|
c687181130 | ||
|
|
685f1ec0b6 | ||
|
|
e0069b6f7d | ||
|
|
cf48762ff2 | ||
|
|
31a7545a19 | ||
|
|
5cd8e8fb97 | ||
|
|
96e4090174 | ||
|
|
0bbebab90b | ||
|
|
57dac0ef47 | ||
|
|
6c3d24551b | ||
|
|
e7dc6d7a5a | ||
|
|
a63b7f611e | ||
|
|
82e15dc36d | ||
|
|
6f96037cb5 | ||
|
|
b6da84b8b2 | ||
|
|
41209f074c | ||
|
|
c47964c942 | ||
|
|
5f13a634e5 | ||
|
|
40af520fe7 | ||
|
|
1e506e0f8c | ||
|
|
96ea5803d4 | ||
|
|
7d99459f50 | ||
|
|
8fa090f435 | ||
|
|
d3c60d197c | ||
|
|
ad8550f7f5 | ||
|
|
a899aa439d | ||
|
|
e0e075b350 | ||
|
|
34ff14547e | ||
|
|
681a80d456 | ||
|
|
ed5f2673ce | ||
|
|
43e87603e2 | ||
|
|
d056416b47 | ||
|
|
1bcf94131d | ||
|
|
17b607b6c3 | ||
|
|
5a16d1dd8b | ||
|
|
144b74306a | ||
|
|
16b9fa956d | ||
|
|
b6af4b9877 | ||
|
|
3f368e721d | ||
|
|
22b4257636 | ||
|
|
ca7a631032 | ||
|
|
da5bbd17af | ||
|
|
b58f3f5c3e | ||
|
|
8c30194f59 | ||
|
|
dc9ec37490 | ||
|
|
5175e77eec | ||
|
|
9553c5467c | ||
|
|
a1f07e3274 | ||
|
|
58deb2eb14 | ||
|
|
83caad7f1b | ||
|
|
26c3cc9126 | ||
|
|
1a231dfb0d | ||
|
|
712d0425d0 | ||
|
|
eaa5db517f | ||
|
|
88c3850d1b | ||
|
|
943df72ae9 | ||
|
|
67ab11a036 | ||
|
|
c87ef7526b | ||
|
|
bccf2d52ad | ||
|
|
be6dbdd3e4 | ||
|
|
3c34ee9897 | ||
|
|
9ad97813e3 | ||
|
|
028f04e47f | ||
|
|
4974c9247f | ||
|
|
1ffe6a11bf | ||
|
|
19699ea445 | ||
|
|
d98ccfb12a | ||
|
|
41cb056b0f | ||
|
|
48bda0bdea | ||
|
|
1b393c7b67 | ||
|
|
f52e518b7b | ||
|
|
08970cff88 | ||
|
|
6d38ca6453 | ||
|
|
60db4bc66b | ||
|
|
0661237b28 | ||
|
|
6ccac712a8 | ||
|
|
3d4877940c | ||
|
|
70fc95ef27 | ||
|
|
463f65d25c | ||
|
|
09d176c82e | ||
|
|
fce96baf3d | ||
|
|
c6785c533f | ||
|
|
64de021149 | ||
|
|
de9e17a1a0 | ||
|
|
987bccea2e | ||
|
|
1434b86b8f | ||
|
|
a398b2201f | ||
|
|
f015837c38 | ||
|
|
5b51588995 | ||
|
|
7383e521e5 | ||
|
|
b10f05786c | ||
|
|
a212351528 | ||
|
|
55c01af260 | ||
|
|
1cf6ffad2b | ||
|
|
00d0ab9de1 | ||
|
|
b38e60a9a7 | ||
|
|
29f7e46439 | ||
|
|
fa0add8564 | ||
|
|
5bec38c404 | ||
|
|
43b66b6507 | ||
|
|
7e370b3a23 | ||
|
|
2b270a3c9f | ||
|
|
cf0d9a2d3f | ||
|
|
5d70622819 | ||
|
|
fcebdb6d6f | ||
|
|
3d020b5159 | ||
|
|
530d1bcd03 | ||
|
|
a4151c2941 | ||
|
|
a801d30fb6 | ||
|
|
1fe9b605dd | ||
|
|
ecfd822d94 | ||
|
|
a5e4d68993 | ||
|
|
ca5c002d37 | ||
|
|
6e28760da4 | ||
|
|
a253c4edb5 | ||
|
|
7c96525d35 | ||
|
|
3f0457efc2 | ||
|
|
bfb241d995 | ||
|
|
314ad8c3f2 | ||
|
|
aa85371f82 | ||
|
|
d0a08dadd9 | ||
|
|
eeff764345 | ||
|
|
4870ec4f40 | ||
|
|
1c3cfbfa0c | ||
|
|
3c9b7de6c7 | ||
|
|
22e5488f16 | ||
|
|
b37887993e | ||
|
|
75361cb0ff | ||
|
|
894992bc4c | ||
|
|
d955fab169 | ||
|
|
580d225387 | ||
|
|
d48f59e48d | ||
|
|
108b49ea03 | ||
|
|
9295349886 | ||
|
|
a51658ffac | ||
|
|
47f08e9e04 | ||
|
|
7906ae63dc | ||
|
|
0e76271dba | ||
|
|
e117619e34 | ||
|
|
67b416fe80 | ||
|
|
78dbfa46fa | ||
|
|
01db9261d5 | ||
|
|
674c38b384 | ||
|
|
0700e824eb | ||
|
|
0362eaf472 | ||
|
|
696b3964e6 | ||
|
|
5d0c2eed7b | ||
|
|
e4c3289ad8 | ||
|
|
4449bdae6f | ||
|
|
064957db81 | ||
|
|
ccd89ef0a6 | ||
|
|
47beb5f41f | ||
|
|
9f205392a3 | ||
|
|
adce7ccbee | ||
|
|
b83b3a9437 | ||
|
|
147dbcf24f | ||
|
|
2afff1b41f | ||
|
|
d1a1be49c5 | ||
|
|
4b6ad647a2 | ||
|
|
04f656cafa | ||
|
|
09bbd5f6c9 | ||
|
|
dbc3df6d09 | ||
|
|
26865f92e3 | ||
|
|
73045de73d | ||
|
|
6d3491b9f1 | ||
|
|
886f3a3c08 | ||
|
|
c72f976895 | ||
|
|
ab8b381d8b | ||
|
|
443e29a3be | ||
|
|
117bb5717a | ||
|
|
5fb76baa16 | ||
|
|
274b3498d4 | ||
|
|
fa9e1c53e1 | ||
|
|
3ebf7eb424 | ||
|
|
7d11e6f9a5 | ||
|
|
a0d6384b01 | ||
|
|
47afe2cfc6 | ||
|
|
c37a2fc756 | ||
|
|
e2545276bb | ||
|
|
4219409ef8 | ||
|
|
c9e64d2a32 | ||
|
|
41db3b2e35 | ||
|
|
ebe15dada6 | ||
|
|
c2cb5dc574 | ||
|
|
ba451348c0 | ||
|
|
ec76b11666 | ||
|
|
7603f9e6c1 | ||
|
|
b50eab11c0 | ||
|
|
66d05c1771 | ||
|
|
fd7c3d7e10 | ||
|
|
28d4c7d808 | ||
|
|
43d36fbcf6 | ||
|
|
e54eef2369 | ||
|
|
296842858f | ||
|
|
ba8849a3e9 | ||
|
|
e333c3d8d9 | ||
|
|
0fe6a21624 | ||
|
|
0abedb81c6 | ||
|
|
08eda72d4b | ||
|
|
70d4126c84 | ||
|
|
dcccab705c | ||
|
|
e45ff6d026 | ||
|
|
b49c2314e7 | ||
|
|
0ac085756a | ||
|
|
542a690c89 | ||
|
|
ff23ead797 | ||
|
|
ae55e4fbf7 | ||
|
|
b17412163d | ||
|
|
46dcbf9a42 | ||
|
|
193dfcc32f | ||
|
|
a81011cf94 | ||
|
|
d43a8b2e11 | ||
|
|
dff859ba68 | ||
|
|
5169b6ee69 | ||
|
|
f4405667fe | ||
|
|
49ff636305 | ||
|
|
d77d686c76 | ||
|
|
502c6a3451 | ||
|
|
b58c77683d | ||
|
|
b9f82fc549 | ||
|
|
25b8dba607 | ||
|
|
1bc4f2c334 | ||
|
|
aee8ac6b0a | ||
|
|
aa7e30070f | ||
|
|
64b5855f65 | ||
|
|
d7ff9e706e | ||
|
|
15ba6f6261 | ||
|
|
8c88a880c6 | ||
|
|
74566cce7b | ||
|
|
16f6deed5e | ||
|
|
40edc131fe | ||
|
|
3e014b38e6 | ||
|
|
b4cfdbffab | ||
|
|
cbfb6f8f59 | ||
|
|
b5bc15ab8b | ||
|
|
0b343fc0f8 | ||
|
|
e7f9693873 | ||
|
|
a0a5c3185d | ||
|
|
151d4693a9 | ||
|
|
cdb27d8ec2 | ||
|
|
055e4d1261 | ||
|
|
bf753255ab | ||
|
|
e2230ef454 | ||
|
|
0f5b01b856 | ||
|
|
82787c96c6 | ||
|
|
f89028d5fe | ||
|
|
ba24a2e917 | ||
|
|
b549bbf46b | ||
|
|
1e87f58f36 | ||
|
|
f643426067 | ||
|
|
94d26c76ec | ||
|
|
8fe262a712 | ||
|
|
122ee968cb | ||
|
|
d2ff350db9 | ||
|
|
9100aabbac | ||
|
|
1e73f69253 | ||
|
|
7153cb4158 | ||
|
|
999dc6f8a5 | ||
|
|
724574afe7 | ||
|
|
0352a30b6b | ||
|
|
41b4cd5c55 | ||
|
|
89f16f3123 | ||
|
|
261a4eede3 | ||
|
|
f623b382f7 | ||
|
|
51537c619a | ||
|
|
3df943572f | ||
|
|
aa10804f6f | ||
|
|
981407f00f | ||
|
|
74f7098e0a | ||
|
|
c2e46bf16d | ||
|
|
78b26d2d40 | ||
|
|
e4d5be85f6 | ||
|
|
23b5601eeb | ||
|
|
859679ce09 | ||
|
|
71543c2351 | ||
|
|
edae5057c8 | ||
|
|
8dd450ded4 | ||
|
|
bc2061723e | ||
|
|
5753e37307 | ||
|
|
e74da70a9d | ||
|
|
737bbc225a | ||
|
|
9313551559 | ||
|
|
5b8f53f050 | ||
|
|
7358e4715b | ||
|
|
a9005d86d6 | ||
|
|
788c05d86e | ||
|
|
de6ba69631 | ||
|
|
4153fed250 | ||
|
|
c68b89831e | ||
|
|
01c9c5ed53 | ||
|
|
573fb135a7 | ||
|
|
0ee7256e37 | ||
|
|
9829ee558c | ||
|
|
34b563dd48 | ||
|
|
f6bb200146 | ||
|
|
af36e3a52c | ||
|
|
c50c7ae6ef | ||
|
|
61739d5ba1 | ||
|
|
34c4a6055e | ||
|
|
27dabdaf52 | ||
|
|
2ee3242f41 | ||
|
|
67ae9627af | ||
|
|
29f7e12df6 | ||
|
|
a4bb2c8268 | ||
|
|
6521c5f533 | ||
|
|
6925c18821 | ||
|
|
9269d94677 | ||
|
|
d438814ad6 | ||
|
|
bc205a350b | ||
|
|
6bf6fddd28 | ||
|
|
23f8eb9713 | ||
|
|
8ab3097328 | ||
|
|
644d0e6c2e | ||
|
|
6a69fdfbbf | ||
|
|
16e9a64941 | ||
|
|
f3cbc070ea | ||
|
|
df22526229 | ||
|
|
3739bdaa89 | ||
|
|
1f55f38bd2 | ||
|
|
c9deb0d88f | ||
|
|
eecfb39463 | ||
|
|
51bb27da42 | ||
|
|
9c0d296e87 | ||
|
|
0793e0bf8c | ||
|
|
e9ad88d50e | ||
|
|
fbe24c04b8 | ||
|
|
8a7d4d3be3 | ||
|
|
61c9a3bb93 | ||
|
|
3721a11f34 | ||
|
|
21039dec1f | ||
|
|
1393f565d8 | ||
|
|
1530e55f9d | ||
|
|
c982505f73 | ||
|
|
ec8c0d3e8b | ||
|
|
8cb0269676 | ||
|
|
27f460cfe3 | ||
|
|
e98e8d6a0d | ||
|
|
2f94662837 | ||
|
|
d46d6a9acd | ||
|
|
093d2cfa7c | ||
|
|
35b31a21dc | ||
|
|
8b9741a722 | ||
|
|
d5cfa9b0e9 | ||
|
|
129d1214fe | ||
|
|
abb3375c3a | ||
|
|
4cfa06b43f | ||
|
|
8fa80ac0f6 | ||
|
|
2d011c68df | ||
|
|
640ef4bdab | ||
|
|
cdd20c0b99 | ||
|
|
3a12123bf9 | ||
|
|
5657d5395b | ||
|
|
66b1108c5c | ||
|
|
7bf7e207c2 | ||
|
|
01098395ec | ||
|
|
3e21dfdc03 | ||
|
|
a400fb2362 | ||
|
|
44172aa359 | ||
|
|
82cab2827a | ||
|
|
a198eb1515 | ||
|
|
6e67cd6c97 | ||
|
|
e51e89df56 | ||
|
|
e46fd07d39 | ||
|
|
b2cf9aed83 | ||
|
|
c632030437 | ||
|
|
9dc683d289 | ||
|
|
6cef6190b1 | ||
|
|
75dd443d79 | ||
|
|
13dacb591d | ||
|
|
429bf5456e | ||
|
|
527c0f5015 | ||
|
|
527ab27bee | ||
|
|
7991403022 | ||
|
|
61d2e6c5e5 | ||
|
|
e005a3fc0c | ||
|
|
2dfb0fb59a | ||
|
|
70c011e7e2 | ||
|
|
8134322626 | ||
|
|
60152749bb | ||
|
|
b257e120d4 | ||
|
|
6dc75acd21 | ||
|
|
a04400170c |
+14
-2
@@ -1,4 +1,4 @@
|
||||
25
|
||||
29
|
||||
1.4.2
|
||||
1.6.2
|
||||
1.11.2
|
||||
@@ -8,5 +8,17 @@
|
||||
2.8.2
|
||||
3.2.2
|
||||
3.2.3
|
||||
3.3.2
|
||||
3.6.2
|
||||
3.6.3
|
||||
3.6.4
|
||||
3.7.2
|
||||
3.7.3
|
||||
3.9.2
|
||||
3.9.3
|
||||
3.10.2
|
||||
4.0.2
|
||||
4.0.3
|
||||
|
||||
3.3.2
|
||||
4.6.2
|
||||
4.7.2
|
||||
@@ -24,8 +24,6 @@ module.exports = {
|
||||
...base.rules,
|
||||
// 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',
|
||||
// this seems very broken atm, false positives
|
||||
'@typescript-eslint/unbound-method': 'off'
|
||||
}
|
||||
|
||||
File diff suppressed because one or more lines are too long
+1
-1
@@ -10,4 +10,4 @@ plugins:
|
||||
- path: .yarn/plugins/@yarnpkg/plugin-version.cjs
|
||||
spec: "@yarnpkg/plugin-version"
|
||||
|
||||
yarnPath: .yarn/releases/yarn-2.4.0.cjs
|
||||
yarnPath: .yarn/releases/yarn-2.4.1.cjs
|
||||
|
||||
+380
@@ -1,5 +1,385 @@
|
||||
# CHANGELOG
|
||||
|
||||
## 4.8.1 May 2, 2021
|
||||
|
||||
Upgrade priority: Low. Recommended when using or developing for parachains.
|
||||
|
||||
Changes:
|
||||
|
||||
- De-alias xcm `Outcome` (used in multiple pallettes)
|
||||
- Adjust xcm types as per latest, e.g. `XcmError`
|
||||
- Fix generate of well-known storage keys (e.g. `:code`)
|
||||
- Optimize metadata unknown type validation
|
||||
- Allow metadata creation for `Map` or `Record`
|
||||
- Expose additional camelCase `method` on `AbiMessage` (maps to decorated name)
|
||||
- Added explicit double-byte ss58 `AccountId` encoding test
|
||||
- Add known upgrade block for Polkadot v30
|
||||
- Cleanup WebSocket handlers when close event has been received
|
||||
- Update to latest Substrate metadata
|
||||
|
||||
|
||||
## 4.7.2 Apr 26, 2021
|
||||
|
||||
Upgrade priority: Low. Recommended for users of 4.7.1 using nvm
|
||||
|
||||
Changes:
|
||||
|
||||
- Update `EthBlock`/`EthHeader` types (as per Rust origin)
|
||||
- Updated Xcm `OriginKind` enum
|
||||
- Add derives for `membership`
|
||||
- Cleanups on encodedLength calculations
|
||||
- Update `.nvmrc` to reflect engines changes
|
||||
|
||||
|
||||
## 4.7.1 Apr 25, 2021
|
||||
|
||||
Upgrade priority: Low. Recommended for users following Substrate master.
|
||||
|
||||
Changes:
|
||||
|
||||
- Adjust Struct decoding with better error messages on invalid input objects
|
||||
- Add support for new `BoundedVec` type
|
||||
- Expand `Data` type (as used in identity), with all is/as getters
|
||||
- Updated `Xcm` types (with Plularity)
|
||||
- Adjust `DispatchError` type as per current Substrate master
|
||||
- Adjusted Statemint `Proxy` type
|
||||
- Remove metadata generation dependency on well-known.json (dedupe)
|
||||
- Adjust WebSocket reconnection delay from 1s to 2.5s
|
||||
- Revert Beefy keys addition for Westend
|
||||
- Add explicit `engines` config to `package.json`
|
||||
- Support for `None` in `RewardDestination`
|
||||
- Align with latest substrate metadata
|
||||
|
||||
|
||||
## 4.6.2 Apr 19, 2021
|
||||
|
||||
Upgrade priority: Low. Recommended for users of Kusama/Polkadot.
|
||||
|
||||
Changes:
|
||||
|
||||
- Correct Kusama/Polkadot runtime 30 session key definitions
|
||||
|
||||
|
||||
## 4.6.1 Apr 19, 2021
|
||||
|
||||
Upgrade priority: Low. Recommended if used in a Node.js 15.x environment.
|
||||
|
||||
Changes:
|
||||
|
||||
- Assert keypair validity in signing operations
|
||||
- Expose `internalError` on submittable results (e.g. event decoding errors)
|
||||
- Simplify session derives for old/new
|
||||
- Add Statemint to known types
|
||||
- Add support for `rpc.beefy.subscribeJustifications`
|
||||
- Update Xcm types
|
||||
- Explicitly handle `isReadyOrError` with `Api.create`
|
||||
- Add Kusama upgrade block for 2030
|
||||
|
||||
|
||||
## 4.5.1 Apr 12, 2021
|
||||
|
||||
Upgrade priority: Low. Recommended with usage with the Rococo testnet.
|
||||
|
||||
Changes:
|
||||
|
||||
- Update parachain types as per latest Polkadot
|
||||
- Cater for `Keys` with `BEEFY` session keys
|
||||
- Update `Keys` injection to allow for on-chain type detection
|
||||
- Add `Westend` known upgrade block for runtime 50
|
||||
- Align types with latest Substrate master
|
||||
- Adjust keepalive `system_health` timer
|
||||
|
||||
|
||||
## 4.4.1 Apr 5, 2021
|
||||
|
||||
Upgrade priority: Low. Recommended with usage with the Rococo testnet.
|
||||
|
||||
Changes:
|
||||
|
||||
- Add `ServiceQuality` type for Cumulus
|
||||
- Adjust XCM MultiLocation type (X5 to X8 junctions)
|
||||
- Add Polkadot 29 upgrade block
|
||||
|
||||
|
||||
## 4.3.1 Mar 29, 2021
|
||||
|
||||
Upgrade priority: Low.
|
||||
|
||||
Contributed:
|
||||
|
||||
- Fix documentation on ABI parameters (Thanks to https://github.com/vminkov)
|
||||
|
||||
Changes:
|
||||
|
||||
- Warn on usage of deprecated contract interfaces
|
||||
- Update `ParaInfo` type
|
||||
- Council should be optional in treasury derives
|
||||
- Allow extraction of session derives indexes with no staking
|
||||
|
||||
|
||||
## 4.2.1 Mar 22, 2021
|
||||
|
||||
Upgrade priority: Low. Recommended when tracking the latest updates from Substrate.
|
||||
|
||||
Contributed:
|
||||
|
||||
- Fix contract even decoding on Substrate 3 (Thanks to https://github.com/vminkov)
|
||||
|
||||
Changes:
|
||||
|
||||
- Adjust `Extender{Header, SignedBlock}` types to ensure at-block `Header` types are used
|
||||
- Explicit definition for new Rococo triple refcount `AccountData` types
|
||||
- Convert metadata private class fields to ES-private
|
||||
- Adjust `SignedBlock` type for new `justifications` field
|
||||
- Optimize society derive for multi accounts
|
||||
- Bump metadata to latest substrate version
|
||||
|
||||
|
||||
## 4.1.1 Mar 15, 2021
|
||||
|
||||
Upgrade priority: Low. Recommended when tracking the latest updates from Substrate.
|
||||
|
||||
Changes:
|
||||
|
||||
- Fix author extraction for last block in a session
|
||||
- Expand `SignerPayload` to inject/expose custom signed extensions
|
||||
- `ConsensusEngineId` formats non-Ascii engines correctly
|
||||
- Allow `getBlock/Header` derives to use as-at registry (instead of latest)
|
||||
- Cleanup `RpcCore` augmentation (removing TS warnings on typegen chains)
|
||||
- Add upgrade block for Kusama 2029
|
||||
- Ensure that type alias overrides also apply to map keys
|
||||
- Check type generation against fallbacks (build-time only sanity check)
|
||||
- Add `mmr_generateProof` RPC
|
||||
- Align types with latest substrate master
|
||||
- Apply latest Polkadot auctions/crowdloan/parachains/slots types
|
||||
|
||||
|
||||
## 4.0.3 Mar 8, 2021
|
||||
|
||||
Upgrade priority: Low. Recommended if you use the API to sync the full chain, most notably Polkadot.
|
||||
|
||||
Contributed:
|
||||
|
||||
- Re-add unused historical `SudoBalances` to `ProxyType` (Thanks to https://github.com/emostov)
|
||||
|
||||
|
||||
## 4.0.2 Mar 8, 2021
|
||||
|
||||
Upgrade priority: High. Required if you are using 4.0.1 in a Node.js environment.
|
||||
|
||||
Changes:
|
||||
|
||||
- Fix import from `@polkadot/x-rxjs` in Node environments (From common)
|
||||
- Add correct types for `Phase` is new validator elections module
|
||||
|
||||
|
||||
## 4.0.1 Mar 7, 2021
|
||||
|
||||
Upgrade priority: Low. Recommended for users wanting to keep updated with chain changes.
|
||||
|
||||
**Important** In the 4.0 version the default package type has been changed to ESM modules by default. This should not affect usage, however since the output formats changed, a new major version is required.
|
||||
|
||||
Contributed:
|
||||
|
||||
- Expose `unknownTypes` on the registry interface (Thanks to https://github.com/ii-ii-ii)
|
||||
|
||||
Changes:
|
||||
|
||||
- Build to ESM by default (with cjs versions via export map)
|
||||
- Enum `.toSON()` now encodes all keys as `camelCase` (aligning with the output from Substrate)
|
||||
- Add `createdAtHash?: Hash` to `Codec` interface (filled-in by storage retrievals)
|
||||
- Expose the source hash as `wamHash` on Abi parsed instances
|
||||
- Use `parentHash` when creating mortal era (handles frequent forks better)
|
||||
- Add `AccountInfoWithTripleRefCount` to cater for latest Substrate
|
||||
- Add upgrade block for Westend 49
|
||||
|
||||
|
||||
## 3.11.1 Feb 28, 2021
|
||||
|
||||
Upgrade priority: Low. Recommended for users wanting to keep updated with chain changes.
|
||||
|
||||
Contributed:
|
||||
|
||||
- Clean Websocket states on disconnects (Thanks to https://github.com/ianhe8x)
|
||||
- Support for C-like indexed enums (Thanks to https://github.com/xlc)
|
||||
|
||||
Changes:
|
||||
|
||||
- Adjust council derives to cater for current-generation candidate mapping
|
||||
- Allow for override of codec hasher (& output type)
|
||||
- Adjust submittables to submit hex-encoded addresses to queries
|
||||
- Adjust initialization to always retrieve tx version from Metadata only
|
||||
- Update election types as per latest Substrate
|
||||
- Add types for the new gilt module
|
||||
- Upgrade to the latest Substrate metadata
|
||||
- Adjust package detection to check for local monorepo dependencies
|
||||
- Ensure that metadata `.toJSON()` does apply type aliasses
|
||||
|
||||
|
||||
## 3.10.2 Feb 23, 2021
|
||||
|
||||
Upgrade priority: Medium. Recommended for users of chains where `MultiAddress` is in-use and blocks are decoded.
|
||||
|
||||
Changes:
|
||||
|
||||
- Fix decoding for `MultiAddress` enum where non-`AccountId` variable-lengths are provided as part of a stream
|
||||
- Added known Polkadot 28 upgrade block
|
||||
- Update for latest Substrate contracts `Schedule` types
|
||||
|
||||
|
||||
## 3.10.1 Feb 22, 2021
|
||||
|
||||
Upgrade priority: Low.
|
||||
|
||||
Changes:
|
||||
|
||||
- Adjust ConsumedWeight types to align with Rust module code
|
||||
- Check for connection status in subscription unsubscribe
|
||||
- Adjust staking reward derives ordering for better performance
|
||||
- Adapt detection imports to remove `.json` dependencies (Better behavior using Node.js with ESM)
|
||||
|
||||
|
||||
## 3.9.3 Feb 16, 2021
|
||||
|
||||
Upgrade priority: Low. Recommended for parachain builders since it contains the updated parachain types.
|
||||
|
||||
Changes:
|
||||
|
||||
- Adjusted parachain `PersistedValidationData` structure
|
||||
|
||||
|
||||
## 3.9.2 Feb 15, 2021
|
||||
|
||||
Upgrade priority: Low. Recommended for parachain builders since it contains the latest parachain types.
|
||||
|
||||
Contributed:
|
||||
|
||||
- Update README links (Thanks to https://github.com/wirednkod)
|
||||
|
||||
Changes:
|
||||
|
||||
- Added missing Culmulus `ParachainInherentData` & `MessageQueueChain` types
|
||||
- Add alias for `system_unstable_networkState` RPC
|
||||
|
||||
|
||||
## 3.9.1 Feb 14, 2021
|
||||
|
||||
Upgrade priority: Low.
|
||||
|
||||
- **Important** The `Result<T, E>` has been updated in the generation and the base types to follow the Rust version 100%. This means `{as, is}Error` is now available as `{as, is}Err` on the `Result` type. The older versions can still be used, but the `*Error` interfaces are now marked as deprecated.
|
||||
|
||||
Changes:
|
||||
|
||||
- Adjust `Result<T, E>` interface to be 100% compatible with the Rust version
|
||||
- Add the `2028` upgrade to the known upgrades (optimizing certain `.at` queries)
|
||||
- Adjust council derives to cater for latest Substrate & Polkadot
|
||||
- Adjust Rococo know type definitions to cater for the latest update
|
||||
- Update types for latest Polkadot/Substrate
|
||||
- Add generic arguments for TypeScript users to `.entries/.keys` to deal with the key typings
|
||||
|
||||
|
||||
## 3.8.1 Feb 7, 2021
|
||||
|
||||
Upgrade priority: Low. Recommended for users of the latest Substrate master, especially using contracts.
|
||||
|
||||
- **Important** The `api-contract` `Code` now supports deploying the code and a contract in on operation. This aligns with the latest Substrate where code cannot be uploaded with a contract. The `createBlueprint` is therefore deprecated, use `code.tx.<constructor>(...)` to deploy code. (Compatible with both old and new versions of Substrate)
|
||||
|
||||
Contributed:
|
||||
|
||||
- Add support for latest Frontier RPCs (Thanks to https://github.com/jnaviask)
|
||||
- Fix user-supplied signed extensions type signature (Thanks to https://github.com/ntduan)
|
||||
|
||||
Changes:
|
||||
|
||||
- Expand `api-contract` to allow for `Code` to deploy contract alongside code. `createBlueprint` is now deprecated, replaced by `createContract` or the preferred `code.tx.<constructor>`, which uploads and deploys the code in one operation. This aligns with the current Substrate master contracts implementation.
|
||||
- Allow for signed extensions to be supplied inside type bundles
|
||||
- Ensure that the auto-connect state is checked on auto-connections (respecting disconnect)
|
||||
- Added `CancelProxy` to `ProxyTypes on Polkadot, Kusama & Westend
|
||||
- Updated to latest Substrate metadata
|
||||
|
||||
|
||||
## 3.7.3 Feb 2, 2021
|
||||
|
||||
Changes:
|
||||
|
||||
- Added Polkadot upgrade block for runtime 27 (known checkpoint optimization)
|
||||
|
||||
|
||||
## 3.7.2 Feb 2, 2021
|
||||
|
||||
Changes:
|
||||
|
||||
- Adjusted the `Keys` type for the 28 runtime on Kusama, Polkadot & Westend
|
||||
|
||||
|
||||
## 3.7.1 Feb 1, 2021
|
||||
|
||||
Upgrade priority: Low. However recommended for current Substrate master, Polkadot and Rococo users and those wishing to support the upcoming Polkadot 28 runtime with the new `MultiAddress`.
|
||||
|
||||
- **Breaking change** As indicated in the 3.5.1 release notes, the `Address`/`LookupSource` defaults have now been adjusted for `MultiAddress`. If your chain does not use these types, explicitly add the correct `Address`/`LookupSource` types. This new extensible format is mean to cater for all address types into the future, removing a lot of discrepancies between chains.
|
||||
|
||||
Contributed:
|
||||
|
||||
- Extraction of the block author on Moonbeam (Thanks to https://github.com/joelamouche)
|
||||
- Cleanup logs with HTTP providers, no subs (Thanks to https://github.com/Tbaut)
|
||||
|
||||
Changes:
|
||||
|
||||
- Allow `.slice` operator on the `Vec` type
|
||||
- Apply `MultiAddress` as a default
|
||||
- Adds support for the upcoming Polkadot 28 and Kusama 2028 runtimes
|
||||
- Add checkpoint for Kusama 2027 upgrade
|
||||
- Update all parachain types (as per latest Rococo)
|
||||
- Correctly use relay blockNumber in parachain validation data
|
||||
- remove information log for capabilities detection (creates confusion)
|
||||
- Remove explicit references to `global`, use the `x-global` detection
|
||||
- Remove explicit `module` in `package.json` (exports map available)
|
||||
|
||||
|
||||
## 3.6.1 Jan 24, 2020
|
||||
|
||||
Upgrade priority: Medium if not already on at least 3.3.1. The next upgrade of Kusama/Polkadot requires it.
|
||||
|
||||
- **Breaking change** To support chains with multiple tokens, such as bridges, the `ChainProperties` type now returns an array of tokens and decimals (instead of singular values) in the `token{Decimals, Symbol}` getters. Additionally, this means that the `registry` interfaces has been changes, to `registry.chainDecimals: number[]` and `registry.chainTokens: string[]`. Where used the `[0]` index will return the first value if only interested in a single, for a straight conversion.
|
||||
|
||||
Changes:
|
||||
|
||||
- Allow for the detection of on-chain capabilities as available (e.g. `AccountData`, `ValidatorPrefs`)
|
||||
- Cater for multiple tokens and decimals in the chain the chain `system.properties` (as per the chain specification)
|
||||
- Add a `instances: { [key]: [module1, module2] }` definition in teh bundle types, allowing for multiple instances (e.g. Balances)
|
||||
- Adjust the `api-derive` for balances to retrieve values via `instances` as well as across multiple modules
|
||||
- Ensure all types are registered for all metadata typegen steps
|
||||
- Add `rpc.payment.queryFeeDetails` RPC endpoint
|
||||
- Update types & metadata to latest Substrate
|
||||
- Move the `@polkadot/x-rxjs` package into the common repo
|
||||
- Allow doc generation for errors/events (markdown outputs)
|
||||
|
||||
|
||||
## 3.5.1 Jan 18, 2020
|
||||
|
||||
Upgrade priority: Low. Recommended for parachain developers.
|
||||
|
||||
- **Important** The default for Substrate on the Address types are `MultiAddress`. It is recommended that chains add explicit definitions for `Address` and `LookupSource` in their types, instead of relying on the API-defaults. A future update will swap the API defaults to align with Substrate.
|
||||
- **Important** Like the above changes in Substrate, the `AccountInfo` structure has also changed. It is recommended that chain developers explicitly add `AccountInfo: 'AccountInfoWithRefCount'` for the version with `refCount` on and `AccountInfoWithProviders` for the latest Substrate version. As per the above, the API defaults will be changed to align with Substrate.
|
||||
|
||||
Contributed:
|
||||
|
||||
- Apply correct TypeScript type for `toBigInt()` (Thanks to https://github.com/ianhe8x)
|
||||
- Expand type definitions for storage key tuples (Thanks to https://github.com/monitz87)
|
||||
- Adjust bounty derive to cater for non-council chains (Thanks to https://github.com/ekowalsk)
|
||||
|
||||
Changes:
|
||||
|
||||
- Remove recursion in vector/struct U8a stream decoding
|
||||
- Availability of staking made optional in session length calcs (era does require it)
|
||||
- Updates to parachain types, ensuring it has coverage for all the latest
|
||||
- Update all Rococo types to the latest (session keys, session reports, parachain indexes)
|
||||
- Update known upgrade checkpoints fo WestEnd
|
||||
- Add types of the lottery module in Substrate
|
||||
- Add and extend types for the crowdloan module in Polkadot
|
||||
- Adjust node-template to default to `MultiAddress` on specVersion >= 100
|
||||
|
||||
|
||||
## 3.4.1 Jan 11, 2020
|
||||
|
||||
Upgrade priority: Low. Fixes for parachain types, `.entries()` (with no values) and `event.is(...)` checks, users of these interfaces will have benefit.
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
|
||||
# @polkadot/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/).
|
||||
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/docs/api/).
|
||||
|
||||
If you are an existing user, please be sure to track the [CHANGELOG](CHANGELOG.md) and [UPGRADING](UPGRADING.md) guides when changing versions.
|
||||
|
||||
@@ -21,8 +21,8 @@ The API is split up into a number of internal packages -
|
||||
|
||||
- [@polkadot/api](packages/api/) The API library, providing both Promise and RxJS Observable-based interfaces. This is the main user-facing entry point.
|
||||
- [@polkadot/api-derive](packages/api-derive/) Derived results that are injected into the API, allowing for combinations of various query results (only used internally and exposed on the Api instances via `api.derive.*`)
|
||||
- [@polkadot/api-metadata](packages/api-metadata/) Base extrinsic, storage and constant injectors for injection
|
||||
- [@polkadot/rpc-core](packages/rpc-core/) Wrapper around all [JSON-RPC methods](https://polkadot.js.org/api/substrate/rpc.html) exposed by a Polkadot network client
|
||||
- [@polkadot/metadata](packages/metadata/) Base extrinsic, storage and constant injectors for injection
|
||||
- [@polkadot/rpc-core](packages/rpc-core/) Wrapper around all [JSON-RPC methods](https://polkadot.js.org/docs/substrate/rpc) exposed by a Polkadot network client
|
||||
- [@polkadot/rpc-provider](packages/rpc-provider/) Providers for connecting to nodes, including WebSockets and Http
|
||||
|
||||
Type definitions for interfaces as exposed by Polkadot & Substrate clients -
|
||||
|
||||
@@ -3,7 +3,8 @@
|
||||
|
||||
const config = require('@polkadot/dev/config/jest.cjs');
|
||||
|
||||
module.exports = Object.assign({}, config, {
|
||||
module.exports = {
|
||||
...config,
|
||||
moduleNameMapper: {
|
||||
'@polkadot/api-(contract|derive)(.*)$': '<rootDir>/packages/api-$1/src/$2',
|
||||
// eslint-disable-next-line sort-keys
|
||||
@@ -13,8 +14,7 @@ module.exports = Object.assign({}, config, {
|
||||
'@polkadot/typegen(.*)$': '<rootDir>/packages/typegen/src/$1',
|
||||
'@polkadot/types-known(.*)$': '<rootDir>/packages/types-known/src/$1',
|
||||
// eslint-disable-next-line sort-keys
|
||||
'@polkadot/types(.*)$': '<rootDir>/packages/types/src/$1',
|
||||
'@polkadot/x-rxjs(.*)$': '<rootDir>/packages/x-rxjs/src/$1'
|
||||
'@polkadot/types(.*)$': '<rootDir>/packages/types/src/$1'
|
||||
},
|
||||
modulePathIgnorePatterns: [
|
||||
'<rootDir>/packages/api/build',
|
||||
@@ -25,8 +25,7 @@ module.exports = Object.assign({}, config, {
|
||||
'<rootDir>/packages/rpc-provider/build',
|
||||
'<rootDir>/packages/typegen/build',
|
||||
'<rootDir>/packages/types/build',
|
||||
'<rootDir>/packages/types-known/build',
|
||||
'<rootDir>/packages/x-rxjs/build'
|
||||
'<rootDir>/packages/types-known/build'
|
||||
],
|
||||
resolver: '@polkadot/dev/config/jest-resolver.cjs'
|
||||
});
|
||||
transformIgnorePatterns: ['/node_modules/(?!@polkadot|@babel/runtime/helpers/esm/)']
|
||||
};
|
||||
+8
-8
@@ -8,7 +8,7 @@
|
||||
"packages/*"
|
||||
],
|
||||
"resolutions": {
|
||||
"typescript": "^4.1.3"
|
||||
"typescript": "^4.2.4"
|
||||
},
|
||||
"scripts": {
|
||||
"build": "yarn build:interfaces && polkadot-dev-build-ts",
|
||||
@@ -25,14 +25,14 @@
|
||||
"test:watch": "polkadot-dev-run-test --watch"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@babel/core": "^7.12.10",
|
||||
"@babel/register": "^7.12.10",
|
||||
"@babel/runtime": "^7.12.5",
|
||||
"@polkadot/dev": "^0.61.24",
|
||||
"@polkadot/ts": "^0.3.59",
|
||||
"@babel/core": "^7.14.0",
|
||||
"@babel/register": "^7.13.16",
|
||||
"@babel/runtime": "^7.14.0",
|
||||
"@polkadot/dev": "^0.62.11",
|
||||
"@polkadot/ts": "^0.3.64",
|
||||
"@polkadot/typegen": "workspace:packages/typegen",
|
||||
"@types/jest": "^26.0.20",
|
||||
"@types/jest": "^26.0.23",
|
||||
"copyfiles": "^2.4.1"
|
||||
},
|
||||
"version": "3.4.1"
|
||||
"version": "4.8.1"
|
||||
}
|
||||
|
||||
@@ -8,7 +8,7 @@ import { Abi } from '@polkadot/api-contract';
|
||||
|
||||
const wsProvider = new WsProvider(<...Node Url...>);
|
||||
const api = await ApiPromise.create({ provider: wsProvider });
|
||||
const abi = new Abi(api.registry, <...JSON ABI...>);
|
||||
const abi = new Abi(<...JSON ABI...>, api.registry.getChainProperties());
|
||||
|
||||
api.tx.contracts
|
||||
.call(<contract addr>, <value>, <max gas>, abi.messages.<method name>(<...params...>))
|
||||
|
||||
@@ -1,10 +1,16 @@
|
||||
{
|
||||
"name": "@polkadot/api-contract",
|
||||
"version": "3.4.1",
|
||||
"version": "4.8.1",
|
||||
"type": "module",
|
||||
"description": "Interfaces for interacting with contracts and contract ABIs",
|
||||
"main": "index.js",
|
||||
"module": "index.mjs",
|
||||
"sideEffects": false,
|
||||
"sideEffects": [
|
||||
"./detectPackage.js",
|
||||
"./detectPackage.cjs"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=14.0.0"
|
||||
},
|
||||
"author": "Jaco Greeff <jacogr@gmail.com>",
|
||||
"maintainers": [],
|
||||
"contributors": [],
|
||||
@@ -13,11 +19,11 @@
|
||||
"bugs": "https://github.com/polkadot-js/api/issues",
|
||||
"homepage": "https://github.com/polkadot-js/api/tree/master/packages/api-contract#readme",
|
||||
"dependencies": {
|
||||
"@babel/runtime": "^7.12.5",
|
||||
"@polkadot/api": "3.4.1",
|
||||
"@polkadot/types": "3.4.1",
|
||||
"@polkadot/util": "^5.2.3",
|
||||
"@polkadot/x-rxjs": "3.4.1",
|
||||
"@babel/runtime": "^7.14.0",
|
||||
"@polkadot/api": "4.8.1",
|
||||
"@polkadot/types": "4.8.1",
|
||||
"@polkadot/util": "^6.3.1",
|
||||
"@polkadot/x-rxjs": "^6.3.1",
|
||||
"bn.js": "^4.11.9"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,10 +1,18 @@
|
||||
// Copyright 2017-2021 @polkadot/api-contract authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import { blake2AsHex } from '@polkadot/util-crypto';
|
||||
|
||||
import abis from '../test/contracts';
|
||||
import { Abi } from '.';
|
||||
|
||||
interface JSONAbi {
|
||||
source: {
|
||||
compiler: string,
|
||||
hash: string,
|
||||
language: string,
|
||||
wasm: string
|
||||
},
|
||||
spec: {
|
||||
messages: {
|
||||
name: string[] | string
|
||||
@@ -27,4 +35,18 @@ describe('Abi', (): void => {
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
it('has the correct hash for the source', (): void => {
|
||||
const bundle = abis.ink_flipperBundle as JSONAbi;
|
||||
const abi = new Abi(bundle as any);
|
||||
|
||||
// manual
|
||||
expect(bundle.source.hash).toEqual(blake2AsHex(bundle.source.wasm));
|
||||
|
||||
// the Codec hash
|
||||
expect(bundle.source.hash).toEqual(abi.project.source.wasm.hash.toHex());
|
||||
|
||||
// the hash as per the actual Abi
|
||||
expect(bundle.source.hash).toEqual(abi.project.source.wasmHash.toHex());
|
||||
});
|
||||
});
|
||||
|
||||
@@ -6,7 +6,7 @@ import type { ChainProperties, ContractConstructorSpec, ContractEventSpec, Contr
|
||||
import type { AnyJson, Codec, CodecArg } from '@polkadot/types/types';
|
||||
import type { AbiConstructor, AbiEvent, AbiMessage, AbiParam, DecodedEvent, DecodedMessage } from './types';
|
||||
|
||||
import { assert, assertReturn, compactAddLength, compactStripLength, isNumber, isObject, isString, logger, stringCamelCase, u8aConcat, u8aToHex } from '@polkadot/util';
|
||||
import { assert, assertReturn, compactAddLength, compactStripLength, isNumber, isObject, isString, logger, stringCamelCase, stringify, u8aConcat, u8aToHex } from '@polkadot/util';
|
||||
|
||||
import { MetaRegistry } from './MetaRegistry';
|
||||
|
||||
@@ -21,7 +21,7 @@ function findMessage <T extends AbiMessage> (list: T[], messageOrId: T | string
|
||||
? list.find(({ identifier }) => [identifier, stringCamelCase(identifier)].includes(messageOrId.toString()))
|
||||
: messageOrId;
|
||||
|
||||
return assertReturn(message, `Attempted to call an invalid contract interface, ${JSON.stringify(messageOrId)}`);
|
||||
return assertReturn(message, `Attempted to call an invalid contract interface, ${stringify(messageOrId)}`);
|
||||
}
|
||||
|
||||
export class Abi {
|
||||
@@ -81,7 +81,7 @@ export class Abi {
|
||||
const index = data[0];
|
||||
const event = this.#events[index];
|
||||
|
||||
assert(event, `Unable to find event with index ${index}`);
|
||||
assert(event, () => `Unable to find event with index ${index}`);
|
||||
|
||||
return event.fromU8a(data.subarray(1));
|
||||
}
|
||||
@@ -118,7 +118,7 @@ export class Abi {
|
||||
type: this.registry.getMetaTypeDef(arg.type)
|
||||
};
|
||||
} catch (error) {
|
||||
l.error(`Error expanding argument ${index} in ${JSON.stringify(spec)}`);
|
||||
l.error(`Error expanding argument ${index} in ${stringify(spec)}`);
|
||||
|
||||
throw error;
|
||||
}
|
||||
@@ -143,6 +143,7 @@ export class Abi {
|
||||
|
||||
#createMessage = (spec: ContractMessageSpec | ContractConstructorSpec, index: number, add: Partial<AbiMessage> = {}): AbiMessage => {
|
||||
const args = this.#createArgs(spec.args, spec);
|
||||
const identifier = spec.name.toString();
|
||||
const message = {
|
||||
...add,
|
||||
args,
|
||||
@@ -151,8 +152,9 @@ export class Abi {
|
||||
args: this.#decodeArgs(args, data),
|
||||
message
|
||||
}),
|
||||
identifier: spec.name.toString(),
|
||||
identifier,
|
||||
index,
|
||||
method: stringCamelCase(identifier),
|
||||
selector: spec.selector,
|
||||
toU8a: (params: CodecArg[], additional?: Uint8Array) =>
|
||||
this.#encodeArgs(spec, args, params, additional)
|
||||
@@ -186,7 +188,7 @@ export class Abi {
|
||||
}
|
||||
|
||||
#encodeArgs = ({ name, selector }: ContractMessageSpec | ContractConstructorSpec, args: AbiParam[], data: CodecArg[], additional = EMPTY_U8A): Uint8Array => {
|
||||
assert(data.length === args.length, `Expected ${args.length} arguments to contract message '${name.toString()}', found ${data.length}`);
|
||||
assert(data.length === args.length, () => `Expected ${args.length} arguments to contract message '${name.toString()}', found ${data.length}`);
|
||||
|
||||
return compactAddLength(
|
||||
u8aConcat(
|
||||
|
||||
@@ -80,7 +80,7 @@ export class MetaRegistry extends TypeRegistry {
|
||||
#getMetaType = (id: SiLookupTypeId): SiType => {
|
||||
const type = this.#siTypes[getRegistryOffset(id)];
|
||||
|
||||
assert(!isUndefined(type), `getMetaType:: Unable to find ${id.toNumber()} in type values`);
|
||||
assert(!isUndefined(type), () => `getMetaType:: Unable to find ${id.toNumber()} in type values`);
|
||||
|
||||
return this.createType('SiType', type);
|
||||
}
|
||||
@@ -184,7 +184,7 @@ export class MetaRegistry extends TypeRegistry {
|
||||
}
|
||||
|
||||
#extractSequence = ({ type }: SiTypeDefSequence, id: SiLookupTypeId): Omit<TypeDef, 'type'> => {
|
||||
assert(!!type, `ContractRegistry: Invalid sequence type found at id ${id.toString()}`);
|
||||
assert(!!type, () => `ContractRegistry: Invalid sequence type found at id ${id.toString()}`);
|
||||
|
||||
return {
|
||||
info: TypeDefInfo.Vec,
|
||||
|
||||
@@ -26,6 +26,6 @@ export abstract class Base<ApiType extends ApiTypes> {
|
||||
this.registry = this.abi.registry;
|
||||
this._decorateMethod = decorateMethod;
|
||||
|
||||
assert(this.api.rx.tx.contracts && this.api.rx.tx.contracts.putCode, 'You need to connect to a node with the contracts module, the metadata does not enable api.tx.contracts on this instance');
|
||||
assert(api.rx.tx.contracts?.instantiate, 'You need to connect to a node with the contracts module, the metadata does not enable api.tx.contracts on this instance');
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,44 +6,17 @@ import type { ApiTypes, DecorateMethod } from '@polkadot/api/types';
|
||||
import type { AccountId, EventRecord, Hash } from '@polkadot/types/interfaces';
|
||||
import type { AnyJson, CodecArg, ISubmittableResult } from '@polkadot/types/types';
|
||||
import type { AbiConstructor, BlueprintOptions } from '../types';
|
||||
import type { BlueprintDeploy, ContractGeneric, MapConstructorExec } from './types';
|
||||
|
||||
import BN from 'bn.js';
|
||||
import type { ContractGeneric, MapConstructorExec } from './types';
|
||||
|
||||
import { SubmittableResult } from '@polkadot/api';
|
||||
import { ApiBase } from '@polkadot/api/base';
|
||||
import { Bytes } from '@polkadot/types';
|
||||
import { compactAddLength, isUndefined, stringCamelCase, u8aToU8a } from '@polkadot/util';
|
||||
import { randomAsU8a } from '@polkadot/util-crypto';
|
||||
import { isUndefined } from '@polkadot/util';
|
||||
|
||||
import { Abi } from '../Abi';
|
||||
import { applyOnEvent, extractOptions, isOptions } from '../util';
|
||||
import { applyOnEvent } from '../util';
|
||||
import { Base } from './Base';
|
||||
import { Contract } from './Contract';
|
||||
|
||||
const EMPTY_SALT = new Uint8Array();
|
||||
|
||||
function createTx <ApiType extends ApiTypes> (fn: (options: BlueprintOptions, params: CodecArg[]) => SubmittableExtrinsic<ApiType, BlueprintSubmittableResult<ApiType>>): BlueprintDeploy<ApiType> {
|
||||
return (options: BigInt | string | number | BN | BlueprintOptions, ...params: CodecArg[]): SubmittableExtrinsic<ApiType, BlueprintSubmittableResult<ApiType>> =>
|
||||
isOptions(options)
|
||||
? fn(options, params)
|
||||
: fn(...extractOptions(options, params));
|
||||
}
|
||||
|
||||
function createWithId <T> (fn: (constructorOrId: AbiConstructor | string | number, options: BlueprintOptions, params: CodecArg[]) => T): ContractGeneric<BlueprintOptions, T> {
|
||||
return (constructorOrId: AbiConstructor | string | number, options: BigInt | string | number | BN | BlueprintOptions, ...params: CodecArg[]): T =>
|
||||
isOptions(options)
|
||||
? fn(constructorOrId, options, params)
|
||||
: fn(constructorOrId, ...extractOptions(options, params));
|
||||
}
|
||||
|
||||
function encodeSalt (salt: Uint8Array | string | null = randomAsU8a()) {
|
||||
return salt instanceof Bytes
|
||||
? salt
|
||||
: salt && salt.length
|
||||
? compactAddLength(u8aToU8a(salt))
|
||||
: EMPTY_SALT;
|
||||
}
|
||||
import { createBluePrintTx, createBluePrintWithId, EMPTY_SALT, encodeSalt } from './util';
|
||||
|
||||
export class BlueprintSubmittableResult<ApiType extends ApiTypes> extends SubmittableResult {
|
||||
public readonly contract?: Contract<ApiType>;
|
||||
@@ -73,13 +46,11 @@ export class Blueprint<ApiType extends ApiTypes> extends Base<ApiType> {
|
||||
super(api, abi, decorateMethod);
|
||||
|
||||
this.codeHash = this.registry.createType('Hash', codeHash);
|
||||
this.createContract = createWithId(this.#deploy);
|
||||
this.createContract = createBluePrintWithId(this.#deploy);
|
||||
|
||||
this.abi.constructors.forEach((c): void => {
|
||||
const messageName = stringCamelCase(c.identifier);
|
||||
|
||||
if (isUndefined(this.#tx[messageName])) {
|
||||
this.#tx[messageName] = createTx((o, p) => this.#deploy(c, o, p));
|
||||
if (isUndefined(this.#tx[c.method])) {
|
||||
this.#tx[c.method] = createBluePrintTx((o, p) => this.#deploy(c, o, p));
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -88,7 +59,7 @@ export class Blueprint<ApiType extends ApiTypes> extends Base<ApiType> {
|
||||
return this.#tx;
|
||||
}
|
||||
|
||||
#deploy = (constructorOrId: AbiConstructor | string| number, { gasLimit = 0, salt, value = 0 }: BlueprintOptions, params: CodecArg[]): SubmittableExtrinsic<ApiType, BlueprintSubmittableResult<ApiType>> => {
|
||||
#deploy = (constructorOrId: AbiConstructor | string | number, { gasLimit = 0, salt, value = 0 }: BlueprintOptions, params: CodecArg[]): SubmittableExtrinsic<ApiType, BlueprintSubmittableResult<ApiType>> => {
|
||||
const encodedSalt = encodeSalt(salt);
|
||||
const withSalt = this.api.tx.contracts.instantiate.meta.args.length === 5;
|
||||
const encoded = this.abi.findConstructor(constructorOrId).toU8a(params, withSalt ? EMPTY_SALT : encodedSalt);
|
||||
@@ -99,7 +70,7 @@ export class Blueprint<ApiType extends ApiTypes> extends Base<ApiType> {
|
||||
: this.api.tx.contracts.instantiate(value, gasLimit, this.codeHash, encoded);
|
||||
|
||||
return tx.withResultTransform((result: ISubmittableResult) =>
|
||||
new BlueprintSubmittableResult(result, applyOnEvent(result, 'Instantiated', ([record]: EventRecord[]) =>
|
||||
new BlueprintSubmittableResult(result, applyOnEvent(result, ['Instantiated'], ([record]: EventRecord[]) =>
|
||||
new Contract<ApiType>(this.api, this.abi, record.event.data[1] as AccountId, this._decorateMethod)
|
||||
))
|
||||
);
|
||||
|
||||
@@ -3,31 +3,42 @@
|
||||
|
||||
import type { SubmittableExtrinsic } from '@polkadot/api/submittable/types';
|
||||
import type { ApiTypes, DecorateMethod } from '@polkadot/api/types';
|
||||
import type { EventRecord, Hash } from '@polkadot/types/interfaces';
|
||||
import type { AnyJson, ISubmittableResult } from '@polkadot/types/types';
|
||||
import type { EventRecord } from '@polkadot/types/interfaces';
|
||||
import type { AnyJson, CodecArg, ISubmittableResult } from '@polkadot/types/types';
|
||||
import type { AbiConstructor, BlueprintOptions } from '../types';
|
||||
import type { MapConstructorExec } from './types';
|
||||
|
||||
import { SubmittableResult } from '@polkadot/api';
|
||||
import { ApiBase } from '@polkadot/api/base';
|
||||
import { assert, compactAddLength, isWasm, u8aToU8a } from '@polkadot/util';
|
||||
import { assert, compactAddLength, isFunction, isUndefined, isWasm, logger, u8aToU8a } from '@polkadot/util';
|
||||
import { blake2AsU8a } from '@polkadot/util-crypto';
|
||||
|
||||
import { Abi } from '../Abi';
|
||||
import { applyOnEvent } from '../util';
|
||||
import { Base } from './Base';
|
||||
import { Blueprint } from './Blueprint';
|
||||
import { Contract } from './Contract';
|
||||
import { createBluePrintTx, EMPTY_SALT, encodeSalt } from './util';
|
||||
|
||||
const l = logger('Code');
|
||||
|
||||
export class CodeSubmittableResult<ApiType extends ApiTypes> extends SubmittableResult {
|
||||
public readonly blueprint?: Blueprint<ApiType>;
|
||||
public readonly contract?: Contract<ApiType>;
|
||||
|
||||
constructor (result: ISubmittableResult, blueprint?: Blueprint<ApiType>) {
|
||||
constructor (result: ISubmittableResult, blueprint?: Blueprint<ApiType>, contract?: Contract<ApiType>) {
|
||||
super(result);
|
||||
|
||||
this.blueprint = blueprint;
|
||||
this.contract = contract;
|
||||
}
|
||||
}
|
||||
|
||||
export class Code<ApiType extends ApiTypes> extends Base<ApiType> {
|
||||
public readonly code: Uint8Array;
|
||||
|
||||
readonly #tx: MapConstructorExec<ApiType> = {};
|
||||
|
||||
constructor (api: ApiBase<ApiType>, abi: AnyJson | Abi, wasm: Uint8Array | string | Buffer | null | undefined, decorateMethod: DecorateMethod<ApiType>) {
|
||||
super(api, abi, decorateMethod);
|
||||
|
||||
@@ -36,18 +47,67 @@ export class Code<ApiType extends ApiTypes> extends Base<ApiType> {
|
||||
: u8aToU8a(wasm);
|
||||
|
||||
assert(isWasm(this.code), 'No WASM code provided');
|
||||
|
||||
this.abi.constructors.forEach((c): void => {
|
||||
if (isUndefined(this.#tx[c.method])) {
|
||||
this.#tx[c.method] = createBluePrintTx((o, p) => this.#instantiate(c, o, p));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public get tx (): MapConstructorExec<ApiType> {
|
||||
return this.#tx;
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Deploy the code bundle, creating a Blueprint.
|
||||
* @description Deploy the code bundle and the contract, creating a Blueprint.
|
||||
* @deprecated Use the `code.tx.<constructor>(...) format to put code and deploy
|
||||
*/
|
||||
public createBlueprint (): SubmittableExtrinsic<ApiType, CodeSubmittableResult<ApiType>> {
|
||||
public createContract (constructorOrId: AbiConstructor | string | number, options: BlueprintOptions, params: CodecArg[]): SubmittableExtrinsic<ApiType, CodeSubmittableResult<ApiType>> {
|
||||
l.warn('.createContract is deprecated, use code.tx.<constructorName>(...) instead (where code refers to this instance)');
|
||||
|
||||
return this.#instantiate(constructorOrId, options, params);
|
||||
}
|
||||
|
||||
#instantiate = (constructorOrId: AbiConstructor | string | number, options: BlueprintOptions, params: CodecArg[]): SubmittableExtrinsic<ApiType, CodeSubmittableResult<ApiType>> => {
|
||||
return isFunction(this.api.tx.contracts.instantiateWithCode)
|
||||
? this.#instantiateCurrent(constructorOrId, options, params)
|
||||
: this.#instantiatePrev(constructorOrId, options, params);
|
||||
}
|
||||
|
||||
#instantiateCurrent = (constructorOrId: AbiConstructor | string | number, { gasLimit = 0, salt, value = 0 }: BlueprintOptions, params: CodecArg[]): SubmittableExtrinsic<ApiType, CodeSubmittableResult<ApiType>> => {
|
||||
return this.api.tx.contracts
|
||||
.putCode(compactAddLength(this.code))
|
||||
.withResultTransform((result: ISubmittableResult) =>
|
||||
new CodeSubmittableResult(result, applyOnEvent(result, 'CodeStored', ([record]: EventRecord[]) =>
|
||||
new Blueprint<ApiType>(this.api, this.abi, record.event.data[0] as Hash, this._decorateMethod)
|
||||
))
|
||||
);
|
||||
.instantiateWithCode(value, gasLimit, compactAddLength(this.code), this.abi.findConstructor(constructorOrId).toU8a(params), encodeSalt(salt))
|
||||
.withResultTransform(this.#transformEvents);
|
||||
}
|
||||
|
||||
#instantiatePrev = (constructorOrId: AbiConstructor | string | number, { gasLimit = 0, salt, value = 0 }: BlueprintOptions, params: CodecArg[]): SubmittableExtrinsic<ApiType, CodeSubmittableResult<ApiType>> => {
|
||||
assert(isFunction(this.api.tx.utility?.batch), 'Your chain does not include the utility pallet, for contracts v2 deployment, this is required');
|
||||
|
||||
const encodedSalt = encodeSalt(salt);
|
||||
const withSalt = this.api.tx.contracts.instantiate.meta.args.length === 5;
|
||||
const encoded = this.abi.findConstructor(constructorOrId).toU8a(params, withSalt ? EMPTY_SALT : encodedSalt);
|
||||
const codeHash = blake2AsU8a(this.code);
|
||||
|
||||
return this.api.tx.utility.batch([
|
||||
this.api.tx.contracts.putCode(compactAddLength(this.code)),
|
||||
withSalt
|
||||
? this.api.tx.contracts.instantiate(value, gasLimit, codeHash, encoded, encodedSalt)
|
||||
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
||||
// @ts-ignore old style with salt included in the params itself
|
||||
: this.api.tx.contracts.instantiate(value, gasLimit, codeHash, encoded)
|
||||
]).withResultTransform(this.#transformEvents);
|
||||
}
|
||||
|
||||
#transformEvents = (result: ISubmittableResult): CodeSubmittableResult<ApiType> => {
|
||||
return new CodeSubmittableResult(result, ...(applyOnEvent(result, ['CodeStored', 'Instantiated'], (records: EventRecord[]) =>
|
||||
records.reduce(([blueprint, contract], { event }): [Blueprint<ApiType>?, Contract<ApiType>?] =>
|
||||
this.api.events.contracts.Instantiated.is(event)
|
||||
? [blueprint, new Contract<ApiType>(this.api, this.abi, event.data[1], this._decorateMethod)]
|
||||
: this.api.events.contracts.CodeStored.is(event)
|
||||
? [new Blueprint<ApiType>(this.api, this.abi, event.data[0], this._decorateMethod), contract]
|
||||
: [blueprint, contract],
|
||||
[] as [Blueprint<ApiType>?, Contract<ApiType>?])
|
||||
) || []));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -13,7 +13,7 @@ import BN from 'bn.js';
|
||||
|
||||
import { SubmittableResult } from '@polkadot/api';
|
||||
import { ApiBase } from '@polkadot/api/base';
|
||||
import { assert, bnToBn, isFunction, isUndefined, logger, stringCamelCase } from '@polkadot/util';
|
||||
import { assert, bnToBn, isFunction, isUndefined, logger } from '@polkadot/util';
|
||||
import { map } from '@polkadot/x-rxjs/operators';
|
||||
|
||||
import { Abi } from '../Abi';
|
||||
@@ -23,6 +23,7 @@ import { Base } from './Base';
|
||||
// As per Rust, 5 * GAS_PER_SEC
|
||||
const MAX_CALL_GAS = new BN(5_000_000_000_000).subn(1);
|
||||
const ERROR_NO_CALL = 'Your node does not expose the contracts.call RPC. This is most probably due to a runtime configuration.';
|
||||
|
||||
const l = logger('Contract');
|
||||
|
||||
function createQuery <ApiType extends ApiTypes> (fn: (origin: string | AccountId | Uint8Array, options: ContractOptions, params: CodecArg[]) => ContractCallResult<ApiType, ContractCallOutcome>): ContractQuery<ApiType> {
|
||||
@@ -39,11 +40,14 @@ function createTx <ApiType extends ApiTypes> (fn: (options: ContractOptions, par
|
||||
: fn(...extractOptions(options, params));
|
||||
}
|
||||
|
||||
function createWithId <T> (fn: (messageOrId: AbiMessage | string | number, options: ContractOptions, params: CodecArg[]) => T): ContractGeneric<ContractOptions, T> {
|
||||
return (messageOrId: AbiMessage | string | number, options: BigInt | string | number | BN | ContractOptions, ...params: CodecArg[]): T =>
|
||||
isOptions(options)
|
||||
function createWithId <T> (fn: (messageOrId: AbiMessage | string | number, options: ContractOptions, params: CodecArg[]) => T, warn?: string): ContractGeneric<ContractOptions, T> {
|
||||
return (messageOrId: AbiMessage | string | number, options: BigInt | string | number | BN | ContractOptions, ...params: CodecArg[]): T => {
|
||||
warn && l.warn(warn);
|
||||
|
||||
return isOptions(options)
|
||||
? fn(messageOrId, options, params)
|
||||
: fn(messageOrId, ...extractOptions(options, params));
|
||||
};
|
||||
}
|
||||
|
||||
export class ContractSubmittableResult extends SubmittableResult {
|
||||
@@ -109,18 +113,16 @@ export class Contract<ApiType extends ApiTypes> extends Base<ApiType> {
|
||||
super(api, abi, decorateMethod);
|
||||
|
||||
this.address = this.registry.createType('AccountId', address);
|
||||
this.exec = createWithId(this.#exec);
|
||||
this.read = createWithId(this.#read);
|
||||
this.exec = createWithId(this.#exec, '.exec is deprecated, use contract.tx.<messageName>(...) instead (where contract refers to this instance)');
|
||||
this.read = createWithId(this.#read, '.read is deprecated, use contract.query.<messageName>(...) instead (where contract refers to this instance)');
|
||||
|
||||
this.abi.messages.forEach((m): void => {
|
||||
const messageName = stringCamelCase(m.identifier);
|
||||
|
||||
if (isUndefined(this.#tx[messageName])) {
|
||||
this.#tx[messageName] = createTx((o, p) => this.#exec(m, o, p));
|
||||
if (isUndefined(this.#tx[m.method])) {
|
||||
this.#tx[m.method] = createTx((o, p) => this.#exec(m, o, p));
|
||||
}
|
||||
|
||||
if (isUndefined(this.#query[messageName])) {
|
||||
this.#query[messageName] = createQuery((f, o, p) => this.#read(m, o, p).send(f));
|
||||
if (isUndefined(this.#query[m.method])) {
|
||||
this.#query[m.method] = createQuery((f, o, p) => this.#read(m, o, p).send(f));
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -156,7 +158,8 @@ export class Contract<ApiType extends ApiTypes> extends Base<ApiType> {
|
||||
return this.api.tx.contracts
|
||||
.call(this.address, value, this.#getGas(gasLimit), this.abi.findMessage(messageOrId).toU8a(params))
|
||||
.withResultTransform((result: ISubmittableResult) =>
|
||||
new ContractSubmittableResult(result, applyOnEvent(result, 'ContractExecution', (records: EventRecord[]) =>
|
||||
// ContractEmitted is the current generation, ContractExecution is the previous generation
|
||||
new ContractSubmittableResult(result, applyOnEvent(result, ['ContractEmitted', 'ContractExecution'], (records: EventRecord[]) =>
|
||||
records
|
||||
.map(({ event: { data: [, data] } }): DecodedEvent | null => {
|
||||
try {
|
||||
|
||||
@@ -11,6 +11,9 @@ export const mockApi = {
|
||||
rx: {
|
||||
tx: {
|
||||
contracts: {
|
||||
instantiate: (): never => {
|
||||
throw new Error('mock');
|
||||
},
|
||||
putCode: (): never => {
|
||||
throw new Error('mock');
|
||||
}
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
// Copyright 2017-2021 @polkadot/api-contract authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import type { SubmittableResult } from '@polkadot/api';
|
||||
import type { SubmittableExtrinsic } from '@polkadot/api/submittable/types';
|
||||
import type { ApiTypes } from '@polkadot/api/types';
|
||||
import type { CodecArg } from '@polkadot/types/types';
|
||||
import type { AbiConstructor, BlueprintOptions } from '../types';
|
||||
import type { BlueprintDeploy, ContractGeneric } from './types';
|
||||
|
||||
import BN from 'bn.js';
|
||||
|
||||
import { Bytes } from '@polkadot/types';
|
||||
import { compactAddLength, u8aToU8a } from '@polkadot/util';
|
||||
import { randomAsU8a } from '@polkadot/util-crypto';
|
||||
|
||||
import { extractOptions, isOptions } from '../util';
|
||||
|
||||
export const EMPTY_SALT = new Uint8Array();
|
||||
|
||||
export function createBluePrintTx <ApiType extends ApiTypes, R extends SubmittableResult> (fn: (options: BlueprintOptions, params: CodecArg[]) => SubmittableExtrinsic<ApiType, R>): BlueprintDeploy<ApiType> {
|
||||
return (options: BigInt | string | number | BN | BlueprintOptions, ...params: CodecArg[]): SubmittableExtrinsic<ApiType, R> =>
|
||||
isOptions(options)
|
||||
? fn(options, params)
|
||||
: fn(...extractOptions(options, params));
|
||||
}
|
||||
|
||||
export function createBluePrintWithId <T> (fn: (constructorOrId: AbiConstructor | string | number, options: BlueprintOptions, params: CodecArg[]) => T): ContractGeneric<BlueprintOptions, T> {
|
||||
return (constructorOrId: AbiConstructor | string | number, options: BigInt | string | number | BN | BlueprintOptions, ...params: CodecArg[]): T =>
|
||||
isOptions(options)
|
||||
? fn(constructorOrId, options, params)
|
||||
: fn(constructorOrId, ...extractOptions(options, params));
|
||||
}
|
||||
|
||||
export function encodeSalt (salt: Uint8Array | string | null = randomAsU8a()): Uint8Array {
|
||||
return salt instanceof Bytes
|
||||
? salt
|
||||
: salt && salt.length
|
||||
? compactAddLength(u8aToU8a(salt))
|
||||
: EMPTY_SALT;
|
||||
}
|
||||
@@ -37,7 +37,9 @@ async function checkContract (api: ApiPromise, pairs: TestKeyringMap): Promise<v
|
||||
}
|
||||
|
||||
async function main (): Promise<void> {
|
||||
const api = await ApiPromise.create();
|
||||
const api = await ApiPromise.create({
|
||||
hasher: (data: Uint8Array): Uint8Array => data
|
||||
});
|
||||
const pairs = createTestPairs();
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-floating-promises
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
// Copyright 2017-2021 @polkadot/api-contract authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import { packageInfo as apiInfo } from '@polkadot/api/packageInfo';
|
||||
import { packageInfo as typesInfo } from '@polkadot/types/packageInfo';
|
||||
import { detectPackage } from '@polkadot/util';
|
||||
|
||||
import { packageInfo } from './packageInfo';
|
||||
|
||||
detectPackage(packageInfo, typeof __dirname !== 'undefined' && __dirname, [apiInfo, typesInfo]);
|
||||
@@ -1,7 +1,9 @@
|
||||
// Copyright 2017-2021 @polkadot/api-contract authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
export { Abi } from './Abi';
|
||||
import './detectPackage';
|
||||
|
||||
export { Blueprint as BlueprintRx, Code as CodeRx, Contract as ContractRx } from './rx';
|
||||
export { Abi } from './Abi';
|
||||
export { packageInfo } from './packageInfo';
|
||||
export { Blueprint as BlueprintPromise, Code as CodePromise, Contract as ContractPromise } from './promise';
|
||||
export { Blueprint as BlueprintRx, Code as CodeRx, Contract as ContractRx } from './rx';
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
// Copyright 2017-2021 @polkadot/api-contract authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
// Auto-generated by @polkadot/dev, do not edit
|
||||
|
||||
export const packageInfo = { name: '@polkadot/api-contract', version: '4.8.1' };
|
||||
@@ -39,6 +39,7 @@ export interface AbiMessage {
|
||||
isConstructor?: boolean;
|
||||
isMutating?: boolean;
|
||||
isPayable?: boolean;
|
||||
method: string;
|
||||
returnType?: TypeDef | null;
|
||||
selector: ContractSelector;
|
||||
toU8a: (params: CodecArg[], additional?: Uint8Array) => Uint8Array;
|
||||
|
||||
@@ -12,7 +12,7 @@ import BN from 'bn.js';
|
||||
import { createTypeUnsafe } from '@polkadot/types/create';
|
||||
import { isBigInt, isBn, isNumber, isString } from '@polkadot/util';
|
||||
|
||||
type ContractEvents = 'CodeStored' | 'ContractExecution' | 'Instantiated';
|
||||
type ContractEvents = 'CodeStored' | 'ContractEmitted' | 'ContractExecution' | 'Instantiated';
|
||||
|
||||
type TOptions = BlueprintOptions | ContractOptions;
|
||||
|
||||
@@ -20,9 +20,9 @@ export function formatData (registry: Registry, data: Raw, { type }: TypeDef): C
|
||||
return createTypeUnsafe(registry, type, [data], { isPedantic: true });
|
||||
}
|
||||
|
||||
export function applyOnEvent <T> (result: SubmittableResult, type: ContractEvents, fn: (records: EventRecord[]) => T): T | undefined {
|
||||
export function applyOnEvent <T> (result: SubmittableResult, types: ContractEvents[], fn: (records: EventRecord[]) => T): T | undefined {
|
||||
if (result.isInBlock || result.isFinalized) {
|
||||
const records = result.filterRecords('contracts', type);
|
||||
const records = result.filterRecords('contracts', types);
|
||||
|
||||
if (records.length) {
|
||||
return fn(records);
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
[
|
||||
{
|
||||
"info": 6,
|
||||
"type": "bool"
|
||||
}
|
||||
]
|
||||
@@ -6,5 +6,6 @@ export { default as dns } from './dns.json';
|
||||
export { default as erc20 } from './erc20.json';
|
||||
export { default as erc721 } from './erc721.json';
|
||||
export { default as flipper } from './flipper.json';
|
||||
export { default as flipperBundle } from './flipper.contract.json';
|
||||
export { default as incrementer } from './incrementer.json';
|
||||
export { default as multisigPlain } from './multisig_plain.json';
|
||||
|
||||
@@ -1,10 +1,16 @@
|
||||
{
|
||||
"name": "@polkadot/api-derive",
|
||||
"version": "3.4.1",
|
||||
"version": "4.8.1",
|
||||
"type": "module",
|
||||
"description": "Common functions used across Polkadot, derived from RPC calls and storage queries.",
|
||||
"main": "index.js",
|
||||
"module": "index.mjs",
|
||||
"sideEffects": false,
|
||||
"sideEffects": [
|
||||
"./detectPackage.js",
|
||||
"./detectPackage.cjs"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=14.0.0"
|
||||
},
|
||||
"author": "Jaco Greeff <jacogr@gmail.com>",
|
||||
"maintainers": [],
|
||||
"contributors": [],
|
||||
@@ -13,17 +19,17 @@
|
||||
"bugs": "https://github.com/polkadot-js/api/issues",
|
||||
"homepage": "https://github.com/polkadot-js/api/tree/master/packages/api-derive#readme",
|
||||
"dependencies": {
|
||||
"@babel/runtime": "^7.12.5",
|
||||
"@polkadot/api": "3.4.1",
|
||||
"@polkadot/rpc-core": "3.4.1",
|
||||
"@polkadot/types": "3.4.1",
|
||||
"@polkadot/util": "^5.2.3",
|
||||
"@polkadot/util-crypto": "^5.2.3",
|
||||
"@polkadot/x-rxjs": "3.4.1",
|
||||
"@babel/runtime": "^7.14.0",
|
||||
"@polkadot/api": "4.8.1",
|
||||
"@polkadot/rpc-core": "4.8.1",
|
||||
"@polkadot/types": "4.8.1",
|
||||
"@polkadot/util": "^6.3.1",
|
||||
"@polkadot/util-crypto": "^6.3.1",
|
||||
"@polkadot/x-rxjs": "^6.3.1",
|
||||
"bn.js": "^4.11.9"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@polkadot/keyring": "^5.2.3",
|
||||
"@polkadot/rpc-provider": "3.4.1"
|
||||
"@polkadot/keyring": "^6.3.1",
|
||||
"@polkadot/rpc-provider": "4.8.1"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,7 +2,6 @@
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import type { ApiInterfaceRx } from '@polkadot/api/types';
|
||||
import type { AccountIndex } from '@polkadot/types/interfaces';
|
||||
import type { Observable } from '@polkadot/x-rxjs';
|
||||
import type { AccountIndexes } from '../types';
|
||||
|
||||
@@ -18,7 +17,7 @@ function queryAccounts (api: ApiInterfaceRx): Observable<AccountIndexes> {
|
||||
map((entries): AccountIndexes =>
|
||||
entries.reduce((indexes: AccountIndexes, [key, idOpt]): AccountIndexes => {
|
||||
if (idOpt.isSome) {
|
||||
indexes[idOpt.unwrap()[0].toString()] = key.args[0] as AccountIndex;
|
||||
indexes[idOpt.unwrap()[0].toString()] = key.args[0];
|
||||
}
|
||||
|
||||
return indexes;
|
||||
|
||||
@@ -1,24 +1,30 @@
|
||||
// Copyright 2017-2021 @polkadot/api-derive authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import type { ApiInterfaceRx } from '@polkadot/api/types';
|
||||
import type { ApiInterfaceRx, QueryableStorageMultiArg } from '@polkadot/api/types';
|
||||
import type { AccountData, AccountId, AccountIndex, AccountInfo, Address, Balance, Index } from '@polkadot/types/interfaces';
|
||||
import type { ITuple } from '@polkadot/types/types';
|
||||
import type { Observable } from '@polkadot/x-rxjs';
|
||||
import type { DeriveBalancesAccount } from '../types';
|
||||
import type { DeriveBalancesAccount, DeriveBalancesAccountData } from '../types';
|
||||
|
||||
import { isFunction } from '@polkadot/util';
|
||||
import { assert, isFunction } from '@polkadot/util';
|
||||
import { combineLatest, of } from '@polkadot/x-rxjs';
|
||||
import { map, switchMap } from '@polkadot/x-rxjs/operators';
|
||||
|
||||
import { memo } from '../util';
|
||||
|
||||
type Result = [Balance, Balance, Balance, Balance, Index];
|
||||
type BalanceResult = [Balance, Balance, Balance, Balance];
|
||||
|
||||
function calcBalances (api: ApiInterfaceRx, [accountId, [freeBalance, reservedBalance, frozenFee, frozenMisc, accountNonce]]: [AccountId, Result]): DeriveBalancesAccount {
|
||||
type Result = [Index, BalanceResult[]];
|
||||
|
||||
type DeriveCustomAccount = ApiInterfaceRx['derive'] & {
|
||||
[custom: string]: {
|
||||
customAccount?: ApiInterfaceRx['query']['balances']['account']
|
||||
}
|
||||
}
|
||||
|
||||
function getBalance (api: ApiInterfaceRx, [freeBalance, reservedBalance, frozenFee, frozenMisc]: BalanceResult): DeriveBalancesAccountData {
|
||||
return {
|
||||
accountId,
|
||||
accountNonce,
|
||||
freeBalance,
|
||||
frozenFee,
|
||||
frozenMisc,
|
||||
@@ -27,6 +33,19 @@ function calcBalances (api: ApiInterfaceRx, [accountId, [freeBalance, reservedBa
|
||||
};
|
||||
}
|
||||
|
||||
function calcBalances (api: ApiInterfaceRx, [accountId, [accountNonce, balances]]: [AccountId, Result]): DeriveBalancesAccount {
|
||||
const primary = balances[0];
|
||||
|
||||
assert(primary, 'No balances retrieved for account');
|
||||
|
||||
return {
|
||||
accountId,
|
||||
accountNonce,
|
||||
additional: balances.filter((_, index) => index !== 0).map((b) => getBalance(api, b)),
|
||||
...getBalance(api, primary)
|
||||
};
|
||||
}
|
||||
|
||||
// old
|
||||
function queryBalancesFree (api: ApiInterfaceRx, accountId: AccountId): Observable<Result> {
|
||||
return api.queryMulti<[Balance, Balance, Index]>([
|
||||
@@ -34,21 +53,31 @@ function queryBalancesFree (api: ApiInterfaceRx, accountId: AccountId): Observab
|
||||
[api.query.balances.reservedBalance, accountId],
|
||||
[api.query.system.accountNonce, accountId]
|
||||
]).pipe(
|
||||
map(([freeBalance, reservedBalance, accountNonce]): Result =>
|
||||
[freeBalance, reservedBalance, api.registry.createType('Balance'), api.registry.createType('Balance'), accountNonce]
|
||||
)
|
||||
map(([freeBalance, reservedBalance, accountNonce]): Result => [
|
||||
accountNonce,
|
||||
[[freeBalance, reservedBalance, api.registry.createType('Balance'), api.registry.createType('Balance')]]
|
||||
])
|
||||
);
|
||||
}
|
||||
|
||||
function queryBalancesAccount (api: ApiInterfaceRx, accountId: AccountId): Observable<Result> {
|
||||
return api.queryMulti<[AccountData, Index]>([
|
||||
[api.query.balances.account, accountId],
|
||||
[api.query.system.accountNonce, accountId]
|
||||
]).pipe(
|
||||
map(([{ feeFrozen, free, miscFrozen, reserved }, accountNonce]): Result =>
|
||||
[free, reserved, feeFrozen, miscFrozen, accountNonce]
|
||||
)
|
||||
function queryBalancesAccount (api: ApiInterfaceRx, accountId: AccountId, modules: string[] = ['balances']): Observable<Result> {
|
||||
const balances = modules.map(
|
||||
(m): QueryableStorageMultiArg<'rxjs'> => [
|
||||
(api.derive as DeriveCustomAccount)[m]?.customAccount || api.query[m].account,
|
||||
accountId
|
||||
]
|
||||
);
|
||||
|
||||
const extract = (data: AccountData[]) =>
|
||||
data.map(({ feeFrozen, free, miscFrozen, reserved }): BalanceResult => [free, reserved, feeFrozen, miscFrozen]);
|
||||
|
||||
return isFunction(api.query.system.account)
|
||||
? api.queryMulti<[AccountInfo, ...(AccountData[])]>([[api.query.system.account, accountId], ...balances]).pipe(
|
||||
map(([{ nonce }, ...balances]): Result => [nonce, extract(balances)])
|
||||
)
|
||||
: api.queryMulti<[Index, ...(AccountData[])]>([[api.query.system.accountNonce, accountId], ...balances]).pipe(
|
||||
map(([nonce, ...balances]): Result => [nonce, extract(balances)])
|
||||
);
|
||||
}
|
||||
|
||||
function queryCurrent (api: ApiInterfaceRx, accountId: AccountId): Observable<Result> {
|
||||
@@ -58,9 +87,11 @@ function queryCurrent (api: ApiInterfaceRx, accountId: AccountId): Observable<Re
|
||||
const { feeFrozen, free, miscFrozen, reserved } = (infoOrTuple as AccountInfo).nonce
|
||||
? (infoOrTuple as AccountInfo).data
|
||||
: (infoOrTuple as [Index, AccountData])[1];
|
||||
const accountNonce = (infoOrTuple as AccountInfo).nonce || (infoOrTuple as [Index, AccountData])[0];
|
||||
|
||||
return [free, reserved, feeFrozen, miscFrozen, accountNonce];
|
||||
return [
|
||||
(infoOrTuple as AccountInfo).nonce || (infoOrTuple as [Index, AccountData])[0],
|
||||
[[free, reserved, feeFrozen, miscFrozen]]
|
||||
];
|
||||
})
|
||||
);
|
||||
}
|
||||
@@ -81,19 +112,29 @@ function queryCurrent (api: ApiInterfaceRx, accountId: AccountId): Observable<Re
|
||||
* ```
|
||||
*/
|
||||
export function account (instanceId: string, api: ApiInterfaceRx): (address: AccountIndex | AccountId | Address | string) => Observable<DeriveBalancesAccount> {
|
||||
const balanceInstances = api.registry.getModuleInstances(api.runtimeVersion.specName.toString(), 'balances');
|
||||
|
||||
return memo(instanceId, (address: AccountIndex | AccountId | Address | string): Observable<DeriveBalancesAccount> =>
|
||||
api.derive.accounts.accountId(address).pipe(
|
||||
switchMap((accountId): Observable<[AccountId, Result]> =>
|
||||
(accountId
|
||||
? combineLatest([
|
||||
of(accountId),
|
||||
isFunction(api.query.system.account)
|
||||
? queryCurrent(api, accountId)
|
||||
: isFunction(api.query.balances.account)
|
||||
? queryBalancesAccount(api, accountId)
|
||||
: queryBalancesFree(api, accountId)
|
||||
balanceInstances
|
||||
? queryBalancesAccount(api, accountId, balanceInstances)
|
||||
: isFunction(api.query.system.account)
|
||||
? queryCurrent(api, accountId)
|
||||
: isFunction(api.query.balances.account)
|
||||
? queryBalancesAccount(api, accountId)
|
||||
: queryBalancesFree(api, accountId)
|
||||
])
|
||||
: of([
|
||||
api.registry.createType('AccountId'),
|
||||
[
|
||||
api.registry.createType('Index'),
|
||||
[[api.registry.createType('Balance'), api.registry.createType('Balance'), api.registry.createType('Balance'), api.registry.createType('Balance')]]
|
||||
]
|
||||
])
|
||||
: of([api.registry.createType('AccountId'), [api.registry.createType('Balance'), api.registry.createType('Balance'), api.registry.createType('Balance'), api.registry.createType('Balance'), api.registry.createType('Index')]])
|
||||
)
|
||||
),
|
||||
map((result): DeriveBalancesAccount => calcBalances(api, result))
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
// Copyright 2017-2021 @polkadot/api-derive authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import type { ApiInterfaceRx } from '@polkadot/api/types';
|
||||
import type { ApiInterfaceRx, QueryableStorageMultiArg } from '@polkadot/api/types';
|
||||
import type { Option, Vec } from '@polkadot/types';
|
||||
import type { AccountId, AccountIndex, Address, Balance, BalanceLock, BalanceLockTo212, BlockNumber, VestingInfo, VestingSchedule } from '@polkadot/types/interfaces';
|
||||
import type { Observable } from '@polkadot/x-rxjs';
|
||||
import type { DeriveBalancesAccount, DeriveBalancesAll } from '../types';
|
||||
import type { DeriveBalancesAccount, DeriveBalancesAccountData, DeriveBalancesAll, DeriveBalancesAllAccountData } from '../types';
|
||||
|
||||
import BN from 'bn.js';
|
||||
|
||||
@@ -15,7 +15,9 @@ import { map, switchMap } from '@polkadot/x-rxjs/operators';
|
||||
|
||||
import { memo } from '../util';
|
||||
|
||||
type ResultBalance = [VestingInfo | null, (BalanceLock | BalanceLockTo212)[]];
|
||||
type BalanceLocksEntry = Vec<BalanceLock | BalanceLockTo212>;
|
||||
type BalanceLocks = BalanceLocksEntry[];
|
||||
type ResultBalance = [VestingInfo | null, ((BalanceLock | BalanceLockTo212)[])[]];
|
||||
type Result = [DeriveBalancesAccount, BlockNumber, ResultBalance];
|
||||
|
||||
interface AllLocked {
|
||||
@@ -25,6 +27,12 @@ interface AllLocked {
|
||||
vestingLocked: Balance
|
||||
}
|
||||
|
||||
type DeriveCustomLocks = ApiInterfaceRx['derive'] & {
|
||||
[custom: string]: {
|
||||
customLocks?: ApiInterfaceRx['query']['balances']['locks']
|
||||
}
|
||||
}
|
||||
|
||||
const VESTING_ID = '0x76657374696e6720';
|
||||
|
||||
function calcLocked (api: ApiInterfaceRx, bestNumber: BlockNumber, locks: (BalanceLock | BalanceLockTo212)[]): AllLocked {
|
||||
@@ -50,8 +58,20 @@ function calcLocked (api: ApiInterfaceRx, bestNumber: BlockNumber, locks: (Balan
|
||||
return { allLocked, lockedBalance, lockedBreakdown, vestingLocked };
|
||||
}
|
||||
|
||||
function calcBalances (api: ApiInterfaceRx, [{ accountId, accountNonce, freeBalance, frozenFee, frozenMisc, reservedBalance, votingBalance }, bestNumber, [vesting, locks]]: Result): DeriveBalancesAll {
|
||||
function calcShared (api: ApiInterfaceRx, bestNumber: BlockNumber, data: DeriveBalancesAccountData, locks: (BalanceLock | BalanceLockTo212)[]): DeriveBalancesAllAccountData {
|
||||
const { allLocked, lockedBalance, lockedBreakdown, vestingLocked } = calcLocked(api, bestNumber, locks);
|
||||
|
||||
return {
|
||||
...data,
|
||||
availableBalance: api.registry.createType('Balance', allLocked ? 0 : bnMax(new BN(0), data.freeBalance.sub(lockedBalance))),
|
||||
lockedBalance,
|
||||
lockedBreakdown,
|
||||
vestingLocked
|
||||
};
|
||||
}
|
||||
|
||||
function calcBalances (api: ApiInterfaceRx, [data, bestNumber, [vesting, allLocks]]: Result): DeriveBalancesAll {
|
||||
const shared = calcShared(api, bestNumber, data, allLocks[0]);
|
||||
// Calculate the vesting balances,
|
||||
// - offset = balance locked at startingBlock
|
||||
// - perBlock is the unlock amount
|
||||
@@ -59,29 +79,19 @@ function calcBalances (api: ApiInterfaceRx, [{ accountId, accountNonce, freeBala
|
||||
const isStarted = bestNumber.gt(startingBlock);
|
||||
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)));
|
||||
const vestingEndBlock = api.registry.createType('BlockNumber', isVesting ? vestingTotal.div(perBlock).add(startingBlock) : 0);
|
||||
const isVesting = isStarted && !shared.vestingLocked.isZero();
|
||||
|
||||
return {
|
||||
accountId,
|
||||
accountNonce,
|
||||
availableBalance,
|
||||
freeBalance,
|
||||
frozenFee,
|
||||
frozenMisc,
|
||||
...shared,
|
||||
accountId: data.accountId,
|
||||
accountNonce: data.accountNonce,
|
||||
additional: allLocks.filter((_, index) => index !== 0).map((l, index) => calcShared(api, bestNumber, data.additional[index], l)),
|
||||
isVesting,
|
||||
lockedBalance,
|
||||
lockedBreakdown,
|
||||
reservedBalance,
|
||||
vestedBalance,
|
||||
vestedClaimable,
|
||||
vestingEndBlock,
|
||||
vestingLocked,
|
||||
vestedClaimable: api.registry.createType('Balance', isVesting ? shared.vestingLocked.sub(vestingTotal.sub(vestedBalance)) : 0),
|
||||
vestingEndBlock: api.registry.createType('BlockNumber', isVesting ? vestingTotal.div(perBlock).add(startingBlock) : 0),
|
||||
vestingPerBlock: perBlock,
|
||||
vestingTotal,
|
||||
votingBalance
|
||||
vestingTotal
|
||||
};
|
||||
}
|
||||
|
||||
@@ -100,28 +110,43 @@ function queryOld (api: ApiInterfaceRx, accountId: AccountId): Observable<Result
|
||||
vestingNew = api.registry.createType('VestingInfo', { locked, perBlock, startingBlock });
|
||||
}
|
||||
|
||||
return [vestingNew, locks];
|
||||
return [vestingNew, [locks]];
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
// current (balances vesting)
|
||||
function queryCurrent (api: ApiInterfaceRx, accountId: AccountId): Observable<ResultBalance> {
|
||||
const isNonNullable = <T>(nullable: T): nullable is NonNullable<T> => !!nullable;
|
||||
|
||||
// current (balances, vesting)
|
||||
function queryCurrent (api: ApiInterfaceRx, accountId: AccountId, balanceInstances: string[] = ['balances']): Observable<ResultBalance> {
|
||||
const lockCalls = balanceInstances.map(
|
||||
(m): ApiInterfaceRx['query']['balances']['locks'] | undefined =>
|
||||
(api.derive as DeriveCustomLocks)[m]?.customLocks || api.query[m as 'balances']?.locks
|
||||
);
|
||||
|
||||
const lockEmpty = lockCalls.map((c) => !c);
|
||||
const lockQueries = lockCalls.filter(isNonNullable).map((c): QueryableStorageMultiArg<'rxjs'> => [c, accountId]);
|
||||
|
||||
return (
|
||||
api.query.vesting?.vesting
|
||||
? api.queryMulti<[Vec<BalanceLock>, Option<VestingInfo>]>([
|
||||
[api.query.balances.locks, accountId],
|
||||
[api.query.vesting.vesting, accountId]
|
||||
? api.queryMulti<[Option<VestingInfo>, ...BalanceLocks]>([
|
||||
[api.query.vesting.vesting, accountId],
|
||||
...lockQueries
|
||||
])
|
||||
: api.query.balances.locks(accountId).pipe(
|
||||
map((locks): [Vec<BalanceLock>, Option<VestingInfo>] =>
|
||||
[locks, api.registry.createType('Option<VestingInfo>')]
|
||||
// TODO We need to check module instances here as well, not only the balances module
|
||||
: lockQueries.length
|
||||
? api.queryMulti<[...(Vec<BalanceLock>)[]]>(lockQueries).pipe(
|
||||
map((locks): [Option<VestingInfo>, ...BalanceLocks] =>
|
||||
[api.registry.createType('Option<VestingInfo>'), ...locks]
|
||||
)
|
||||
)
|
||||
)
|
||||
: of([api.registry.createType('Option<VestingInfo>')] as [Option<VestingInfo>])
|
||||
).pipe(
|
||||
map(([locks, optVesting]): ResultBalance =>
|
||||
[optVesting.unwrapOr(null), locks]
|
||||
)
|
||||
map(([optVesting, ...locks]): ResultBalance => {
|
||||
let offset = -1;
|
||||
|
||||
return [optVesting.unwrapOr(null), lockEmpty.map((e) => e ? api.registry.createType('Vec<BalanceLock>') : locks[++offset])];
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
@@ -141,6 +166,8 @@ function queryCurrent (api: ApiInterfaceRx, accountId: AccountId): Observable<Re
|
||||
* ```
|
||||
*/
|
||||
export function all (instanceId: string, api: ApiInterfaceRx): (address: AccountIndex | AccountId | Address | string) => Observable<DeriveBalancesAll> {
|
||||
const balanceInstances = api.registry.getModuleInstances(api.runtimeVersion.specName.toString(), 'balances');
|
||||
|
||||
return memo(instanceId, (address: AccountIndex | AccountId | Address | string): Observable<DeriveBalancesAll> =>
|
||||
api.derive.balances.account(address).pipe(
|
||||
switchMap((account): Observable<Result> =>
|
||||
@@ -148,11 +175,11 @@ export function all (instanceId: string, api: ApiInterfaceRx): (address: Account
|
||||
? combineLatest([
|
||||
of(account),
|
||||
api.derive.chain.bestNumber(),
|
||||
isFunction(api.query.system.account) || isFunction(api.query.balances.account)
|
||||
? queryCurrent(api, account.accountId)
|
||||
isFunction(api.query.system?.account) || isFunction(api.query.balances?.account)
|
||||
? queryCurrent(api, account.accountId, balanceInstances)
|
||||
: queryOld(api, account.accountId)
|
||||
])
|
||||
: of([account, api.registry.createType('BlockNumber'), [null, api.registry.createType('Vec<BalanceLock>')]])
|
||||
: of([account, api.registry.createType('BlockNumber'), [null, []]])
|
||||
)
|
||||
),
|
||||
map((result): DeriveBalancesAll => calcBalances(api, result))
|
||||
|
||||
@@ -23,7 +23,7 @@ describe('bounties derive', () => {
|
||||
let storageKey: (index: number) => StorageKey;
|
||||
let defaultBounty: () => Bounty;
|
||||
let emptyOption: <T extends Codec> (typeName: keyof InterfaceTypes) => Option<T>;
|
||||
let optionOf: <T extends Codec> (value: T)=> Option<T>;
|
||||
let optionOf: <T extends Codec> (value: T) => Option<T>;
|
||||
let bountyIndex: (index: number) => BountyIndex;
|
||||
let proposalIndex: (index: number) => ProposalIndex;
|
||||
let bytes: (value: string) => Bytes;
|
||||
@@ -59,7 +59,7 @@ describe('bounties derive', () => {
|
||||
bountyDescriptions: {
|
||||
multi: () => of([
|
||||
optionOf(bytes('make polkadot even better')),
|
||||
optionOf(bytes('this will be totally ignored'))
|
||||
optionOf(bytes('some other bounty'))
|
||||
])
|
||||
}
|
||||
}
|
||||
@@ -117,6 +117,28 @@ describe('bounties derive', () => {
|
||||
expect(result[1].proposals).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('when no council, returns bounties without motions', async () => {
|
||||
const mockApi = {
|
||||
...defaultMockApi,
|
||||
query: {
|
||||
...defaultMockApi.query,
|
||||
council: null
|
||||
}
|
||||
} as unknown as ApiInterfaceRx;
|
||||
|
||||
const result = await bounties('', mockApi)().toPromise();
|
||||
|
||||
expect(result).toHaveLength(2);
|
||||
expect(result[0].bounty.proposer.toString()).toEqual(DEFAULT_PROPOSER);
|
||||
expect(result[0].description).toEqual('make polkadot even better');
|
||||
expect(result[0].index.eq(0)).toBe(true);
|
||||
expect(result[0].proposals).toHaveLength(0);
|
||||
expect(result[1].bounty.proposer.toString()).toEqual(DEFAULT_PROPOSER);
|
||||
expect(result[1].description).toEqual('some other bounty');
|
||||
expect(result[1].index.eq(1)).toBe(true);
|
||||
expect(result[1].proposals).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('combines bounties with motions', async () => {
|
||||
const mockApi = {
|
||||
...defaultMockApi,
|
||||
|
||||
@@ -32,21 +32,25 @@ function parseResult ([maybeBounties, maybeDescriptions, ids, bountyProposals]:
|
||||
}
|
||||
|
||||
export function bounties (instanceId: string, api: ApiInterfaceRx): () => Observable<DeriveBounties> {
|
||||
const bountyBase = api.query.bounties ? api.query.bounties : api.query.treasury;
|
||||
const bountyBase = api.query.bounties || api.query.treasury;
|
||||
|
||||
return memo(instanceId, (): Observable<DeriveBounties> =>
|
||||
combineLatest([
|
||||
bountyBase.bountyCount<BountyIndex>(),
|
||||
api.query.council.proposalCount<ProposalIndex>()
|
||||
api.query.council
|
||||
? api.query.council.proposalCount<ProposalIndex>()
|
||||
: of(0)
|
||||
]).pipe(
|
||||
switchMap(() =>
|
||||
combineLatest([
|
||||
bountyBase.bounties.keys(),
|
||||
api.derive.council.proposals()
|
||||
bountyBase.bounties.keys<[BountyIndex]>(),
|
||||
api.derive.council
|
||||
? api.derive.council.proposals()
|
||||
: of([])
|
||||
])
|
||||
),
|
||||
switchMap(([keys, proposals]): Observable<Result> => {
|
||||
const ids = keys.map(({ args: [id] }) => id as BountyIndex);
|
||||
const ids = keys.map(({ args: [id] }) => id);
|
||||
|
||||
return combineLatest([
|
||||
bountyBase.bounties.multi<Option<Bounty>>(ids),
|
||||
|
||||
@@ -3,11 +3,12 @@
|
||||
|
||||
import type { ApiInterfaceRx } from '@polkadot/api/types';
|
||||
import type { Observable } from '@polkadot/x-rxjs';
|
||||
import type { SignedBlockExtended } from '../type/types';
|
||||
|
||||
import { combineLatest, of } from '@polkadot/x-rxjs';
|
||||
import { catchError, map } from '@polkadot/x-rxjs/operators';
|
||||
|
||||
import { SignedBlockExtended } from '../type';
|
||||
import { createSignedBlockExtended } from '../type';
|
||||
import { memo } from '../util';
|
||||
|
||||
/**
|
||||
@@ -33,7 +34,7 @@ export function getBlock (instanceId: string, api: ApiInterfaceRx): (hash: Uint8
|
||||
: of([])
|
||||
]).pipe(
|
||||
map(([signedBlock, events, validators]): SignedBlockExtended =>
|
||||
new SignedBlockExtended(api.registry, signedBlock, events, validators)
|
||||
createSignedBlockExtended(api.registry, signedBlock, events, validators)
|
||||
),
|
||||
catchError((): Observable<undefined> =>
|
||||
// where rpc.chain.getHeader throws, we will land here - it can happen that
|
||||
|
||||
@@ -3,11 +3,12 @@
|
||||
|
||||
import type { ApiInterfaceRx } from '@polkadot/api/types';
|
||||
import type { Observable } from '@polkadot/x-rxjs';
|
||||
import type { HeaderExtended } from '../type/types';
|
||||
|
||||
import { combineLatest, of } from '@polkadot/x-rxjs';
|
||||
import { catchError, map } from '@polkadot/x-rxjs/operators';
|
||||
|
||||
import { HeaderExtended } from '../type';
|
||||
import { createHeaderExtended } from '../type';
|
||||
import { memo } from '../util';
|
||||
|
||||
/**
|
||||
@@ -33,7 +34,7 @@ export function getHeader (instanceId: string, api: ApiInterfaceRx): (hash: Uint
|
||||
: of([])
|
||||
]).pipe(
|
||||
map(([header, validators]): HeaderExtended =>
|
||||
new HeaderExtended(api.registry, header, validators)
|
||||
createHeaderExtended(header.registry, header, validators)
|
||||
),
|
||||
catchError((): Observable<undefined> =>
|
||||
// where rpc.chain.getHeader throws, we will land here - it can happen that
|
||||
|
||||
@@ -2,13 +2,15 @@
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import type { ApiInterfaceRx } from '@polkadot/api/types';
|
||||
import type { AccountId, EventRecord, SignedBlock } from '@polkadot/types/interfaces';
|
||||
import type { Vec } from '@polkadot/types';
|
||||
import type { EventRecord, SignedBlock } from '@polkadot/types/interfaces';
|
||||
import type { Observable } from '@polkadot/x-rxjs';
|
||||
import type { HeaderExtended, SignedBlockExtended } from '../type/types';
|
||||
|
||||
import { combineLatest, of } from '@polkadot/x-rxjs';
|
||||
import { map, switchMap } from '@polkadot/x-rxjs/operators';
|
||||
|
||||
import { SignedBlockExtended } from '../type';
|
||||
import { createSignedBlockExtended } from '../type';
|
||||
import { memo } from '../util';
|
||||
|
||||
/**
|
||||
@@ -18,17 +20,17 @@ import { memo } from '../util';
|
||||
export function subscribeNewBlocks (instanceId: string, api: ApiInterfaceRx): () => Observable<SignedBlockExtended> {
|
||||
return memo(instanceId, (): Observable<SignedBlockExtended> =>
|
||||
api.derive.chain.subscribeNewHeads().pipe(
|
||||
switchMap((header): Observable<[SignedBlock, EventRecord[], AccountId[] | undefined]> => {
|
||||
const blockHash = header.hash;
|
||||
switchMap((header): Observable<[SignedBlock, Vec<EventRecord>, HeaderExtended]> => {
|
||||
const blockHash = header.createdAtHash || header.hash;
|
||||
|
||||
return combineLatest(
|
||||
api.rpc.chain.getBlock(blockHash),
|
||||
api.query.system.events.at(blockHash),
|
||||
of(header.validators)
|
||||
of(header)
|
||||
);
|
||||
}),
|
||||
map(([block, events, validators]) =>
|
||||
new SignedBlockExtended(api.registry, block, events, validators)
|
||||
map(([block, events, header]) =>
|
||||
createSignedBlockExtended(block.registry, block, events, header.validators)
|
||||
)
|
||||
)
|
||||
);
|
||||
|
||||
@@ -3,11 +3,12 @@
|
||||
|
||||
import type { ApiInterfaceRx } from '@polkadot/api/types';
|
||||
import type { Observable } from '@polkadot/x-rxjs';
|
||||
import type { HeaderExtended } from '../type/types';
|
||||
|
||||
import { combineLatest, of } from '@polkadot/x-rxjs';
|
||||
import { map } from '@polkadot/x-rxjs/operators';
|
||||
|
||||
import { HeaderExtended } from '../type';
|
||||
import { createHeaderExtended } from '../type';
|
||||
import { memo } from '../util';
|
||||
|
||||
/**
|
||||
@@ -29,10 +30,13 @@ export function subscribeNewHeads (instanceId: string, api: ApiInterfaceRx): ()
|
||||
api.rpc.chain.subscribeNewHeads(),
|
||||
api.query.session
|
||||
? api.query.session.validators()
|
||||
: of([])
|
||||
: of(undefined)
|
||||
]).pipe(
|
||||
map(([header, validators]): HeaderExtended =>
|
||||
new HeaderExtended(api.registry, header, validators)
|
||||
)
|
||||
));
|
||||
map(([header, validators]): HeaderExtended => {
|
||||
header.createdAtHash = header.hash;
|
||||
|
||||
return createHeaderExtended(header.registry, header, validators);
|
||||
})
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -13,6 +13,8 @@ import { catchError, map, switchMap } from '@polkadot/x-rxjs/operators';
|
||||
|
||||
import { memo } from '../util';
|
||||
|
||||
type Collective = 'council' | 'membership' | 'technicalCommittee';
|
||||
|
||||
type Result = [(Hash | Uint8Array | string)[], (Option<Proposal> | null)[], Option<Votes>[]];
|
||||
|
||||
function parse (api: ApiInterfaceRx, [hashes, proposals, votes]: Result): DeriveCollectiveProposal[] {
|
||||
@@ -29,7 +31,7 @@ function parse (api: ApiInterfaceRx, [hashes, proposals, votes]: Result): Derive
|
||||
.filter((proposal): proposal is DeriveCollectiveProposal => !!proposal);
|
||||
}
|
||||
|
||||
function _proposalsFrom (instanceId: string, api: ApiInterfaceRx, section: 'council' | 'technicalCommittee' = 'council'): (hashes: (Hash | Uint8Array | string)[]) => Observable<DeriveCollectiveProposal[]> {
|
||||
function _proposalsFrom (instanceId: string, api: ApiInterfaceRx, section: Collective): (hashes: (Hash | Uint8Array | string)[]) => Observable<DeriveCollectiveProposal[]> {
|
||||
return memo(instanceId, (hashes: (Hash | Uint8Array | string)[]): Observable<DeriveCollectiveProposal[]> =>
|
||||
(isFunction(api.query[section]?.proposals) && hashes.length
|
||||
? combineLatest<Result>([
|
||||
@@ -49,19 +51,19 @@ function _proposalsFrom (instanceId: string, api: ApiInterfaceRx, section: 'coun
|
||||
);
|
||||
}
|
||||
|
||||
export function proposals (instanceId: string, api: ApiInterfaceRx, section: 'council' | 'technicalCommittee' = 'council'): () => Observable<DeriveCollectiveProposal[]> {
|
||||
export function proposals (instanceId: string, api: ApiInterfaceRx, section: Collective): () => Observable<DeriveCollectiveProposal[]> {
|
||||
const proposalsFrom = _proposalsFrom(instanceId, api, section);
|
||||
|
||||
return memo(instanceId, (): Observable<DeriveCollectiveProposal[]> =>
|
||||
isFunction(api.query[section]?.proposals)
|
||||
? api.query[section].proposals().pipe(
|
||||
? api.query[section as 'council'].proposals().pipe(
|
||||
switchMap(proposalsFrom)
|
||||
)
|
||||
: of([] as DeriveCollectiveProposal[])
|
||||
);
|
||||
}
|
||||
|
||||
export function proposal (instanceId: string, api: ApiInterfaceRx, section: 'council' | 'technicalCommittee' = 'council'): (hash: Hash | Uint8Array | string) => Observable<DeriveCollectiveProposal | null> {
|
||||
export function proposal (instanceId: string, api: ApiInterfaceRx, section: Collective): (hash: Hash | Uint8Array | string) => Observable<DeriveCollectiveProposal | null> {
|
||||
const proposalsFrom = _proposalsFrom(instanceId, api, section);
|
||||
|
||||
return memo(instanceId, (hash: Hash | Uint8Array | string): Observable<DeriveCollectiveProposal | null> =>
|
||||
|
||||
@@ -10,9 +10,9 @@ import { proposal as collectiveProposal, proposals as collectiveProposals } from
|
||||
import { memo } from '../util';
|
||||
|
||||
export function proposal (instanceId: string, api: ApiInterfaceRx): (hash: Hash | Uint8Array | string) => Observable<DeriveCollectiveProposal | null> {
|
||||
return memo(instanceId, collectiveProposal(instanceId, api));
|
||||
return memo(instanceId, collectiveProposal(instanceId, api, 'council'));
|
||||
}
|
||||
|
||||
export function proposals (instanceId: string, api: ApiInterfaceRx): () => Observable<DeriveCollectiveProposal[]> {
|
||||
return memo(instanceId, collectiveProposals(instanceId, api));
|
||||
return memo(instanceId, collectiveProposals(instanceId, api, 'council'));
|
||||
}
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
|
||||
import type { ApiInterfaceRx } from '@polkadot/api/types';
|
||||
import type { Vec } from '@polkadot/types';
|
||||
import type { AccountId, Balance } from '@polkadot/types/interfaces';
|
||||
import type { AccountId, Balance, Voter } from '@polkadot/types/interfaces';
|
||||
import type { ITuple } from '@polkadot/types/types';
|
||||
import type { Observable } from '@polkadot/x-rxjs';
|
||||
import type { DeriveCouncilVote, DeriveCouncilVotes } from '../types';
|
||||
@@ -13,18 +13,25 @@ import { map } from '@polkadot/x-rxjs/operators';
|
||||
|
||||
import { memo } from '../util';
|
||||
|
||||
// Voter is current tuple is 2.x-era
|
||||
type VoteEntry = Voter | ITuple<[Balance, Vec<AccountId>]>;
|
||||
|
||||
function isVoter (value: VoteEntry): value is Voter {
|
||||
return !Array.isArray(value);
|
||||
}
|
||||
|
||||
function retrieveStakeOf (api: ApiInterfaceRx): Observable<[AccountId, Balance][]> {
|
||||
return (api.query.electionsPhragmen || api.query.elections).stakeOf.entries<Balance>().pipe(
|
||||
return (api.query.electionsPhragmen || api.query.elections).stakeOf.entries<Balance, [AccountId]>().pipe(
|
||||
map((entries) =>
|
||||
entries.map(([key, stake]) => [key.args[0] as AccountId, stake])
|
||||
entries.map(([{ args: [accountId] }, stake]) => [accountId, stake])
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
function retrieveVoteOf (api: ApiInterfaceRx): Observable<[AccountId, AccountId[]][]> {
|
||||
return (api.query.electionsPhragmen || api.query.elections).votesOf.entries<Vec<AccountId>>().pipe(
|
||||
return (api.query.electionsPhragmen || api.query.elections).votesOf.entries<Vec<AccountId>, [AccountId]>().pipe(
|
||||
map((entries) =>
|
||||
entries.map(([key, votes]) => [key.args[0] as AccountId, votes])
|
||||
entries.map(([{ args: [accountId] }, votes]) => [accountId, votes])
|
||||
)
|
||||
);
|
||||
}
|
||||
@@ -56,11 +63,14 @@ function retrievePrev (api: ApiInterfaceRx): Observable<DeriveCouncilVotes> {
|
||||
function retrieveCurrent (api: ApiInterfaceRx): Observable<DeriveCouncilVotes> {
|
||||
const elections = (api.query.electionsPhragmen || api.query.elections);
|
||||
|
||||
return elections.voting.entries<ITuple<[Balance, Vec<AccountId>]>>().pipe(
|
||||
return elections.voting.entries<VoteEntry, [AccountId]>().pipe(
|
||||
map((entries): DeriveCouncilVotes =>
|
||||
entries.map(([key, [stake, votes]]): [AccountId, DeriveCouncilVote] =>
|
||||
[key.args[0] as AccountId, { stake, votes }]
|
||||
)
|
||||
entries.map(([{ args: [accountId] }, value]): [AccountId, DeriveCouncilVote] => [
|
||||
accountId,
|
||||
isVoter(value)
|
||||
? { stake: value.stake, votes: value.votes }
|
||||
: { stake: value[0], votes: value[1] }
|
||||
])
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -51,7 +51,7 @@ function schedulerEntries (api: ApiInterfaceRx): Observable<[BlockNumber[], Opti
|
||||
api.query.scheduler.agenda.keys()
|
||||
),
|
||||
switchMap((keys) => {
|
||||
const blockNumbers = keys.map((key) => key.args[0] as BlockNumber);
|
||||
const blockNumbers = keys.map(({ args: [blockNumber] }) => blockNumber);
|
||||
|
||||
return combineLatest([
|
||||
of(blockNumbers),
|
||||
|
||||
@@ -51,7 +51,7 @@ function parse ([proposals, images, optDepositors]: Result): DeriveProposal[] {
|
||||
|
||||
export function proposals (instanceId: string, api: ApiInterfaceRx): () => Observable<DeriveProposal[]> {
|
||||
return memo(instanceId, (): Observable<DeriveProposal[]> =>
|
||||
api.query.democracy?.publicProps && api.query.democracy?.preimages
|
||||
isFunction(api.query.democracy?.publicProps) && isFunction(api.query.democracy?.preimages)
|
||||
? api.query.democracy.publicProps<Proposals>().pipe(
|
||||
switchMap((proposals) =>
|
||||
combineLatest([
|
||||
|
||||
@@ -67,9 +67,9 @@ function extractVotes (mapped: [AccountId, Voting][], referendumId: BN): DeriveR
|
||||
}
|
||||
|
||||
function votesCurr (api: ApiInterfaceRx, referendumId: BN): Observable<DeriveReferendumVote[]> {
|
||||
return api.query.democracy.votingOf.entries<Voting>().pipe(
|
||||
return api.query.democracy.votingOf.entries<Voting, [AccountId]>().pipe(
|
||||
map((allVoting): DeriveReferendumVote[] => {
|
||||
const mapped = allVoting.map(([key, voting]): [AccountId, Voting] => [key.args[0] as AccountId, voting]);
|
||||
const mapped = allVoting.map(([{ args: [accountId] }, voting]): [AccountId, Voting] => [accountId, voting]);
|
||||
const votes = extractVotes(mapped, referendumId);
|
||||
const delegations = mapped
|
||||
.filter(([, voting]) => voting.isDelegating)
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
// Copyright 2017-2021 @polkadot/api-derive authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import { packageInfo as apiInfo } from '@polkadot/api/packageInfo';
|
||||
import { packageInfo as coreInfo } from '@polkadot/rpc-core/packageInfo';
|
||||
import { packageInfo as typesInfo } from '@polkadot/types/packageInfo';
|
||||
import { detectPackage } from '@polkadot/util';
|
||||
|
||||
import { packageInfo } from './packageInfo';
|
||||
|
||||
detectPackage(packageInfo, typeof __dirname !== 'undefined' && __dirname, [apiInfo, coreInfo, typesInfo]);
|
||||
@@ -3,7 +3,7 @@
|
||||
|
||||
import type { ApiInterfaceRx } from '@polkadot/api/types';
|
||||
import type { u32, Vec } from '@polkadot/types';
|
||||
import type { AccountId, Balance, BlockNumber } from '@polkadot/types/interfaces';
|
||||
import type { AccountId, Balance, BlockNumber, SeatHolder } from '@polkadot/types/interfaces';
|
||||
import type { ITuple } from '@polkadot/types/types';
|
||||
import type { Observable } from '@polkadot/x-rxjs';
|
||||
import type { DeriveElectionsInfo } from './types';
|
||||
@@ -12,14 +12,39 @@ import { map } from '@polkadot/x-rxjs/operators';
|
||||
|
||||
import { memo } from '../util';
|
||||
|
||||
function sortAccounts ([, balanceA]: ITuple<[AccountId, Balance]>, [, balanceB]: ITuple<[AccountId, Balance]>): number {
|
||||
// SeatHolder is current tuple is 2.x-era Substrate
|
||||
type Member = SeatHolder | ITuple<[AccountId, Balance]>;
|
||||
|
||||
type Candidate = AccountId | ITuple<[AccountId, Balance]>;
|
||||
|
||||
function isSeatHolder (value: Member): value is SeatHolder {
|
||||
return !Array.isArray(value);
|
||||
}
|
||||
|
||||
function isCandidateTuple (value: Candidate): value is ITuple<[AccountId, Balance]> {
|
||||
return Array.isArray(value);
|
||||
}
|
||||
|
||||
function getAccountTuple (value: Member): [AccountId, Balance] {
|
||||
return isSeatHolder(value)
|
||||
? [value.who, value.stake]
|
||||
: value;
|
||||
}
|
||||
|
||||
function getCandidate (value: Candidate): AccountId {
|
||||
return isCandidateTuple(value)
|
||||
? value[0]
|
||||
: value;
|
||||
}
|
||||
|
||||
function sortAccounts ([, balanceA]: [AccountId, Balance], [, balanceB]: [AccountId, Balance]): number {
|
||||
return balanceB.cmp(balanceA);
|
||||
}
|
||||
|
||||
function queryElections (api: ApiInterfaceRx): Observable<DeriveElectionsInfo> {
|
||||
const section = api.query.electionsPhragmen ? 'electionsPhragmen' : 'elections';
|
||||
|
||||
return api.queryMulti<[Vec<AccountId>, Vec<AccountId>, Vec<ITuple<[AccountId, Balance]>>, Vec<ITuple<[AccountId, Balance]>>]>([
|
||||
return api.queryMulti<[Vec<AccountId>, Vec<Candidate>, Vec<Member>, Vec<Member>]>([
|
||||
api.query.council.members,
|
||||
api.query[section].candidates,
|
||||
api.query[section].members,
|
||||
@@ -28,13 +53,13 @@ function queryElections (api: ApiInterfaceRx): Observable<DeriveElectionsInfo> {
|
||||
map(([councilMembers, candidates, members, runnersUp]): DeriveElectionsInfo => ({
|
||||
candidacyBond: api.consts[section].candidacyBond as Balance,
|
||||
candidateCount: api.registry.createType('u32', candidates.length),
|
||||
candidates,
|
||||
candidates: candidates.map(getCandidate),
|
||||
desiredRunnersUp: api.consts[section].desiredRunnersUp as u32,
|
||||
desiredSeats: api.consts[section].desiredMembers as u32,
|
||||
members: members.length
|
||||
? members.sort(sortAccounts)
|
||||
? members.map(getAccountTuple).sort(sortAccounts)
|
||||
: councilMembers.map((accountId): [AccountId, Balance] => [accountId, api.registry.createType('Balance')]),
|
||||
runnersUp: runnersUp.sort(sortAccounts),
|
||||
runnersUp: runnersUp.map(getAccountTuple).sort(sortAccounts),
|
||||
termDuration: api.consts[section].termDuration as BlockNumber,
|
||||
votingBond: api.consts[section].votingBond as Balance
|
||||
}))
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
// Copyright 2017-2021 @polkadot/api-derive authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import './detectPackage';
|
||||
|
||||
import type { ApiInterfaceRx } from '@polkadot/api/types';
|
||||
import type { AnyFunction } from '@polkadot/types/types';
|
||||
import type { Observable } from '@polkadot/x-rxjs';
|
||||
@@ -14,6 +16,7 @@ import * as council from './council';
|
||||
import * as democracy from './democracy';
|
||||
import * as elections from './elections';
|
||||
import * as imOnline from './imOnline';
|
||||
import * as membership from './membership';
|
||||
import * as parachains from './parachains';
|
||||
import * as session from './session';
|
||||
import * as society from './society';
|
||||
@@ -22,9 +25,10 @@ import * as technicalCommittee from './technicalCommittee';
|
||||
import * as treasury from './treasury';
|
||||
import * as tx from './tx';
|
||||
|
||||
export { packageInfo } from './packageInfo';
|
||||
export * from './type';
|
||||
|
||||
export const derive = { accounts, balances, bounties, chain, contracts, council, democracy, elections, imOnline, parachains, session, society, staking, technicalCommittee, treasury, tx };
|
||||
export const derive = { accounts, balances, bounties, chain, contracts, council, democracy, elections, imOnline, membership, parachains, session, society, staking, technicalCommittee, treasury, tx };
|
||||
|
||||
type DeriveSection<Section> = {
|
||||
[Method in keyof Section]: Section[Method] extends AnyFunction
|
||||
@@ -46,6 +50,7 @@ const deriveAvail: Record<string, string[]> = {
|
||||
democracy: ['democracy'],
|
||||
elections: ['electionsPhragmen', 'elections'],
|
||||
imOnline: ['imOnline'],
|
||||
membership: ['membership'],
|
||||
parachains: ['parachains', 'registrar'],
|
||||
session: ['session'],
|
||||
society: ['society'],
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
// Copyright 2017-2021 @polkadot/api-derive authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
export * from './proposals';
|
||||
@@ -0,0 +1,13 @@
|
||||
// Copyright 2017-2021 @polkadot/api-derive authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import type { ApiInterfaceRx } from '@polkadot/api/types';
|
||||
import type { Observable } from '@polkadot/x-rxjs';
|
||||
import type { DeriveCollectiveProposal } from '../types';
|
||||
|
||||
import { proposals as collectiveProposals } from '../collective';
|
||||
import { memo } from '../util';
|
||||
|
||||
export function proposals (instanceId: string, api: ApiInterfaceRx): () => Observable<DeriveCollectiveProposal[]> {
|
||||
return memo(instanceId, collectiveProposals(instanceId, api, 'membership'));
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
// Copyright 2017-2021 @polkadot/api-derive authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
// Auto-generated by @polkadot/dev, do not edit
|
||||
|
||||
export const packageInfo = { name: '@polkadot/api-derive', version: '4.8.1' };
|
||||
@@ -13,7 +13,7 @@ import { map } from '@polkadot/x-rxjs/operators';
|
||||
import { memo } from '../util';
|
||||
|
||||
// parse into Indexes
|
||||
function parse ([activeEra, activeEraStart, currentEra, currentIndex, validatorCount]: [EraIndex, Option<Moment>, EraIndex, SessionIndex, u32]): DeriveSessionIndexes {
|
||||
function parse ([currentIndex, activeEra, activeEraStart, currentEra, validatorCount]: [SessionIndex, EraIndex, Option<Moment>, EraIndex, u32]): DeriveSessionIndexes {
|
||||
return {
|
||||
activeEra,
|
||||
activeEraStart,
|
||||
@@ -24,42 +24,57 @@ function parse ([activeEra, activeEraStart, currentEra, currentIndex, validatorC
|
||||
}
|
||||
|
||||
// query based on latest
|
||||
function query (api: ApiInterfaceRx): Observable<DeriveSessionIndexes> {
|
||||
return api.queryMulti<[Option<ActiveEraInfo>, Option<EraIndex>, SessionIndex, u32]>([
|
||||
function queryStaking (api: ApiInterfaceRx): Observable<DeriveSessionIndexes> {
|
||||
return api.queryMulti<[SessionIndex, Option<ActiveEraInfo>, Option<EraIndex>, u32]>([
|
||||
api.query.session.currentIndex,
|
||||
api.query.staking.activeEra,
|
||||
api.query.staking.currentEra,
|
||||
api.query.session.currentIndex,
|
||||
api.query.staking.validatorCount
|
||||
]).pipe(
|
||||
map(([activeOpt, currentEra, currentIndex, validatorCount]): DeriveSessionIndexes => {
|
||||
map(([currentIndex, activeOpt, currentEra, validatorCount]): DeriveSessionIndexes => {
|
||||
const { index, start } = activeOpt.unwrapOrDefault();
|
||||
|
||||
return parse([
|
||||
currentIndex,
|
||||
index,
|
||||
start,
|
||||
currentEra.unwrapOrDefault(),
|
||||
currentIndex,
|
||||
validatorCount
|
||||
]);
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
// query based on latest
|
||||
function querySession (api: ApiInterfaceRx): Observable<DeriveSessionIndexes> {
|
||||
return api.query.session.currentIndex().pipe(
|
||||
map((currentIndex): DeriveSessionIndexes => parse([
|
||||
currentIndex,
|
||||
api.registry.createType('EraIndex'),
|
||||
api.registry.createType('Option<Moment>'),
|
||||
api.registry.createType('EraIndex'),
|
||||
api.registry.createType('u32')
|
||||
]))
|
||||
);
|
||||
}
|
||||
|
||||
// empty set when none is available
|
||||
function empty (api: ApiInterfaceRx): Observable<DeriveSessionIndexes> {
|
||||
return of(parse([
|
||||
api.registry.createType('SessionIndex', 1),
|
||||
api.registry.createType('EraIndex'),
|
||||
api.registry.createType('Option<Moment>'),
|
||||
api.registry.createType('EraIndex'),
|
||||
api.registry.createType('SessionIndex', 1),
|
||||
api.registry.createType('u32')
|
||||
]));
|
||||
}
|
||||
|
||||
export function indexes (instanceId: string, api: ApiInterfaceRx): () => Observable<DeriveSessionIndexes> {
|
||||
return memo(instanceId, (): Observable<DeriveSessionIndexes> =>
|
||||
api.query.session && api.query.staking
|
||||
? query(api)
|
||||
api.query.session
|
||||
? api.query.staking
|
||||
? queryStaking(api)
|
||||
: querySession(api)
|
||||
: empty(api)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -2,69 +2,31 @@
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import type { ApiInterfaceRx } from '@polkadot/api/types';
|
||||
import type { u64 } from '@polkadot/types';
|
||||
import type { SessionIndex } from '@polkadot/types/interfaces';
|
||||
import type { Observable } from '@polkadot/x-rxjs';
|
||||
import type { DeriveSessionIndexes, DeriveSessionInfo } from '../types';
|
||||
import type { DeriveSessionInfo } from '../types';
|
||||
|
||||
import { map } from '@polkadot/x-rxjs/operators';
|
||||
|
||||
import { memo } from '../util';
|
||||
|
||||
type ResultType = [boolean, u64, SessionIndex];
|
||||
type Result = [ResultType, DeriveSessionIndexes];
|
||||
|
||||
function createDerive (api: ApiInterfaceRx, [[hasBabe, epochDuration, sessionsPerEra], { activeEra, activeEraStart, currentEra, currentIndex, validatorCount }]: Result): DeriveSessionInfo {
|
||||
return {
|
||||
activeEra,
|
||||
activeEraStart,
|
||||
currentEra,
|
||||
currentIndex,
|
||||
eraLength: api.registry.createType('BlockNumber', sessionsPerEra.mul(epochDuration)),
|
||||
isEpoch: hasBabe,
|
||||
sessionLength: epochDuration,
|
||||
sessionsPerEra,
|
||||
validatorCount
|
||||
};
|
||||
}
|
||||
|
||||
function queryAura (api: ApiInterfaceRx): Observable<DeriveSessionInfo> {
|
||||
return api.derive.session.indexes().pipe(
|
||||
map((indexes): DeriveSessionInfo =>
|
||||
createDerive(api, [
|
||||
[
|
||||
false,
|
||||
api.registry.createType('u64', 1),
|
||||
api.consts.staking?.sessionsPerEra || api.registry.createType('SessionIndex', 1)
|
||||
],
|
||||
indexes
|
||||
])
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
function queryBabe (api: ApiInterfaceRx): Observable<DeriveSessionInfo> {
|
||||
return api.derive.session.indexes().pipe(
|
||||
map((indexes) =>
|
||||
createDerive(api, [
|
||||
[
|
||||
true,
|
||||
api.consts.babe.epochDuration,
|
||||
api.consts.staking.sessionsPerEra
|
||||
],
|
||||
indexes
|
||||
])
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Retrieves all the session and era query and calculates specific values on it as the length of the session and eras
|
||||
*/
|
||||
export function info (instanceId: string, api: ApiInterfaceRx): () => Observable<DeriveSessionInfo> {
|
||||
return memo(instanceId, (): Observable<DeriveSessionInfo> =>
|
||||
api.consts.babe
|
||||
? queryBabe(api)
|
||||
: queryAura(api)
|
||||
api.derive.session.indexes().pipe(
|
||||
map((indexes) => {
|
||||
const sessionLength = api.consts?.babe?.epochDuration || api.registry.createType('u64', 1);
|
||||
const sessionsPerEra = api.consts?.staking?.sessionsPerEra || api.registry.createType('SessionIndex', 1);
|
||||
|
||||
return {
|
||||
...indexes,
|
||||
eraLength: api.registry.createType('BlockNumber', sessionsPerEra.mul(sessionLength)),
|
||||
isEpoch: !!api.query.babe,
|
||||
sessionLength,
|
||||
sessionsPerEra
|
||||
};
|
||||
})
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -12,6 +12,7 @@ import { map, switchMap } from '@polkadot/x-rxjs/operators';
|
||||
|
||||
import { memo } from '../util';
|
||||
|
||||
type ResultSlotsNoSession = [u64, u64, u64];
|
||||
type ResultSlots = [u64, u64, u64, Option<SessionIndex>];
|
||||
type ResultSlotsFlat = [u64, u64, u64, SessionIndex];
|
||||
|
||||
@@ -39,19 +40,26 @@ function queryAura (api: ApiInterfaceRx): Observable<DeriveSessionProgress> {
|
||||
|
||||
function queryBabe (api: ApiInterfaceRx): Observable<[DeriveSessionInfo, ResultSlotsFlat]> {
|
||||
return api.derive.session.info().pipe(
|
||||
switchMap((info): Observable<[DeriveSessionInfo, ResultSlots]> =>
|
||||
switchMap((info): Observable<[DeriveSessionInfo, ResultSlots | ResultSlotsNoSession]> =>
|
||||
combineLatest([
|
||||
of(info),
|
||||
api.queryMulti<ResultSlots>([
|
||||
api.query.babe.currentSlot,
|
||||
api.query.babe.epochIndex,
|
||||
api.query.babe.genesisSlot,
|
||||
[api.query.staking.erasStartSessionIndex, info.activeEra]
|
||||
])
|
||||
// we may have no staking, but have babe (permissioned)
|
||||
api.query.staking?.erasStartSessionIndex
|
||||
? api.queryMulti<ResultSlots>([
|
||||
api.query.babe.currentSlot,
|
||||
api.query.babe.epochIndex,
|
||||
api.query.babe.genesisSlot,
|
||||
[api.query.staking.erasStartSessionIndex, info.activeEra]
|
||||
])
|
||||
: api.queryMulti<ResultSlotsNoSession>([
|
||||
api.query.babe.currentSlot,
|
||||
api.query.babe.epochIndex,
|
||||
api.query.babe.genesisSlot
|
||||
])
|
||||
])
|
||||
),
|
||||
map(([info, [currentSlot, epochIndex, genesisSlot, optStartIndex]]): [DeriveSessionInfo, ResultSlotsFlat] => [
|
||||
info, [currentSlot, epochIndex, genesisSlot, optStartIndex.unwrapOr(api.registry.createType('SessionIndex', 1))]
|
||||
info, [currentSlot, epochIndex, genesisSlot, optStartIndex && optStartIndex.isSome ? optStartIndex.unwrap() : api.registry.createType('SessionIndex', 1)]
|
||||
])
|
||||
);
|
||||
}
|
||||
@@ -61,7 +69,7 @@ function queryBabe (api: ApiInterfaceRx): Observable<[DeriveSessionInfo, ResultS
|
||||
*/
|
||||
export function progress (instanceId: string, api: ApiInterfaceRx): () => Observable<DeriveSessionProgress> {
|
||||
return memo(instanceId, (): Observable<DeriveSessionProgress> =>
|
||||
api.consts.babe
|
||||
api.query.babe
|
||||
? queryBabe(api).pipe(
|
||||
map(([info, slots]: [DeriveSessionInfo, ResultSlotsFlat]): DeriveSessionProgress =>
|
||||
createDerive(api, info, slots)
|
||||
|
||||
@@ -2,9 +2,7 @@
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import type { ApiInterfaceRx } from '@polkadot/api/types';
|
||||
import type { bool, Option, Vec } from '@polkadot/types';
|
||||
import type { AccountId, Balance, BlockNumber, SocietyVote, StrikeCount, VouchingStatus } from '@polkadot/types/interfaces';
|
||||
import type { ITuple } from '@polkadot/types/types';
|
||||
import type { AccountId } from '@polkadot/types/interfaces';
|
||||
import type { Observable } from '@polkadot/x-rxjs';
|
||||
import type { DeriveSocietyMember } from '../types';
|
||||
|
||||
@@ -12,28 +10,13 @@ import { map } from '@polkadot/x-rxjs/operators';
|
||||
|
||||
import { memo } from '../util';
|
||||
|
||||
type Result = [Vec<ITuple<[BlockNumber, Balance]>>, StrikeCount, Option<SocietyVote>, bool, Option<VouchingStatus>];
|
||||
|
||||
/**
|
||||
* @description Get the member info for a society
|
||||
*/
|
||||
export function member (instanceId: string, api: ApiInterfaceRx): (accountId: AccountId) => Observable<DeriveSocietyMember> {
|
||||
return memo(instanceId, (accountId: AccountId): Observable<DeriveSocietyMember> =>
|
||||
api.queryMulti<Result>([
|
||||
[api.query.society.payouts, accountId],
|
||||
[api.query.society.strikes, accountId],
|
||||
[api.query.society.defenderVotes, accountId],
|
||||
[api.query.society.suspendedMembers, accountId],
|
||||
[api.query.society.vouching, accountId]
|
||||
]).pipe(
|
||||
map(([payouts, strikes, defenderVotes, suspended, vouching]: Result): DeriveSocietyMember => ({
|
||||
accountId,
|
||||
isSuspended: suspended.isTrue,
|
||||
payouts,
|
||||
strikes,
|
||||
vote: defenderVotes.unwrapOr(undefined),
|
||||
vouching: vouching.unwrapOr(undefined)
|
||||
}))
|
||||
api.derive.society._members([accountId]).pipe(
|
||||
map(([result]) => result)
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -2,28 +2,51 @@
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import type { ApiInterfaceRx } from '@polkadot/api/types';
|
||||
import type { AccountId } from '@polkadot/types/interfaces';
|
||||
import type { bool, Option, Vec } from '@polkadot/types';
|
||||
import type { AccountId, Balance, BlockNumber, SocietyVote, StrikeCount, VouchingStatus } from '@polkadot/types/interfaces';
|
||||
import type { ITuple } from '@polkadot/types/types';
|
||||
import type { Observable } from '@polkadot/x-rxjs';
|
||||
import type { DeriveSocietyMember } from '../types';
|
||||
|
||||
import { combineLatest } from '@polkadot/x-rxjs';
|
||||
import { switchMap } from '@polkadot/x-rxjs/operators';
|
||||
import { combineLatest, of } from '@polkadot/x-rxjs';
|
||||
import { map, switchMap } from '@polkadot/x-rxjs/operators';
|
||||
|
||||
import { memo } from '../util';
|
||||
|
||||
type Result = [AccountId[], Vec<ITuple<[BlockNumber, Balance]>>[], StrikeCount[], Option<SocietyVote>[], bool[], Option<VouchingStatus>[]];
|
||||
|
||||
export function _members (instanceId: string, api: ApiInterfaceRx): (accountIds: AccountId[]) => Observable<DeriveSocietyMember[]> {
|
||||
return memo(instanceId, (accountIds: AccountId[]): Observable<DeriveSocietyMember[]> =>
|
||||
combineLatest<Result>([
|
||||
of(accountIds),
|
||||
api.query.society.payouts.multi(accountIds),
|
||||
api.query.society.strikes.multi(accountIds),
|
||||
api.query.society.defenderVotes.multi(accountIds),
|
||||
api.query.society.suspendedMembers.multi(accountIds),
|
||||
api.query.society.vouching.multi(accountIds)
|
||||
]).pipe(
|
||||
map(([accountIds, payouts, strikes, defenderVotes, suspended, vouching]) =>
|
||||
accountIds.map((accountId, index) => ({
|
||||
accountId,
|
||||
isDefenderVoter: defenderVotes[index].isSome,
|
||||
isSuspended: suspended[index].isTrue,
|
||||
payouts: payouts[index],
|
||||
strikes: strikes[index],
|
||||
vote: defenderVotes[index].unwrapOr(undefined),
|
||||
vouching: vouching[index].unwrapOr(undefined)
|
||||
}))
|
||||
)
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Get the member info for a society
|
||||
*/
|
||||
export function members (instanceId: string, api: ApiInterfaceRx): () => Observable<DeriveSocietyMember[]> {
|
||||
return memo(instanceId, (): Observable<DeriveSocietyMember[]> =>
|
||||
api.query.society.members<AccountId[]>().pipe(
|
||||
switchMap((members): Observable<DeriveSocietyMember[]> =>
|
||||
combineLatest(
|
||||
members.map((accountId): Observable<DeriveSocietyMember> =>
|
||||
api.derive.society.member(accountId)
|
||||
)
|
||||
)
|
||||
)
|
||||
switchMap((members) => api.derive.society._members(members))
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
|
||||
import type { ApiInterfaceRx } from '@polkadot/api/types';
|
||||
import type { StorageKey } from '@polkadot/types';
|
||||
import type { EraIndex, Exposure } from '@polkadot/types/interfaces';
|
||||
import type { AccountId, EraIndex, Exposure } from '@polkadot/types/interfaces';
|
||||
import type { Observable } from '@polkadot/x-rxjs';
|
||||
import type { DeriveEraExposure, DeriveEraNominatorExposure, DeriveEraValidatorExposure } from '../types';
|
||||
|
||||
@@ -12,7 +12,7 @@ import { map, switchMap } from '@polkadot/x-rxjs/operators';
|
||||
|
||||
import { deriveCache, memo } from '../util';
|
||||
|
||||
type KeysAndExposures = [StorageKey, Exposure][];
|
||||
type KeysAndExposures = [StorageKey<[EraIndex, AccountId]>, Exposure][];
|
||||
|
||||
const CACHE_KEY = 'eraExposure';
|
||||
|
||||
|
||||
@@ -1,55 +1,37 @@
|
||||
// Copyright 2017-2021 @polkadot/api-derive authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import type { ApiInterfaceRx } from '@polkadot/api/types';
|
||||
import type { ApiInterfaceRx, QueryableStorageMultiArg } from '@polkadot/api/types';
|
||||
import type { EraIndex, Exposure } from '@polkadot/types/interfaces';
|
||||
import type { Observable } from '@polkadot/x-rxjs';
|
||||
import type { DeriveOwnExposure } from '../types';
|
||||
|
||||
import { combineLatest, of } from '@polkadot/x-rxjs';
|
||||
import { of } from '@polkadot/x-rxjs';
|
||||
import { map, switchMap } from '@polkadot/x-rxjs/operators';
|
||||
|
||||
import { deriveCache, memo } from '../util';
|
||||
import { memo } from '../util';
|
||||
|
||||
const CACHE_KEY = 'ownExposure';
|
||||
|
||||
export function _ownExposure (instanceId: string, api: ApiInterfaceRx): (accountId: Uint8Array | string, era: EraIndex, withActive: boolean) => Observable<DeriveOwnExposure> {
|
||||
return memo(instanceId, (accountId: Uint8Array | string, era: EraIndex, withActive: boolean): Observable<DeriveOwnExposure> => {
|
||||
const cacheKey = `${CACHE_KEY}-${era.toString()}-${accountId.toString()}`;
|
||||
const cached = withActive
|
||||
? undefined
|
||||
: deriveCache.get<DeriveOwnExposure>(cacheKey);
|
||||
|
||||
return cached
|
||||
? of(cached)
|
||||
: api.queryMulti<[Exposure, Exposure]>([
|
||||
[api.query.staking.erasStakersClipped, [era, accountId]],
|
||||
[api.query.staking.erasStakers, [era, accountId]]
|
||||
export function _ownExposures (instanceId: string, api: ApiInterfaceRx): (accountId: Uint8Array | string, eras: EraIndex[], withActive: boolean) => Observable<DeriveOwnExposure[]> {
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
return memo(instanceId, (accountId: Uint8Array | string, eras: EraIndex[], _withActive: boolean): Observable<DeriveOwnExposure[]> =>
|
||||
eras.length
|
||||
? api.queryMulti<Exposure[]>([
|
||||
...eras.map((era): QueryableStorageMultiArg<'rxjs'> => [api.query.staking.erasStakersClipped, [era, accountId]]),
|
||||
...eras.map((era): QueryableStorageMultiArg<'rxjs'> => [api.query.staking.erasStakers, [era, accountId]])
|
||||
]).pipe(
|
||||
map(([clipped, exposure]): DeriveOwnExposure => {
|
||||
const value = { clipped, era, exposure };
|
||||
|
||||
!withActive && deriveCache.set(cacheKey, value);
|
||||
|
||||
return value;
|
||||
})
|
||||
);
|
||||
});
|
||||
map((all): DeriveOwnExposure[] =>
|
||||
eras.map((era, index) => ({ clipped: all[index], era, exposure: all[eras.length + index] }))
|
||||
)
|
||||
)
|
||||
: of([])
|
||||
);
|
||||
}
|
||||
|
||||
export function ownExposure (instanceId: string, api: ApiInterfaceRx): (accountId: Uint8Array | string, era: EraIndex) => Observable<DeriveOwnExposure> {
|
||||
return memo(instanceId, (accountId: Uint8Array | string, era: EraIndex): Observable<DeriveOwnExposure> =>
|
||||
api.derive.staking._ownExposure(accountId, era, true)
|
||||
);
|
||||
}
|
||||
|
||||
export function _ownExposures (instanceId: string, api: ApiInterfaceRx): (accountId: Uint8Array | string, eras: EraIndex[], withActive: boolean) => Observable<DeriveOwnExposure[]> {
|
||||
return memo(instanceId, (accountId: Uint8Array | string, eras: EraIndex[], withActive: boolean): Observable<DeriveOwnExposure[]> =>
|
||||
eras.length
|
||||
? combineLatest(
|
||||
eras.map((era) => api.derive.staking._ownExposure(accountId, era, withActive))
|
||||
)
|
||||
: of([])
|
||||
api.derive.staking._ownExposures(accountId, [era], true).pipe(
|
||||
map(([first]) => first)
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,62 +1,44 @@
|
||||
// Copyright 2017-2021 @polkadot/api-derive authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import type { ApiInterfaceRx } from '@polkadot/api/types';
|
||||
import type { ApiInterfaceRx, QueryableStorageMultiArg } from '@polkadot/api/types';
|
||||
import type { Option } from '@polkadot/types';
|
||||
import type { BalanceOf, EraIndex, Perbill } from '@polkadot/types/interfaces';
|
||||
import type { ITuple } from '@polkadot/types/types';
|
||||
import type { Observable } from '@polkadot/x-rxjs';
|
||||
import type { DeriveStakerSlashes } from '../types';
|
||||
|
||||
import { combineLatest, of } from '@polkadot/x-rxjs';
|
||||
import { of } from '@polkadot/x-rxjs';
|
||||
import { map, switchMap } from '@polkadot/x-rxjs/operators';
|
||||
|
||||
import { deriveCache, memo } from '../util';
|
||||
import { memo } from '../util';
|
||||
|
||||
const CACHE_KEY = 'ownSlash';
|
||||
|
||||
export function _ownSlash (instanceId: string, api: ApiInterfaceRx): (accountId: Uint8Array | string, era: EraIndex, withActive: boolean) => Observable<DeriveStakerSlashes> {
|
||||
return memo(instanceId, (accountId: Uint8Array | string, era: EraIndex, withActive: boolean): Observable<DeriveStakerSlashes> => {
|
||||
const cacheKey = `${CACHE_KEY}-${era.toString()}-${accountId.toString()}`;
|
||||
const cached = withActive
|
||||
? undefined
|
||||
: deriveCache.get<DeriveStakerSlashes>(cacheKey);
|
||||
|
||||
return cached
|
||||
? of(cached)
|
||||
: api.queryMulti<[Option<BalanceOf>, Option<ITuple<[Perbill, BalanceOf]>>]>([
|
||||
[api.query.staking.nominatorSlashInEra, [era, accountId]],
|
||||
[api.query.staking.validatorSlashInEra, [era, accountId]]
|
||||
export function _ownSlashes (instanceId: string, api: ApiInterfaceRx): (accountId: Uint8Array | string, eras: EraIndex[], withActive: boolean) => Observable<DeriveStakerSlashes[]> {
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
return memo(instanceId, (accountId: Uint8Array | string, eras: EraIndex[], _withActive: boolean): Observable<DeriveStakerSlashes[]> =>
|
||||
eras.length
|
||||
? api.queryMulti<(Option<ITuple<[Perbill, BalanceOf]>> | Option<BalanceOf>)[]>([
|
||||
...eras.map((era): QueryableStorageMultiArg<'rxjs'> => [api.query.staking.validatorSlashInEra, [era, accountId]]),
|
||||
...eras.map((era): QueryableStorageMultiArg<'rxjs'> => [api.query.staking.nominatorSlashInEra, [era, accountId]])
|
||||
]).pipe(
|
||||
map(([optNom, optVal]): DeriveStakerSlashes => {
|
||||
const value = {
|
||||
map((values): DeriveStakerSlashes[] =>
|
||||
eras.map((era, index) => ({
|
||||
era,
|
||||
total: optVal.isSome
|
||||
? optVal.unwrap()[1]
|
||||
: optNom.unwrapOrDefault()
|
||||
};
|
||||
|
||||
!withActive && deriveCache.set(cacheKey, value);
|
||||
|
||||
return value;
|
||||
})
|
||||
);
|
||||
});
|
||||
total: values[index].isSome
|
||||
? (values[index].unwrap() as ITuple<[Perbill, BalanceOf]>)[1]
|
||||
: (values[index + eras.length].unwrapOrDefault() as BalanceOf)
|
||||
}))
|
||||
)
|
||||
)
|
||||
: of([])
|
||||
);
|
||||
}
|
||||
|
||||
export function ownSlash (instanceId: string, api: ApiInterfaceRx): (accountId: Uint8Array | string, era: EraIndex) => Observable<DeriveStakerSlashes> {
|
||||
return memo(instanceId, (accountId: Uint8Array | string, era: EraIndex): Observable<DeriveStakerSlashes> =>
|
||||
api.derive.staking._ownSlash(accountId, era, true)
|
||||
);
|
||||
}
|
||||
|
||||
export function _ownSlashes (instanceId: string, api: ApiInterfaceRx): (accountId: Uint8Array | string, eras: EraIndex[], withActive: boolean) => Observable<DeriveStakerSlashes[]> {
|
||||
return memo(instanceId, (accountId: Uint8Array | string, eras: EraIndex[], withActive: boolean): Observable<DeriveStakerSlashes[]> =>
|
||||
eras.length
|
||||
? combineLatest(
|
||||
eras.map((era) => api.derive.staking._ownSlash(accountId, era, withActive))
|
||||
)
|
||||
: of([])
|
||||
api.derive.staking._ownSlashes(accountId, [era], true).pipe(
|
||||
map(([first]) => first)
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -10,36 +10,46 @@ import { map, switchMap } from '@polkadot/x-rxjs/operators';
|
||||
|
||||
import { memo } from '../util';
|
||||
|
||||
export function _stakerExposure (instanceId: string, api: ApiInterfaceRx): (accountId: Uint8Array | string, eras: EraIndex[], withActive: boolean) => Observable<DeriveStakerExposure[]> {
|
||||
return memo(instanceId, (accountId: Uint8Array | string, eras: EraIndex[], withActive: boolean): Observable<DeriveStakerExposure[]> => {
|
||||
const stakerId = api.registry.createType('AccountId', accountId).toString();
|
||||
export function _stakerExposures (instanceId: string, api: ApiInterfaceRx): (accountIds: (Uint8Array | string)[], eras: EraIndex[], withActive: boolean) => Observable<DeriveStakerExposure[][]> {
|
||||
return memo(instanceId, (accountIds: (Uint8Array | string)[], eras: EraIndex[], withActive: boolean): Observable<DeriveStakerExposure[][]> => {
|
||||
const stakerIds = accountIds.map((a) => api.registry.createType('AccountId', a).toString());
|
||||
|
||||
return api.derive.staking._erasExposure(eras, withActive).pipe(
|
||||
map((exposures): DeriveStakerExposure[] =>
|
||||
exposures.map(({ era, nominators: allNominators, validators: allValidators }): DeriveStakerExposure => {
|
||||
const isValidator = !!allValidators[stakerId];
|
||||
const validators: DeriveEraValidatorExposure = {};
|
||||
const nominating = allNominators[stakerId] || [];
|
||||
map((exposures): DeriveStakerExposure[][] =>
|
||||
stakerIds.map((stakerId) =>
|
||||
exposures.map(({ era, nominators: allNominators, validators: allValidators }): DeriveStakerExposure => {
|
||||
const isValidator = !!allValidators[stakerId];
|
||||
const validators: DeriveEraValidatorExposure = {};
|
||||
const nominating = allNominators[stakerId] || [];
|
||||
|
||||
if (isValidator) {
|
||||
validators[stakerId] = allValidators[stakerId];
|
||||
} else if (nominating) {
|
||||
nominating.forEach(({ validatorId }): void => {
|
||||
validators[validatorId] = allValidators[validatorId];
|
||||
});
|
||||
}
|
||||
if (isValidator) {
|
||||
validators[stakerId] = allValidators[stakerId];
|
||||
} else if (nominating) {
|
||||
nominating.forEach(({ validatorId }): void => {
|
||||
validators[validatorId] = allValidators[validatorId];
|
||||
});
|
||||
}
|
||||
|
||||
return { era, isEmpty: !Object.keys(validators).length, isValidator, nominating, validators };
|
||||
})
|
||||
return { era, isEmpty: !Object.keys(validators).length, isValidator, nominating, validators };
|
||||
})
|
||||
)
|
||||
)
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
export function stakerExposure (instanceId: string, api: ApiInterfaceRx): (accountId: Uint8Array | string, withActive?: boolean) => Observable<DeriveStakerExposure[]> {
|
||||
return memo(instanceId, (accountId: Uint8Array | string, withActive = false): Observable<DeriveStakerExposure[]> =>
|
||||
export function stakerExposures (instanceId: string, api: ApiInterfaceRx): (accountIds: (Uint8Array | string)[], withActive?: boolean) => Observable<DeriveStakerExposure[][]> {
|
||||
return memo(instanceId, (accountIds: (Uint8Array | string)[], withActive = false): Observable<DeriveStakerExposure[][]> =>
|
||||
api.derive.staking.erasHistoric(withActive).pipe(
|
||||
switchMap((eras) => api.derive.staking._stakerExposure(accountId, eras, withActive))
|
||||
switchMap((eras) => api.derive.staking._stakerExposures(accountIds, eras, withActive))
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
export function stakerExposure (instanceId: string, api: ApiInterfaceRx): (accountId: Uint8Array | string, withActive?: boolean) => Observable<DeriveStakerExposure[]> {
|
||||
return memo(instanceId, (accountId: Uint8Array | string, withActive = false): Observable<DeriveStakerExposure[]> =>
|
||||
api.derive.staking.stakerExposures([accountId, withActive]).pipe(
|
||||
map(([first]) => first)
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -2,45 +2,40 @@
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import type { ApiInterfaceRx } from '@polkadot/api/types';
|
||||
import type { Option } from '@polkadot/types';
|
||||
import type { AccountId, EraIndex, StakingLedger, StakingLedgerTo240 } from '@polkadot/types/interfaces';
|
||||
import type { AccountId, EraIndex, StakingLedger } from '@polkadot/types/interfaces';
|
||||
import type { Observable } from '@polkadot/x-rxjs';
|
||||
import type { DeriveEraPoints, DeriveEraPrefs, DeriveEraRewards, DeriveEraValPrefs, DeriveStakerExposure, DeriveStakerReward, DeriveStakerRewardValidator } from '../types';
|
||||
import type { DeriveStakingQuery } from './types';
|
||||
|
||||
import BN from 'bn.js';
|
||||
|
||||
import { isFunction } from '@polkadot/util';
|
||||
import { BN_BILLION, BN_ZERO } from '@polkadot/util';
|
||||
import { combineLatest, of } from '@polkadot/x-rxjs';
|
||||
import { map, switchMap } from '@polkadot/x-rxjs/operators';
|
||||
|
||||
import { memo } from '../util';
|
||||
|
||||
type ErasResult = [{ unwrapOr: (value: BN) => BN }, DeriveEraPoints[], DeriveEraPrefs[], DeriveEraRewards[]];
|
||||
type ErasResult = [DeriveEraPoints[], DeriveEraPrefs[], DeriveEraRewards[]];
|
||||
|
||||
const ZERO = new BN(0);
|
||||
const MIN_ONE = new BN(-1);
|
||||
const COMM_DIV = new BN(1_000_000_000);
|
||||
|
||||
function parseRewards (api: ApiInterfaceRx, stashId: AccountId, [, erasPoints, erasPrefs, erasRewards]: ErasResult, exposures: DeriveStakerExposure[]): DeriveStakerReward[] {
|
||||
function parseRewards (api: ApiInterfaceRx, stashId: AccountId, [erasPoints, erasPrefs, erasRewards]: ErasResult, exposures: DeriveStakerExposure[]): DeriveStakerReward[] {
|
||||
return exposures.map(({ era, isEmpty, isValidator, nominating, validators: eraValidators }): DeriveStakerReward => {
|
||||
const { eraPoints, validators: allValPoints } = erasPoints.find((p) => p.era.eq(era)) || { eraPoints: ZERO, validators: {} };
|
||||
const { eraPoints, validators: allValPoints } = erasPoints.find((p) => p.era.eq(era)) || { eraPoints: BN_ZERO, validators: {} };
|
||||
const { eraReward } = erasRewards.find((r) => r.era.eq(era)) || { eraReward: api.registry.createType('Balance') };
|
||||
const { validators: allValPrefs } = erasPrefs.find((p) => p.era.eq(era)) || { validators: {} as DeriveEraValPrefs };
|
||||
const validators: Record<string, DeriveStakerRewardValidator> = {};
|
||||
const stakerId = stashId.toString();
|
||||
|
||||
Object.entries(eraValidators).forEach(([validatorId, exposure]): void => {
|
||||
const valPoints = allValPoints[validatorId] || ZERO;
|
||||
const valComm = allValPrefs[validatorId]?.commission.unwrap() || ZERO;
|
||||
const valPoints = allValPoints[validatorId] || BN_ZERO;
|
||||
const valComm = allValPrefs[validatorId]?.commission.unwrap() || BN_ZERO;
|
||||
const expTotal = exposure.total.unwrap();
|
||||
let avail = ZERO;
|
||||
let avail = BN_ZERO;
|
||||
let value: BN | undefined;
|
||||
|
||||
if (!(expTotal.isZero() || valPoints.isZero() || eraPoints.isZero())) {
|
||||
avail = eraReward.mul(valPoints).div(eraPoints);
|
||||
|
||||
const valCut = valComm.mul(avail).div(COMM_DIV);
|
||||
const valCut = valComm.mul(avail).div(BN_BILLION);
|
||||
let staked: BN;
|
||||
|
||||
if (validatorId === stakerId) {
|
||||
@@ -50,10 +45,10 @@ function parseRewards (api: ApiInterfaceRx, stashId: AccountId, [, erasPoints, e
|
||||
|
||||
staked = stakerExp
|
||||
? stakerExp.value.unwrap()
|
||||
: ZERO;
|
||||
: BN_ZERO;
|
||||
}
|
||||
|
||||
value = avail.sub(valCut).imul(staked).div(expTotal).iadd(validatorId === stakerId ? valCut : ZERO);
|
||||
value = avail.sub(valCut).imul(staked).div(expTotal).iadd(validatorId === stakerId ? valCut : BN_ZERO);
|
||||
}
|
||||
|
||||
validators[validatorId] = {
|
||||
@@ -73,32 +68,25 @@ function parseRewards (api: ApiInterfaceRx, stashId: AccountId, [, erasPoints, e
|
||||
});
|
||||
}
|
||||
|
||||
function uniqValidators (rewards: DeriveStakerReward[]): string[] {
|
||||
const uniq: string[] = [];
|
||||
function allUniqValidators (rewards: DeriveStakerReward[][]): [string[], string[][]] {
|
||||
return rewards.reduce(([all, perStash]: [string[], string[][]], rewards) => {
|
||||
const uniq: string[] = [];
|
||||
|
||||
rewards.forEach(({ validators }): void => {
|
||||
Object.keys(validators).forEach((validatorId): void => {
|
||||
if (!uniq.includes(validatorId)) {
|
||||
uniq.push(validatorId);
|
||||
}
|
||||
});
|
||||
});
|
||||
perStash.push(uniq);
|
||||
rewards.forEach(({ validators }) =>
|
||||
Object.keys(validators).forEach((validatorId): void => {
|
||||
if (!uniq.includes(validatorId)) {
|
||||
uniq.push(validatorId);
|
||||
|
||||
return uniq;
|
||||
}
|
||||
if (!all.includes(validatorId)) {
|
||||
all.push(validatorId);
|
||||
}
|
||||
}
|
||||
})
|
||||
);
|
||||
|
||||
function isOldLedger (ledger?: StakingLedger | StakingLedgerTo240): ledger is StakingLedgerTo240 {
|
||||
return !!(ledger as StakingLedgerTo240)?.lastReward;
|
||||
}
|
||||
|
||||
function filterEra (era: EraIndex, stakingLedger: StakingLedger): boolean {
|
||||
return isOldLedger(stakingLedger)
|
||||
? era.gt(stakingLedger.lastReward.unwrapOr(MIN_ONE))
|
||||
: !stakingLedger.claimedRewards.some((e) => e.eq(era));
|
||||
}
|
||||
|
||||
function filterEras (eras: EraIndex[], stakingLedger: StakingLedger): EraIndex[] {
|
||||
return eras.filter((era) => filterEra(era, stakingLedger));
|
||||
return [all, perStash];
|
||||
}, [[], []]);
|
||||
}
|
||||
|
||||
function removeClaimed (validators: string[], queryValidators: DeriveStakingQuery[], reward: DeriveStakerReward): void {
|
||||
@@ -121,43 +109,34 @@ function removeClaimed (validators: string[], queryValidators: DeriveStakingQuer
|
||||
});
|
||||
}
|
||||
|
||||
function filterRewards (api: ApiInterfaceRx, eras: EraIndex[], { migrateEra, rewards, stakingLedger }: { migrateEra: BN, rewards: DeriveStakerReward[]; stakingLedger: StakingLedger }): Observable<DeriveStakerReward[]> {
|
||||
const validators = uniqValidators(rewards);
|
||||
const filter = filterEras(eras, stakingLedger);
|
||||
function filterRewards (eras: EraIndex[], valInfo: [string, DeriveStakingQuery][], { rewards, stakingLedger }: { rewards: DeriveStakerReward[]; stakingLedger: StakingLedger }): DeriveStakerReward[] {
|
||||
const filter = eras.filter((era) => !stakingLedger.claimedRewards.some((e) => e.eq(era)));
|
||||
const validators = valInfo.map(([v]) => v);
|
||||
const queryValidators = valInfo.map(([, q]) => q);
|
||||
|
||||
return api.derive.staking.queryMulti(validators, { withLedger: true }).pipe(
|
||||
map((queryValidators): DeriveStakerReward[] =>
|
||||
rewards
|
||||
.filter(({ isEmpty }) => !isEmpty)
|
||||
.filter((reward): boolean => {
|
||||
if (!filter.some((filter) => reward.era.eq(filter))) {
|
||||
return false;
|
||||
} else if (reward.era.lt(migrateEra)) {
|
||||
// we filter again here, the actual ledger may have changed, e.g. something has been claimed
|
||||
return filterEra(reward.era, stakingLedger);
|
||||
}
|
||||
return rewards
|
||||
.filter(({ isEmpty }) => !isEmpty)
|
||||
.filter((reward): boolean => {
|
||||
if (!filter.some((filter) => reward.era.eq(filter))) {
|
||||
return false;
|
||||
}
|
||||
|
||||
reward.isStakerPayout = true;
|
||||
reward.isStakerPayout = true;
|
||||
|
||||
removeClaimed(validators, queryValidators, reward);
|
||||
removeClaimed(validators, queryValidators, reward);
|
||||
|
||||
return true;
|
||||
})
|
||||
.filter(({ validators }) => Object.keys(validators).length !== 0)
|
||||
.map((reward) => ({
|
||||
...reward,
|
||||
nominators: reward.nominating.filter((n) => reward.validators[n.validatorId])
|
||||
}))
|
||||
)
|
||||
);
|
||||
return true;
|
||||
})
|
||||
.filter(({ validators }) => Object.keys(validators).length !== 0)
|
||||
.map((reward) => ({
|
||||
...reward,
|
||||
nominators: reward.nominating.filter((n) => reward.validators[n.validatorId])
|
||||
}));
|
||||
}
|
||||
|
||||
export function _stakerRewardsEras (instanceId: string, api: ApiInterfaceRx): (eras: EraIndex[], withActive: boolean) => Observable<ErasResult> {
|
||||
return memo(instanceId, (eras: EraIndex[], withActive: boolean): Observable<ErasResult> =>
|
||||
combineLatest([
|
||||
isFunction(api.query.staking.migrateEra)
|
||||
? api.query.staking.migrateEra<Option<EraIndex>>()
|
||||
: of(api.registry.createType('Option<EraIndex>')),
|
||||
api.derive.staking._erasPoints(eras, withActive),
|
||||
api.derive.staking._erasPrefs(eras, withActive),
|
||||
api.derive.staking._erasRewards(eras, withActive)
|
||||
@@ -165,23 +144,39 @@ export function _stakerRewardsEras (instanceId: string, api: ApiInterfaceRx): (e
|
||||
);
|
||||
}
|
||||
|
||||
export function _stakerRewards (instanceId: string, api: ApiInterfaceRx): (accountId: Uint8Array | string, eras: EraIndex[], withActive: boolean) => Observable<DeriveStakerReward[]> {
|
||||
return memo(instanceId, (accountId: Uint8Array | string, eras: EraIndex[], withActive: boolean): Observable<DeriveStakerReward[]> =>
|
||||
export function _stakerRewards (instanceId: string, api: ApiInterfaceRx): (accountIds: (Uint8Array | string)[], eras: EraIndex[], withActive: boolean) => Observable<DeriveStakerReward[][]> {
|
||||
return memo(instanceId, (accountIds: (Uint8Array | string)[], eras: EraIndex[], withActive: boolean): Observable<DeriveStakerReward[][]> =>
|
||||
combineLatest([
|
||||
api.derive.staking.query(accountId, { withLedger: true }),
|
||||
api.derive.staking._stakerExposure(accountId, eras, withActive),
|
||||
api.derive.staking.queryMulti(accountIds, { withLedger: true }),
|
||||
api.derive.staking._stakerExposures(accountIds, eras, withActive),
|
||||
api.derive.staking._stakerRewardsEras(eras, withActive)
|
||||
]).pipe(
|
||||
switchMap(([{ stakingLedger, stashId }, exposures, erasResult]): Observable<DeriveStakerReward[]> => {
|
||||
if (!stashId || !stakingLedger) {
|
||||
return of([]);
|
||||
switchMap(([queries, exposures, erasResult]): Observable<DeriveStakerReward[][]> => {
|
||||
const allRewards = queries.map(({ stakingLedger, stashId }, index): DeriveStakerReward[] =>
|
||||
(!stashId || !stakingLedger)
|
||||
? []
|
||||
: parseRewards(api, stashId, erasResult, exposures[index])
|
||||
);
|
||||
|
||||
if (withActive) {
|
||||
return of(allRewards);
|
||||
}
|
||||
|
||||
const rewards = parseRewards(api, stashId, erasResult, exposures);
|
||||
const [allValidators, stashValidators] = allUniqValidators(allRewards);
|
||||
|
||||
return withActive
|
||||
? of(rewards)
|
||||
: filterRewards(api, eras, { migrateEra: erasResult[0].unwrapOr(ZERO), rewards, stakingLedger });
|
||||
return api.derive.staking.queryMulti(allValidators, { withLedger: true }).pipe(
|
||||
map((queriedVals): DeriveStakerReward[][] => {
|
||||
return queries.map(({ stakingLedger }, index): DeriveStakerReward[] => {
|
||||
const rewards = allRewards[index];
|
||||
const ownValidators = stashValidators[index].map((validatorId): [string, DeriveStakingQuery] => [
|
||||
validatorId,
|
||||
queriedVals.find((q) => q.accountId.eq(validatorId)) as DeriveStakingQuery
|
||||
]);
|
||||
|
||||
return filterRewards(eras, ownValidators, { rewards, stakingLedger });
|
||||
});
|
||||
})
|
||||
);
|
||||
})
|
||||
)
|
||||
);
|
||||
@@ -190,7 +185,8 @@ export function _stakerRewards (instanceId: string, api: ApiInterfaceRx): (accou
|
||||
export function stakerRewards (instanceId: string, api: ApiInterfaceRx): (accountId: Uint8Array | string, withActive?: boolean) => Observable<DeriveStakerReward[]> {
|
||||
return memo(instanceId, (accountId: Uint8Array | string, withActive = false): Observable<DeriveStakerReward[]> =>
|
||||
api.derive.staking.erasHistoric(withActive).pipe(
|
||||
switchMap((eras) => api.derive.staking._stakerRewards(accountId, eras, withActive))
|
||||
switchMap((eras) => api.derive.staking._stakerRewards([accountId], eras, withActive)),
|
||||
map(([first]) => first)
|
||||
)
|
||||
);
|
||||
}
|
||||
@@ -198,7 +194,7 @@ export function stakerRewards (instanceId: string, api: ApiInterfaceRx): (accoun
|
||||
export function stakerRewardsMultiEras (instanceId: string, api: ApiInterfaceRx): (accountIds: (Uint8Array | string)[], eras: EraIndex[]) => Observable<DeriveStakerReward[][]> {
|
||||
return memo(instanceId, (accountIds: (Uint8Array | string)[], eras: EraIndex[]): Observable<DeriveStakerReward[][]> =>
|
||||
accountIds.length && eras.length
|
||||
? combineLatest(accountIds.map((acc) => api.derive.staking._stakerRewards(acc, eras, false)))
|
||||
? api.derive.staking._stakerRewards(accountIds, eras, false)
|
||||
: of([])
|
||||
);
|
||||
}
|
||||
|
||||
@@ -5,17 +5,42 @@ import type { ApiInterfaceRx } from '@polkadot/api/types';
|
||||
import type { AccountId } from '@polkadot/types/interfaces';
|
||||
import type { Observable } from '@polkadot/x-rxjs';
|
||||
|
||||
import { map } from '@polkadot/x-rxjs/operators';
|
||||
import { map, startWith, switchMap } from '@polkadot/x-rxjs/operators';
|
||||
|
||||
import { memo } from '../util';
|
||||
import { drr, memo } from '../util';
|
||||
|
||||
function onBondedEvent (api: ApiInterfaceRx): Observable<number> {
|
||||
let current = Date.now();
|
||||
|
||||
return api.query.system.events().pipe(
|
||||
map((events): number => {
|
||||
current = events.filter(({ event, phase }): boolean => {
|
||||
try {
|
||||
return phase.isApplyExtrinsic &&
|
||||
event.section === 'staking' &&
|
||||
event.method === 'Bonded';
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
})
|
||||
? Date.now()
|
||||
: current;
|
||||
|
||||
return current;
|
||||
}),
|
||||
startWith(current),
|
||||
drr({ skipTimeout: true })
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Retrieve the list of all validator stashes
|
||||
*/
|
||||
export function stashes (instanceId: string, api: ApiInterfaceRx): () => Observable<AccountId[]> {
|
||||
return memo(instanceId, (): Observable<AccountId[]> =>
|
||||
api.query.staking.validators.keys().pipe(
|
||||
map((keys) => keys.map((key) => key.args[0] as AccountId).filter((a) => a))
|
||||
onBondedEvent(api).pipe(
|
||||
switchMap(() => api.query.staking.validators.keys()),
|
||||
map((keys) => keys.map(({ args: [validatorId] }) => validatorId).filter((a) => a))
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -18,7 +18,7 @@ export function nextElected (instanceId: string, api: ApiInterfaceRx): () => Obs
|
||||
// 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) => keys.map((key) => key.args[1] as AccountId))
|
||||
map((keys) => keys.map(({ args: [, accountId] }) => accountId))
|
||||
)
|
||||
: api.query.staking.currentElected<AccountId[]>()
|
||||
);
|
||||
|
||||
@@ -61,7 +61,9 @@ function retrieveProposals (api: ApiInterfaceRx, proposalCount: ProposalIndex, a
|
||||
|
||||
return combineLatest([
|
||||
api.query.treasury.proposals.multi<Option<TreasuryProposal>>(allIds),
|
||||
api.derive.council.proposals()
|
||||
api.derive.council
|
||||
? api.derive.council.proposals()
|
||||
: of([] as DeriveCollectiveProposal[])
|
||||
]).pipe(
|
||||
map(([allProposals, councilProposals]: [Option<TreasuryProposal>[], DeriveCollectiveProposal[]]): DeriveTreasuryProposals =>
|
||||
parseResult(api, { allIds, allProposals, approvalIds, councilProposals, proposalCount })
|
||||
|
||||
@@ -33,10 +33,19 @@ function nextNonce (api: ApiInterfaceRx, address: string): Observable<Index> {
|
||||
function signingHeader (api: ApiInterfaceRx): Observable<Header> {
|
||||
return combineLatest([
|
||||
api.rpc.chain.getHeader(),
|
||||
api.rpc.chain.getFinalizedHead().pipe(
|
||||
switchMap((hash) => api.rpc.chain.getHeader(hash))
|
||||
)
|
||||
api.rpc.chain.getFinalizedHead()
|
||||
]).pipe(
|
||||
switchMap(([bestHeader, finHash]) =>
|
||||
// retrieve the headers - in the case of the current block, we use the parent
|
||||
// to minimize (not completely remove) the impact that forks do have on the system
|
||||
// (when at genesis, just return the current header as the last known)
|
||||
bestHeader.parentHash.isEmpty
|
||||
? of([bestHeader, bestHeader])
|
||||
: combineLatest([
|
||||
api.rpc.chain.getHeader(bestHeader.parentHash),
|
||||
api.rpc.chain.getHeader(finHash)
|
||||
])
|
||||
),
|
||||
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)
|
||||
|
||||
@@ -2,43 +2,41 @@
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import type { AccountId, Header } from '@polkadot/types/interfaces';
|
||||
import type { Constructor, Registry } from '@polkadot/types/types';
|
||||
|
||||
import { Struct } from '@polkadot/types';
|
||||
import runtimeTypes from '@polkadot/types/interfaces/runtime/definitions';
|
||||
import type { Registry } from '@polkadot/types/types';
|
||||
import type { HeaderExtended } from './types';
|
||||
|
||||
import { extractAuthor } from './util';
|
||||
|
||||
// We can ignore the properties, added via Struct.with
|
||||
const _Header = Struct.with(runtimeTypes.types.Header as any) as Constructor<Header>;
|
||||
export function createHeaderExtended (registry: Registry, header?: Header, validators?: AccountId[]): HeaderExtended {
|
||||
// an instance of the base extrinsic for us to extend
|
||||
const HeaderBase = registry.createClass('Header');
|
||||
|
||||
/**
|
||||
* @name HeaderExtended
|
||||
* @description
|
||||
* A [[Block]] header with an additional `author` field that indicates the block author
|
||||
*/
|
||||
export class HeaderExtended extends _Header {
|
||||
readonly #author?: AccountId;
|
||||
readonly #validators?: AccountId[];
|
||||
class Implementation extends HeaderBase implements HeaderExtended {
|
||||
readonly #author?: AccountId;
|
||||
readonly #validators?: AccountId[];
|
||||
|
||||
constructor (registry: Registry, header?: Header, validators?: AccountId[]) {
|
||||
super(registry, header);
|
||||
constructor (registry: Registry, header?: Header, validators?: AccountId[]) {
|
||||
super(registry, header);
|
||||
|
||||
this.#author = extractAuthor(this.digest, validators);
|
||||
this.#validators = validators;
|
||||
this.#author = extractAuthor(this.digest, validators);
|
||||
this.#validators = validators;
|
||||
this.createdAtHash = header?.createdAtHash;
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Convenience method, returns the author for the block
|
||||
*/
|
||||
public get author (): AccountId | undefined {
|
||||
return this.#author;
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Convenience method, returns the validators for the block
|
||||
*/
|
||||
public get validators (): AccountId[] | undefined {
|
||||
return this.#validators;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Convenience method, returns the author for the block
|
||||
*/
|
||||
public get author (): AccountId | undefined {
|
||||
return this.#author;
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Convenience method, returns the validators for the block
|
||||
*/
|
||||
public get validators (): AccountId[] | undefined {
|
||||
return this.#validators;
|
||||
}
|
||||
return new Implementation(registry, header, validators);
|
||||
}
|
||||
|
||||
@@ -1,24 +1,12 @@
|
||||
// Copyright 2017-2021 @polkadot/api-derive authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import type { AccountId, DispatchError, DispatchInfo, Event, EventRecord, Extrinsic, SignedBlock } from '@polkadot/types/interfaces';
|
||||
import type { Constructor, Registry } from '@polkadot/types/types';
|
||||
|
||||
import { Struct } from '@polkadot/types';
|
||||
import runtimeTypes from '@polkadot/types/interfaces/runtime/definitions';
|
||||
import type { AccountId, DispatchError, DispatchInfo, EventRecord, Extrinsic, SignedBlock } from '@polkadot/types/interfaces';
|
||||
import type { Registry } from '@polkadot/types/types';
|
||||
import type { SignedBlockExtended, TxWithEvent } from './types';
|
||||
|
||||
import { extractAuthor } from './util';
|
||||
|
||||
// We can ignore the properties, added via Struct.with
|
||||
const _SignedBlock = Struct.with(runtimeTypes.types.SignedBlock as any) as Constructor<SignedBlock>;
|
||||
|
||||
interface TxWithEvent {
|
||||
dispatchError?: DispatchError;
|
||||
dispatchInfo?: DispatchInfo;
|
||||
events: Event[];
|
||||
extrinsic: Extrinsic;
|
||||
}
|
||||
|
||||
function mapExtrinsics (extrinsics: Extrinsic[], records: EventRecord[]): TxWithEvent[] {
|
||||
return extrinsics.map((extrinsic, index): TxWithEvent => {
|
||||
let dispatchError: DispatchError | undefined;
|
||||
@@ -43,42 +31,45 @@ function mapExtrinsics (extrinsics: Extrinsic[], records: EventRecord[]): TxWith
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* @name SignedBlockExtended
|
||||
* @description
|
||||
* A [[Block]] header with an additional `author` field that indicates the block author
|
||||
*/
|
||||
export class SignedBlockExtended extends _SignedBlock {
|
||||
readonly #author?: AccountId;
|
||||
readonly #events: EventRecord[];
|
||||
readonly #extrinsics: TxWithEvent[];
|
||||
export function createSignedBlockExtended (registry: Registry, block?: SignedBlock, events?: EventRecord[], validators?: AccountId[]): SignedBlockExtended {
|
||||
// an instance of the base extrinsic for us to extend
|
||||
const SignedBlockBase = registry.createClass('SignedBlock');
|
||||
|
||||
constructor (registry: Registry, block?: SignedBlock, events?: EventRecord[], sessionValidators?: AccountId[]) {
|
||||
super(registry, block);
|
||||
class Implementation extends SignedBlockBase implements SignedBlockExtended {
|
||||
readonly #author?: AccountId;
|
||||
readonly #events: EventRecord[];
|
||||
readonly #extrinsics: TxWithEvent[];
|
||||
|
||||
this.#author = extractAuthor(this.block.header.digest, sessionValidators);
|
||||
this.#events = events || ([] as EventRecord[]);
|
||||
this.#extrinsics = mapExtrinsics(this.block.extrinsics, this.#events);
|
||||
constructor (registry: Registry, block?: SignedBlock, events?: EventRecord[], validators?: AccountId[]) {
|
||||
super(registry, block);
|
||||
|
||||
this.#author = extractAuthor(this.block.header.digest, validators);
|
||||
this.#events = events || ([] as EventRecord[]);
|
||||
this.#extrinsics = mapExtrinsics(this.block.extrinsics, this.#events);
|
||||
this.createdAtHash = block?.createdAtHash;
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Convenience method, returns the author for the block
|
||||
*/
|
||||
public get author (): AccountId | undefined {
|
||||
return this.#author;
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Convenience method, returns the events associated with the block
|
||||
*/
|
||||
public get events (): EventRecord[] {
|
||||
return this.#events;
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Returns the extrinsics and their events, mapped
|
||||
*/
|
||||
public get extrinsics (): TxWithEvent[] {
|
||||
return this.#extrinsics;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Convenience method, returns the author for the block
|
||||
*/
|
||||
public get author (): AccountId | undefined {
|
||||
return this.#author;
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Convenience method, returns the events associated with the block
|
||||
*/
|
||||
public get events (): EventRecord[] {
|
||||
return this.#events;
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Returns the extrinsics and their events, mapped
|
||||
*/
|
||||
public get extrinsics (): TxWithEvent[] {
|
||||
return this.#extrinsics;
|
||||
}
|
||||
return new Implementation(registry, block, events, validators);
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
// Copyright 2017-2021 @polkadot/api-derive authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
export { HeaderExtended } from './HeaderExtended';
|
||||
export { SignedBlockExtended } from './SignedBlockExtended';
|
||||
export { createHeaderExtended } from './HeaderExtended';
|
||||
export { createSignedBlockExtended } from './SignedBlockExtended';
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
// Copyright 2017-2021 @polkadot/api-derive authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import type { AccountId, DispatchError, DispatchInfo, Event, EventRecord, Extrinsic, Header, SignedBlock } from '@polkadot/types/interfaces';
|
||||
|
||||
export interface HeaderExtended extends Header {
|
||||
readonly author: AccountId | undefined;
|
||||
readonly validators: AccountId[] | undefined;
|
||||
}
|
||||
|
||||
export interface SignedBlockExtended extends SignedBlock {
|
||||
readonly author: AccountId | undefined;
|
||||
readonly events: EventRecord[];
|
||||
readonly extrinsics: TxWithEvent[];
|
||||
}
|
||||
|
||||
export interface TxWithEvent {
|
||||
dispatchError?: DispatchError;
|
||||
dispatchInfo?: DispatchInfo;
|
||||
events: Event[];
|
||||
extrinsic: Extrinsic;
|
||||
}
|
||||
@@ -4,23 +4,44 @@
|
||||
import type { AccountId, Digest } from '@polkadot/types/interfaces';
|
||||
|
||||
export function extractAuthor (digest: Digest, sessionValidators: AccountId[] = []): AccountId | undefined {
|
||||
const [citem] = digest.logs.filter(({ type }) => type === 'Consensus');
|
||||
const [pitem] = digest.logs.filter(({ type }) => type === 'PreRuntime');
|
||||
const [sitem] = digest.logs.filter(({ type }) => type === 'Seal');
|
||||
|
||||
// extract from the substrate 2.0 PreRuntime digest
|
||||
let accountId: AccountId | undefined;
|
||||
|
||||
// This is critical to be first for BABE (before Consensus)
|
||||
// If not first, we end up dropping the author at session-end
|
||||
if (pitem) {
|
||||
const [engine, data] = pitem.asPreRuntime;
|
||||
try {
|
||||
const [engine, data] = pitem.asPreRuntime;
|
||||
|
||||
return engine.extractAuthor(data, sessionValidators);
|
||||
} else {
|
||||
const [citem] = digest.logs.filter(({ type }) => type === 'Consensus');
|
||||
|
||||
// extract author from the consensus (substrate 1.0, digest)
|
||||
if (citem) {
|
||||
const [engine, data] = citem.asConsensus;
|
||||
|
||||
return engine.extractAuthor(data, sessionValidators);
|
||||
accountId = engine.extractAuthor(data, sessionValidators);
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
}
|
||||
|
||||
return undefined;
|
||||
if (!accountId && citem) {
|
||||
try {
|
||||
const [engine, data] = citem.asConsensus;
|
||||
|
||||
accountId = engine.extractAuthor(data, sessionValidators);
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
}
|
||||
|
||||
// SEAL, still used in e.g. Kulupu for pow
|
||||
if (!accountId && sitem) {
|
||||
try {
|
||||
const [engine, data] = sitem.asSeal;
|
||||
|
||||
accountId = engine.extractAuthor(data, sessionValidators);
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
}
|
||||
|
||||
return accountId;
|
||||
}
|
||||
|
||||
@@ -12,10 +12,9 @@ export * from './elections/types';
|
||||
export * from './parachains/types';
|
||||
export * from './session/types';
|
||||
export * from './staking/types';
|
||||
export * from './type/types';
|
||||
|
||||
export interface DeriveBalancesAccount {
|
||||
accountId: AccountId;
|
||||
accountNonce: Index;
|
||||
export interface DeriveBalancesAccountData {
|
||||
freeBalance: Balance;
|
||||
frozenFee: Balance;
|
||||
frozenMisc: Balance;
|
||||
@@ -23,16 +22,25 @@ export interface DeriveBalancesAccount {
|
||||
votingBalance: Balance;
|
||||
}
|
||||
|
||||
export interface DeriveBalancesAll extends DeriveBalancesAccount {
|
||||
isVesting: boolean;
|
||||
export interface DeriveBalancesAccount extends DeriveBalancesAccountData {
|
||||
accountId: AccountId;
|
||||
accountNonce: Index;
|
||||
additional: DeriveBalancesAccountData[];
|
||||
}
|
||||
|
||||
export interface DeriveBalancesAllAccountData extends DeriveBalancesAccountData {
|
||||
availableBalance: Balance;
|
||||
lockedBalance: Balance;
|
||||
lockedBreakdown: (BalanceLock | BalanceLockTo212)[];
|
||||
availableBalance: Balance;
|
||||
votingBalance: Balance;
|
||||
vestingLocked: Balance;
|
||||
}
|
||||
|
||||
export interface DeriveBalancesAll extends DeriveBalancesAccount, DeriveBalancesAllAccountData {
|
||||
additional: DeriveBalancesAllAccountData[];
|
||||
isVesting: boolean;
|
||||
vestedBalance: Balance;
|
||||
vestedClaimable: Balance;
|
||||
vestingEndBlock: BlockNumber;
|
||||
vestingLocked: Balance;
|
||||
vestingPerBlock: Balance;
|
||||
vestingTotal: Balance;
|
||||
}
|
||||
@@ -100,6 +108,7 @@ export interface DeriveSocietyCandidate {
|
||||
|
||||
export interface DeriveSocietyMember {
|
||||
accountId: AccountId;
|
||||
isDefenderVoter: boolean;
|
||||
isSuspended: boolean;
|
||||
payouts: [BlockNumber, Balance][];
|
||||
strikes: StrikeCount;
|
||||
|
||||
@@ -5,7 +5,7 @@ import type { DeriveCache } from './types';
|
||||
|
||||
const mapCache = new Map<string, any>();
|
||||
|
||||
const deriveMapCache: DeriveCache = {
|
||||
export const deriveMapCache: DeriveCache = {
|
||||
del: (key: string): void => {
|
||||
mapCache.delete(key);
|
||||
},
|
||||
@@ -24,11 +24,9 @@ const deriveMapCache: DeriveCache = {
|
||||
}
|
||||
};
|
||||
|
||||
const deriveNoopCache: DeriveCache = {
|
||||
export const deriveNoopCache: DeriveCache = {
|
||||
del: (): void => undefined,
|
||||
forEach: () => undefined,
|
||||
get: (): undefined => undefined,
|
||||
set: (_: string, value: unknown): unknown => value
|
||||
};
|
||||
|
||||
export { deriveMapCache, deriveNoopCache };
|
||||
|
||||
+17
-14
@@ -1,13 +1,16 @@
|
||||
{
|
||||
"name": "@polkadot/api",
|
||||
"version": "3.4.1",
|
||||
"version": "4.8.1",
|
||||
"type": "module",
|
||||
"description": "Promise and RxJS wrappers around the Polkadot JS RPC",
|
||||
"main": "index.js",
|
||||
"module": "index.mjs",
|
||||
"sideEffects": [
|
||||
"./detectPackage.js",
|
||||
"./detectPackage.mjs"
|
||||
"./detectPackage.cjs"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=14.0.0"
|
||||
},
|
||||
"author": "Jaco Greeff <jacogr@gmail.com>",
|
||||
"maintainers": [],
|
||||
"contributors": [],
|
||||
@@ -16,17 +19,17 @@
|
||||
"bugs": "https://github.com/polkadot-js/api/issues",
|
||||
"homepage": "https://github.com/polkadot-js/api/tree/master/packages/api#readme",
|
||||
"dependencies": {
|
||||
"@babel/runtime": "^7.12.5",
|
||||
"@polkadot/api-derive": "3.4.1",
|
||||
"@polkadot/keyring": "^5.2.3",
|
||||
"@polkadot/metadata": "3.4.1",
|
||||
"@polkadot/rpc-core": "3.4.1",
|
||||
"@polkadot/rpc-provider": "3.4.1",
|
||||
"@polkadot/types": "3.4.1",
|
||||
"@polkadot/types-known": "3.4.1",
|
||||
"@polkadot/util": "^5.2.3",
|
||||
"@polkadot/util-crypto": "^5.2.3",
|
||||
"@polkadot/x-rxjs": "3.4.1",
|
||||
"@babel/runtime": "^7.14.0",
|
||||
"@polkadot/api-derive": "4.8.1",
|
||||
"@polkadot/keyring": "^6.3.1",
|
||||
"@polkadot/metadata": "4.8.1",
|
||||
"@polkadot/rpc-core": "4.8.1",
|
||||
"@polkadot/rpc-provider": "4.8.1",
|
||||
"@polkadot/types": "4.8.1",
|
||||
"@polkadot/types-known": "4.8.1",
|
||||
"@polkadot/util": "^6.3.1",
|
||||
"@polkadot/util-crypto": "^6.3.1",
|
||||
"@polkadot/x-rxjs": "^6.3.1",
|
||||
"bn.js": "^4.11.9",
|
||||
"eventemitter3": "^4.0.7"
|
||||
}
|
||||
|
||||
@@ -3,11 +3,12 @@
|
||||
|
||||
import type { Vec, u16, u32, u64, u8 } from '@polkadot/types';
|
||||
import type { Codec } from '@polkadot/types/types';
|
||||
import type { Balance, BalanceOf, BlockNumber, LockIdentifier, ModuleId, Moment, Perbill, Percent, Permill, RuntimeDbWeight } from '@polkadot/types/interfaces/runtime';
|
||||
import type { Balance, BalanceOf, BlockNumber, LockIdentifier, Moment, PalletId, Perbill, Percent, Permill, RuntimeDbWeight, Weight } from '@polkadot/types/interfaces/runtime';
|
||||
import type { SessionIndex } from '@polkadot/types/interfaces/session';
|
||||
import type { EraIndex } from '@polkadot/types/interfaces/staking';
|
||||
import type { RuntimeVersion } from '@polkadot/types/interfaces/state';
|
||||
import type { WeightToFeeCoefficient } from '@polkadot/types/interfaces/support';
|
||||
import type { BlockWeights } from '@polkadot/types/interfaces/system';
|
||||
import type { BlockLength, BlockWeights } from '@polkadot/types/interfaces/system';
|
||||
import type { ApiTypes } from '@polkadot/api/types';
|
||||
|
||||
declare module '@polkadot/api/types/consts' {
|
||||
@@ -15,8 +16,9 @@ declare module '@polkadot/api/types/consts' {
|
||||
babe: {
|
||||
[key: string]: Codec;
|
||||
/**
|
||||
* The number of **slots** that an epoch takes. We couple sessions to
|
||||
* epochs, i.e. we start a new session once the new epoch begins.
|
||||
* The amount of time, in slots, that each epoch should last.
|
||||
* NOTE: Currently it is not possible to change the epoch duration after
|
||||
* the chain has started. Attempting to do so will brick block production.
|
||||
**/
|
||||
epochDuration: u64 & AugmentedConst<ApiType>;
|
||||
/**
|
||||
@@ -49,6 +51,10 @@ declare module '@polkadot/api/types/consts' {
|
||||
* The delay period for which a bounty beneficiary need to wait before claim the payout.
|
||||
**/
|
||||
bountyDepositPayoutDelay: BlockNumber & AugmentedConst<ApiType>;
|
||||
/**
|
||||
* Bounty duration in blocks.
|
||||
**/
|
||||
bountyUpdatePeriod: BlockNumber & AugmentedConst<ApiType>;
|
||||
/**
|
||||
* Minimum value for a bounty.
|
||||
**/
|
||||
@@ -65,28 +71,61 @@ declare module '@polkadot/api/types/consts' {
|
||||
contracts: {
|
||||
[key: string]: Codec;
|
||||
/**
|
||||
* The maximum nesting level of a call/instantiate stack. A reasonable default
|
||||
* value is 100.
|
||||
* The maximum number of tries that can be queued for deletion.
|
||||
**/
|
||||
maxDepth: u32 & AugmentedConst<ApiType>;
|
||||
deletionQueueDepth: u32 & AugmentedConst<ApiType>;
|
||||
/**
|
||||
* The maximum size of a storage value in bytes. A reasonable default is 16 KiB.
|
||||
* The maximum amount of weight that can be consumed per block for lazy trie removal.
|
||||
**/
|
||||
maxValueSize: u32 & AugmentedConst<ApiType>;
|
||||
deletionWeightLimit: Weight & AugmentedConst<ApiType>;
|
||||
/**
|
||||
* Price of a byte of storage per one block interval. Should be greater than 0.
|
||||
* The balance every contract needs to deposit to stay alive indefinitely.
|
||||
*
|
||||
* This is different from the [`Self::TombstoneDeposit`] because this only needs to be
|
||||
* deposited while the contract is alive. Costs for additional storage are added to
|
||||
* this base cost.
|
||||
*
|
||||
* This is a simple way to ensure that contracts with empty storage eventually get deleted by
|
||||
* making them pay rent. This creates an incentive to remove them early in order to save rent.
|
||||
**/
|
||||
rentByteFee: BalanceOf & AugmentedConst<ApiType>;
|
||||
depositPerContract: BalanceOf & AugmentedConst<ApiType>;
|
||||
/**
|
||||
* The amount of funds a contract should deposit in order to offset
|
||||
* the cost of one byte.
|
||||
* The balance a contract needs to deposit per storage byte to stay alive indefinitely.
|
||||
*
|
||||
* Let's suppose the deposit is 1,000 BU (balance units)/byte and the rent is 1 BU/byte/day,
|
||||
* then a contract with 1,000,000 BU that uses 1,000 bytes of storage would pay no rent.
|
||||
* But if the balance reduced to 500,000 BU and the storage stayed the same at 1,000,
|
||||
* then it would pay 500 BU/day.
|
||||
**/
|
||||
rentDepositOffset: BalanceOf & AugmentedConst<ApiType>;
|
||||
depositPerStorageByte: BalanceOf & AugmentedConst<ApiType>;
|
||||
/**
|
||||
* The balance a contract needs to deposit per storage item to stay alive indefinitely.
|
||||
*
|
||||
* It works the same as [`Self::DepositPerStorageByte`] but for storage items.
|
||||
**/
|
||||
depositPerStorageItem: BalanceOf & AugmentedConst<ApiType>;
|
||||
/**
|
||||
* The maximum length of a contract code in bytes. This limit applies to the instrumented
|
||||
* version of the code. Therefore `instantiate_with_code` can fail even when supplying
|
||||
* a wasm binary below this maximum size.
|
||||
**/
|
||||
maxCodeSize: u32 & AugmentedConst<ApiType>;
|
||||
/**
|
||||
* The maximum nesting level of a call/instantiate stack.
|
||||
**/
|
||||
maxDepth: u32 & AugmentedConst<ApiType>;
|
||||
/**
|
||||
* The maximum size of a storage value and event payload in bytes.
|
||||
**/
|
||||
maxValueSize: u32 & AugmentedConst<ApiType>;
|
||||
/**
|
||||
* The fraction of the deposit that should be used as rent per block.
|
||||
*
|
||||
* When a contract hasn't enough balance deposited to stay alive indefinitely it needs
|
||||
* to pay per block for the storage it consumes that is not covered by the deposit.
|
||||
* This determines how high this rent payment is per block as a fraction of the deposit.
|
||||
**/
|
||||
rentFraction: Perbill & AugmentedConst<ApiType>;
|
||||
/**
|
||||
* Number of block delay an extrinsic claim surcharge has.
|
||||
*
|
||||
@@ -94,15 +133,6 @@ declare module '@polkadot/api/types/consts' {
|
||||
* for current_block - delay
|
||||
**/
|
||||
signedClaimHandicap: BlockNumber & AugmentedConst<ApiType>;
|
||||
/**
|
||||
* A size offset for an contract. A just created account with untouched storage will have that
|
||||
* much of storage from the perspective of the state rent.
|
||||
*
|
||||
* This is a simple way to ensure that contracts with empty storage eventually get deleted
|
||||
* by making them pay rent. This creates an incentive to remove them early in order to save
|
||||
* rent.
|
||||
**/
|
||||
storageSizeOffset: u32 & AugmentedConst<ApiType>;
|
||||
/**
|
||||
* Reward that is received by the party whose touch has led
|
||||
* to removal of a contract.
|
||||
@@ -152,14 +182,103 @@ declare module '@polkadot/api/types/consts' {
|
||||
**/
|
||||
votingPeriod: BlockNumber & AugmentedConst<ApiType>;
|
||||
};
|
||||
electionProviderMultiPhase: {
|
||||
[key: string]: Codec;
|
||||
/**
|
||||
* Duration of the signed phase.
|
||||
**/
|
||||
signedPhase: BlockNumber & AugmentedConst<ApiType>;
|
||||
/**
|
||||
* The minimum amount of improvement to the solution score that defines a solution as
|
||||
* "better" (in any phase).
|
||||
**/
|
||||
solutionImprovementThreshold: Perbill & AugmentedConst<ApiType>;
|
||||
/**
|
||||
* Duration of the unsigned phase.
|
||||
**/
|
||||
unsignedPhase: BlockNumber & AugmentedConst<ApiType>;
|
||||
};
|
||||
elections: {
|
||||
[key: string]: Codec;
|
||||
/**
|
||||
* How much should be locked up in order to submit one's candidacy.
|
||||
**/
|
||||
candidacyBond: BalanceOf & AugmentedConst<ApiType>;
|
||||
/**
|
||||
* Number of members to elect.
|
||||
**/
|
||||
desiredMembers: u32 & AugmentedConst<ApiType>;
|
||||
/**
|
||||
* Number of runners_up to keep.
|
||||
**/
|
||||
desiredRunnersUp: u32 & AugmentedConst<ApiType>;
|
||||
moduleId: LockIdentifier & AugmentedConst<ApiType>;
|
||||
/**
|
||||
* Identifier for the elections-phragmen pallet's lock
|
||||
**/
|
||||
palletId: LockIdentifier & AugmentedConst<ApiType>;
|
||||
/**
|
||||
* How long each seat is kept. This defines the next block number at which an election
|
||||
* round will happen. If set to zero, no elections are ever triggered and the module will
|
||||
* be in passive mode.
|
||||
**/
|
||||
termDuration: BlockNumber & AugmentedConst<ApiType>;
|
||||
votingBond: BalanceOf & AugmentedConst<ApiType>;
|
||||
/**
|
||||
* Base deposit associated with voting.
|
||||
*
|
||||
* This should be sensibly high to economically ensure the pallet cannot be attacked by
|
||||
* creating a gigantic number of votes.
|
||||
**/
|
||||
votingBondBase: BalanceOf & AugmentedConst<ApiType>;
|
||||
/**
|
||||
* The amount of bond that need to be locked for each vote (32 bytes).
|
||||
**/
|
||||
votingBondFactor: BalanceOf & AugmentedConst<ApiType>;
|
||||
};
|
||||
gilt: {
|
||||
[key: string]: Codec;
|
||||
/**
|
||||
* Portion of the queue which is free from ordering and just a FIFO.
|
||||
*
|
||||
* Must be no greater than `MaxQueueLen`.
|
||||
**/
|
||||
fifoQueueLen: u32 & AugmentedConst<ApiType>;
|
||||
/**
|
||||
* The number of blocks between consecutive attempts to issue more gilts in an effort to
|
||||
* get to the target amount to be frozen.
|
||||
*
|
||||
* A larger value results in fewer storage hits each block, but a slower period to get to
|
||||
* the target.
|
||||
**/
|
||||
intakePeriod: BlockNumber & AugmentedConst<ApiType>;
|
||||
/**
|
||||
* The maximum amount of bids that can be turned into issued gilts each block. A larger
|
||||
* value here means less of the block available for transactions should there be a glut of
|
||||
* bids to make into gilts to reach the target.
|
||||
**/
|
||||
maxIntakeBids: u32 & AugmentedConst<ApiType>;
|
||||
/**
|
||||
* Maximum number of items that may be in each duration queue.
|
||||
**/
|
||||
maxQueueLen: u32 & AugmentedConst<ApiType>;
|
||||
/**
|
||||
* The minimum amount of funds that may be offered to freeze for a gilt. Note that this
|
||||
* does not actually limit the amount which may be frozen in a gilt since gilts may be
|
||||
* split up in order to satisfy the desired amount of funds under gilts.
|
||||
*
|
||||
* It should be at least big enough to ensure that there is no possible storage spam attack
|
||||
* or queue-filling attack.
|
||||
**/
|
||||
minFreeze: BalanceOf & AugmentedConst<ApiType>;
|
||||
/**
|
||||
* The base period for the duration queues. This is the common multiple across all
|
||||
* supported freezing durations that can be bid upon.
|
||||
**/
|
||||
period: BlockNumber & AugmentedConst<ApiType>;
|
||||
/**
|
||||
* Number of duration queues in total. This sets the maximum duration supported, which is
|
||||
* this value multiplied by `Period`.
|
||||
**/
|
||||
queueCount: u32 & AugmentedConst<ApiType>;
|
||||
};
|
||||
identity: {
|
||||
[key: string]: Codec;
|
||||
@@ -199,6 +318,11 @@ declare module '@polkadot/api/types/consts' {
|
||||
**/
|
||||
deposit: BalanceOf & AugmentedConst<ApiType>;
|
||||
};
|
||||
lottery: {
|
||||
[key: string]: Codec;
|
||||
maxCalls: u32 & AugmentedConst<ApiType>;
|
||||
palletId: PalletId & AugmentedConst<ApiType>;
|
||||
};
|
||||
multisig: {
|
||||
[key: string]: Codec;
|
||||
/**
|
||||
@@ -218,15 +342,20 @@ declare module '@polkadot/api/types/consts' {
|
||||
proxy: {
|
||||
[key: string]: Codec;
|
||||
/**
|
||||
* `AnnouncementDepositBase` metadata shadow.
|
||||
* The base amount of currency needed to reserve for creating an announcement.
|
||||
*
|
||||
* This is held when a new storage item holding a `Balance` is created (typically 16 bytes).
|
||||
**/
|
||||
announcementDepositBase: BalanceOf & AugmentedConst<ApiType>;
|
||||
/**
|
||||
* `AnnouncementDepositFactor` metadata shadow.
|
||||
* The amount of currency needed per announcement made.
|
||||
*
|
||||
* This is held for adding an `AccountId`, `Hash` and `BlockNumber` (typically 68 bytes)
|
||||
* into a pre-existing storage value.
|
||||
**/
|
||||
announcementDepositFactor: BalanceOf & AugmentedConst<ApiType>;
|
||||
/**
|
||||
* `MaxPending` metadata shadow.
|
||||
* The maximum amount of time-delayed announcements that are allowed to be pending.
|
||||
**/
|
||||
maxPending: u32 & AugmentedConst<ApiType>;
|
||||
/**
|
||||
@@ -235,10 +364,17 @@ declare module '@polkadot/api/types/consts' {
|
||||
maxProxies: u16 & AugmentedConst<ApiType>;
|
||||
/**
|
||||
* The base amount of currency needed to reserve for creating a proxy.
|
||||
*
|
||||
* This is held for an additional storage item whose value size is
|
||||
* `sizeof(Balance)` bytes and whose key size is `sizeof(AccountId)` bytes.
|
||||
**/
|
||||
proxyDepositBase: BalanceOf & AugmentedConst<ApiType>;
|
||||
/**
|
||||
* The amount of currency needed per proxy added.
|
||||
*
|
||||
* This is held for adding 32 bytes plus an instance of `ProxyType` more into a pre-existing
|
||||
* storage value. Thus, when configuring `ProxyDepositFactor` one should take into account
|
||||
* `32 + proxy_type.encode().len()` bytes of data.
|
||||
**/
|
||||
proxyDepositFactor: BalanceOf & AugmentedConst<ApiType>;
|
||||
};
|
||||
@@ -271,6 +407,10 @@ declare module '@polkadot/api/types/consts' {
|
||||
* The number of blocks between membership challenges.
|
||||
**/
|
||||
challengePeriod: BlockNumber & AugmentedConst<ApiType>;
|
||||
/**
|
||||
* Maximum candidate intake per round.
|
||||
**/
|
||||
maxCandidateIntake: u32 & AugmentedConst<ApiType>;
|
||||
/**
|
||||
* The number of times a member may vote the wrong way (or not at all, when they are a skeptic)
|
||||
* before they become suspended.
|
||||
@@ -279,7 +419,7 @@ declare module '@polkadot/api/types/consts' {
|
||||
/**
|
||||
* The societies's module id
|
||||
**/
|
||||
moduleId: ModuleId & AugmentedConst<ApiType>;
|
||||
palletId: PalletId & AugmentedConst<ApiType>;
|
||||
/**
|
||||
* The amount of incentive paid within each period. Doesn't include VoterTip.
|
||||
**/
|
||||
@@ -301,21 +441,9 @@ declare module '@polkadot/api/types/consts' {
|
||||
**/
|
||||
bondingDuration: EraIndex & AugmentedConst<ApiType>;
|
||||
/**
|
||||
* 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.
|
||||
* Maximum number of nominations per nominator.
|
||||
**/
|
||||
electionLookahead: BlockNumber & AugmentedConst<ApiType>;
|
||||
/**
|
||||
* Maximum number of balancing iterations to run in the offchain submission.
|
||||
*
|
||||
* If set to 0, balance_solution will not be executed at all.
|
||||
**/
|
||||
maxIterations: u32 & AugmentedConst<ApiType>;
|
||||
maxNominations: u32 & AugmentedConst<ApiType>;
|
||||
/**
|
||||
* The maximum number of nominators rewarded for each validator.
|
||||
*
|
||||
@@ -323,10 +451,6 @@ declare module '@polkadot/api/types/consts' {
|
||||
* their reward. This used to limit the i/o cost for the nominator payout.
|
||||
**/
|
||||
maxNominatorRewardedPerValidator: u32 & AugmentedConst<ApiType>;
|
||||
/**
|
||||
* The threshold of improvement that should be provided for a new solution to be accepted.
|
||||
**/
|
||||
minSolutionScoreBump: Perbill & AugmentedConst<ApiType>;
|
||||
/**
|
||||
* Number of sessions per era.
|
||||
**/
|
||||
@@ -343,11 +467,15 @@ declare module '@polkadot/api/types/consts' {
|
||||
system: {
|
||||
[key: string]: Codec;
|
||||
/**
|
||||
* The maximum number of blocks to allow in mortal eras.
|
||||
* Maximum number of block number to block hash mappings to keep (oldest pruned first).
|
||||
**/
|
||||
blockHashCount: BlockNumber & AugmentedConst<ApiType>;
|
||||
/**
|
||||
* The weight configuration (limits & base values) for each class of extrinsics and block.
|
||||
* The maximum length of a block (in bytes).
|
||||
**/
|
||||
blockLength: BlockLength & AugmentedConst<ApiType>;
|
||||
/**
|
||||
* Block & extrinsics weights: base values and limits.
|
||||
**/
|
||||
blockWeights: BlockWeights & AugmentedConst<ApiType>;
|
||||
/**
|
||||
@@ -362,6 +490,10 @@ declare module '@polkadot/api/types/consts' {
|
||||
* an identifier of the chain.
|
||||
**/
|
||||
ss58Prefix: u8 & AugmentedConst<ApiType>;
|
||||
/**
|
||||
* Get the chain's current version.
|
||||
**/
|
||||
version: RuntimeVersion & AugmentedConst<ApiType>;
|
||||
};
|
||||
timestamp: {
|
||||
[key: string]: Codec;
|
||||
@@ -416,7 +548,7 @@ declare module '@polkadot/api/types/consts' {
|
||||
/**
|
||||
* The treasury's module id, used for deriving its sovereign account ID.
|
||||
**/
|
||||
moduleId: ModuleId & AugmentedConst<ApiType>;
|
||||
palletId: PalletId & AugmentedConst<ApiType>;
|
||||
/**
|
||||
* Fraction of a proposal's value that should be bonded in order to place the proposal.
|
||||
* An accepted proposal gets these back. A rejected proposal does not.
|
||||
@@ -434,7 +566,7 @@ declare module '@polkadot/api/types/consts' {
|
||||
vesting: {
|
||||
[key: string]: Codec;
|
||||
/**
|
||||
* The minimum amount to be transferred to create a new vesting schedule.
|
||||
* The minimum amount transferred to call `vested_transfer`.
|
||||
**/
|
||||
minVestedTransfer: BalanceOf & AugmentedConst<ApiType>;
|
||||
};
|
||||
|
||||
@@ -8,9 +8,9 @@ declare module '@polkadot/api/types/errors' {
|
||||
assets: {
|
||||
[key: string]: AugmentedError<ApiType>;
|
||||
/**
|
||||
* Transfer amount should be non-zero.
|
||||
* Invalid metadata given.
|
||||
**/
|
||||
AmountZero: AugmentedError<ApiType>;
|
||||
BadMetadata: AugmentedError<ApiType>;
|
||||
/**
|
||||
* Invalid witness data given.
|
||||
**/
|
||||
@@ -39,22 +39,26 @@ declare module '@polkadot/api/types/errors' {
|
||||
* The signing account has no permission to do the operation.
|
||||
**/
|
||||
NoPermission: AugmentedError<ApiType>;
|
||||
/**
|
||||
* No provider reference exists to allow a non-zero balance of a non-self-sufficient asset.
|
||||
**/
|
||||
NoProvider: AugmentedError<ApiType>;
|
||||
/**
|
||||
* A mint operation lead to an overflow.
|
||||
**/
|
||||
Overflow: AugmentedError<ApiType>;
|
||||
/**
|
||||
* Attempt to destroy an asset class when non-zombie, reference-bearing accounts exist.
|
||||
* No approval exists that would allow the transfer.
|
||||
**/
|
||||
RefsLeft: AugmentedError<ApiType>;
|
||||
/**
|
||||
* Too many zombie accounts in use.
|
||||
**/
|
||||
TooManyZombies: AugmentedError<ApiType>;
|
||||
Unapproved: AugmentedError<ApiType>;
|
||||
/**
|
||||
* The given asset ID is unknown.
|
||||
**/
|
||||
Unknown: AugmentedError<ApiType>;
|
||||
/**
|
||||
* The source account would not survive the transfer and it needs to stay alive.
|
||||
**/
|
||||
WouldDie: AugmentedError<ApiType>;
|
||||
};
|
||||
authorship: {
|
||||
[key: string]: AugmentedError<ApiType>;
|
||||
@@ -87,6 +91,21 @@ declare module '@polkadot/api/types/errors' {
|
||||
**/
|
||||
UnclesAlreadySet: AugmentedError<ApiType>;
|
||||
};
|
||||
babe: {
|
||||
[key: string]: AugmentedError<ApiType>;
|
||||
/**
|
||||
* A given equivocation report is valid but already previously reported.
|
||||
**/
|
||||
DuplicateOffenceReport: AugmentedError<ApiType>;
|
||||
/**
|
||||
* An equivocation proof provided as part of an equivocation report is invalid.
|
||||
**/
|
||||
InvalidEquivocationProof: AugmentedError<ApiType>;
|
||||
/**
|
||||
* A key ownership proof provided as part of an equivocation report is invalid.
|
||||
**/
|
||||
InvalidKeyOwnershipProof: AugmentedError<ApiType>;
|
||||
};
|
||||
balances: {
|
||||
[key: string]: AugmentedError<ApiType>;
|
||||
/**
|
||||
@@ -176,9 +195,17 @@ declare module '@polkadot/api/types/errors' {
|
||||
**/
|
||||
CodeNotFound: AugmentedError<ApiType>;
|
||||
/**
|
||||
* The code supplied to `put_code` exceeds the limit specified in the current schedule.
|
||||
* The code supplied to `instantiate_with_code` exceeds the limit specified in the
|
||||
* current schedule.
|
||||
**/
|
||||
CodeTooLarge: AugmentedError<ApiType>;
|
||||
/**
|
||||
* A contract could not be evicted because it has enough balance to pay rent.
|
||||
*
|
||||
* This can be returned from [`Pallet::claim_surcharge`] because the target
|
||||
* contract has enough balance to pay for its rent.
|
||||
**/
|
||||
ContractNotEvictable: AugmentedError<ApiType>;
|
||||
/**
|
||||
* Contract trapped during execution.
|
||||
**/
|
||||
@@ -187,6 +214,18 @@ declare module '@polkadot/api/types/errors' {
|
||||
* Input passed to a contract API function failed to decode as expected type.
|
||||
**/
|
||||
DecodingFailed: AugmentedError<ApiType>;
|
||||
/**
|
||||
* Removal of a contract failed because the deletion queue is full.
|
||||
*
|
||||
* This can happen when either calling [`Pallet::claim_surcharge`] or `seal_terminate`.
|
||||
* The queue is filled by deleting contracts and emptied by a fixed amount each block.
|
||||
* Trying again during another block is the only way to resolve this issue.
|
||||
**/
|
||||
DeletionQueueFull: AugmentedError<ApiType>;
|
||||
/**
|
||||
* A contract with the same AccountId already exists.
|
||||
**/
|
||||
DuplicateContract: AugmentedError<ApiType>;
|
||||
/**
|
||||
* The topics passed to `seal_deposit_events` contains at least one duplicate.
|
||||
**/
|
||||
@@ -229,6 +268,12 @@ declare module '@polkadot/api/types/errors' {
|
||||
* its contructor. No contracts are allowed to exist below that threshold.
|
||||
**/
|
||||
NewContractNotFunded: AugmentedError<ApiType>;
|
||||
/**
|
||||
* The chain does not provide a chain extension. Calling the chain extension results
|
||||
* in this error. Note that this usually shouldn't happen as deploying such contracts
|
||||
* is rejected.
|
||||
**/
|
||||
NoChainExtension: AugmentedError<ApiType>;
|
||||
/**
|
||||
* The contract that was called is either no contract at all (a plain account)
|
||||
* or is a tombstone.
|
||||
@@ -256,6 +301,13 @@ declare module '@polkadot/api/types/errors' {
|
||||
* of a tombstone.
|
||||
**/
|
||||
ReentranceDenied: AugmentedError<ApiType>;
|
||||
/**
|
||||
* A storage modification exhausted the 32bit type that holds the storage size.
|
||||
*
|
||||
* This can either happen when the accumulated storage in bytes is too large or
|
||||
* when number of storage items is too large.
|
||||
**/
|
||||
StorageExhausted: AugmentedError<ApiType>;
|
||||
/**
|
||||
* The amount of topics passed to `seal_deposit_events` exceeds the limit.
|
||||
**/
|
||||
@@ -458,6 +510,21 @@ declare module '@polkadot/api/types/errors' {
|
||||
**/
|
||||
WrongUpperBound: AugmentedError<ApiType>;
|
||||
};
|
||||
electionProviderMultiPhase: {
|
||||
[key: string]: AugmentedError<ApiType>;
|
||||
/**
|
||||
* Submission was too early.
|
||||
**/
|
||||
PreDispatchEarlySubmission: AugmentedError<ApiType>;
|
||||
/**
|
||||
* Submission was too weak, score-wise.
|
||||
**/
|
||||
PreDispatchWeakSubmission: AugmentedError<ApiType>;
|
||||
/**
|
||||
* Wrong number of winners presented.
|
||||
**/
|
||||
PreDispatchWrongWinnerCount: AugmentedError<ApiType>;
|
||||
};
|
||||
elections: {
|
||||
[key: string]: AugmentedError<ApiType>;
|
||||
/**
|
||||
@@ -468,10 +535,6 @@ declare module '@polkadot/api/types/errors' {
|
||||
* Candidate does not have enough funds.
|
||||
**/
|
||||
InsufficientCandidateFunds: AugmentedError<ApiType>;
|
||||
/**
|
||||
* The provided count of number of candidates is incorrect.
|
||||
**/
|
||||
InvalidCandidateCount: AugmentedError<ApiType>;
|
||||
/**
|
||||
* The renouncing origin presented a wrong `Renouncing` parameter.
|
||||
**/
|
||||
@@ -484,6 +547,10 @@ declare module '@polkadot/api/types/errors' {
|
||||
* The provided count of number of votes is incorrect.
|
||||
**/
|
||||
InvalidVoteCount: AugmentedError<ApiType>;
|
||||
/**
|
||||
* The provided count of number of candidates is incorrect.
|
||||
**/
|
||||
InvalidWitnessData: AugmentedError<ApiType>;
|
||||
/**
|
||||
* Cannot vote with stake less than minimum balance.
|
||||
**/
|
||||
@@ -515,7 +582,7 @@ declare module '@polkadot/api/types/errors' {
|
||||
/**
|
||||
* Runner cannot re-submit candidacy.
|
||||
**/
|
||||
RunnerSubmit: AugmentedError<ApiType>;
|
||||
RunnerUpSubmit: AugmentedError<ApiType>;
|
||||
/**
|
||||
* Cannot vote more than candidates.
|
||||
**/
|
||||
@@ -529,6 +596,42 @@ declare module '@polkadot/api/types/errors' {
|
||||
**/
|
||||
UnableToVote: AugmentedError<ApiType>;
|
||||
};
|
||||
gilt: {
|
||||
[key: string]: AugmentedError<ApiType>;
|
||||
/**
|
||||
* The amount of the bid is less than the minimum allowed.
|
||||
**/
|
||||
AmountTooSmall: AugmentedError<ApiType>;
|
||||
/**
|
||||
* The queue for the bid's duration is full and the amount bid is too low to get in through
|
||||
* replacing an existing bid.
|
||||
**/
|
||||
BidTooLow: AugmentedError<ApiType>;
|
||||
/**
|
||||
* The duration is the bid is greater than the number of queues.
|
||||
**/
|
||||
DurationTooBig: AugmentedError<ApiType>;
|
||||
/**
|
||||
* The duration of the bid is less than one.
|
||||
**/
|
||||
DurationTooSmall: AugmentedError<ApiType>;
|
||||
/**
|
||||
* Gilt not yet at expiry date.
|
||||
**/
|
||||
NotExpired: AugmentedError<ApiType>;
|
||||
/**
|
||||
* The given bid for retraction is not found.
|
||||
**/
|
||||
NotFound: AugmentedError<ApiType>;
|
||||
/**
|
||||
* Not the owner of the gilt.
|
||||
**/
|
||||
NotOwner: AugmentedError<ApiType>;
|
||||
/**
|
||||
* Gilt index is unknown.
|
||||
**/
|
||||
Unknown: AugmentedError<ApiType>;
|
||||
};
|
||||
grandpa: {
|
||||
[key: string]: AugmentedError<ApiType>;
|
||||
/**
|
||||
@@ -640,6 +743,64 @@ declare module '@polkadot/api/types/errors' {
|
||||
**/
|
||||
InvalidKey: AugmentedError<ApiType>;
|
||||
};
|
||||
indices: {
|
||||
[key: string]: AugmentedError<ApiType>;
|
||||
/**
|
||||
* The index was not available.
|
||||
**/
|
||||
InUse: AugmentedError<ApiType>;
|
||||
/**
|
||||
* The index was not already assigned.
|
||||
**/
|
||||
NotAssigned: AugmentedError<ApiType>;
|
||||
/**
|
||||
* The index is assigned to another account.
|
||||
**/
|
||||
NotOwner: AugmentedError<ApiType>;
|
||||
/**
|
||||
* The source and destination accounts are identical.
|
||||
**/
|
||||
NotTransfer: AugmentedError<ApiType>;
|
||||
/**
|
||||
* The index is permanent and may not be freed/changed.
|
||||
**/
|
||||
Permanent: AugmentedError<ApiType>;
|
||||
};
|
||||
lottery: {
|
||||
[key: string]: AugmentedError<ApiType>;
|
||||
/**
|
||||
* A lottery has already ended.
|
||||
**/
|
||||
AlreadyEnded: AugmentedError<ApiType>;
|
||||
/**
|
||||
* You are already participating in the lottery with this call.
|
||||
**/
|
||||
AlreadyParticipating: AugmentedError<ApiType>;
|
||||
/**
|
||||
* Failed to encode calls
|
||||
**/
|
||||
EncodingFailed: AugmentedError<ApiType>;
|
||||
/**
|
||||
* A lottery is already in progress.
|
||||
**/
|
||||
InProgress: AugmentedError<ApiType>;
|
||||
/**
|
||||
* The call is not valid for an open lottery.
|
||||
**/
|
||||
InvalidCall: AugmentedError<ApiType>;
|
||||
/**
|
||||
* A lottery has not been configured.
|
||||
**/
|
||||
NotConfigured: AugmentedError<ApiType>;
|
||||
/**
|
||||
* An overflow has occurred.
|
||||
**/
|
||||
Overflow: AugmentedError<ApiType>;
|
||||
/**
|
||||
* Too many calls for a single lottery.
|
||||
**/
|
||||
TooManyCalls: AugmentedError<ApiType>;
|
||||
};
|
||||
multisig: {
|
||||
[key: string]: AugmentedError<ApiType>;
|
||||
/**
|
||||
@@ -650,6 +811,10 @@ declare module '@polkadot/api/types/errors' {
|
||||
* The data to be stored is already stored.
|
||||
**/
|
||||
AlreadyStored: AugmentedError<ApiType>;
|
||||
/**
|
||||
* The maximum weight information provided was too low.
|
||||
**/
|
||||
MaxWeightTooLow: AugmentedError<ApiType>;
|
||||
/**
|
||||
* Threshold must be 2 or greater.
|
||||
**/
|
||||
@@ -690,10 +855,6 @@ declare module '@polkadot/api/types/errors' {
|
||||
* A timepoint was given, yet no multisig operation is underway.
|
||||
**/
|
||||
UnexpectedTimepoint: AugmentedError<ApiType>;
|
||||
/**
|
||||
* The maximum weight information provided was too low.
|
||||
**/
|
||||
WeightTooLow: AugmentedError<ApiType>;
|
||||
/**
|
||||
* A different timepoint was given to the multisig operation that is underway.
|
||||
**/
|
||||
@@ -752,6 +913,10 @@ declare module '@polkadot/api/types/errors' {
|
||||
* This user has already vouched for this recovery
|
||||
**/
|
||||
AlreadyVouched: AugmentedError<ApiType>;
|
||||
/**
|
||||
* Some internal state is broken.
|
||||
**/
|
||||
BadState: AugmentedError<ApiType>;
|
||||
/**
|
||||
* The friend must wait until the delay period to vouch for this recovery
|
||||
**/
|
||||
@@ -830,6 +995,10 @@ declare module '@polkadot/api/types/errors' {
|
||||
* Invalid ownership proof.
|
||||
**/
|
||||
InvalidProof: AugmentedError<ApiType>;
|
||||
/**
|
||||
* Key setting account is not live, so it's impossible to associate keys.
|
||||
**/
|
||||
NoAccount: AugmentedError<ApiType>;
|
||||
/**
|
||||
* No associated validator ID for account.
|
||||
**/
|
||||
@@ -929,9 +1098,13 @@ declare module '@polkadot/api/types/errors' {
|
||||
**/
|
||||
AlreadyPaired: AugmentedError<ApiType>;
|
||||
/**
|
||||
* The call is not allowed at the given time due to restrictions of election period.
|
||||
* Internal state has become somehow corrupted and the operation cannot continue.
|
||||
**/
|
||||
CallNotAllowed: AugmentedError<ApiType>;
|
||||
BadState: AugmentedError<ApiType>;
|
||||
/**
|
||||
* A nomination target was supplied that was blocked or otherwise not a validator.
|
||||
**/
|
||||
BadTarget: AugmentedError<ApiType>;
|
||||
/**
|
||||
* Duplicate index.
|
||||
**/
|
||||
@@ -989,60 +1162,9 @@ declare module '@polkadot/api/types/errors' {
|
||||
**/
|
||||
NoUnlockChunk: AugmentedError<ApiType>;
|
||||
/**
|
||||
* Error while building the assignment type from the compact. This can happen if an index
|
||||
* is invalid, or if the weights _overflow_.
|
||||
* Too many nomination targets supplied.
|
||||
**/
|
||||
OffchainElectionBogusCompact: AugmentedError<ApiType>;
|
||||
/**
|
||||
* The submitted result has unknown edges that are not among the presented winners.
|
||||
**/
|
||||
OffchainElectionBogusEdge: AugmentedError<ApiType>;
|
||||
/**
|
||||
* The election size is invalid.
|
||||
**/
|
||||
OffchainElectionBogusElectionSize: AugmentedError<ApiType>;
|
||||
/**
|
||||
* One of the submitted nominators has an edge to which they have not voted on chain.
|
||||
**/
|
||||
OffchainElectionBogusNomination: AugmentedError<ApiType>;
|
||||
/**
|
||||
* One of the submitted nominators is not an active nominator on chain.
|
||||
**/
|
||||
OffchainElectionBogusNominator: AugmentedError<ApiType>;
|
||||
/**
|
||||
* The claimed score does not match with the one computed from the data.
|
||||
**/
|
||||
OffchainElectionBogusScore: AugmentedError<ApiType>;
|
||||
/**
|
||||
* A self vote must only be originated from a validator to ONLY themselves.
|
||||
**/
|
||||
OffchainElectionBogusSelfVote: AugmentedError<ApiType>;
|
||||
/**
|
||||
* One of the submitted winners is not an active candidate on chain (index is out of range
|
||||
* in snapshot).
|
||||
**/
|
||||
OffchainElectionBogusWinner: AugmentedError<ApiType>;
|
||||
/**
|
||||
* Incorrect number of winners were presented.
|
||||
**/
|
||||
OffchainElectionBogusWinnerCount: AugmentedError<ApiType>;
|
||||
/**
|
||||
* The submitted result is received out of the open window.
|
||||
**/
|
||||
OffchainElectionEarlySubmission: AugmentedError<ApiType>;
|
||||
/**
|
||||
* One of the submitted nominators has an edge which is submitted before the last non-zero
|
||||
* slash of the target.
|
||||
**/
|
||||
OffchainElectionSlashedNomination: AugmentedError<ApiType>;
|
||||
/**
|
||||
* The submitted result is not as good as the one stored on chain.
|
||||
**/
|
||||
OffchainElectionWeakSubmission: AugmentedError<ApiType>;
|
||||
/**
|
||||
* The snapshot data of the current window is missing.
|
||||
**/
|
||||
SnapshotUnavailable: AugmentedError<ApiType>;
|
||||
TooManyTargets: AugmentedError<ApiType>;
|
||||
};
|
||||
sudo: {
|
||||
[key: string]: AugmentedError<ApiType>;
|
||||
@@ -1121,6 +1243,17 @@ declare module '@polkadot/api/types/errors' {
|
||||
**/
|
||||
WrongProposalWeight: AugmentedError<ApiType>;
|
||||
};
|
||||
technicalMembership: {
|
||||
[key: string]: AugmentedError<ApiType>;
|
||||
/**
|
||||
* Already a member.
|
||||
**/
|
||||
AlreadyMember: AugmentedError<ApiType>;
|
||||
/**
|
||||
* Not a member.
|
||||
**/
|
||||
NotMember: AugmentedError<ApiType>;
|
||||
};
|
||||
tips: {
|
||||
[key: string]: AugmentedError<ApiType>;
|
||||
/**
|
||||
@@ -1158,6 +1291,10 @@ declare module '@polkadot/api/types/errors' {
|
||||
* No proposal or bounty at that index.
|
||||
**/
|
||||
InvalidIndex: AugmentedError<ApiType>;
|
||||
/**
|
||||
* Too many approvals in the queue.
|
||||
**/
|
||||
TooManyApprovals: AugmentedError<ApiType>;
|
||||
};
|
||||
vesting: {
|
||||
[key: string]: AugmentedError<ApiType>;
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
// Auto-generated via `yarn polkadot-types-from-chain`, do not edit
|
||||
/* eslint-disable */
|
||||
|
||||
import type { Bytes, Option, Vec, bool, u16, u32 } from '@polkadot/types';
|
||||
import type { Bytes, Option, Vec, bool, u16, u32, u8 } from '@polkadot/types';
|
||||
import type { ITuple } from '@polkadot/types/types';
|
||||
import type { TAssetBalance } from '@polkadot/types/interfaces/assets';
|
||||
import type { BalanceStatus } from '@polkadot/types/interfaces/balances';
|
||||
@@ -9,11 +9,13 @@ import type { MemberCount, ProposalIndex } from '@polkadot/types/interfaces/coll
|
||||
import type { AuthorityId } from '@polkadot/types/interfaces/consensus';
|
||||
import type { PropIndex, ReferendumIndex } from '@polkadot/types/interfaces/democracy';
|
||||
import type { VoteThreshold } from '@polkadot/types/interfaces/elections';
|
||||
import type { ActiveIndex } from '@polkadot/types/interfaces/gilt';
|
||||
import type { AuthorityList } from '@polkadot/types/interfaces/grandpa';
|
||||
import type { RegistrarIndex } from '@polkadot/types/interfaces/identity';
|
||||
import type { CallIndex } from '@polkadot/types/interfaces/lottery';
|
||||
import type { Kind, OpaqueTimeSlot } from '@polkadot/types/interfaces/offences';
|
||||
import type { ProxyType } from '@polkadot/types/interfaces/proxy';
|
||||
import type { AccountId, AccountIndex, AssetId, Balance, BlockNumber, CallHash, Hash, PhantomData } from '@polkadot/types/interfaces/runtime';
|
||||
import type { AccountId, AccountIndex, AssetId, Balance, BalanceOf, BlockNumber, CallHash, Hash, PhantomData } from '@polkadot/types/interfaces/runtime';
|
||||
import type { TaskAddress } from '@polkadot/types/interfaces/scheduler';
|
||||
import type { IdentificationTuple, SessionIndex } from '@polkadot/types/interfaces/session';
|
||||
import type { ElectionCompute, EraIndex } from '@polkadot/types/interfaces/staking';
|
||||
@@ -26,6 +28,29 @@ declare module '@polkadot/api/types/events' {
|
||||
export interface AugmentedEvents<ApiType> {
|
||||
assets: {
|
||||
[key: string]: AugmentedEvent<ApiType>;
|
||||
/**
|
||||
* An approval for account `delegate` was cancelled by `owner`.
|
||||
* \[id, owner, delegate\]
|
||||
**/
|
||||
ApprovalCancelled: AugmentedEvent<ApiType, [AssetId, AccountId, AccountId]>;
|
||||
/**
|
||||
* (Additional) funds have been approved for transfer to a destination account.
|
||||
* \[asset_id, source, delegate, amount\]
|
||||
**/
|
||||
ApprovedTransfer: AugmentedEvent<ApiType, [AssetId, AccountId, AccountId, TAssetBalance]>;
|
||||
/**
|
||||
* Some asset `asset_id` was frozen. \[asset_id\]
|
||||
**/
|
||||
AssetFrozen: AugmentedEvent<ApiType, [AssetId]>;
|
||||
/**
|
||||
* An asset has had its attributes changed by the `Force` origin.
|
||||
* \[id\]
|
||||
**/
|
||||
AssetStatusChanged: AugmentedEvent<ApiType, [AssetId]>;
|
||||
/**
|
||||
* Some asset `asset_id` was thawed. \[asset_id\]
|
||||
**/
|
||||
AssetThawed: AugmentedEvent<ApiType, [AssetId]>;
|
||||
/**
|
||||
* Some assets were destroyed. \[asset_id, owner, balance\]
|
||||
**/
|
||||
@@ -42,10 +67,6 @@ declare module '@polkadot/api/types/events' {
|
||||
* Some asset class was force-created. \[asset_id, owner\]
|
||||
**/
|
||||
ForceCreated: AugmentedEvent<ApiType, [AssetId, AccountId]>;
|
||||
/**
|
||||
* Some assets was transferred by an admin. \[asset_id, from, to, amount\]
|
||||
**/
|
||||
ForceTransferred: AugmentedEvent<ApiType, [AssetId, AccountId, AccountId, TAssetBalance]>;
|
||||
/**
|
||||
* Some account `who` was frozen. \[asset_id, who\]
|
||||
**/
|
||||
@@ -55,9 +76,13 @@ declare module '@polkadot/api/types/events' {
|
||||
**/
|
||||
Issued: AugmentedEvent<ApiType, [AssetId, AccountId, TAssetBalance]>;
|
||||
/**
|
||||
* The maximum amount of zombies allowed has changed. \[asset_id, max_zombies\]
|
||||
* Metadata has been cleared for an asset. \[asset_id\]
|
||||
**/
|
||||
MaxZombiesChanged: AugmentedEvent<ApiType, [AssetId, u32]>;
|
||||
MetadataCleared: AugmentedEvent<ApiType, [AssetId]>;
|
||||
/**
|
||||
* New metadata has been set for an asset. \[asset_id, name, symbol, decimals, is_frozen\]
|
||||
**/
|
||||
MetadataSet: AugmentedEvent<ApiType, [AssetId, Bytes, Bytes, u8, bool]>;
|
||||
/**
|
||||
* The owner changed \[asset_id, owner\]
|
||||
**/
|
||||
@@ -74,6 +99,12 @@ declare module '@polkadot/api/types/events' {
|
||||
* Some assets were transferred. \[asset_id, from, to, amount\]
|
||||
**/
|
||||
Transferred: AugmentedEvent<ApiType, [AssetId, AccountId, AccountId, TAssetBalance]>;
|
||||
/**
|
||||
* An `amount` was transferred in its entirety from `owner` to `destination` by
|
||||
* the approved `delegate`.
|
||||
* \[id, owner, delegate, destination\]
|
||||
**/
|
||||
TransferredApproved: AugmentedEvent<ApiType, [AssetId, AccountId, AccountId, AccountId, TAssetBalance]>;
|
||||
};
|
||||
balances: {
|
||||
[key: string]: AugmentedEvent<ApiType>;
|
||||
@@ -147,45 +178,71 @@ declare module '@polkadot/api/types/events' {
|
||||
contracts: {
|
||||
[key: string]: AugmentedEvent<ApiType>;
|
||||
/**
|
||||
* Code with the specified hash has been stored.
|
||||
* A code with the specified hash was removed.
|
||||
* \[code_hash\]
|
||||
*
|
||||
* This happens when the last contract that uses this code hash was removed or evicted.
|
||||
**/
|
||||
CodeRemoved: AugmentedEvent<ApiType, [Hash]>;
|
||||
/**
|
||||
* Code with the specified hash has been stored. \[code_hash\]
|
||||
**/
|
||||
CodeStored: AugmentedEvent<ApiType, [Hash]>;
|
||||
/**
|
||||
* An event deposited upon execution of a contract from the account.
|
||||
* \[account, data\]
|
||||
**/
|
||||
ContractExecution: AugmentedEvent<ApiType, [AccountId, Bytes]>;
|
||||
/**
|
||||
* Contract has been evicted and is now in tombstone state.
|
||||
* \[contract, tombstone\]
|
||||
* A custom event emitted by the contract.
|
||||
* \[contract, data\]
|
||||
*
|
||||
* # Params
|
||||
*
|
||||
* - `contract`: `AccountId`: The account ID of the evicted contract.
|
||||
* - `tombstone`: `bool`: True if the evicted contract left behind a tombstone.
|
||||
* - `contract`: The contract that emitted the event.
|
||||
* - `data`: Data supplied by the contract. Metadata generated during contract
|
||||
* compilation is needed to decode it.
|
||||
**/
|
||||
Evicted: AugmentedEvent<ApiType, [AccountId, bool]>;
|
||||
ContractEmitted: AugmentedEvent<ApiType, [AccountId, Bytes]>;
|
||||
/**
|
||||
* Contract deployed by address at the specified address. \[owner, contract\]
|
||||
* Contract has been evicted and is now in tombstone state. \[contract\]
|
||||
**/
|
||||
Evicted: AugmentedEvent<ApiType, [AccountId]>;
|
||||
/**
|
||||
* Contract deployed by address at the specified address. \[deployer, contract\]
|
||||
**/
|
||||
Instantiated: AugmentedEvent<ApiType, [AccountId, AccountId]>;
|
||||
/**
|
||||
* Restoration for a contract has been successful.
|
||||
* \[donor, dest, code_hash, rent_allowance\]
|
||||
* Restoration of a contract has been successful.
|
||||
* \[restorer, dest, code_hash, rent_allowance\]
|
||||
*
|
||||
* # Params
|
||||
*
|
||||
* - `donor`: `AccountId`: Account ID of the restoring contract
|
||||
* - `dest`: `AccountId`: Account ID of the restored contract
|
||||
* - `code_hash`: `Hash`: Code hash of the restored contract
|
||||
* - `rent_allowance: `Balance`: Rent allowance of the restored contract
|
||||
* - `restorer`: Account ID of the restoring contract.
|
||||
* - `dest`: Account ID of the restored contract.
|
||||
* - `code_hash`: Code hash of the restored contract.
|
||||
* - `rent_allowance`: Rent allowance of the restored contract.
|
||||
**/
|
||||
Restored: AugmentedEvent<ApiType, [AccountId, AccountId, Hash, Balance]>;
|
||||
/**
|
||||
* Triggered when the current \[schedule\] is updated.
|
||||
* Triggered when the current schedule is updated.
|
||||
* \[version\]
|
||||
*
|
||||
* # Params
|
||||
*
|
||||
* - `version`: The version of the newly set schedule.
|
||||
**/
|
||||
ScheduleUpdated: AugmentedEvent<ApiType, [u32]>;
|
||||
/**
|
||||
* Contract has been terminated without leaving a tombstone.
|
||||
* \[contract, beneficiary\]
|
||||
*
|
||||
* # Params
|
||||
*
|
||||
* - `contract`: The contract that was terminated.
|
||||
* - `beneficiary`: The account that received the contracts remaining balance.
|
||||
*
|
||||
* # Note
|
||||
*
|
||||
* The only way for a contract to be removed without a tombstone and emitting
|
||||
* this event is by calling `seal_terminate`.
|
||||
**/
|
||||
Terminated: AugmentedEvent<ApiType, [AccountId, AccountId]>;
|
||||
};
|
||||
council: {
|
||||
[key: string]: AugmentedEvent<ApiType>;
|
||||
@@ -306,10 +363,44 @@ declare module '@polkadot/api/types/events' {
|
||||
**/
|
||||
Vetoed: AugmentedEvent<ApiType, [AccountId, Hash, BlockNumber]>;
|
||||
};
|
||||
electionProviderMultiPhase: {
|
||||
[key: string]: AugmentedEvent<ApiType>;
|
||||
/**
|
||||
* The election has been finalized, with `Some` of the given computation, or else if the
|
||||
* election failed, `None`.
|
||||
**/
|
||||
ElectionFinalized: AugmentedEvent<ApiType, [Option<ElectionCompute>]>;
|
||||
/**
|
||||
* An account has been rewarded for their signed submission being finalized.
|
||||
**/
|
||||
Rewarded: AugmentedEvent<ApiType, [AccountId]>;
|
||||
/**
|
||||
* The signed phase of the given round has started.
|
||||
**/
|
||||
SignedPhaseStarted: AugmentedEvent<ApiType, [u32]>;
|
||||
/**
|
||||
* An account has been slashed for submitting an invalid signed submission.
|
||||
**/
|
||||
Slashed: AugmentedEvent<ApiType, [AccountId]>;
|
||||
/**
|
||||
* A solution was stored with the given compute.
|
||||
*
|
||||
* If the solution is signed, this means that it hasn't yet been processed. If the
|
||||
* solution is unsigned, this means that it has also been processed.
|
||||
**/
|
||||
SolutionStored: AugmentedEvent<ApiType, [ElectionCompute]>;
|
||||
/**
|
||||
* The unsigned phase of the given round has started.
|
||||
**/
|
||||
UnsignedPhaseStarted: AugmentedEvent<ApiType, [u32]>;
|
||||
};
|
||||
elections: {
|
||||
[key: string]: AugmentedEvent<ApiType>;
|
||||
/**
|
||||
* A candidate was slashed due to failing to obtain a seat as member or runner-up
|
||||
* A \[candidate\] was slashed by \[amount\] due to failing to obtain a seat as member or
|
||||
* runner-up.
|
||||
*
|
||||
* Note that old members and runners-up are also candidates.
|
||||
**/
|
||||
CandidateSlashed: AugmentedEvent<ApiType, [AccountId, Balance]>;
|
||||
/**
|
||||
@@ -327,25 +418,44 @@ declare module '@polkadot/api/types/events' {
|
||||
**/
|
||||
MemberKicked: AugmentedEvent<ApiType, [AccountId]>;
|
||||
/**
|
||||
* A \[member\] has renounced their candidacy.
|
||||
**/
|
||||
MemberRenounced: AugmentedEvent<ApiType, [AccountId]>;
|
||||
/**
|
||||
* A new term with \[new_members\]. This indicates that enough candidates existed to run the
|
||||
* election, not that enough have has been elected. The inner value must be examined for
|
||||
* this purpose. A `NewTerm(\[\])` indicates that some candidates got their bond slashed and
|
||||
* none were elected, whilst `EmptyTerm` means that no candidates existed to begin with.
|
||||
* A new term with \[new_members\]. This indicates that enough candidates existed to run
|
||||
* the election, not that enough have has been elected. The inner value must be examined
|
||||
* for this purpose. A `NewTerm(\[\])` indicates that some candidates got their bond
|
||||
* slashed and none were elected, whilst `EmptyTerm` means that no candidates existed to
|
||||
* begin with.
|
||||
**/
|
||||
NewTerm: AugmentedEvent<ApiType, [Vec<ITuple<[AccountId, Balance]>>]>;
|
||||
/**
|
||||
* A seat holder (member or runner-up) was slashed due to failing to retaining their position.
|
||||
* Someone has renounced their candidacy.
|
||||
**/
|
||||
Renounced: AugmentedEvent<ApiType, [AccountId]>;
|
||||
/**
|
||||
* A \[seat holder\] was slashed by \[amount\] by being forcefully removed from the set.
|
||||
**/
|
||||
SeatHolderSlashed: AugmentedEvent<ApiType, [AccountId, Balance]>;
|
||||
};
|
||||
gilt: {
|
||||
[key: string]: AugmentedEvent<ApiType>;
|
||||
/**
|
||||
* A voter was reported with the the report being successful or not.
|
||||
* \[voter, reporter, success\]
|
||||
* A bid was successfully placed.
|
||||
* \[ who, amount, duration \]
|
||||
**/
|
||||
VoterReported: AugmentedEvent<ApiType, [AccountId, AccountId, bool]>;
|
||||
BidPlaced: AugmentedEvent<ApiType, [AccountId, BalanceOf, u32]>;
|
||||
/**
|
||||
* A bid was successfully removed (before being accepted as a gilt).
|
||||
* \[ who, amount, duration \]
|
||||
**/
|
||||
BidRetracted: AugmentedEvent<ApiType, [AccountId, BalanceOf, u32]>;
|
||||
/**
|
||||
* A bid was accepted as a gilt. The balance may not be released until expiry.
|
||||
* \[ index, expiry, who, amount \]
|
||||
**/
|
||||
GiltIssued: AugmentedEvent<ApiType, [ActiveIndex, BlockNumber, AccountId, BalanceOf]>;
|
||||
/**
|
||||
* An expired gilt has been thawed.
|
||||
* \[ index, who, original_amount, additional_amount \]
|
||||
**/
|
||||
GiltThawed: AugmentedEvent<ApiType, [ActiveIndex, AccountId, BalanceOf, BalanceOf]>;
|
||||
};
|
||||
grandpa: {
|
||||
[key: string]: AugmentedEvent<ApiType>;
|
||||
@@ -437,6 +547,25 @@ declare module '@polkadot/api/types/events' {
|
||||
**/
|
||||
IndexFrozen: AugmentedEvent<ApiType, [AccountIndex, AccountId]>;
|
||||
};
|
||||
lottery: {
|
||||
[key: string]: AugmentedEvent<ApiType>;
|
||||
/**
|
||||
* A new set of calls have been set!
|
||||
**/
|
||||
CallsUpdated: AugmentedEvent<ApiType, []>;
|
||||
/**
|
||||
* A lottery has been started!
|
||||
**/
|
||||
LotteryStarted: AugmentedEvent<ApiType, []>;
|
||||
/**
|
||||
* A ticket has been bought!
|
||||
**/
|
||||
TicketBought: AugmentedEvent<ApiType, [AccountId, CallIndex]>;
|
||||
/**
|
||||
* A winner has been chosen!
|
||||
**/
|
||||
Winner: AugmentedEvent<ApiType, [AccountId, Balance]>;
|
||||
};
|
||||
multisig: {
|
||||
[key: string]: AugmentedEvent<ApiType>;
|
||||
/**
|
||||
@@ -622,6 +751,10 @@ declare module '@polkadot/api/types/events' {
|
||||
* \[era_index, validator_payout, remainder\]
|
||||
**/
|
||||
EraPayout: AugmentedEvent<ApiType, [EraIndex, Balance, Balance]>;
|
||||
/**
|
||||
* A nominator has been kicked from a validator. \[nominator, stash\]
|
||||
**/
|
||||
Kicked: AugmentedEvent<ApiType, [AccountId, AccountId]>;
|
||||
/**
|
||||
* An old slashing report from a prior era was discarded because it could
|
||||
* not be processed. \[session_index\]
|
||||
@@ -637,13 +770,9 @@ declare module '@polkadot/api/types/events' {
|
||||
**/
|
||||
Slash: AugmentedEvent<ApiType, [AccountId, Balance]>;
|
||||
/**
|
||||
* A new solution for the upcoming election has been stored. \[compute\]
|
||||
* A new set of stakers was elected.
|
||||
**/
|
||||
SolutionStored: AugmentedEvent<ApiType, [ElectionCompute]>;
|
||||
/**
|
||||
* A new set of stakers was elected with the given \[compute\].
|
||||
**/
|
||||
StakingElection: AugmentedEvent<ApiType, [ElectionCompute]>;
|
||||
StakingElection: AugmentedEvent<ApiType, []>;
|
||||
/**
|
||||
* An account has unbonded this amount. \[stash, amount\]
|
||||
**/
|
||||
@@ -691,6 +820,10 @@ declare module '@polkadot/api/types/events' {
|
||||
* A new \[account\] was created.
|
||||
**/
|
||||
NewAccount: AugmentedEvent<ApiType, [AccountId]>;
|
||||
/**
|
||||
* On on-chain remark happened. \[origin, remark_hash\]
|
||||
**/
|
||||
Remarked: AugmentedEvent<ApiType, [AccountId, Hash]>;
|
||||
};
|
||||
technicalCommittee: {
|
||||
[key: string]: AugmentedEvent<ApiType>;
|
||||
|
||||
@@ -3,26 +3,28 @@
|
||||
|
||||
import type { Bytes, Data, Option, U8aFixed, Vec, bool, u32, u64 } from '@polkadot/types';
|
||||
import type { AnyNumber, ITuple, Observable } from '@polkadot/types/types';
|
||||
import type { AssetBalance, AssetDetails } from '@polkadot/types/interfaces/assets';
|
||||
import type { AssetApproval, AssetApprovalKey, AssetBalance, AssetDetails, AssetMetadata } from '@polkadot/types/interfaces/assets';
|
||||
import type { UncleEntryItem } from '@polkadot/types/interfaces/authorship';
|
||||
import type { BabeAuthorityWeight, MaybeRandomness, NextConfigDescriptor, Randomness } from '@polkadot/types/interfaces/babe';
|
||||
import type { BabeAuthorityWeight, BabeEpochConfiguration, MaybeRandomness, NextConfigDescriptor, Randomness } from '@polkadot/types/interfaces/babe';
|
||||
import type { AccountData, BalanceLock } from '@polkadot/types/interfaces/balances';
|
||||
import type { ProposalIndex, Votes } from '@polkadot/types/interfaces/collective';
|
||||
import type { AuthorityId } from '@polkadot/types/interfaces/consensus';
|
||||
import type { CodeHash, ContractInfo, PrefabWasmModule, Schedule } from '@polkadot/types/interfaces/contracts';
|
||||
import type { CodeHash, ContractInfo, DeletedContract, PrefabWasmModule, Schedule } from '@polkadot/types/interfaces/contracts';
|
||||
import type { PreimageStatus, PropIndex, Proposal, ReferendumIndex, ReferendumInfo, Voting } from '@polkadot/types/interfaces/democracy';
|
||||
import type { VoteThreshold } from '@polkadot/types/interfaces/elections';
|
||||
import type { ActiveGilt, ActiveGiltsTotal, ActiveIndex, GiltBid } from '@polkadot/types/interfaces/gilt';
|
||||
import type { SetId, StoredPendingChange, StoredState } from '@polkadot/types/interfaces/grandpa';
|
||||
import type { RegistrarInfo, Registration } from '@polkadot/types/interfaces/identity';
|
||||
import type { AuthIndex } from '@polkadot/types/interfaces/imOnline';
|
||||
import type { CallIndex, LotteryConfig } from '@polkadot/types/interfaces/lottery';
|
||||
import type { DeferredOffenceOf, Kind, OffenceDetails, OpaqueTimeSlot, ReportIdOf } from '@polkadot/types/interfaces/offences';
|
||||
import type { ProxyAnnouncement, ProxyDefinition } from '@polkadot/types/interfaces/proxy';
|
||||
import type { ActiveRecovery, RecoveryConfig } from '@polkadot/types/interfaces/recovery';
|
||||
import type { AccountId, AccountIndex, AssetId, Balance, BalanceOf, BlockNumber, Hash, KeyTypeId, Moment, OpaqueCall, Perbill, Releases, ValidatorId } from '@polkadot/types/interfaces/runtime';
|
||||
import type { AccountId, AccountIndex, AssetId, Balance, BalanceOf, BlockNumber, Hash, KeyTypeId, Moment, OpaqueCall, Perbill, Releases, Slot, ValidatorId } from '@polkadot/types/interfaces/runtime';
|
||||
import type { Scheduled, TaskAddress } from '@polkadot/types/interfaces/scheduler';
|
||||
import type { Keys, SessionIndex } from '@polkadot/types/interfaces/session';
|
||||
import type { Bid, BidKind, SocietyVote, StrikeCount, VouchingStatus } from '@polkadot/types/interfaces/society';
|
||||
import type { ActiveEraInfo, ElectionResult, ElectionScore, ElectionStatus, EraIndex, EraRewardPoints, Exposure, Forcing, Nominations, RewardDestination, SlashingSpans, SpanIndex, SpanRecord, StakingLedger, UnappliedSlash, ValidatorPrefs } from '@polkadot/types/interfaces/staking';
|
||||
import type { ActiveEraInfo, ElectionPhase, EraIndex, EraRewardPoints, Exposure, Forcing, Nominations, ReadySolution, RewardDestination, RoundSnapshot, SeatHolder, SlashingSpans, SolutionOrSnapshotSize, SpanIndex, SpanRecord, StakingLedger, UnappliedSlash, ValidatorPrefs, Voter } from '@polkadot/types/interfaces/staking';
|
||||
import type { AccountInfo, ConsumedWeight, DigestOf, EventIndex, EventRecord, LastRuntimeUpgradeInfo, Phase } from '@polkadot/types/interfaces/system';
|
||||
import type { Bounty, BountyIndex, OpenTip, TreasuryProposal } from '@polkadot/types/interfaces/treasury';
|
||||
import type { Multiplier } from '@polkadot/types/interfaces/txpayment';
|
||||
@@ -38,10 +40,19 @@ declare module '@polkadot/api/types/storage' {
|
||||
* The number of units of assets held by any given account.
|
||||
**/
|
||||
account: AugmentedQueryDoubleMap<ApiType, (key1: AssetId | AnyNumber | Uint8Array, key2: AccountId | string | Uint8Array) => Observable<AssetBalance>, [AssetId, AccountId]> & QueryableStorageEntry<ApiType, [AssetId, AccountId]>;
|
||||
/**
|
||||
* Approved balance transfers. First balance is the amount approved for transfer. Second
|
||||
* is the amount of `T::Currency` reserved for storing this.
|
||||
**/
|
||||
approvals: AugmentedQueryDoubleMap<ApiType, (key1: AssetId | AnyNumber | Uint8Array, key2: AssetApprovalKey | { owner?: any; delegate?: any } | string | Uint8Array) => Observable<Option<AssetApproval>>, [AssetId, AssetApprovalKey]> & QueryableStorageEntry<ApiType, [AssetId, AssetApprovalKey]>;
|
||||
/**
|
||||
* Details of an asset.
|
||||
**/
|
||||
asset: AugmentedQuery<ApiType, (arg: AssetId | AnyNumber | Uint8Array) => Observable<Option<AssetDetails>>, [AssetId]> & QueryableStorageEntry<ApiType, [AssetId]>;
|
||||
/**
|
||||
* Metadata of an asset.
|
||||
**/
|
||||
metadata: AugmentedQuery<ApiType, (arg: AssetId | AnyNumber | Uint8Array) => Observable<AssetMetadata>, [AssetId]> & QueryableStorageEntry<ApiType, [AssetId]>;
|
||||
};
|
||||
authorship: {
|
||||
[key: string]: QueryableStorageEntry<ApiType>;
|
||||
@@ -73,16 +84,28 @@ declare module '@polkadot/api/types/storage' {
|
||||
/**
|
||||
* Current slot number.
|
||||
**/
|
||||
currentSlot: AugmentedQuery<ApiType, () => Observable<u64>, []> & QueryableStorageEntry<ApiType, []>;
|
||||
currentSlot: AugmentedQuery<ApiType, () => Observable<Slot>, []> & QueryableStorageEntry<ApiType, []>;
|
||||
/**
|
||||
* The configuration for the current epoch. Should never be `None` as it is initialized in genesis.
|
||||
**/
|
||||
epochConfig: AugmentedQuery<ApiType, () => Observable<Option<BabeEpochConfiguration>>, []> & QueryableStorageEntry<ApiType, []>;
|
||||
/**
|
||||
* Current epoch index.
|
||||
**/
|
||||
epochIndex: AugmentedQuery<ApiType, () => Observable<u64>, []> & QueryableStorageEntry<ApiType, []>;
|
||||
/**
|
||||
* The block numbers when the last and current epoch have started, respectively `N-1` and
|
||||
* `N`.
|
||||
* NOTE: We track this is in order to annotate the block number when a given pool of
|
||||
* entropy was fixed (i.e. it was known to chain observers). Since epochs are defined in
|
||||
* slots, which may be skipped, the block numbers may not line up with the slot numbers.
|
||||
**/
|
||||
epochStart: AugmentedQuery<ApiType, () => Observable<ITuple<[BlockNumber, BlockNumber]>>, []> & QueryableStorageEntry<ApiType, []>;
|
||||
/**
|
||||
* The slot at which the first epoch actually started. This is 0
|
||||
* until the first block of the chain.
|
||||
**/
|
||||
genesisSlot: AugmentedQuery<ApiType, () => Observable<u64>, []> & QueryableStorageEntry<ApiType, []>;
|
||||
genesisSlot: AugmentedQuery<ApiType, () => Observable<Slot>, []> & QueryableStorageEntry<ApiType, []>;
|
||||
/**
|
||||
* Temporary value (cleared at block finalization) which is `Some`
|
||||
* if per-block initialization has already been called for current block.
|
||||
@@ -97,13 +120,22 @@ declare module '@polkadot/api/types/storage' {
|
||||
**/
|
||||
lateness: AugmentedQuery<ApiType, () => Observable<BlockNumber>, []> & QueryableStorageEntry<ApiType, []>;
|
||||
/**
|
||||
* Next epoch configuration, if changed.
|
||||
* Next epoch authorities.
|
||||
**/
|
||||
nextEpochConfig: AugmentedQuery<ApiType, () => Observable<Option<NextConfigDescriptor>>, []> & QueryableStorageEntry<ApiType, []>;
|
||||
nextAuthorities: AugmentedQuery<ApiType, () => Observable<Vec<ITuple<[AuthorityId, BabeAuthorityWeight]>>>, []> & QueryableStorageEntry<ApiType, []>;
|
||||
/**
|
||||
* The configuration for the next epoch, `None` if the config will not change
|
||||
* (you can fallback to `EpochConfig` instead in that case).
|
||||
**/
|
||||
nextEpochConfig: AugmentedQuery<ApiType, () => Observable<Option<BabeEpochConfiguration>>, []> & QueryableStorageEntry<ApiType, []>;
|
||||
/**
|
||||
* Next epoch randomness.
|
||||
**/
|
||||
nextRandomness: AugmentedQuery<ApiType, () => Observable<Randomness>, []> & QueryableStorageEntry<ApiType, []>;
|
||||
/**
|
||||
* Pending epoch configuration change that will be applied when the next epoch is enacted.
|
||||
**/
|
||||
pendingEpochConfigChange: AugmentedQuery<ApiType, () => Observable<Option<NextConfigDescriptor>>, []> & QueryableStorageEntry<ApiType, []>;
|
||||
/**
|
||||
* The epoch randomness for the *current* epoch.
|
||||
*
|
||||
@@ -139,7 +171,7 @@ declare module '@polkadot/api/types/storage' {
|
||||
/**
|
||||
* The balance of an account.
|
||||
*
|
||||
* NOTE: This is only used in the case that this module is used to store balances.
|
||||
* NOTE: This is only used in the case that this pallet is used to store balances.
|
||||
**/
|
||||
account: AugmentedQuery<ApiType, (arg: AccountId | string | Uint8Array) => Observable<AccountData>, [AccountId]> & QueryableStorageEntry<ApiType, [AccountId]>;
|
||||
/**
|
||||
@@ -197,6 +229,13 @@ declare module '@polkadot/api/types/storage' {
|
||||
* Current cost schedule for contracts.
|
||||
**/
|
||||
currentSchedule: AugmentedQuery<ApiType, () => Observable<Schedule>, []> & QueryableStorageEntry<ApiType, []>;
|
||||
/**
|
||||
* Evicted contracts that await child trie deletion.
|
||||
*
|
||||
* Child trie deletion is a heavy operation depending on the amount of storage items
|
||||
* stored in said trie. Therefore this operation is performed lazily in `on_initialize`.
|
||||
**/
|
||||
deletionQueue: AugmentedQuery<ApiType, () => Observable<Vec<DeletedContract>>, []> & QueryableStorageEntry<ApiType, []>;
|
||||
/**
|
||||
* A mapping from an original code hash to the original code, untouched by instrumentation.
|
||||
**/
|
||||
@@ -307,31 +346,101 @@ declare module '@polkadot/api/types/storage' {
|
||||
**/
|
||||
votingOf: AugmentedQuery<ApiType, (arg: AccountId | string | Uint8Array) => Observable<Voting>, [AccountId]> & QueryableStorageEntry<ApiType, [AccountId]>;
|
||||
};
|
||||
electionProviderMultiPhase: {
|
||||
[key: string]: QueryableStorageEntry<ApiType>;
|
||||
/**
|
||||
* Current phase.
|
||||
**/
|
||||
currentPhase: AugmentedQuery<ApiType, () => Observable<ElectionPhase>, []> & QueryableStorageEntry<ApiType, []>;
|
||||
/**
|
||||
* Desired number of targets to elect for this round.
|
||||
*
|
||||
* Only exists when [`Snapshot`] is present.
|
||||
**/
|
||||
desiredTargets: AugmentedQuery<ApiType, () => Observable<Option<u32>>, []> & QueryableStorageEntry<ApiType, []>;
|
||||
/**
|
||||
* Current best solution, signed or unsigned, queued to be returned upon `elect`.
|
||||
**/
|
||||
queuedSolution: AugmentedQuery<ApiType, () => Observable<Option<ReadySolution>>, []> & QueryableStorageEntry<ApiType, []>;
|
||||
/**
|
||||
* Internal counter for the number of rounds.
|
||||
*
|
||||
* This is useful for de-duplication of transactions submitted to the pool, and general
|
||||
* diagnostics of the pallet.
|
||||
*
|
||||
* This is merely incremented once per every time that an upstream `elect` is called.
|
||||
**/
|
||||
round: AugmentedQuery<ApiType, () => Observable<u32>, []> & QueryableStorageEntry<ApiType, []>;
|
||||
/**
|
||||
* Snapshot data of the round.
|
||||
*
|
||||
* This is created at the beginning of the signed phase and cleared upon calling `elect`.
|
||||
**/
|
||||
snapshot: AugmentedQuery<ApiType, () => Observable<Option<RoundSnapshot>>, []> & QueryableStorageEntry<ApiType, []>;
|
||||
/**
|
||||
* The metadata of the [`RoundSnapshot`]
|
||||
*
|
||||
* Only exists when [`Snapshot`] is present.
|
||||
**/
|
||||
snapshotMetadata: AugmentedQuery<ApiType, () => Observable<Option<SolutionOrSnapshotSize>>, []> & QueryableStorageEntry<ApiType, []>;
|
||||
};
|
||||
elections: {
|
||||
[key: string]: QueryableStorageEntry<ApiType>;
|
||||
/**
|
||||
* The present candidate list. Sorted based on account-id. A current member or runner-up
|
||||
* can never enter this vector and is always implicitly assumed to be a candidate.
|
||||
* The present candidate list. A current member or runner-up can never enter this vector
|
||||
* and is always implicitly assumed to be a candidate.
|
||||
*
|
||||
* Second element is the deposit.
|
||||
*
|
||||
* Invariant: Always sorted based on account id.
|
||||
**/
|
||||
candidates: AugmentedQuery<ApiType, () => Observable<Vec<AccountId>>, []> & QueryableStorageEntry<ApiType, []>;
|
||||
candidates: AugmentedQuery<ApiType, () => Observable<Vec<ITuple<[AccountId, BalanceOf]>>>, []> & QueryableStorageEntry<ApiType, []>;
|
||||
/**
|
||||
* The total number of vote rounds that have happened, excluding the upcoming one.
|
||||
**/
|
||||
electionRounds: AugmentedQuery<ApiType, () => Observable<u32>, []> & QueryableStorageEntry<ApiType, []>;
|
||||
/**
|
||||
* The current elected membership. Sorted based on account id.
|
||||
* The current elected members.
|
||||
*
|
||||
* Invariant: Always sorted based on account id.
|
||||
**/
|
||||
members: AugmentedQuery<ApiType, () => Observable<Vec<ITuple<[AccountId, BalanceOf]>>>, []> & QueryableStorageEntry<ApiType, []>;
|
||||
members: AugmentedQuery<ApiType, () => Observable<Vec<SeatHolder>>, []> & QueryableStorageEntry<ApiType, []>;
|
||||
/**
|
||||
* The current runners_up. Sorted based on low to high merit (worse to best).
|
||||
* The current reserved runners-up.
|
||||
*
|
||||
* Invariant: Always sorted based on rank (worse to best). Upon removal of a member, the
|
||||
* last (i.e. _best_) runner-up will be replaced.
|
||||
**/
|
||||
runnersUp: AugmentedQuery<ApiType, () => Observable<Vec<ITuple<[AccountId, BalanceOf]>>>, []> & QueryableStorageEntry<ApiType, []>;
|
||||
runnersUp: AugmentedQuery<ApiType, () => Observable<Vec<SeatHolder>>, []> & QueryableStorageEntry<ApiType, []>;
|
||||
/**
|
||||
* Votes and locked stake of a particular voter.
|
||||
*
|
||||
* TWOX-NOTE: SAFE as `AccountId` is a crypto hash
|
||||
* TWOX-NOTE: SAFE as `AccountId` is a crypto hash.
|
||||
**/
|
||||
voting: AugmentedQuery<ApiType, (arg: AccountId | string | Uint8Array) => Observable<ITuple<[BalanceOf, Vec<AccountId>]>>, [AccountId]> & QueryableStorageEntry<ApiType, [AccountId]>;
|
||||
voting: AugmentedQuery<ApiType, (arg: AccountId | string | Uint8Array) => Observable<Voter>, [AccountId]> & QueryableStorageEntry<ApiType, [AccountId]>;
|
||||
};
|
||||
gilt: {
|
||||
[key: string]: QueryableStorageEntry<ApiType>;
|
||||
/**
|
||||
* The currently active gilts, indexed according to the order of creation.
|
||||
**/
|
||||
active: AugmentedQuery<ApiType, (arg: ActiveIndex | AnyNumber | Uint8Array) => Observable<Option<ActiveGilt>>, [ActiveIndex]> & QueryableStorageEntry<ApiType, [ActiveIndex]>;
|
||||
/**
|
||||
* Information relating to the gilts currently active.
|
||||
**/
|
||||
activeTotal: AugmentedQuery<ApiType, () => Observable<ActiveGiltsTotal>, []> & QueryableStorageEntry<ApiType, []>;
|
||||
/**
|
||||
* The queues of bids ready to become gilts. Indexed by duration (in `Period`s).
|
||||
**/
|
||||
queues: AugmentedQuery<ApiType, (arg: u32 | AnyNumber | Uint8Array) => Observable<Vec<GiltBid>>, [u32]> & QueryableStorageEntry<ApiType, [u32]>;
|
||||
/**
|
||||
* The totals of items and balances within each queue. Saves a lot of storage reads in the
|
||||
* case of sparsely packed queues.
|
||||
*
|
||||
* The vector is indexed by duration in `Period`s, offset by one, so information on the queue
|
||||
* whose duration is one `Period` would be storage `0`.
|
||||
**/
|
||||
queueTotals: AugmentedQuery<ApiType, () => Observable<Vec<ITuple<[u32, BalanceOf]>>>, []> & QueryableStorageEntry<ApiType, []>;
|
||||
};
|
||||
grandpa: {
|
||||
[key: string]: QueryableStorageEntry<ApiType>;
|
||||
@@ -396,17 +505,22 @@ declare module '@polkadot/api/types/storage' {
|
||||
imOnline: {
|
||||
[key: string]: QueryableStorageEntry<ApiType>;
|
||||
/**
|
||||
* For each session index, we keep a mapping of `T::ValidatorId` to the
|
||||
* For each session index, we keep a mapping of `ValidatorId<T>` to the
|
||||
* number of blocks authored by the given authority.
|
||||
**/
|
||||
authoredBlocks: AugmentedQueryDoubleMap<ApiType, (key1: SessionIndex | AnyNumber | Uint8Array, key2: ValidatorId | string | Uint8Array) => Observable<u32>, [SessionIndex, ValidatorId]> & QueryableStorageEntry<ApiType, [SessionIndex, ValidatorId]>;
|
||||
/**
|
||||
* The block number after which it's ok to send heartbeats in current session.
|
||||
* The block number after which it's ok to send heartbeats in the current
|
||||
* session.
|
||||
*
|
||||
* At the beginning of each session we set this to a value that should
|
||||
* fall roughly in the middle of the session duration.
|
||||
* The idea is to first wait for the validators to produce a block
|
||||
* in the current session, so that the heartbeat later on will not be necessary.
|
||||
* At the beginning of each session we set this to a value that should fall
|
||||
* roughly in the middle of the session duration. The idea is to first wait for
|
||||
* the validators to produce a block in the current session, so that the
|
||||
* heartbeat later on will not be necessary.
|
||||
*
|
||||
* This value will only be used as a fallback if we fail to get a proper session
|
||||
* progress estimate from `NextSessionRotation`, as those estimates should be
|
||||
* more accurate then the value we calculate for `HeartbeatAfter`.
|
||||
**/
|
||||
heartbeatAfter: AugmentedQuery<ApiType, () => Observable<BlockNumber>, []> & QueryableStorageEntry<ApiType, []>;
|
||||
/**
|
||||
@@ -426,6 +540,34 @@ declare module '@polkadot/api/types/storage' {
|
||||
**/
|
||||
accounts: AugmentedQuery<ApiType, (arg: AccountIndex | AnyNumber | Uint8Array) => Observable<Option<ITuple<[AccountId, BalanceOf, bool]>>>, [AccountIndex]> & QueryableStorageEntry<ApiType, [AccountIndex]>;
|
||||
};
|
||||
lottery: {
|
||||
[key: string]: QueryableStorageEntry<ApiType>;
|
||||
/**
|
||||
* The calls stored in this pallet to be used in an active lottery if configured
|
||||
* by `Config::ValidateCall`.
|
||||
**/
|
||||
callIndices: AugmentedQuery<ApiType, () => Observable<Vec<CallIndex>>, []> & QueryableStorageEntry<ApiType, []>;
|
||||
/**
|
||||
* The configuration for the current lottery.
|
||||
**/
|
||||
lottery: AugmentedQuery<ApiType, () => Observable<Option<LotteryConfig>>, []> & QueryableStorageEntry<ApiType, []>;
|
||||
lotteryIndex: AugmentedQuery<ApiType, () => Observable<u32>, []> & QueryableStorageEntry<ApiType, []>;
|
||||
/**
|
||||
* Users who have purchased a ticket. (Lottery Index, Tickets Purchased)
|
||||
**/
|
||||
participants: AugmentedQuery<ApiType, (arg: AccountId | string | Uint8Array) => Observable<ITuple<[u32, Vec<CallIndex>]>>, [AccountId]> & QueryableStorageEntry<ApiType, [AccountId]>;
|
||||
/**
|
||||
* Each ticket's owner.
|
||||
*
|
||||
* May have residual storage from previous lotteries. Use `TicketsCount` to see which ones
|
||||
* are actually valid ticket mappings.
|
||||
**/
|
||||
tickets: AugmentedQuery<ApiType, (arg: u32 | AnyNumber | Uint8Array) => Observable<Option<AccountId>>, [u32]> & QueryableStorageEntry<ApiType, [u32]>;
|
||||
/**
|
||||
* Total number of tickets sold.
|
||||
**/
|
||||
ticketsCount: AugmentedQuery<ApiType, () => Observable<u32>, []> & QueryableStorageEntry<ApiType, []>;
|
||||
};
|
||||
mmr: {
|
||||
[key: string]: QueryableStorageEntry<ApiType>;
|
||||
/**
|
||||
@@ -670,15 +812,16 @@ declare module '@polkadot/api/types/storage' {
|
||||
* set, it might be active or not.
|
||||
**/
|
||||
currentEra: AugmentedQuery<ApiType, () => Observable<Option<EraIndex>>, []> & QueryableStorageEntry<ApiType, []>;
|
||||
/**
|
||||
* The last planned session scheduled by the session pallet.
|
||||
*
|
||||
* This is basically in sync with the call to [`SessionManager::new_session`].
|
||||
**/
|
||||
currentPlannedSession: AugmentedQuery<ApiType, () => Observable<SessionIndex>, []> & QueryableStorageEntry<ApiType, []>;
|
||||
/**
|
||||
* The earliest era for which we have a pending, unapplied slash.
|
||||
**/
|
||||
earliestUnappliedSlash: AugmentedQuery<ApiType, () => Observable<Option<EraIndex>>, []> & QueryableStorageEntry<ApiType, []>;
|
||||
/**
|
||||
* Flag to control the execution of the offchain election. When `Open(_)`, we accept
|
||||
* solutions to be submitted.
|
||||
**/
|
||||
eraElectionStatus: AugmentedQuery<ApiType, () => Observable<ElectionStatus>, []> & QueryableStorageEntry<ApiType, []>;
|
||||
/**
|
||||
* Rewards for the last `HISTORY_DEPTH` eras.
|
||||
* If reward hasn't been set or has been removed then 0 reward is returned.
|
||||
@@ -753,11 +896,6 @@ declare module '@polkadot/api/types/storage' {
|
||||
* invulnerables) and restricted to testnets.
|
||||
**/
|
||||
invulnerables: AugmentedQuery<ApiType, () => Observable<Vec<AccountId>>, []> & QueryableStorageEntry<ApiType, []>;
|
||||
/**
|
||||
* True if the current **planned** session is final. Note that this does not take era
|
||||
* forcing into account.
|
||||
**/
|
||||
isCurrentSessionFinal: AugmentedQuery<ApiType, () => Observable<bool>, []> & QueryableStorageEntry<ApiType, []>;
|
||||
/**
|
||||
* Map from all (unlocked) "controller" accounts to the info regarding the staking.
|
||||
**/
|
||||
@@ -778,16 +916,6 @@ declare module '@polkadot/api/types/storage' {
|
||||
* Where the reward payment should be made. Keyed by stash.
|
||||
**/
|
||||
payee: AugmentedQuery<ApiType, (arg: AccountId | string | Uint8Array) => Observable<RewardDestination>, [AccountId]> & QueryableStorageEntry<ApiType, [AccountId]>;
|
||||
/**
|
||||
* The next validator set. At the end of an era, if this is available (potentially from the
|
||||
* result of an offchain worker), it is immediately used. Otherwise, the on-chain election
|
||||
* is executed.
|
||||
**/
|
||||
queuedElected: AugmentedQuery<ApiType, () => Observable<Option<ElectionResult>>, []> & QueryableStorageEntry<ApiType, []>;
|
||||
/**
|
||||
* The score of the current [`QueuedElected`].
|
||||
**/
|
||||
queuedScore: AugmentedQuery<ApiType, () => Observable<Option<ElectionScore>>, []> & QueryableStorageEntry<ApiType, []>;
|
||||
/**
|
||||
* Slashing spans for stash accounts.
|
||||
**/
|
||||
@@ -798,16 +926,6 @@ declare module '@polkadot/api/types/storage' {
|
||||
* The rest of the slashed value is handled by the `Slash`.
|
||||
**/
|
||||
slashRewardFraction: AugmentedQuery<ApiType, () => Observable<Perbill>, []> & QueryableStorageEntry<ApiType, []>;
|
||||
/**
|
||||
* Snapshot of nominators at the beginning of the current election window. This should only
|
||||
* have a value when [`EraElectionStatus`] == `ElectionStatus::Open(_)`.
|
||||
**/
|
||||
snapshotNominators: AugmentedQuery<ApiType, () => Observable<Option<Vec<AccountId>>>, []> & QueryableStorageEntry<ApiType, []>;
|
||||
/**
|
||||
* Snapshot of validators at the beginning of the current election window. This should only
|
||||
* have a value when [`EraElectionStatus`] == `ElectionStatus::Open(_)`.
|
||||
**/
|
||||
snapshotValidators: AugmentedQuery<ApiType, () => Observable<Option<Vec<AccountId>>>, []> & QueryableStorageEntry<ApiType, []>;
|
||||
/**
|
||||
* Records information about the maximum slash of a stash within a slashing span,
|
||||
* as well as how much reward has been paid out.
|
||||
@@ -817,7 +935,7 @@ declare module '@polkadot/api/types/storage' {
|
||||
* True if network has been upgraded to this version.
|
||||
* Storage version of the pallet.
|
||||
*
|
||||
* This is set to v3.0.0 for new networks.
|
||||
* This is set to v6.0.0 for new networks.
|
||||
**/
|
||||
storageVersion: AugmentedQuery<ApiType, () => Observable<Releases>, []> & QueryableStorageEntry<ApiType, []>;
|
||||
/**
|
||||
@@ -912,6 +1030,11 @@ declare module '@polkadot/api/types/storage' {
|
||||
* Hash of the previous block.
|
||||
**/
|
||||
parentHash: AugmentedQuery<ApiType, () => Observable<Hash>, []> & QueryableStorageEntry<ApiType, []>;
|
||||
/**
|
||||
* True if we have upgraded so that AccountInfo contains three types of `RefCount`. False
|
||||
* (default) if not.
|
||||
**/
|
||||
upgradedToTripleRefCount: AugmentedQuery<ApiType, () => Observable<bool>, []> & QueryableStorageEntry<ApiType, []>;
|
||||
/**
|
||||
* True if we have upgraded so that `type RefCount` is `u32`. False (default) if not.
|
||||
**/
|
||||
|
||||
@@ -6,16 +6,18 @@ import type { Bytes, HashMap, Json, Null, Option, StorageKey, Text, U256, U64, V
|
||||
import type { AnyNumber, Codec, IExtrinsic, Observable } from '@polkadot/types/types';
|
||||
import type { ExtrinsicOrHash, ExtrinsicStatus } from '@polkadot/types/interfaces/author';
|
||||
import type { EpochAuthorship } from '@polkadot/types/interfaces/babe';
|
||||
import type { BeefySignedCommitment } from '@polkadot/types/interfaces/beefy';
|
||||
import type { BlockHash } from '@polkadot/types/interfaces/chain';
|
||||
import type { PrefixedStorageKey } from '@polkadot/types/interfaces/childstate';
|
||||
import type { AuthorityId } from '@polkadot/types/interfaces/consensus';
|
||||
import type { ContractCallRequest, ContractExecResult } from '@polkadot/types/interfaces/contracts';
|
||||
import type { CreatedBlock } from '@polkadot/types/interfaces/engine';
|
||||
import type { EthAccount, EthCallRequest, EthFilter, EthLog, EthReceipt, EthRichBlock, EthSubKind, EthSubParams, EthSyncStatus, EthTransaction, EthTransactionRequest, EthWork } from '@polkadot/types/interfaces/eth';
|
||||
import type { EthAccount, EthCallRequest, EthFilter, EthFilterChanges, EthLog, EthReceipt, EthRichBlock, EthSubKind, EthSubParams, EthSyncStatus, EthTransaction, EthTransactionRequest, EthWork } from '@polkadot/types/interfaces/eth';
|
||||
import type { Extrinsic } from '@polkadot/types/interfaces/extrinsics';
|
||||
import type { EncodedFinalityProofs, JustificationNotification, ReportedRoundStates } from '@polkadot/types/interfaces/grandpa';
|
||||
import type { MmrLeafProof } from '@polkadot/types/interfaces/mmr';
|
||||
import type { StorageKind } from '@polkadot/types/interfaces/offchain';
|
||||
import type { RuntimeDispatchInfo } from '@polkadot/types/interfaces/payment';
|
||||
import type { FeeDetails, RuntimeDispatchInfo } from '@polkadot/types/interfaces/payment';
|
||||
import type { RpcMethods } from '@polkadot/types/interfaces/rpc';
|
||||
import type { AccountId, BlockNumber, H160, H256, H64, Hash, Header, Index, Justification, KeyValue, SignedBlock, StorageData } from '@polkadot/types/interfaces/runtime';
|
||||
import type { ReadProof, RuntimeVersion } from '@polkadot/types/interfaces/state';
|
||||
@@ -63,6 +65,12 @@ declare module '@polkadot/rpc-core/types.jsonrpc' {
|
||||
**/
|
||||
epochAuthorship: AugmentedRpc<() => Observable<HashMap<AuthorityId, EpochAuthorship>>>;
|
||||
};
|
||||
beefy: {
|
||||
/**
|
||||
* Returns the block most recently finalized by BEEFY, alongside side its justification.
|
||||
**/
|
||||
subscribeJustifications: AugmentedRpc<() => Observable<BeefySignedCommitment>>;
|
||||
};
|
||||
chain: {
|
||||
/**
|
||||
* Get header and body of a relay chain block
|
||||
@@ -133,7 +141,7 @@ declare module '@polkadot/rpc-core/types.jsonrpc' {
|
||||
/**
|
||||
* Instructs the manual-seal authorship task to finalize a block
|
||||
**/
|
||||
finalizeBlock: AugmentedRpc<(hash: BlockHash | string | Uint8Array, justification?: Justification | string | Uint8Array) => Observable<bool>>;
|
||||
finalizeBlock: AugmentedRpc<(hash: BlockHash | string | Uint8Array, justification?: Justification) => Observable<bool>>;
|
||||
};
|
||||
eth: {
|
||||
/**
|
||||
@@ -188,6 +196,14 @@ declare module '@polkadot/rpc-core/types.jsonrpc' {
|
||||
* Returns the code at given address at given time (block number).
|
||||
**/
|
||||
getCode: AugmentedRpc<(address: H160 | string | Uint8Array, number?: BlockNumber | AnyNumber | Uint8Array) => Observable<Bytes>>;
|
||||
/**
|
||||
* Returns filter changes since last poll.
|
||||
**/
|
||||
getFilterChanges: AugmentedRpc<(index: U256 | AnyNumber | Uint8Array) => Observable<EthFilterChanges>>;
|
||||
/**
|
||||
* Returns all logs matching given filter (in a range 'from' - 'to').
|
||||
**/
|
||||
getFilterLogs: AugmentedRpc<(index: U256 | AnyNumber | Uint8Array) => Observable<Vec<EthLog>>>;
|
||||
/**
|
||||
* Returns logs matching given filter object.
|
||||
**/
|
||||
@@ -248,6 +264,18 @@ declare module '@polkadot/rpc-core/types.jsonrpc' {
|
||||
* Returns true if client is actively mining new blocks.
|
||||
**/
|
||||
mining: AugmentedRpc<() => Observable<bool>>;
|
||||
/**
|
||||
* Returns id of new block filter.
|
||||
**/
|
||||
newBlockFilter: AugmentedRpc<() => Observable<U256>>;
|
||||
/**
|
||||
* Returns id of new filter.
|
||||
**/
|
||||
newFilter: AugmentedRpc<(filter: EthFilter | { fromBlock?: any; toBlock?: any; blockHash?: any; address?: any; topics?: any } | string | Uint8Array) => Observable<U256>>;
|
||||
/**
|
||||
* Returns id of new block filter.
|
||||
**/
|
||||
newPendingTransactionFilter: AugmentedRpc<() => Observable<U256>>;
|
||||
/**
|
||||
* Returns protocol version encoded as a string (quotes are necessary).
|
||||
**/
|
||||
@@ -276,6 +304,10 @@ declare module '@polkadot/rpc-core/types.jsonrpc' {
|
||||
* Returns an object with data about the sync status or false.
|
||||
**/
|
||||
syncing: AugmentedRpc<() => Observable<EthSyncStatus>>;
|
||||
/**
|
||||
* Uninstalls filter.
|
||||
**/
|
||||
uninstallFilter: AugmentedRpc<(index: U256 | AnyNumber | Uint8Array) => Observable<bool>>;
|
||||
};
|
||||
grandpa: {
|
||||
/**
|
||||
@@ -291,6 +323,12 @@ declare module '@polkadot/rpc-core/types.jsonrpc' {
|
||||
**/
|
||||
subscribeJustifications: AugmentedRpc<() => Observable<JustificationNotification>>;
|
||||
};
|
||||
mmr: {
|
||||
/**
|
||||
* Generate MMR proof for given leaf index.
|
||||
**/
|
||||
generateProof: AugmentedRpc<(leafIndex: u64 | AnyNumber | Uint8Array, at?: BlockHash | string | Uint8Array) => Observable<MmrLeafProof>>;
|
||||
};
|
||||
net: {
|
||||
/**
|
||||
* Returns true if client is actively listening for network connections. Otherwise false.
|
||||
@@ -309,13 +347,17 @@ declare module '@polkadot/rpc-core/types.jsonrpc' {
|
||||
/**
|
||||
* Get offchain local storage under given key and prefix
|
||||
**/
|
||||
localStorageGet: AugmentedRpc<(kind: StorageKind | '__UNUSED' | 'PERSISTENT' | 'LOCAL' | number | Uint8Array, key: Bytes | string | Uint8Array) => Observable<Option<Bytes>>>;
|
||||
localStorageGet: AugmentedRpc<(kind: StorageKind | 'PERSISTENT' | 'LOCAL' | number | Uint8Array, key: Bytes | string | Uint8Array) => Observable<Option<Bytes>>>;
|
||||
/**
|
||||
* Set offchain local storage under given key and prefix
|
||||
**/
|
||||
localStorageSet: AugmentedRpc<(kind: StorageKind | '__UNUSED' | 'PERSISTENT' | 'LOCAL' | number | Uint8Array, key: Bytes | string | Uint8Array, value: Bytes | string | Uint8Array) => Observable<Null>>;
|
||||
localStorageSet: AugmentedRpc<(kind: StorageKind | 'PERSISTENT' | 'LOCAL' | number | Uint8Array, key: Bytes | string | Uint8Array, value: Bytes | string | Uint8Array) => Observable<Null>>;
|
||||
};
|
||||
payment: {
|
||||
/**
|
||||
* Query the detailed fee of a given encoded extrinsic
|
||||
**/
|
||||
queryFeeDetails: AugmentedRpc<(extrinsic: Bytes | string | Uint8Array, at?: BlockHash | string | Uint8Array) => Observable<FeeDetails>>;
|
||||
/**
|
||||
* Retrieves the fee information for an encoded extrinsic
|
||||
**/
|
||||
|
||||
+501
-275
File diff suppressed because it is too large
Load Diff
@@ -79,7 +79,7 @@ export abstract class Decorate<ApiType extends ApiTypes> extends Events {
|
||||
|
||||
protected _rpc?: DecoratedRpc<ApiType, RpcInterface>;
|
||||
|
||||
protected _rpcCore: RpcCore;
|
||||
protected _rpcCore: RpcCore & RpcInterface;
|
||||
|
||||
protected _runtimeChain?: Text;
|
||||
|
||||
@@ -136,6 +136,7 @@ export abstract class Decorate<ApiType extends ApiTypes> extends Events {
|
||||
|
||||
this.#instanceId = `${++instanceCounter}`;
|
||||
this.#registry = options.source?.registry || options.registry || new TypeRegistry();
|
||||
this._rx.registry = this.#registry;
|
||||
|
||||
const thisProvider = options.source
|
||||
? options.source._rpcCore.provider.clone()
|
||||
@@ -144,10 +145,11 @@ export abstract class Decorate<ApiType extends ApiTypes> extends Events {
|
||||
this._decorateMethod = decorateMethod;
|
||||
this._options = options;
|
||||
this._type = type;
|
||||
this._rpcCore = new RpcCore(this.#instanceId, this.#registry, thisProvider, this._options.rpc);
|
||||
|
||||
// The RPC interface decorates the known interfaces on init
|
||||
this._rpcCore = new RpcCore(this.#instanceId, this.#registry, thisProvider, this._options.rpc) as (RpcCore & RpcInterface);
|
||||
this._isConnected = new BehaviorSubject(this._rpcCore.provider.isConnected);
|
||||
this._rx.hasSubscriptions = this._rpcCore.provider.hasSubscriptions;
|
||||
this._rx.registry = this.#registry;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -281,7 +283,7 @@ export abstract class Decorate<ApiType extends ApiTypes> extends Events {
|
||||
});
|
||||
}
|
||||
|
||||
protected _decorateRpc<ApiType extends ApiTypes> (rpc: RpcCore, decorateMethod: DecorateMethod<ApiType>, input: Partial<DecoratedRpc<ApiType, RpcInterface>> = {}): DecoratedRpc<ApiType, RpcInterface> {
|
||||
protected _decorateRpc<ApiType extends ApiTypes> (rpc: RpcCore & RpcInterface, decorateMethod: DecorateMethod<ApiType>, input: Partial<DecoratedRpc<ApiType, RpcInterface>> = {}): DecoratedRpc<ApiType, RpcInterface> {
|
||||
return rpc.sections.reduce((out, _sectionName): DecoratedRpc<ApiType, RpcInterface> => {
|
||||
const sectionName = _sectionName as keyof DecoratedRpc<ApiType, RpcInterface>;
|
||||
|
||||
@@ -492,9 +494,11 @@ export abstract class Decorate<ApiType extends ApiTypes> extends Events {
|
||||
)
|
||||
),
|
||||
tap((keys): void => {
|
||||
keys.length === PAGE_SIZE
|
||||
? startSubject.next(keys[PAGE_SIZE - 1].toHex())
|
||||
: startSubject.complete();
|
||||
setTimeout((): void => {
|
||||
keys.length === PAGE_SIZE
|
||||
? startSubject.next(keys[PAGE_SIZE - 1].toHex())
|
||||
: startSubject.complete();
|
||||
}, 0);
|
||||
}),
|
||||
toArray(), // toArray since we want to startSubject to be completed
|
||||
map((keysArr: StorageKey[][]) => arrayFlatten(keysArr))
|
||||
|
||||
@@ -9,7 +9,7 @@ import type { ApiInterfaceRx, ApiTypes, DecoratedErrors, DecoratedEvents, Decora
|
||||
|
||||
import { assertReturn } from '@polkadot/util';
|
||||
|
||||
import { packageInfo } from '../detectPackage';
|
||||
import { packageInfo } from '../packageInfo';
|
||||
import { Init } from './Init';
|
||||
|
||||
interface PkgJson {
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import type { Text } from '@polkadot/types';
|
||||
import type { ChainProperties, Hash, RuntimeVersion, SignedBlock } from '@polkadot/types/interfaces';
|
||||
import type { ChainProperties, Hash, RuntimeVersion } from '@polkadot/types/interfaces';
|
||||
import type { Registry } from '@polkadot/types/types';
|
||||
import type { Observable, Subscription } from '@polkadot/x-rxjs';
|
||||
import type { ApiBase, ApiOptions, ApiTypes, DecorateMethod } from '../types';
|
||||
@@ -12,16 +12,16 @@ import BN from 'bn.js';
|
||||
|
||||
import { Metadata } from '@polkadot/metadata';
|
||||
import { TypeRegistry } from '@polkadot/types/create';
|
||||
import { LATEST_EXTRINSIC_VERSION } from '@polkadot/types/extrinsic/Extrinsic';
|
||||
import { getSpecAlias, getSpecRpc, getSpecTypes, getUpgradeVersion } from '@polkadot/types-known';
|
||||
import { assert, BN_ZERO, logger, u8aEq, u8aToU8a } from '@polkadot/util';
|
||||
import { getSpecAlias, getSpecExtensions, getSpecHasher, getSpecRpc, getSpecTypes, getUpgradeVersion } from '@polkadot/types-known';
|
||||
import { assert, BN_ZERO, logger, stringify, u8aEq, u8aToHex, u8aToU8a } from '@polkadot/util';
|
||||
import { cryptoWaitReady } from '@polkadot/util-crypto';
|
||||
import { of } from '@polkadot/x-rxjs';
|
||||
import { map, switchMap } from '@polkadot/x-rxjs/operators';
|
||||
|
||||
import { detectedCapabilities } from './capabilities';
|
||||
import { Decorate } from './Decorate';
|
||||
|
||||
const KEEPALIVE_INTERVAL = 15000;
|
||||
const KEEPALIVE_INTERVAL = 10000;
|
||||
const DEFAULT_BLOCKNUMBER = { unwrap: () => BN_ZERO };
|
||||
|
||||
const l = logger('api/init');
|
||||
@@ -31,15 +31,11 @@ export abstract class Init<ApiType extends ApiTypes> extends Decorate<ApiType> {
|
||||
|
||||
#registries: VersionedRegistry[] = [];
|
||||
|
||||
#updateSub?: Subscription;
|
||||
#updateSub?: Subscription | null = null;
|
||||
|
||||
constructor (options: ApiOptions, type: ApiTypes, decorateMethod: DecorateMethod<ApiType>) {
|
||||
super(options, type, decorateMethod);
|
||||
|
||||
if (!this.hasSubscriptions) {
|
||||
l.warn('Api will be available in a limited mode since the provider does not support subscriptions');
|
||||
}
|
||||
|
||||
// all injected types added to the registry for overrides
|
||||
this.registry.setKnownTypes(options);
|
||||
|
||||
@@ -63,9 +59,14 @@ export abstract class Init<ApiType extends ApiTypes> extends Decorate<ApiType> {
|
||||
this._rx.signer = options.signer;
|
||||
|
||||
this._rpcCore.setRegistrySwap((hash: string | Uint8Array) => this.getBlockRegistry(hash));
|
||||
this._rpcCore.provider.on('disconnected', this.#onProviderDisconnect);
|
||||
this._rpcCore.provider.on('error', this.#onProviderError);
|
||||
this._rpcCore.provider.on('connected', this.#onProviderConnect);
|
||||
|
||||
if (this.hasSubscriptions) {
|
||||
this._rpcCore.provider.on('disconnected', this.#onProviderDisconnect);
|
||||
this._rpcCore.provider.on('error', this.#onProviderError);
|
||||
this._rpcCore.provider.on('connected', this.#onProviderConnect);
|
||||
} else {
|
||||
l.warn('Api will be available in a limited mode since the provider does not support subscriptions');
|
||||
}
|
||||
|
||||
// If the provider was instantiated earlier, and has already emitted a
|
||||
// 'connected' event, then the `on('connected')` won't fire anymore. To
|
||||
@@ -83,13 +84,17 @@ export abstract class Init<ApiType extends ApiTypes> extends Decorate<ApiType> {
|
||||
registry.setChainProperties(chainProps || this.registry.getChainProperties());
|
||||
registry.setKnownTypes(this._options);
|
||||
registry.register(getSpecTypes(registry, chain, version.specName, version.specVersion));
|
||||
registry.setHasher(getSpecHasher(registry, chain, version.specName));
|
||||
|
||||
// for bundled types, pull through the aliases defined
|
||||
if (registry.knownTypes.typesBundle) {
|
||||
registry.knownTypes.typesAlias = getSpecAlias(registry, chain, version.specName);
|
||||
}
|
||||
|
||||
registry.setMetadata(metadata, undefined, this._options.signedExtensions);
|
||||
registry.setMetadata(metadata, undefined, {
|
||||
...getSpecExtensions(registry, chain, version.specName),
|
||||
...(this._options.signedExtensions || {})
|
||||
});
|
||||
|
||||
return registry;
|
||||
}
|
||||
@@ -134,7 +139,12 @@ export abstract class Init<ApiType extends ApiTypes> extends Decorate<ApiType> {
|
||||
|
||||
// nothing has been found, construct new
|
||||
const metadata = await this._rpcCore.state.getMetadata(header.parentHash).toPromise();
|
||||
const registry = this._initRegistry(new TypeRegistry(), this._runtimeChain as Text, version, metadata);
|
||||
const registry = this._initRegistry(new TypeRegistry(blockHash), this._runtimeChain as Text, version, metadata);
|
||||
|
||||
// For now, since this is new we ignore the capability lookups (this could be useful once proven)
|
||||
// this._detectCapabilities(registry, blockHash);
|
||||
|
||||
// add our new registry
|
||||
const result = { isDefault: false, lastBlockHash, metadata, metadataConsts: null, registry, specVersion: version.specVersion };
|
||||
|
||||
this.#registries.push(result);
|
||||
@@ -146,10 +156,10 @@ export abstract class Init<ApiType extends ApiTypes> extends Decorate<ApiType> {
|
||||
// on re-connection to the same chain, we don't want to re-do everything from chain again
|
||||
if (this._isReady) {
|
||||
return true;
|
||||
} else if (this.#updateSub) {
|
||||
this.#updateSub.unsubscribe();
|
||||
}
|
||||
|
||||
this._unsubscribeUpdates();
|
||||
|
||||
// only load from on-chain if we are not a clone (default path), alternatively
|
||||
// just use the values from the source instance provided
|
||||
[this._genesisHash, this._runtimeMetadata] = this._options.source?._isReady
|
||||
@@ -180,6 +190,19 @@ export abstract class Init<ApiType extends ApiTypes> extends Decorate<ApiType> {
|
||||
return [source.genesisHash, source.runtimeMetadata];
|
||||
}
|
||||
|
||||
private _detectCapabilities (registry?: Registry, blockHash?: string | Uint8Array): void {
|
||||
detectedCapabilities(this._rx, blockHash)
|
||||
.toPromise()
|
||||
.then((types): void => {
|
||||
if (Object.keys(types).length) {
|
||||
(registry || this.registry).register(types as Record<string, string>);
|
||||
|
||||
l.debug(() => `Capabilities detected${blockHash ? ` (${u8aToHex(u8aToU8a(blockHash))})` : ''}: ${stringify(types)}`);
|
||||
}
|
||||
})
|
||||
.catch(l.error);
|
||||
}
|
||||
|
||||
// subscribe to metadata updates, inject the types on changes
|
||||
private _subscribeUpdates (): void {
|
||||
if (this.#updateSub || !this.hasSubscriptions) {
|
||||
@@ -212,6 +235,7 @@ export abstract class Init<ApiType extends ApiTypes> extends Decorate<ApiType> {
|
||||
// clear the registry types to ensure that we override correctly
|
||||
this._initRegistry(thisRegistry.registry.init(), this._runtimeChain as Text, version, metadata);
|
||||
this.injectMetadata(metadata, false, thisRegistry.registry);
|
||||
this._detectCapabilities(thisRegistry.registry);
|
||||
|
||||
return true;
|
||||
})
|
||||
@@ -261,25 +285,15 @@ export abstract class Init<ApiType extends ApiTypes> extends Decorate<ApiType> {
|
||||
return [genesisHash, metadata];
|
||||
}
|
||||
|
||||
private async _initFromMeta (metadata: Metadata): Promise<boolean> {
|
||||
const metaExtrinsic = metadata.asLatest.extrinsic;
|
||||
|
||||
// only inject if we are not a clone (global init)
|
||||
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
|
||||
const { block: { extrinsics: [firstTx] } }: SignedBlock = await this._rpcCore.chain.getBlock().toPromise();
|
||||
|
||||
// If we haven't sync-ed to 1 yes, this won't have any values
|
||||
this._extrinsicType = firstTx ? firstTx.type : LATEST_EXTRINSIC_VERSION;
|
||||
}
|
||||
|
||||
private _initFromMeta (metadata: Metadata): boolean {
|
||||
this._extrinsicType = metadata.asLatest.extrinsic.version.toNumber();
|
||||
this._rx.extrinsicType = this._extrinsicType;
|
||||
this._rx.genesisHash = this._genesisHash;
|
||||
this._rx.runtimeVersion = this._runtimeVersion;
|
||||
this._rx.runtimeVersion = this._runtimeVersion as RuntimeVersion; // must be set here
|
||||
|
||||
// inject metadata and adjust the types as detected
|
||||
this.injectMetadata(metadata, true);
|
||||
this._detectCapabilities();
|
||||
|
||||
// derive is last, since it uses the decorated rx
|
||||
this._rx.derive = this._decorateDeriveRx(this._rxDecorateMethod);
|
||||
@@ -288,6 +302,25 @@ export abstract class Init<ApiType extends ApiTypes> extends Decorate<ApiType> {
|
||||
return true;
|
||||
}
|
||||
|
||||
private _unsubscribeHealth (): void {
|
||||
if (this.#healthTimer) {
|
||||
clearInterval(this.#healthTimer);
|
||||
this.#healthTimer = null;
|
||||
}
|
||||
}
|
||||
|
||||
private _unsubscribeUpdates (): void {
|
||||
if (this.#updateSub) {
|
||||
this.#updateSub.unsubscribe();
|
||||
this.#updateSub = null;
|
||||
}
|
||||
}
|
||||
|
||||
protected _unsubscribe (): void {
|
||||
this._unsubscribeHealth();
|
||||
this._unsubscribeUpdates();
|
||||
}
|
||||
|
||||
#onProviderConnect = async (): Promise<void> => {
|
||||
this.emit('connected');
|
||||
this._isConnected.next(true);
|
||||
@@ -307,7 +340,7 @@ export abstract class Init<ApiType extends ApiTypes> extends Decorate<ApiType> {
|
||||
}
|
||||
|
||||
this.#healthTimer = setInterval((): void => {
|
||||
this._rpcCore.system.health().toPromise().catch(() => null);
|
||||
this._rpcCore.system.health().toPromise().catch((error) => l.warn(`Health keepalive check failed: ${(error as Error).message}`));
|
||||
}, KEEPALIVE_INTERVAL);
|
||||
} catch (_error) {
|
||||
const error = new Error(`FATAL: Unable to initialize the API: ${(_error as Error).message}`);
|
||||
@@ -323,10 +356,7 @@ export abstract class Init<ApiType extends ApiTypes> extends Decorate<ApiType> {
|
||||
this.emit('disconnected');
|
||||
this._isConnected.next(false);
|
||||
|
||||
if (this.#healthTimer) {
|
||||
clearInterval(this.#healthTimer);
|
||||
this.#healthTimer = null;
|
||||
}
|
||||
this._unsubscribeHealth();
|
||||
};
|
||||
|
||||
#onProviderError = (error: Error): void => {
|
||||
|
||||
@@ -0,0 +1,181 @@
|
||||
// Copyright 2017-2021 @polkadot/api-derive authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import type { ApiInterfaceRx } from '@polkadot/api/types';
|
||||
import type { bool, Raw, u32 } from '@polkadot/types';
|
||||
import type { Releases } from '@polkadot/types/interfaces';
|
||||
import type { InterfaceTypes } from '@polkadot/types/types';
|
||||
|
||||
import { assert, compactFromU8a } from '@polkadot/util';
|
||||
import { combineLatest, Observable, of } from '@polkadot/x-rxjs';
|
||||
import { map, take } from '@polkadot/x-rxjs/operators';
|
||||
|
||||
// the order and types needs to map with the all array setup below
|
||||
type ExtractedQ = [bool | null, bool | null, bool | null, Releases | null];
|
||||
|
||||
type ExtractedR = [Raw | null];
|
||||
|
||||
type ExtractedC = [u32 | null, u32 | null];
|
||||
|
||||
type DetectedKeys = keyof Pick<InterfaceTypes, 'AccountInfo' | 'ValidatorPrefs'>;
|
||||
|
||||
type DetectedValues = keyof InterfaceTypes;
|
||||
|
||||
interface DetectedTypes extends Record<DetectedKeys, DetectedValues> {
|
||||
AccountInfo: 'AccountInfoWithRefCount' | 'AccountInfoWithDualRefCount' | 'AccountInfoWithTripleRefCount',
|
||||
Keys: 'SessionKeys1' | 'SessionKeys2' | 'SessionKeys3' | 'SessionKeys4' | 'SessionKeys5' | 'SessionKeys6' | 'SessionKeys7' | 'SessionKeys8' | 'SessionKeys9' | 'SessionKeys10';
|
||||
RefCount: 'u8' | 'u32',
|
||||
SlotRange: Record<string, unknown>;
|
||||
ValidatorPrefs: 'ValidatorPrefsWithBlocked' | 'ValidatorPrefsWithCommission';
|
||||
WinningData: string;
|
||||
}
|
||||
|
||||
interface AvailableMap<T> {
|
||||
filtered: T[];
|
||||
included: boolean[];
|
||||
original: T[];
|
||||
}
|
||||
|
||||
interface Constants {
|
||||
accountIdLength: number;
|
||||
}
|
||||
|
||||
const NumberMap = ['Zero', 'One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine', 'Ten'];
|
||||
|
||||
function mapCapabilities ({ accountIdLength }: Constants, [leasePeriodsPerSlot, slotRangeCount]: ExtractedC, [systemRefcount32, systemRefcountDual, systemRefcountTriple, stakingVersion]: ExtractedQ, [keys]: ExtractedR): Partial<DetectedTypes> {
|
||||
const types: Partial<DetectedTypes> = {};
|
||||
|
||||
// AccountInfo
|
||||
if (systemRefcountTriple && systemRefcountTriple.isTrue) {
|
||||
types.AccountInfo = 'AccountInfoWithTripleRefCount';
|
||||
} else if (systemRefcountDual && systemRefcountDual.isTrue) {
|
||||
types.AccountInfo = 'AccountInfoWithDualRefCount';
|
||||
} else {
|
||||
types.AccountInfo = 'AccountInfoWithRefCount';
|
||||
|
||||
if (!systemRefcount32 || systemRefcount32.isFalse) {
|
||||
types.RefCount = 'u8';
|
||||
}
|
||||
}
|
||||
|
||||
// ValidatorPrefs
|
||||
if (stakingVersion) {
|
||||
if (stakingVersion.index >= 4) { // v1 = index 0, V5 = index 4
|
||||
types.ValidatorPrefs = 'ValidatorPrefsWithBlocked';
|
||||
} else {
|
||||
types.ValidatorPrefs = 'ValidatorPrefsWithCommission';
|
||||
}
|
||||
}
|
||||
|
||||
// Keys
|
||||
if (keys) {
|
||||
try {
|
||||
const [offset, numItems] = compactFromU8a(keys);
|
||||
const tupleLength = (keys.length - offset) / numItems.toNumber();
|
||||
const numIds = tupleLength / accountIdLength;
|
||||
const numIdsRound = Math.floor(numIds);
|
||||
|
||||
assert(numIds >= 2 && numIds <= 11, () => `Detected ${numIds} in Keys, should be >= 2 and <= 11`);
|
||||
|
||||
if (numIdsRound !== numIds) {
|
||||
// Beefy?
|
||||
if ((((numIdsRound - 1) * accountIdLength) + 33) === tupleLength) {
|
||||
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
||||
// @ts-ignore
|
||||
types.Keys = `SessionKeys${numIdsRound - 1}B`;
|
||||
} else {
|
||||
assert(false, () => `Expected integer number of keys, found ${numIds.toFixed(2)}`);
|
||||
}
|
||||
} else {
|
||||
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
||||
// @ts-ignore
|
||||
types.Keys = `SessionKeys${numIds - 1}`;
|
||||
}
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
}
|
||||
}
|
||||
|
||||
// auctions
|
||||
if (leasePeriodsPerSlot && slotRangeCount) {
|
||||
const _enum: string[] = [];
|
||||
|
||||
for (let i = 0; leasePeriodsPerSlot.gtn(i); i++) {
|
||||
for (let j = i; leasePeriodsPerSlot.gtn(j); j++) {
|
||||
_enum.push(`${NumberMap[i]}${NumberMap[j]}`);
|
||||
}
|
||||
}
|
||||
|
||||
types.SlotRange = { _enum };
|
||||
types.WinningData = `[WinningDataEntry; ${slotRangeCount.toNumber()}]`;
|
||||
}
|
||||
|
||||
return types;
|
||||
}
|
||||
|
||||
function filterEntries <T> (original: T[]): AvailableMap<T> {
|
||||
const included = original.map((c) => !!c);
|
||||
const filtered = original.filter((_, index) => included[index]);
|
||||
|
||||
return { filtered, included, original };
|
||||
}
|
||||
|
||||
function extractResults <R, T = unknown> (results: unknown[], map: AvailableMap<T>): R {
|
||||
let offset = -1;
|
||||
|
||||
return map.included.map((isIncluded) =>
|
||||
isIncluded
|
||||
? results[++offset]
|
||||
: null
|
||||
) as unknown as R;
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Query the chain for the specific capabilities
|
||||
*/
|
||||
export function detectedCapabilities (api: ApiInterfaceRx, blockHash?: Uint8Array | string | undefined): Observable<Partial<DetectedTypes>> {
|
||||
const consts = filterEntries([
|
||||
api.consts.auctions?.leasePeriodsPerSlot,
|
||||
api.consts.auctions?.slotRangeCount
|
||||
]);
|
||||
const queries = filterEntries([
|
||||
api.query.system?.upgradedToU32RefCount,
|
||||
api.query.system?.upgradedToDualRefCount,
|
||||
api.query.system?.upgradedToTripleRefCount,
|
||||
api.query.staking?.storageVersion
|
||||
]);
|
||||
const raws = filterEntries([
|
||||
api.query.session?.queuedKeys
|
||||
]);
|
||||
|
||||
return combineLatest([
|
||||
consts.filtered.length
|
||||
? blockHash
|
||||
// FIXME consts don't have .at as of yet...
|
||||
? of([])
|
||||
: of(consts.filtered)
|
||||
: of([]),
|
||||
queries.filtered.length
|
||||
? blockHash
|
||||
? combineLatest(queries.filtered.map((c) => c.at(blockHash)))
|
||||
: api.queryMulti(queries.filtered)
|
||||
: of([]),
|
||||
raws.filtered.length
|
||||
? blockHash
|
||||
? combineLatest(raws.filtered.map((k) => api.rpc.state.getStorage.raw(k.key(), blockHash)))
|
||||
: combineLatest(raws.filtered.map((k) => api.rpc.state.getStorage.raw(k.key())))
|
||||
: of([])
|
||||
]).pipe(
|
||||
map(([cResults, qResults, rResults]): Partial<DetectedTypes> =>
|
||||
mapCapabilities(
|
||||
{
|
||||
accountIdLength: api.registry.createType('AccountId').encodedLength
|
||||
},
|
||||
extractResults<ExtractedC>(cResults, consts),
|
||||
extractResults<ExtractedQ>(qResults, queries),
|
||||
extractResults<ExtractedR>(rResults, raws)
|
||||
)
|
||||
),
|
||||
take(1)
|
||||
);
|
||||
}
|
||||
@@ -50,6 +50,8 @@ export abstract class ApiBase<ApiType extends ApiTypes> extends Getters<ApiType>
|
||||
* @description Disconnect from the underlying provider, halting all network traffic
|
||||
*/
|
||||
public disconnect (): Promise<void> {
|
||||
this._unsubscribe();
|
||||
|
||||
return this._rpcCore.disconnect();
|
||||
}
|
||||
|
||||
|
||||
@@ -3,12 +3,12 @@
|
||||
|
||||
// Simple non-runnable checks to test type definitions in the editor itself
|
||||
|
||||
import type { HeaderExtended } from '@polkadot/api-derive/types';
|
||||
import type { StorageKey } from '@polkadot/types';
|
||||
import type { AccountId, Balance, DispatchErrorModule, Event, Header, Index } from '@polkadot/types/interfaces';
|
||||
import type { AnyTuple, IExtrinsic, IMethod } from '@polkadot/types/types';
|
||||
|
||||
import { ApiPromise } from '@polkadot/api';
|
||||
import { HeaderExtended } from '@polkadot/api-derive';
|
||||
import { createTestPairs, TestKeyringMap } from '@polkadot/keyring/testingPairs';
|
||||
import { createTypeUnsafe, TypeRegistry } from '@polkadot/types/create';
|
||||
|
||||
|
||||
@@ -1,25 +1,14 @@
|
||||
// Copyright 2017-2021 @polkadot/api authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
// For esm, this should be import.meta.url or to get the same behavior as __dirname, we can use
|
||||
//
|
||||
// new URL(import.meta.url).pathname)
|
||||
//
|
||||
// The issue is the WP4 has "some" issues with import.meta.url. So because of bundlers, we can't have
|
||||
// nice things... In this case it is even worse since import.meta.url won't even make it compile, so
|
||||
// there is a complete dead end with usage thereof
|
||||
//
|
||||
// When that is fixed, a solution is to have both .js & .mjs files, with the following content -
|
||||
//
|
||||
// cjs: util.detectPackage(packageInfo, () => __dirname);
|
||||
// esm: detectPackage(packageInfo, () => import.meta.url);
|
||||
//
|
||||
// With the above we additionally need a .d.ts to just export the packageInfo
|
||||
|
||||
import { packageInfo as deriveInfo } from '@polkadot/api-derive/packageInfo';
|
||||
import { packageInfo as metaInfo } from '@polkadot/metadata/packageInfo';
|
||||
import { packageInfo as coreInfo } from '@polkadot/rpc-core/packageInfo';
|
||||
import { packageInfo as providerInfo } from '@polkadot/rpc-provider/packageInfo';
|
||||
import { packageInfo as typesInfo } from '@polkadot/types/packageInfo';
|
||||
import { packageInfo as knownInfo } from '@polkadot/types-known/packageInfo';
|
||||
import { detectPackage } from '@polkadot/util';
|
||||
|
||||
import packageInfo from './package-info.json';
|
||||
import { packageInfo } from './packageInfo';
|
||||
|
||||
detectPackage(packageInfo, typeof __dirname !== 'undefined' && __dirname);
|
||||
|
||||
export { packageInfo };
|
||||
detectPackage(packageInfo, typeof __dirname !== 'undefined' && __dirname, [deriveInfo, metaInfo, coreInfo, providerInfo, typesInfo, knownInfo]);
|
||||
|
||||
@@ -6,7 +6,7 @@ import './detectPackage';
|
||||
export { Keyring } from '@polkadot/keyring';
|
||||
export { WsProvider } from '@polkadot/rpc-provider/ws';
|
||||
|
||||
export { packageInfo } from './packageInfo';
|
||||
export { ApiPromise } from './promise';
|
||||
export { ApiRx } from './rx';
|
||||
|
||||
export { SubmittableResult } from './submittable';
|
||||
export { ApiRx } from './rx';
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
// Copyright 2017-2021 @polkadot/api authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
// Auto-generated by @polkadot/dev, do not edit
|
||||
|
||||
export const packageInfo = { name: '@polkadot/api', version: '4.8.1' };
|
||||
@@ -12,7 +12,7 @@ import { hexToU8a } from '@polkadot/util';
|
||||
import { SingleAccountSigner } from '../../test/util';
|
||||
import { ApiPromise } from '.';
|
||||
|
||||
const TRANSFER_SIG = '0x7a10e5ed9a14284eca7bea53f81631981dddda5a3d2dee973b136475947264801465726e4829ae3994d9058df638d959d4e043c7f1924299546790dda1dea20a';
|
||||
const TRANSFER_SIG = '0x54f39e43f32376a5ab6cdfd4d0ce57802aa9ff85514a7ffa9f2a949078f02beca16af87427c45fe60d54aa847fd241d127ed39e21b101806f6b1f50f7a82500b';
|
||||
|
||||
describe('ApiPromise', (): void => {
|
||||
const registry = new TypeRegistry();
|
||||
|
||||
@@ -211,7 +211,19 @@ export class ApiPromise extends ApiBase<'promise'> {
|
||||
* ```
|
||||
*/
|
||||
public static create (options?: ApiOptions): Promise<ApiPromise> {
|
||||
return new ApiPromise(options).isReady;
|
||||
const instance = new ApiPromise(options);
|
||||
|
||||
if (options && options.throwOnConnect) {
|
||||
return instance.isReadyOrError;
|
||||
}
|
||||
|
||||
// Swallow any rejections on isReadyOrError
|
||||
// (in Node 15.x this creates issues, when not being looked at)
|
||||
instance.isReadyOrError.catch(() => {
|
||||
// ignore
|
||||
});
|
||||
|
||||
return instance.isReady;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -235,18 +247,14 @@ export class ApiPromise extends ApiBase<'promise'> {
|
||||
super(options, 'promise', decorateMethod);
|
||||
|
||||
this.#isReadyPromise = new Promise((resolve): void => {
|
||||
super.once('ready', (): void => {
|
||||
resolve(this);
|
||||
});
|
||||
super.once('ready', () => resolve(this));
|
||||
});
|
||||
|
||||
this.#isReadyOrErrorPromise = new Promise((resolve, reject): void => {
|
||||
super.once('ready', (): void => {
|
||||
resolve(this);
|
||||
});
|
||||
super.once('error', (e): void => {
|
||||
reject(e);
|
||||
});
|
||||
const tracker = promiseTracker(resolve, reject);
|
||||
|
||||
super.once('ready', () => tracker.resolve(this));
|
||||
super.once('error', (e) => tracker.reject(e));
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -165,9 +165,7 @@ export class ApiRx extends ApiBase<'rxjs'> {
|
||||
this.#isReadyRx = from<Promise<ApiRx>>(
|
||||
// You can create an observable from an event, however my mind groks this form better
|
||||
new Promise((resolve): void => {
|
||||
super.on('ready', (): void => {
|
||||
resolve(this);
|
||||
});
|
||||
super.on('ready', () => resolve(this));
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
@@ -32,14 +32,17 @@ export class SubmittableResult implements ISubmittableResult {
|
||||
|
||||
public readonly dispatchInfo?: DispatchInfo;
|
||||
|
||||
public readonly internalError?: Error;
|
||||
|
||||
public readonly events: EventRecord[];
|
||||
|
||||
public readonly status: ExtrinsicStatus;
|
||||
|
||||
constructor ({ dispatchError, dispatchInfo, events, status }: SubmittableResultValue) {
|
||||
constructor ({ dispatchError, dispatchInfo, events, internalError, status }: SubmittableResultValue) {
|
||||
this.dispatchError = dispatchError || extractError(events);
|
||||
this.dispatchInfo = dispatchInfo || extractInfo(events);
|
||||
this.events = events || [];
|
||||
this.internalError = internalError;
|
||||
this.status = status;
|
||||
}
|
||||
|
||||
@@ -66,14 +69,14 @@ export class SubmittableResult implements ISubmittableResult {
|
||||
/**
|
||||
* @description Filters EventRecords for the specified method & section (there could be multiple)
|
||||
*/
|
||||
public filterRecords (section: string, method: string): EventRecord[] {
|
||||
return filterAndApply(this.events, section, [method], recordIdentity);
|
||||
public filterRecords (section: string, method: string | string[]): EventRecord[] {
|
||||
return filterAndApply(this.events, section, Array.isArray(method) ? method : [method], recordIdentity);
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Finds an EventRecord for the specified method & section
|
||||
*/
|
||||
public findRecord (section: string, method: string): EventRecord | undefined {
|
||||
public findRecord (section: string, method: string | string[]): EventRecord | undefined {
|
||||
return this.filterRecords(section, method)[0];
|
||||
}
|
||||
|
||||
@@ -85,6 +88,7 @@ export class SubmittableResult implements ISubmittableResult {
|
||||
dispatchError: this.dispatchError?.toHuman(),
|
||||
dispatchInfo: this.dispatchInfo?.toHuman(),
|
||||
events: this.events.map((event) => event.toHuman(isExtended)),
|
||||
internalError: this.internalError?.message.toString(),
|
||||
status: this.status.toHuman(isExtended)
|
||||
};
|
||||
}
|
||||
|
||||
@@ -11,7 +11,7 @@ import type { AddressOrPair, SignerOptions, SubmittableDryRunResult, Submittable
|
||||
|
||||
import { assert, isBn, isFunction, isNumber, isString, isU8a } from '@polkadot/util';
|
||||
import { of } from '@polkadot/x-rxjs';
|
||||
import { first, map, mapTo, mergeMap, switchMap, tap } from '@polkadot/x-rxjs/operators';
|
||||
import { catchError, first, map, mapTo, mergeMap, switchMap, tap } from '@polkadot/x-rxjs/operators';
|
||||
|
||||
import { ApiBase } from '../base';
|
||||
import { filterEvents, isKeyringPair } from '../util';
|
||||
@@ -242,6 +242,9 @@ export function createClass <ApiType extends ApiTypes> ({ api, apiType, decorate
|
||||
events: filterEvents(hash, block, events, status),
|
||||
status
|
||||
}))
|
||||
),
|
||||
catchError((internalError: Error) =>
|
||||
of(this.#transformResult(new SubmittableResult({ internalError, status })))
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -10,6 +10,7 @@ export interface SubmittableResultValue {
|
||||
dispatchError?: DispatchError;
|
||||
dispatchInfo?: DispatchInfo;
|
||||
events?: EventRecord[];
|
||||
internalError?: Error;
|
||||
status: ExtrinsicStatus;
|
||||
}
|
||||
|
||||
|
||||
@@ -60,7 +60,7 @@ export interface ApiOptions extends RegisteredTypes {
|
||||
/**
|
||||
* @description Any chain-specific signed extensions that are now well-known
|
||||
*/
|
||||
signedExtensions?: Record<string, ExtDef>;
|
||||
signedExtensions?: ExtDef;
|
||||
/**
|
||||
* @description An external signer which will be used to sign extrinsic when account passed in is not KeyringPair
|
||||
*/
|
||||
@@ -69,6 +69,10 @@ export interface ApiOptions extends RegisteredTypes {
|
||||
* @description The source object to use for runtime information (only used when cloning)
|
||||
*/
|
||||
source?: ApiBase<any>;
|
||||
/**
|
||||
* @description Throws an error when the initial connection fails (same as isReadyOrError)
|
||||
*/
|
||||
throwOnConnect?: boolean;
|
||||
}
|
||||
|
||||
// A smaller interface of ApiRx, used in derive and in SubmittableExtrinsic
|
||||
@@ -81,7 +85,7 @@ export interface ApiInterfaceRx {
|
||||
hasSubscriptions: boolean;
|
||||
registry: Registry;
|
||||
runtimeMetadata: Metadata;
|
||||
runtimeVersion?: RuntimeVersion;
|
||||
runtimeVersion: RuntimeVersion;
|
||||
query: QueryableStorage<'rxjs'>;
|
||||
queryMulti: QueryableStorageMulti<'rxjs'>;
|
||||
rpc: DecoratedRpc<'rxjs', RpcInterface>;
|
||||
|
||||
@@ -35,19 +35,19 @@ export type QueryableStorageEntry<ApiType extends ApiTypes, A extends AnyTuple =
|
||||
// eslint-disable-next-line no-use-before-define
|
||||
: AugmentedQuery<'promise', GenericStorageEntryFunction, A> & StorageEntryPromiseOverloads;
|
||||
|
||||
export interface StorageEntryBase<ApiType extends ApiTypes, F extends AnyFunction, A extends AnyTuple> {
|
||||
export interface StorageEntryBase<ApiType extends ApiTypes, F extends AnyFunction, A extends AnyTuple = AnyTuple> {
|
||||
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?: Parameters<F>[0]) => PromiseOrObs<ApiType, [StorageKey, T][]>;
|
||||
entriesAt: <T extends Codec | any = ObsInnerType<ReturnType<F>>>(hash: Hash | Uint8Array | string, 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][]>;
|
||||
entries: <T extends Codec | any = ObsInnerType<ReturnType<F>>, K extends AnyTuple = A>(arg?: Parameters<F>[0]) => PromiseOrObs<ApiType, [StorageKey<K>, T][]>;
|
||||
entriesAt: <T extends Codec | any = ObsInnerType<ReturnType<F>>, K extends AnyTuple = A>(hash: Hash | Uint8Array | string, arg?: Parameters<F>[0]) => PromiseOrObs<ApiType, [StorageKey<K>, T][]>;
|
||||
entriesPaged: <T extends Codec | any = ObsInnerType<ReturnType<F>>, K extends AnyTuple = A>(opts: PaginationOptions<Parameters<F>[0]>) => PromiseOrObs<ApiType, [StorageKey<K>, T][]>;
|
||||
hash: (...args: Parameters<F>) => PromiseOrObs<ApiType, Hash>;
|
||||
is: (key: IStorageKey<AnyTuple>) => key is IStorageKey<A>;
|
||||
key: (...args: Parameters<F>) => string;
|
||||
keyPrefix: () => string;
|
||||
keys: (arg?: any) => PromiseOrObs<ApiType, StorageKey[]>;
|
||||
keysAt: (hash: Hash | Uint8Array | string, arg?: any) => PromiseOrObs<ApiType, StorageKey[]>;
|
||||
keysPaged: (opts: PaginationOptions<Parameters<F>[0]>) => PromiseOrObs<ApiType, StorageKey[]>;
|
||||
keys: <K extends AnyTuple = A> (arg?: any) => PromiseOrObs<ApiType, StorageKey<K>[]>;
|
||||
keysAt: <K extends AnyTuple = A> (hash: Hash | Uint8Array | string, arg?: any) => PromiseOrObs<ApiType, StorageKey<K>[]>;
|
||||
keysPaged: <K extends AnyTuple = A> (opts: PaginationOptions<Parameters<F>[0]>) => PromiseOrObs<ApiType, StorageKey<K>[]>;
|
||||
// @deprecated The underlying RPC this been marked unsafe and is generally not exposed
|
||||
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>;
|
||||
|
||||
@@ -13,7 +13,7 @@ function sig ({ method, section }: StorageEntry, ...args: Type[]): string {
|
||||
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`);
|
||||
assert(args.length === 2, () => `${sig(creator, key1, key2)} is a doublemap, requiring 2 arguments, ${args.length} found`);
|
||||
|
||||
// pass as tuple
|
||||
return [creator, args as [any, any]];
|
||||
@@ -22,7 +22,7 @@ function doDoubleMap (creator: StorageEntry, args: unknown[]): [StorageEntry, [a
|
||||
function doMap (creator: StorageEntry, args: unknown[]): [StorageEntry] | [StorageEntry, any] {
|
||||
const { key } = creator.meta.type.asMap;
|
||||
|
||||
assert(args.length === 1, `${sig(creator, key)} is a map, requiring 1 argument, ${args.length} found`);
|
||||
assert(args.length === 1, () => `${sig(creator, key)} is a map, requiring 1 argument, ${args.length} found`);
|
||||
|
||||
// expand
|
||||
return args.length
|
||||
@@ -41,7 +41,7 @@ export function extractStorageArgs (creator: StorageEntry, _args: unknown[]): [S
|
||||
return doMap(creator, args);
|
||||
}
|
||||
|
||||
assert(args.length === 0, `${sig(creator)} does not take any arguments, ${args.length} found`);
|
||||
assert(args.length === 0, () => `${sig(creator)} does not take any arguments, ${args.length} found`);
|
||||
|
||||
// no args
|
||||
return [creator];
|
||||
|
||||
@@ -1,13 +1,16 @@
|
||||
{
|
||||
"name": "@polkadot/metadata",
|
||||
"version": "3.4.1",
|
||||
"version": "4.8.1",
|
||||
"type": "module",
|
||||
"description": "Helpers to extract information from runtime metadata",
|
||||
"main": "index.js",
|
||||
"module": "index.mjs",
|
||||
"sideEffects": [
|
||||
"./detectPackage.js",
|
||||
"./detectPackage.mjs"
|
||||
"./detectPackage.cjs"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=14.0.0"
|
||||
},
|
||||
"repository": "github:polkadot-js/api",
|
||||
"author": "Jaco Greeff <jacogr@gmail.com>",
|
||||
"maintainers": [],
|
||||
@@ -16,14 +19,14 @@
|
||||
"bugs": "https://github.com/polkadot-js/api/issues",
|
||||
"homepage": "https://github.com/polkadot-js/api/tree/master/packages/type-metadata#readme",
|
||||
"dependencies": {
|
||||
"@babel/runtime": "^7.12.5",
|
||||
"@polkadot/types": "3.4.1",
|
||||
"@polkadot/types-known": "3.4.1",
|
||||
"@polkadot/util": "^5.2.3",
|
||||
"@polkadot/util-crypto": "^5.2.3",
|
||||
"@babel/runtime": "^7.14.0",
|
||||
"@polkadot/types": "4.8.1",
|
||||
"@polkadot/types-known": "4.8.1",
|
||||
"@polkadot/util": "^6.3.1",
|
||||
"@polkadot/util-crypto": "^6.3.1",
|
||||
"bn.js": "^4.11.9"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@polkadot/keyring": "^5.2.3"
|
||||
"@polkadot/keyring": "^6.3.1"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -15,7 +15,7 @@ export class MagicNumber extends U32 {
|
||||
if (!this.isEmpty) {
|
||||
const magic = registry.createType('u32', MAGIC_NUMBER);
|
||||
|
||||
assert(this.eq(magic), `MagicNumber mismatch: expected ${magic.toHex()}, found ${this.toHex()}`);
|
||||
assert(this.eq(magic), () => `MagicNumber mismatch: expected ${magic.toHex()}, found ${this.toHex()}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
|
||||
import type { Registry } from '@polkadot/types/types';
|
||||
|
||||
import { isString, u8aConcat, u8aToU8a } from '@polkadot/util';
|
||||
import { isHex, isU8a, u8aToU8a } from '@polkadot/util';
|
||||
|
||||
import { MetadataVersioned } from './MetadataVersioned';
|
||||
|
||||
@@ -11,37 +11,39 @@ import { MetadataVersioned } from './MetadataVersioned';
|
||||
const VERSION_IDX = 4;
|
||||
|
||||
// magic + lowest supported version
|
||||
const EMPTY_METADATA = u8aConcat(new Uint8Array([0x6d, 0x65, 0x74, 0x61, 9]));
|
||||
const EMPTY_METADATA = new Uint8Array([0x6d, 0x65, 0x74, 0x61, 9]);
|
||||
const EMPTY_U8A = new Uint8Array();
|
||||
|
||||
function sanitizeInput (_value: Uint8Array | string = EMPTY_U8A): Uint8Array {
|
||||
if (isString(_value)) {
|
||||
return sanitizeInput(u8aToU8a(_value));
|
||||
}
|
||||
|
||||
return _value.length === 0
|
||||
? EMPTY_METADATA
|
||||
: _value;
|
||||
function toU8a (value: Uint8Array | string = EMPTY_U8A): Uint8Array {
|
||||
return isHex(value)
|
||||
? toU8a(u8aToU8a(value))
|
||||
: isU8a(value) && value.length === 0
|
||||
? EMPTY_METADATA
|
||||
: value;
|
||||
}
|
||||
|
||||
function decodeMetadata (registry: Registry, _value?: Uint8Array | string): MetadataVersioned {
|
||||
const value = sanitizeInput(_value);
|
||||
const version = value[VERSION_IDX];
|
||||
function decodeMetadata (registry: Registry, _value?: Uint8Array | string | Map<string, unknown> | Record<string, unknown>): MetadataVersioned {
|
||||
if (!_value || isU8a(_value) || isHex(_value)) {
|
||||
const value = toU8a(_value);
|
||||
const version = value[VERSION_IDX];
|
||||
|
||||
try {
|
||||
return new MetadataVersioned(registry, value);
|
||||
} catch (error) {
|
||||
// This is an f-ing hack as a follow-up to another ugly hack
|
||||
// https://github.com/polkadot-js/api/commit/a9211690be6b68ad6c6dad7852f1665cadcfa5b2
|
||||
// when we fail on V9, try to re-parse it as v10... yes... HACK
|
||||
if (version === 9) {
|
||||
value[VERSION_IDX] = 10;
|
||||
try {
|
||||
return new MetadataVersioned(registry, value);
|
||||
} catch (error) {
|
||||
// This is an f-ing hack as a follow-up to another ugly hack
|
||||
// https://github.com/polkadot-js/api/commit/a9211690be6b68ad6c6dad7852f1665cadcfa5b2
|
||||
// when we fail on V9, try to re-parse it as v10... yes... HACK
|
||||
if (version === 9) {
|
||||
value[VERSION_IDX] = 10;
|
||||
|
||||
return decodeMetadata(registry, value);
|
||||
return decodeMetadata(registry, value);
|
||||
}
|
||||
|
||||
throw error;
|
||||
}
|
||||
|
||||
throw error;
|
||||
}
|
||||
|
||||
return new MetadataVersioned(registry, _value);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -50,7 +52,7 @@ function decodeMetadata (registry: Registry, _value?: Uint8Array | string): Meta
|
||||
* The versioned runtime metadata as a decoded structure
|
||||
*/
|
||||
export class Metadata extends MetadataVersioned {
|
||||
constructor (registry: Registry, value?: Uint8Array | string) {
|
||||
constructor (registry: Registry, value?: Uint8Array | string | Map<string, unknown> | Record<string, unknown>) {
|
||||
super(registry, decodeMetadata(registry, value));
|
||||
}
|
||||
}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user