Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
28355424bd | ||
|
|
e7be062522 | ||
|
|
ed5b5eeaa6 | ||
|
|
ad8ad42344 | ||
|
|
f311e5d57f | ||
|
|
065f39ba6d | ||
|
|
64bf72a6d7 | ||
|
|
b59b60ae1f | ||
|
|
e5b7e7f16f | ||
|
|
c2705bdfda | ||
|
|
373eb06713 | ||
|
|
45c2c40a3e | ||
|
|
3b110d7d7f | ||
|
|
0a8d2e5ac1 | ||
|
|
d0bf8b8d82 | ||
|
|
2c3ef10513 | ||
|
|
92022bda94 | ||
|
|
609581430f | ||
|
|
ec083f623d | ||
|
|
395dc79ef7 | ||
|
|
a968fe05b5 | ||
|
|
4b3b853c27 | ||
|
|
ea5843f7c9 | ||
|
|
467ccc5681 | ||
|
|
59922eee8f | ||
|
|
5af98cc89e | ||
|
|
1b7265048d | ||
|
|
3151c08aca | ||
|
|
71332fde1b | ||
|
|
00bc441f0e | ||
|
|
4f4833da74 | ||
|
|
825365bb13 | ||
|
|
48a3a976f9 | ||
|
|
b579b18fad | ||
|
|
27f5547bbf | ||
|
|
4654d15097 | ||
|
|
10574ecc33 | ||
|
|
6ae75ba92e | ||
|
|
5a48a2a3f7 | ||
|
|
40899adf82 | ||
|
|
020effecc8 | ||
|
|
430beb9f25 | ||
|
|
533d6dd441 | ||
|
|
95dd13e218 | ||
|
|
c8cb441a82 | ||
|
|
b6d1be6ee5 | ||
|
|
e13514cd94 | ||
|
|
5a90da5df8 | ||
|
|
8fdc518651 | ||
|
|
eb6b3c5bd4 | ||
|
|
1214572f02 | ||
|
|
df229ffb8a | ||
|
|
334e0bb730 | ||
|
|
f43bc32573 | ||
|
|
bf4a8e28a3 | ||
|
|
9188e29dcc | ||
|
|
7ea89950fe | ||
|
|
7a1089df79 | ||
|
|
f1ca28adcb | ||
|
|
8f675053a4 | ||
|
|
64de91a96b | ||
|
|
6bd10daf43 | ||
|
|
57c54c860a | ||
|
|
0e9a50e020 | ||
|
|
15c35900ac | ||
|
|
6f092a1818 | ||
|
|
c0c6928394 | ||
|
|
391c98c845 | ||
|
|
2e125c5542 | ||
|
|
3d67b75059 | ||
|
|
d958ef8f15 | ||
|
|
97527871d6 | ||
|
|
0317f28e5a | ||
|
|
ebe6d03762 | ||
|
|
59e92fa344 | ||
|
|
cab338e26d | ||
|
|
743ea431b4 | ||
|
|
533f9ce249 | ||
|
|
797ee9c24a | ||
|
|
2f5e2537a3 | ||
|
|
dd52ea4b32 | ||
|
|
5e8ae793c3 | ||
|
|
8713a1f2b6 | ||
|
|
6e6fa4a97c | ||
|
|
ac2a0a34ca | ||
|
|
45fb6d44ad | ||
|
|
6d2265d4ff | ||
|
|
4ec42f1750 | ||
|
|
01166b9684 | ||
|
|
0075dce720 | ||
|
|
7fbb30066e | ||
|
|
637069d723 | ||
|
|
d639a7ee8c | ||
|
|
28ef291c40 | ||
|
|
48ddd0b0d4 | ||
|
|
e88ebf7b2e | ||
|
|
72700e6baf | ||
|
|
f748fcd46d | ||
|
|
7876bb9ced | ||
|
|
a83980b213 | ||
|
|
c4323d5e94 | ||
|
|
11694f1393 | ||
|
|
3989ae67b2 | ||
|
|
b78df57907 | ||
|
|
2f78329738 | ||
|
|
6063054712 | ||
|
|
e42af97928 | ||
|
|
d05ccdb5d7 | ||
|
|
c33334b72b | ||
|
|
94e9fd2b17 | ||
|
|
9c1327ea22 | ||
|
|
9f195e9402 | ||
|
|
3e5e089c68 | ||
|
|
35c37aa66c | ||
|
|
f1aeb564e3 | ||
|
|
c2ff1b32ae | ||
|
|
288427cbb8 | ||
|
|
d099ccedad | ||
|
|
79c7983199 | ||
|
|
80c578fe76 | ||
|
|
de90c048bf | ||
|
|
01a36a994d | ||
|
|
b1ce22d51d | ||
|
|
fe951c2645 | ||
|
|
5a17c542a7 | ||
|
|
59bb5f864f | ||
|
|
abcba20f90 | ||
|
|
014f08c7cc | ||
|
|
7ecd00a4e6 | ||
|
|
6239818c26 | ||
|
|
6af22f41c7 | ||
|
|
77c3a701d0 | ||
|
|
46b17a466c | ||
|
|
e592c6c878 | ||
|
|
ef37586dfc | ||
|
|
5856ce24cc | ||
|
|
8b79056bf9 | ||
|
|
70e0f19ade | ||
|
|
cf1e242c17 | ||
|
|
68856e9692 | ||
|
|
e0626c3dad | ||
|
|
277ea92fda | ||
|
|
aec6694028 | ||
|
|
533abb76f7 | ||
|
|
7660bab86b | ||
|
|
f7c1b6e81b | ||
|
|
b6e9b29570 | ||
|
|
519d9c8fa9 | ||
|
|
ad905db53b | ||
|
|
0a0aa742b4 | ||
|
|
dfbb06a4d6 | ||
|
|
82e71fd51e | ||
|
|
a8b88af97a | ||
|
|
eee36537de | ||
|
|
20a75eafb6 | ||
|
|
00d3a1174b | ||
|
|
e293c7c1cf | ||
|
|
3c8cd499c4 | ||
|
|
cb3816df78 | ||
|
|
fcfcbb2d97 | ||
|
|
321b80ed63 | ||
|
|
73eaa9fe17 | ||
|
|
4d8910f3da | ||
|
|
e6806ed7f9 | ||
|
|
218abf9568 | ||
|
|
a1df864681 | ||
|
|
45640edcff | ||
|
|
53655019b5 | ||
|
|
a1f8bedb6d | ||
|
|
9d1af1eaeb | ||
|
|
38bfd26511 | ||
|
|
1beaf9f208 | ||
|
|
29c29978dd | ||
|
|
a8d1dd0637 | ||
|
|
74571dcd26 | ||
|
|
54b4c2620a | ||
|
|
da05828e74 | ||
|
|
fa935156e1 | ||
|
|
19510c1ede | ||
|
|
97b5c699b1 | ||
|
|
d2befda86e | ||
|
|
740348b48f | ||
|
|
9e2a5cf532 | ||
|
|
6df466d9ea | ||
|
|
e2a2ac2842 | ||
|
|
5adc846e45 | ||
|
|
75aa310837 | ||
|
|
ce0523eb1c | ||
|
|
eb0370bb66 | ||
|
|
5eb491dc67 | ||
|
|
b50294ab0f | ||
|
|
e1cb62d2d2 | ||
|
|
8ed0ef2295 | ||
|
|
956e173323 | ||
|
|
b8a37ba438 | ||
|
|
e7669c2b00 | ||
|
|
6c309a503d | ||
|
|
3cf67c975a | ||
|
|
077914364c | ||
|
|
56e4cbdb27 | ||
|
|
60bfdae734 | ||
|
|
1cf4d6b9b8 | ||
|
|
40cd9ff51f | ||
|
|
c7e6e40030 | ||
|
|
97d0bcbfd4 | ||
|
|
6ca84425d1 | ||
|
|
8481647d2c | ||
|
|
658dda66a4 | ||
|
|
87f18efe72 | ||
|
|
bcdfcce89c | ||
|
|
9418f1de56 | ||
|
|
37c8b8e592 | ||
|
|
4f8db79a40 | ||
|
|
54cf086a89 | ||
|
|
37ddcaa32d | ||
|
|
6a2baf8352 | ||
|
|
ecca91dffd | ||
|
|
42576d74ac | ||
|
|
26a6f20dbf | ||
|
|
c3ee8393b2 | ||
|
|
b6f0b9f262 | ||
|
|
991dc48020 | ||
|
|
e4a82f9a1d | ||
|
|
c8b6012553 | ||
|
|
d0fe862605 | ||
|
|
61a0198695 | ||
|
|
345a97dc9f | ||
|
|
f821ab8ecd | ||
|
|
f9e2bf332d | ||
|
|
ad69430980 | ||
|
|
d25743016c | ||
|
|
ee0a46adc4 | ||
|
|
f516abfc3f | ||
|
|
1a96ca5c0e | ||
|
|
8c73cd7d6e | ||
|
|
36232c0289 | ||
|
|
50d4e0397f | ||
|
|
539a8c4cb5 | ||
|
|
b849976b3b | ||
|
|
2395401a2b | ||
|
|
0e1bbd5cac | ||
|
|
e9489d41cb | ||
|
|
63483b9db7 | ||
|
|
b26c7f9f0a | ||
|
|
a165c9375c | ||
|
|
28631f7180 | ||
|
|
6489251b47 | ||
|
|
66884febea | ||
|
|
8058dc350f | ||
|
|
63096cc238 | ||
|
|
05600c0cd0 | ||
|
|
eed5e23e65 | ||
|
|
cdf5b15673 | ||
|
|
1922676bd7 | ||
|
|
b6c427e985 | ||
|
|
0327aedf8e | ||
|
|
d7035cebb1 | ||
|
|
8b492021af | ||
|
|
6a01fc7c8c | ||
|
|
bbc30ec9dc | ||
|
|
f07c0628bc | ||
|
|
023c7588e5 | ||
|
|
7dfc8625cc | ||
|
|
8643b5da87 | ||
|
|
afa0e63ae8 | ||
|
|
534303ff45 | ||
|
|
f1ebcddec6 | ||
|
|
657a2006dd | ||
|
|
219e928c01 | ||
|
|
43183118d5 | ||
|
|
76e15d465d | ||
|
|
4c0387e1a3 | ||
|
|
bbbd82eb4a | ||
|
|
a34a7450aa | ||
|
|
bf472fdcf4 | ||
|
|
f428a58006 | ||
|
|
fcce2ab340 | ||
|
|
877eb11717 | ||
|
|
4b55f1be93 | ||
|
|
f2a677634e | ||
|
|
eea4c8775e | ||
|
|
792bf0ec36 | ||
|
|
e3d13107a9 | ||
|
|
e5c2c6a228 | ||
|
|
d2be79132c | ||
|
|
76da2638c1 | ||
|
|
daf3912920 | ||
|
|
6dfebbb9fe | ||
|
|
e55c5f77f7 | ||
|
|
c7315ffb74 | ||
|
|
84eb806f07 | ||
|
|
2493442a2e | ||
|
|
77df7907c7 | ||
|
|
f1b6268784 | ||
|
|
9aa9380251 | ||
|
|
b4306cb60a | ||
|
|
1e83daf797 | ||
|
|
d46d32d9bc | ||
|
|
032a0a595c | ||
|
|
34101ec12b | ||
|
|
4e02b982d3 | ||
|
|
5b96d52fa6 | ||
|
|
735f2b835e | ||
|
|
646e64c286 | ||
|
|
fc9060caa8 | ||
|
|
503c2b3c63 | ||
|
|
168abc130f | ||
|
|
5c5db2709b | ||
|
|
5a4ff5420f | ||
|
|
a1655508ba | ||
|
|
64827a6114 | ||
|
|
2eb09374bc | ||
|
|
ddf67d5564 | ||
|
|
ad6b8280a2 | ||
|
|
682c6b6fb2 | ||
|
|
6a281211b4 | ||
|
|
6ef94b3c3b | ||
|
|
e900d1d657 | ||
|
|
7f1a3fa636 | ||
|
|
21802664b8 | ||
|
|
1492df11a7 | ||
|
|
00fed90da2 | ||
|
|
e6beb6554d | ||
|
|
099cf5a351 | ||
|
|
55e762a348 | ||
|
|
0ad146c607 | ||
|
|
4e7f3f5268 | ||
|
|
6a9e3d80f1 | ||
|
|
dee98fae55 | ||
|
|
ff52876920 | ||
|
|
4d01a09c54 | ||
|
|
7310ea825e | ||
|
|
15b80a47c3 | ||
|
|
622682b4ef | ||
|
|
56415df4ab | ||
|
|
8bea5e5a3b | ||
|
|
d6372ade44 | ||
|
|
f501994df8 | ||
|
|
b787a7d5a0 | ||
|
|
11d162a10d | ||
|
|
e2564dea17 | ||
|
|
2b9152871e | ||
|
|
70ecb03d14 | ||
|
|
a2f179acb1 | ||
|
|
c8cb97edef | ||
|
|
69d344c6c3 | ||
|
|
44cdf49b2c | ||
|
|
daaf4654a1 | ||
|
|
f8d4fcaf04 | ||
|
|
eb19a39d82 | ||
|
|
7ed958fb2d | ||
|
|
bbe9b94f26 | ||
|
|
6e83e6aaef | ||
|
|
1545bbf7c5 | ||
|
|
5bfc2cd534 | ||
|
|
b22d0a196f | ||
|
|
b174864804 | ||
|
|
e6834d60c5 | ||
|
|
97438bb2e8 | ||
|
|
f630d43a25 | ||
|
|
0187f1ff19 | ||
|
|
d8db866316 | ||
|
|
28aa9e18a7 | ||
|
|
3eaea97b8f | ||
|
|
ea0e5e4547 | ||
|
|
1256317b65 | ||
|
|
e0c3ed1b96 |
+4
-2
@@ -1,5 +1,7 @@
|
||||
24
|
||||
25
|
||||
1.4.2
|
||||
1.6.2
|
||||
1.11.2
|
||||
1.12.2
|
||||
1.12.2
|
||||
1.17.2
|
||||
1.31.2
|
||||
+3
-1
@@ -13,6 +13,8 @@ module.exports = {
|
||||
// add override for any (a metric ton of them, initial conversion)
|
||||
'@typescript-eslint/no-explicit-any': 'off',
|
||||
// these should be removed, there are 8 of them as errors
|
||||
'@typescript-eslint/no-non-null-assertion': 'off'
|
||||
'@typescript-eslint/no-non-null-assertion': 'off',
|
||||
// this seems very broken atm, false positives
|
||||
'@typescript-eslint/unbound-method': 'off'
|
||||
}
|
||||
};
|
||||
|
||||
@@ -10,7 +10,7 @@ jobs:
|
||||
matrix:
|
||||
step: ['build:release', 'docs:release']
|
||||
name: ${{ matrix.step }}
|
||||
if: "! contains(github.event.head_commit.message, '[CI Skip]') && github.repository == 'polkadot-js/api'"
|
||||
if: "! startsWith(github.event.head_commit.message, '[CI Skip]') && github.repository == 'polkadot-js/api'"
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v1
|
||||
@@ -21,16 +21,13 @@ jobs:
|
||||
CC_TEST_REPORTER_ID: ${{ secrets.CC_TEST_REPORTER_ID }}
|
||||
GH_PAGES_SRC: build-docs
|
||||
GH_PAT: ${{ secrets.GH_PAT }}
|
||||
GH_TOKEN: ${{ secrets.GH_PAT }}
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
GH_RELEASE_GITHUB_API_TOKEN: ${{ secrets.GH_PAT }}
|
||||
NPM_TOKEN: ${{ secrets.NPM_TOKEN }}
|
||||
run: |
|
||||
yarn install --immutable | grep -v 'YN0013'
|
||||
yarn ${{ matrix.step }}
|
||||
|
||||
dummy:
|
||||
name: Dummy
|
||||
if: "contains(github.event.head_commit.message, '[CI Skip]')"
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: dummy
|
||||
|
||||
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+55
File diff suppressed because one or more lines are too long
Vendored
-56
File diff suppressed because one or more lines are too long
+2
-2
@@ -5,7 +5,7 @@ enableProgressBars: false
|
||||
nodeLinker: node-modules
|
||||
|
||||
plugins:
|
||||
- path: .yarn/plugins/@yarnpkg/plugin-interactive-tools.js
|
||||
- path: .yarn/plugins/@yarnpkg/plugin-interactive-tools.cjs
|
||||
spec: "@yarnpkg/plugin-interactive-tools"
|
||||
|
||||
yarnPath: .yarn/releases/yarn-rc.js
|
||||
yarnPath: .yarn/releases/yarn-2.2.2.cjs
|
||||
|
||||
+594
-85
File diff suppressed because it is too large
Load Diff
@@ -7,7 +7,7 @@
|
||||
|
||||
# @polkadot/api
|
||||
|
||||
This library provides a clean wrapper around all the methods exposed by a Polkadot/Subtrate network client and defines all the types exposed by a node. For complete documentation around the classes, interfaces and their use, visit the [documentation portal](https://polkadot.js.org/api/).
|
||||
This library provides a clean wrapper around all the methods exposed by a Polkadot/Substrate network client and defines all the types exposed by a node. For complete documentation around the classes, interfaces and their use, visit the [documentation portal](https://polkadot.js.org/api/).
|
||||
|
||||
If you are an existing user, please be sure to track the [CHANGELOG](CHANGELOG.md) and [UPGRADING](UPGRADING.md) guides when changing versions.
|
||||
|
||||
|
||||
Executable
+23
@@ -0,0 +1,23 @@
|
||||
#!/usr/bin/env bash
|
||||
|
||||
function copy_folder () {
|
||||
SRC="packages/$1/build"
|
||||
DST="../test/js-test/node_modules/@polkadot/$1"
|
||||
|
||||
echo "** Copying $SRC to $DST"
|
||||
|
||||
rm -rf $DST
|
||||
cp -r $SRC $DST
|
||||
}
|
||||
|
||||
yarn polkadot-dev-build-ts
|
||||
|
||||
copy_folder "api"
|
||||
copy_folder "api-contract"
|
||||
copy_folder "api-derive"
|
||||
copy_folder "metadata"
|
||||
copy_folder "rpc-core"
|
||||
copy_folder "rpc-provider"
|
||||
copy_folder "types"
|
||||
copy_folder "types-known"
|
||||
copy_folder "typegen"
|
||||
@@ -42,3 +42,20 @@ const header = await api.derive.chain.getHeader();
|
||||
|
||||
console.log(`#${header.number}: ${header.author}`);
|
||||
```
|
||||
|
||||
## How do I view block extrinsic information?
|
||||
|
||||
The transactions are included in a signed block as part of the extrinsics - some of these will be unsigned and generated by the block author and some of these may be submitted from external sources and be signed. (Some palettes do use unsigned transactions, so signed/unsigned is not an indication of origin). To retrieve the block and display the transaction information, we can do the following -
|
||||
|
||||
```js
|
||||
// no blockHash is specified, so we retrieve the latest
|
||||
const signedBlock = await this.api.rpc.chain.getBlock();
|
||||
|
||||
// the information for each of the contained extrinsics
|
||||
signedBlock.block.extrinsics.forEach((ex, index) => {
|
||||
// the extrinsics are decoded by the API
|
||||
console.log(index, ex.toHuman());
|
||||
});
|
||||
```
|
||||
|
||||
In the above `.toHuman()` is used to format into a human-readable representation. You can inspect/extract specific fields from the decoded extrinsic as required, for instance `ex.method.section` would return the pallete that executed this transaction.
|
||||
|
||||
+6
-6
@@ -16,9 +16,9 @@ const info = await api.tx.balances
|
||||
|
||||
// log relevant info, partialFee is Balance, estimated for current
|
||||
console.log(`
|
||||
class=${class.toString()},
|
||||
weight=${weight.toString()},
|
||||
partialFee=${partialFee.toHuman()}
|
||||
class=${info.class.toString()},
|
||||
weight=${info.weight.toString()},
|
||||
partialFee=${info.partialFee.toHuman()}
|
||||
`);
|
||||
```
|
||||
|
||||
@@ -97,12 +97,12 @@ api.tx.utility
|
||||
|
||||
## How do I take the pending tx pool into account in my nonce?
|
||||
|
||||
The `system.account` query will always contain the current state, i.e. it will reflect the nonce for the last known block. As such when sending multiple transactions in quick succession (see batching above), there may be transactions in the pool that has the same nonce that `signAndSend` would apply - this call doesn't do any magic, it simply reads the state for the nonce. Since we can specify options to the `signandSend` operation, we can override the nonce, either by manually incrementing it o querying it via `nextNonce`.
|
||||
The `system.account` query will always contain the current state, i.e. it will reflect the nonce for the last known block. As such when sending multiple transactions in quick succession (see batching above), there may be transactions in the pool that has the same nonce that `signAndSend` would apply - this call doesn't do any magic, it simply reads the state for the nonce. Since we can specify options to the `signAndSend` operation, we can override the nonce, either by manually incrementing it or querying it via `rpc.system.accountNextIndex`.
|
||||
|
||||
```js
|
||||
for (let i = 0; i < 10; i++) {
|
||||
// retrieve the nextNonce, taking txs in the pool into account
|
||||
const nonce = await api.rpc.account.nextNonce(sender);
|
||||
// retrieve sender's next index/nonce, taking txs in the pool into account
|
||||
const nonce = await api.rpc.system.accountNextIndex(sender);
|
||||
|
||||
// send, just retrieving the hash, not waiting on status
|
||||
const txhash = await api.tx.balances
|
||||
|
||||
@@ -90,7 +90,7 @@ Looking at the example in this repo, it also has `augment*`, `index.ts` and `typ
|
||||
|
||||
## Generating
|
||||
|
||||
Now that both the metadata nd types setup is completed, we just run the build command via `yarn build` and magically (assuming you didn't have the `augment*` and other generated files), these files will be added. When running this command, the console should display something like -
|
||||
Now that both the metadata and types setup is completed, we just run the build command via `yarn build` and magically (assuming you didn't have the `augment*` and other generated files), these files will be added. When running this command, the console should display something like -
|
||||
|
||||
```
|
||||
> yarn build
|
||||
@@ -166,7 +166,7 @@ As mentioned earlier, here you will notice the `import { VoteStage }`, the gener
|
||||
|
||||
## TypeScript config
|
||||
|
||||
Now that we have files generated, it is time to make TypeScript aware of the types and add an explicit override into out `tsconfig.json`. After some changes, the paths in the config looks as follow (comments are in teh actual config file here) -
|
||||
Now that we have files generated, it is time to make TypeScript aware of the types and add an explicit override into out `tsconfig.json`. After some changes, the paths in the config looks as follow (comments are in the actual config file here) -
|
||||
|
||||
```json
|
||||
{
|
||||
|
||||
+2
-13
@@ -20,6 +20,8 @@ All data transferred between the API and the Node is in a SCALE-encoded binary f
|
||||
|
||||
To fix this, you should look at the specific `api.tx.*` params and adjust the type definitions for those param types to match what is found on the node side. In some rare cases the cause could be extrinsic formatting related, to track these make an `api.tx.system.remark(data: Bytes)` call, if it fails, the API and node cannot agree on [an extrinsic format and adjustments are required](types.extend.md#impact-on-extrinsics).
|
||||
|
||||
If you are using a node-template based version of substrate and you changed the specName you need to add these typings(In addition to other custom types) `{"Address": "AccountId","LookupSource": "AccountId"}`. This is also the case when you use [polkadot-js/apps](https://github.com/polkadot-js/apps) to connect to your node. When the specName stays node-template the API is smart enough to add the custom typings.
|
||||
|
||||
## I would like to sign transactions offline
|
||||
|
||||
The API itself is independent on where the signature comes from and how it is injected. Additionally it implements a signer interface, that can be used for external signing - an example of this is the [polkadot-js/apps](https://github.com/polkadot-js/apps) support for signing via extensions and even the [polkadot-js/extension](https://github.com/polkadot-js/extension) support for tools such as the [Parity Signer](https://github.com/paritytech/parity-signer).
|
||||
@@ -63,16 +65,3 @@ Due to these customizations and differences that bleed through to the transactio
|
||||
Recently Substrate master updated the `Weight` type from `u32` -> `u64`. This type is used in the `DispatchInfo` struct in the `system.ExtrinsicSuccess` events, to return the applied call weights as well as the resulting fees. Since the API master branch tracks Substrate master, this means the change has been applied by default, with the default set to `u64`.
|
||||
|
||||
If you are on a chain that has not been upgraded yet, you need to add `Weight: 'u32'` to your types to allow for successful parsing of all events. Without this override, parsing will fail. As soon as one event in the `Vec<EventRecord>` structure from `system.events` fails to parse, all subsequent events are affected and the decoding will return an error.
|
||||
|
||||
## When querying older blocks & events, it fails on parsing
|
||||
|
||||
Upon initialization, the API is decorated with the [current on-chain metadata](basics.md#metadata) and (if [available](https://github.com/polkadot-js/api/tree/master/packages/types-known/src)) the specific types for the runtime version is added. This allows the API to decode all current (as per the on-chain info) state and extrinsics.
|
||||
|
||||
When the chain is upgraded, new metadata (indicating new events, storage and extrinsics) is added on-chain. Additionally this generally goes hand in-hand with changes in types, i.e. fields may be addedd or removed or state that was used could now be migrated to new locations. In most cases, this would mean that the current chain information cannot be used to parse older entries pre-upgrade. A typical consequence of this is that any `.at(...)` or `.range(...)` queries pre-upgrade may fail.
|
||||
|
||||
As of the current time, there is no automatic injection of older metadata (based on the runtime version at a specific block) nor decoration of older types if they are available. It can be emulated with what the API will do to handle these cases when it adds a `.historic(...)` query type -
|
||||
|
||||
- querying the runtime version at the parent of older block you wish to retrieve
|
||||
- retrieving and injecting the metadata from the parent block (if the runtime version has changed)
|
||||
- inject any specific older types for the state at that point
|
||||
- finally retrieve the actual entry via an `.at(...)` query
|
||||
|
||||
@@ -8,7 +8,7 @@ import { ApiPromise, WsProvider } from '@polkadot/api';
|
||||
|
||||
...
|
||||
// Construct
|
||||
const wsProvider = new WsProvider('wss://poc-3.polkadot.io');
|
||||
const wsProvider = new WsProvider('wss://rpc.polkadot.io');
|
||||
const api = await ApiPromise.create({ provider: wsProvider });
|
||||
|
||||
// Do something
|
||||
@@ -49,7 +49,7 @@ The API creation is done via the `ApiPromise.create` interface which is a shortc
|
||||
|
||||
```js
|
||||
ApiPromise
|
||||
.create({ provider: wsProvider })
|
||||
.create({ provider: wsProvider }).isReady
|
||||
.then((api) =>
|
||||
console.log(api.genesisHash.toHex())
|
||||
);
|
||||
@@ -70,7 +70,7 @@ console.log(api.genesisHash.toHex());
|
||||
|
||||
## Failures
|
||||
|
||||
In all cases the API will handle reconnections automatically. This means that when you connect and the endpoint is not (yet) ready, the promise will not resolve immediately, but rather when connected. The same applies to when connection is lost, the API will manage re-connections.
|
||||
In all cases the API will handle reconnecting automatically. This means that when you connect and the endpoint is not (yet) ready, the promise will not resolve immediately, but rather when connected. The same applies to when connection is lost, the API will manage re-connections.
|
||||
|
||||
In cases where the API does not support the chain being connected to, such as it using an unknown metadata version, the ready promise will fail to resolve and instead reject.
|
||||
|
||||
|
||||
@@ -42,7 +42,7 @@ Be aware that while defined, the method will only appear on the API if it is in
|
||||
|
||||
## Definition breakdown
|
||||
|
||||
While the above example should be self-explanatory, it is important to understand teh structure. The `rpc: { ... }` definitions are keyed first and foremost by the name of the module exposing the RPC. This means that when we have 2 modules `firstModule` & `testModule`, the first-level structure would follow the following pattern,
|
||||
While the above example should be self-explanatory, it is important to understand the structure. The `rpc: { ... }` definitions are keyed first and foremost by the name of the module exposing the RPC. This means that when we have 2 modules `firstModule` & `testModule`, the first-level structure would follow the following pattern,
|
||||
|
||||
```js
|
||||
...
|
||||
|
||||
@@ -10,6 +10,7 @@ As a minimum, anything returned by the API, be it a `Vec<...>`, `Option<...>`, `
|
||||
|
||||
- `.eq(<other value>)` - checks for equality against the other value. In all cases, it will accept "like" values, i.e. in the case of a number you can pass a primitive (such as `1`), a hex value (such as `0x01`) or even an `Unit8Array`
|
||||
- `toHex()` - returns a hex-base representation of the value, always prefixed by `0x`
|
||||
- `toHuman()` - returns Human-parsable JSON structure with values formatted as per the settings
|
||||
- `toJSON()` - returns a JSON-like representation of the value, this is generally used when calling `JSON.stringify(...)` on the value
|
||||
- `toString()` - returns a string representation, in some cases this performs additional encoding, i.e. for `Address`, `AccountId` and `AccountIndex` it will encode to the ss58 address
|
||||
- `.toU8a()` - returns a `Uint8Array` representation of the encoded value (generally exactly as passed to the node, where values are SCALE encoded)
|
||||
@@ -41,6 +42,7 @@ const system = modules.find(m => m.name.eq('system'));
|
||||
All numbers wrap and extend an instance of [bn.js](https://github.com/indutny/bn.js/). This means that in addition to the interfaces defined above, they have some additional methods -
|
||||
|
||||
- `.toNumber()` - a JS number (limited to 2^53 - 1). This does mean that for large values, e.g. `Balance` (a `u128` extension), this can cause overflows
|
||||
- `.toBigInt()` - a JS `BigInt` object (on supported platforms)
|
||||
- `.add(...)`, `.sub(...)`, ... - all the base methods available on the `BN` object
|
||||
|
||||
In cases where a `Compact` is returned, i.e. `Compact<Balance>`, the value is wrapped. This object should be `.unwrap()`-ed first to gain access to the underlying `Balance` object.
|
||||
|
||||
@@ -20,7 +20,7 @@ With the conversions done in the API, there are limited reasons to create types
|
||||
import type { Balance } from '@polkadot/types/interfaces';
|
||||
|
||||
...
|
||||
// unwrap out option into a zero Balance whn not found
|
||||
// unwrap out option into a zero Balance when not found
|
||||
// (This can be done via `.unwrapOrDefault()`, which does the same underlying)
|
||||
const balance: Balance = balanceOpt.unwrapOr(api.createType('Balance'));
|
||||
```
|
||||
|
||||
@@ -6,7 +6,7 @@ Therefore to cater for all types, a mapping in done on the [@polkadot/types libr
|
||||
|
||||
Additionally, the API contains some logic for chain type detection, for instance in the case of Substrate 1.x based chains, it will define `BlockNumber` & `Index` (nonce) as a `u64`, while for current-generation chains, these will be defined as `u32`. Some of the work in maintaining the API for Polkadot/Substrate is the addition of types as they appear and gets used in the Rust codebase.
|
||||
|
||||
There is a the [recommendation](install.md#betas) to use a `@polkadot/api@beta` should you wish to track the master branches of Polkadot or Substrate, since master changes for the addition of new types do not make it into a stable release immediately.
|
||||
There is the [recommendation](install.md#betas) to use a `@polkadot/api@beta` should you wish to track the master branches of Polkadot or Substrate, since master changes for the addition of new types do not make it into a stable release immediately.
|
||||
|
||||
## Extension
|
||||
|
||||
@@ -87,7 +87,7 @@ Document: {
|
||||
|
||||
## User-defined enum
|
||||
|
||||
One form of types that appear regularly is enums, these can be defined as follow -
|
||||
One form of types that appear regularly is enums, these can be defined as follows -
|
||||
|
||||
```js
|
||||
...
|
||||
@@ -212,4 +212,4 @@ Always look at customization and understand the impacts, replicating these chang
|
||||
|
||||
## Custom RPC
|
||||
|
||||
In addition to customizing modules and types on your node, you can also add custom RPC definitions. Like the type definitions in ths section, [these can be defined and passed to the API](rpc.custom.md) for decoration.
|
||||
In addition to customizing your node's modules and types, you can also add custom RPC definitions. Like the type definitions in this section, [these can be defined and passed to the API](rpc.custom.md) for decoration.
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# TypeScript user generated
|
||||
|
||||
In the previous section we looked at the TypeScript definitions that are available and is generated from both the chain and definitions. Here we will expand upon the use of the infrastructure created to define types as part of the `@polkadot/types` library and see how to use them to generate your own definitions and chain types.
|
||||
In the previous section we looked at the TypeScript definitions that are available and are generated from both the chain and definitions. Here we will expand upon the use of the infrastructure created to define types as part of the `@polkadot/types` library and see how to use them to generate your own definitions and chain types.
|
||||
|
||||
## Definitions
|
||||
|
||||
@@ -17,7 +17,7 @@ In the root of your project (with the `@polkadot/typegen` package installed), yo
|
||||
|
||||
## Chain modules
|
||||
|
||||
In the same way as the type library provides defaults from a substrate-base chain, you can also, directly from chain from metadata, generate a complete `api.{consts,query}.*` definition for your specific chain. The command will create 2 files, `{consts, query}.types.ts` which you can either use to augment the TypeScript definitions, or replace those in `@polkadot/api/*` with your versions (copy, TypeScript replacement or browser/node aliasing).
|
||||
In the same way as the type library provides defaults from a substrate-base chain, you can also, directly from the chain's metadata, generate a complete `api.{consts,query}.*` definition for your specific chain. The command will create 2 files, `{consts, query}.types.ts` which you can either use to augment the TypeScript definitions, or replace those in `@polkadot/api/*` with your versions (copy, TypeScript replacement or browser/node aliasing).
|
||||
|
||||
In the root of your project, you can run `yarn polkadot-types-from-chain --endpoint wss://<url> --output ./stuff` and it will create the required output. (Here you can specify an optional `--package @MeInc/stuff` to read definitions for the targeted output folder with the specified package name.)
|
||||
|
||||
@@ -27,4 +27,4 @@ The [TypeScript augmentation example](../examples/promise/90_typegen/) example p
|
||||
|
||||
## And that's a wrap
|
||||
|
||||
This brings us to the end of our overview and jump through the API. While the documentation is still very much and ever evolving item, we can encourage you to try out what you have learned with some [examples](../examples). As we [indicated right at the start of this journey](README.md#help-us-help-others), if there are areas for improvement, let us know.
|
||||
This brings us to the end of our overview and jump through the API. While the documentation is still very much an ever evolving item, we can encourage you to try out what you have learned with some [examples](../examples). As we [indicated right at the start of this journey](README.md#help-us-help-others), if there are areas for improvement, let us know.
|
||||
|
||||
+1
-1
@@ -9,5 +9,5 @@
|
||||
"packages": [
|
||||
"packages/*"
|
||||
],
|
||||
"version": "1.16.1"
|
||||
"version": "1.33.1"
|
||||
}
|
||||
|
||||
+15
-10
@@ -7,7 +7,8 @@
|
||||
"packages/*"
|
||||
],
|
||||
"resolutions": {
|
||||
"babel-core": "^7.0.0-bridge.0"
|
||||
"babel-core": "^7.0.0-bridge.0",
|
||||
"typescript": "^4.0.2"
|
||||
},
|
||||
"scripts": {
|
||||
"build": "yarn build:interfaces && polkadot-dev-build-ts && (cd packages/typegen && copyfiles scripts/* build)",
|
||||
@@ -24,14 +25,18 @@
|
||||
"test:watch": "polkadot-dev-run-test --watch"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@babel/core": "^7.9.6",
|
||||
"@babel/register": "^7.9.0",
|
||||
"@babel/runtime": "^7.9.6",
|
||||
"@polkadot/dev": "^0.54.1",
|
||||
"@polkadot/ts": "^0.3.23",
|
||||
"@babel/core": "^7.11.6",
|
||||
"@babel/register": "^7.11.5",
|
||||
"@babel/runtime": "^7.11.2",
|
||||
"@polkadot/dev": "^0.55.51",
|
||||
"@polkadot/ts": "^0.3.46",
|
||||
"@polkadot/typegen": "workspace:packages/typegen",
|
||||
"@types/jest": "^25.2.3",
|
||||
"@vuepress/plugin-search": "^1.5.0",
|
||||
"copyfiles": "^2.2.0"
|
||||
}
|
||||
"@types/jest": "^26.0.13",
|
||||
"@vuepress/plugin-search": "^1.5.4",
|
||||
"copyfiles": "^2.3.0",
|
||||
"typedoc": "^0.19.1",
|
||||
"typedoc-plugin-markdown": "^2.4.2",
|
||||
"typedoc-plugin-no-inherit": "^1.2.0"
|
||||
},
|
||||
"version": "1.33.1"
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@polkadot/api-contract",
|
||||
"version": "1.16.1",
|
||||
"version": "1.33.1",
|
||||
"description": "Interfaces for interacting with contracts and contract ABIs",
|
||||
"main": "index.js",
|
||||
"keywords": [
|
||||
@@ -26,12 +26,12 @@
|
||||
},
|
||||
"homepage": "https://github.com/polkadot-js/api/tree/master/packages/api-contract#readme",
|
||||
"dependencies": {
|
||||
"@babel/runtime": "^7.9.6",
|
||||
"@polkadot/api": "1.16.1",
|
||||
"@polkadot/rpc-core": "1.16.1",
|
||||
"@polkadot/types": "1.16.1",
|
||||
"@polkadot/util": "^2.11.1",
|
||||
"bn.js": "^5.1.2",
|
||||
"rxjs": "^6.5.5"
|
||||
"@babel/runtime": "^7.11.2",
|
||||
"@polkadot/api": "1.33.1",
|
||||
"@polkadot/rpc-core": "1.33.1",
|
||||
"@polkadot/types": "1.33.1",
|
||||
"@polkadot/util": "^3.4.1",
|
||||
"bn.js": "^5.1.3",
|
||||
"rxjs": "^6.6.3"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -17,6 +17,7 @@ import Abi from '../Abi';
|
||||
import Contract from './Contract';
|
||||
import { BaseWithTx } from './util';
|
||||
|
||||
// eslint-disable-next-line no-use-before-define
|
||||
type BlueprintCreateResultSubscription<ApiType extends ApiTypes> = Observable<BlueprintCreateResult<ApiType>>;
|
||||
|
||||
export interface BlueprintCreate<ApiType extends ApiTypes> {
|
||||
|
||||
@@ -17,6 +17,7 @@ import Abi from '../Abi';
|
||||
import Blueprint from './Blueprint';
|
||||
import { BaseWithTx } from './util';
|
||||
|
||||
// eslint-disable-next-line no-use-before-define
|
||||
type CodePutCodeResultSubscription<ApiType extends ApiTypes> = Observable<CodePutCodeResult<ApiType>>;
|
||||
|
||||
export interface CodePutCode<ApiType extends ApiTypes> {
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
|
||||
import { ApiTypes, DecorateMethod, ObsInnerType } from '@polkadot/api/types';
|
||||
import { AccountId, Address, ContractExecResult } from '@polkadot/types/interfaces';
|
||||
import { Codec, IKeyringPair } from '@polkadot/types/types';
|
||||
import { Codec, CodecArg, IKeyringPair } from '@polkadot/types/types';
|
||||
import { ApiObject, ContractABIMessage, ContractABIPre, ContractCallOutcome } from '../types';
|
||||
|
||||
import BN from 'bn.js';
|
||||
@@ -18,7 +18,9 @@ import { BaseWithTxAndRpcCall } from './util';
|
||||
type ContractCallTypes = 'tx' | 'rpc';
|
||||
|
||||
type ContractCallResultSubscription<ApiType extends ApiTypes, CallType extends ContractCallTypes> = ApiType extends 'rxjs'
|
||||
// eslint-disable-next-line no-use-before-define
|
||||
? Observable<ContractCallResult<CallType>>
|
||||
// eslint-disable-next-line no-use-before-define
|
||||
: Promise<ObsInnerType<ContractCallResult<CallType>>>;
|
||||
|
||||
export interface ContractCall<ApiType extends ApiTypes, CallType extends ContractCallTypes> {
|
||||
@@ -38,9 +40,9 @@ export default class Contract<ApiType extends ApiTypes> extends BaseWithTxAndRpc
|
||||
this.address = this.registry.createType('Address', address);
|
||||
}
|
||||
|
||||
public call (as: 'rpc', message: string, value: BN | number, gasLimit: BN | number, ...params: any[]): ContractCall<ApiType, 'rpc'>;
|
||||
public call (as: 'tx', message: string, value: BN | number, gasLimit: BN | number, ...params: any[]): ContractCall<ApiType, 'tx'>;
|
||||
public call<CallType extends ContractCallTypes> (as: CallType, message: string, value: BN | number, gasLimit: BN | number, ...params: any[]): ContractCall<ApiType, CallType> {
|
||||
public call (as: 'rpc', message: string, value: BN | number, gasLimit: BN | number, ...params: CodecArg[]): ContractCall<ApiType, 'rpc'>;
|
||||
public call (as: 'tx', message: string, value: BN | number, gasLimit: BN | number, ...params: CodecArg[]): ContractCall<ApiType, 'tx'>;
|
||||
public call<CallType extends ContractCallTypes> (as: CallType, message: string, value: BN | number, gasLimit: BN | number, ...params: CodecArg[]): ContractCall<ApiType, CallType> {
|
||||
const { def, fn } = this.getMessage(message);
|
||||
|
||||
return {
|
||||
@@ -67,7 +69,7 @@ export default class Contract<ApiType extends ApiTypes> extends BaseWithTxAndRpc
|
||||
};
|
||||
}
|
||||
|
||||
private _createOutcome (result: ContractExecResult, origin: AccountId, message: ContractABIMessage, params: any[]): ContractCallOutcome {
|
||||
private _createOutcome (result: ContractExecResult, origin: AccountId, message: ContractABIMessage, params: CodecArg[]): ContractCallOutcome {
|
||||
let output: Codec | null = null;
|
||||
|
||||
if (result.isSuccess) {
|
||||
|
||||
@@ -4,11 +4,15 @@
|
||||
|
||||
import { ApiTypes, DecorateMethod } from '@polkadot/api/types';
|
||||
import { AccountId, Address, ContractExecResult } from '@polkadot/types/interfaces';
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
import { Codec, CodecArg } from '@polkadot/types/types';
|
||||
import { MetaRegistryJson, StringIndex, TypeIndex, TypeDef } from '@polkadot/types/create/types';
|
||||
|
||||
import { ApiPromise, ApiRx } from '@polkadot/api';
|
||||
|
||||
// I give up, too hard to untangle atm... and is basically deprecated
|
||||
/* eslint-disable no-use-before-define */
|
||||
|
||||
export type ApiObject<ApiType extends ApiTypes> = ApiType extends 'rxjs'
|
||||
? ApiRx
|
||||
: ApiPromise;
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@polkadot/api-derive",
|
||||
"version": "1.16.1",
|
||||
"version": "1.33.1",
|
||||
"description": "Common functions used across Polkadot, derived from RPC calls and storage queries.",
|
||||
"main": "index.js",
|
||||
"keywords": [
|
||||
@@ -27,18 +27,18 @@
|
||||
},
|
||||
"homepage": "https://github.com/polkadot-js/api/tree/master/packages/api-derive#readme",
|
||||
"dependencies": {
|
||||
"@babel/runtime": "^7.9.6",
|
||||
"@polkadot/api": "1.16.1",
|
||||
"@polkadot/rpc-core": "1.16.1",
|
||||
"@polkadot/rpc-provider": "1.16.1",
|
||||
"@polkadot/types": "1.16.1",
|
||||
"@polkadot/util": "^2.11.1",
|
||||
"@polkadot/util-crypto": "^2.11.1",
|
||||
"bn.js": "^5.1.2",
|
||||
"@babel/runtime": "^7.11.2",
|
||||
"@polkadot/api": "1.33.1",
|
||||
"@polkadot/rpc-core": "1.33.1",
|
||||
"@polkadot/rpc-provider": "1.33.1",
|
||||
"@polkadot/types": "1.33.1",
|
||||
"@polkadot/util": "^3.4.1",
|
||||
"@polkadot/util-crypto": "^3.4.1",
|
||||
"bn.js": "^5.1.3",
|
||||
"memoizee": "^0.4.14",
|
||||
"rxjs": "^6.5.5"
|
||||
"rxjs": "^6.6.3"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@polkadot/keyring": "^2.11.1"
|
||||
"@polkadot/keyring": "^3.4.1"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
// Copyright 2017-2020 @polkadot/api-derive authors & contributors
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the Apache-2.0 license. See the LICENSE file for details.
|
||||
|
||||
import { AccountId, AccountIndex, Address } from '@polkadot/types/interfaces';
|
||||
|
||||
import { Observable, of } from 'rxjs';
|
||||
import { map } from 'rxjs/operators';
|
||||
import { ApiInterfaceRx } from '@polkadot/api/types';
|
||||
import { isU8a, assert } from '@polkadot/util';
|
||||
import { decodeAddress } from '@polkadot/util-crypto';
|
||||
|
||||
import { memo } from '../util';
|
||||
|
||||
function retrieve (api: ApiInterfaceRx, address: Address | AccountId | AccountIndex | string | null | undefined): Observable<AccountId> {
|
||||
const decoded = isU8a(address)
|
||||
? address
|
||||
: decodeAddress((address || '').toString());
|
||||
|
||||
if (decoded.length === 32) {
|
||||
return of(api.registry.createType('AccountId', decoded));
|
||||
}
|
||||
|
||||
const accountIndex = api.registry.createType('AccountIndex', decoded);
|
||||
|
||||
return api.derive.accounts.indexToId(accountIndex.toString()).pipe(
|
||||
map((accountId) => {
|
||||
assert(accountId, 'Unable to retrieve accountId');
|
||||
|
||||
return accountId;
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @name accountId
|
||||
* @param {(Address | AccountId | AccountIndex | string | null)} address - An accounts address in various formats.
|
||||
* @description An [[AccountId]]
|
||||
*/
|
||||
export function accountId (instanceId: string, api: ApiInterfaceRx): (address?: Address | AccountId | AccountIndex | string | null) => Observable<AccountId> {
|
||||
return memo(instanceId, (address?: Address | AccountId | AccountIndex | string | null): Observable<AccountId> =>
|
||||
retrieve(api, address));
|
||||
}
|
||||
@@ -31,8 +31,8 @@ function isIncludedFn (accountId: AccountId | Address | string): (_: AccountId |
|
||||
* @name info
|
||||
* @description Returns account membership flags
|
||||
*/
|
||||
export function flags (api: ApiInterfaceRx): (address?: AccountId | Address | string | null) => Observable<DeriveAccountFlags> {
|
||||
return memo((address?: AccountId | Address | string | null): Observable<DeriveAccountFlags> => {
|
||||
export function flags (instanceId: string, api: ApiInterfaceRx): (address?: AccountId | Address | string | null) => Observable<DeriveAccountFlags> {
|
||||
return memo(instanceId, (address?: AccountId | Address | string | null): Observable<DeriveAccountFlags> => {
|
||||
const councilSection = api.query.electionsPhragmen ? 'electionsPhragmen' : 'elections';
|
||||
|
||||
return (
|
||||
|
||||
@@ -30,7 +30,7 @@ function retrieve (api: ApiInterfaceRx, address: Address | AccountId | AccountIn
|
||||
|
||||
const accountIndex = api.registry.createType('AccountIndex', decoded);
|
||||
|
||||
return api.derive.accounts.indexToId(accountIndex).pipe(
|
||||
return api.derive.accounts.indexToId(accountIndex.toString()).pipe(
|
||||
map((accountId): AccountIdAndIndex => [accountId, accountIndex])
|
||||
);
|
||||
} catch (error) {
|
||||
@@ -51,7 +51,7 @@ function retrieve (api: ApiInterfaceRx, address: Address | AccountId | AccountIn
|
||||
* });
|
||||
* ```
|
||||
*/
|
||||
export function idAndIndex (api: ApiInterfaceRx): (address?: Address | AccountId | AccountIndex | string | null) => Observable<AccountIdAndIndex> {
|
||||
return memo((address?: Address | AccountId | AccountIndex | string | null): Observable<AccountIdAndIndex> =>
|
||||
export function idAndIndex (instanceId: string, api: ApiInterfaceRx): (address?: Address | AccountId | AccountIndex | string | null) => Observable<AccountIdAndIndex> {
|
||||
return memo(instanceId, (address?: Address | AccountId | AccountIndex | string | null): Observable<AccountIdAndIndex> =>
|
||||
retrieve(api, address));
|
||||
}
|
||||
|
||||
@@ -25,8 +25,8 @@ import { memo } from '../util';
|
||||
* });
|
||||
* ```
|
||||
*/
|
||||
export function idToIndex (api: ApiInterfaceRx): (accountId: AccountId | string) => Observable<AccountIndex | undefined> {
|
||||
return memo((accountId: AccountId | string): Observable<AccountIndex | undefined> =>
|
||||
export function idToIndex (instanceId: string, api: ApiInterfaceRx): (accountId: AccountId | string) => Observable<AccountIndex | undefined> {
|
||||
return memo(instanceId, (accountId: AccountId | string): Observable<AccountIndex | undefined> =>
|
||||
api.derive.accounts.indexes().pipe(
|
||||
map((indexes: AccountIndexes): AccountIndex | undefined =>
|
||||
(indexes || {})[accountId.toString()]
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the Apache-2.0 license. See the LICENSE file for details.
|
||||
|
||||
export * from './accountId';
|
||||
export * from './flags';
|
||||
export * from './idAndIndex';
|
||||
export * from './idToIndex';
|
||||
|
||||
@@ -49,8 +49,8 @@ function query (api: ApiInterfaceRx, accountIndex: AccountIndex | string): Obser
|
||||
* });
|
||||
* ```
|
||||
*/
|
||||
export function indexToId (api: ApiInterfaceRx): (accountIndex: AccountIndex | string) => Observable<AccountId | undefined> {
|
||||
return memo((accountIndex: AccountIndex | string): Observable<AccountId | undefined> =>
|
||||
export function indexToId (instanceId: string, api: ApiInterfaceRx): (accountIndex: AccountIndex | string) => Observable<AccountId | undefined> {
|
||||
return memo(instanceId, (accountIndex: AccountIndex | string): Observable<AccountId | undefined> =>
|
||||
api.query.indices
|
||||
? isFunction(api.query.indices.accounts)
|
||||
? query(api, accountIndex)
|
||||
|
||||
@@ -16,6 +16,8 @@ import { memo } from '../util';
|
||||
|
||||
const enumsetSize = ENUMSET_SIZE.toNumber();
|
||||
|
||||
let indicesCache: AccountIndexes | null = null;
|
||||
|
||||
function queryEnumSet (api: ApiInterfaceRx): Observable<AccountIndexes> {
|
||||
return api.query.indices.nextEnumSet<AccountIndex>().pipe(
|
||||
// use the nextEnumSet (which is a counter of the number of sets) to construct
|
||||
@@ -70,13 +72,22 @@ function queryAccounts (api: ApiInterfaceRx): Observable<AccountIndexes> {
|
||||
* });
|
||||
* ```
|
||||
*/
|
||||
export function indexes (api: ApiInterfaceRx): () => Observable<AccountIndexes> {
|
||||
return memo((): Observable<AccountIndexes> =>
|
||||
(api.query.indices
|
||||
? isFunction(api.query.indices.accounts)
|
||||
? queryAccounts(api)
|
||||
: queryEnumSet(api)
|
||||
: of({} as AccountIndexes)
|
||||
).pipe(startWith({}))
|
||||
export function indexes (instanceId: string, api: ApiInterfaceRx): () => Observable<AccountIndexes> {
|
||||
return memo(instanceId, (): Observable<AccountIndexes> =>
|
||||
indicesCache
|
||||
? of(indicesCache)
|
||||
: (
|
||||
api.query.indices
|
||||
? isFunction(api.query.indices.accounts)
|
||||
? queryAccounts(api).pipe(startWith({}))
|
||||
: queryEnumSet(api).pipe(startWith({}))
|
||||
: of({} as AccountIndexes)
|
||||
).pipe(
|
||||
map((indices): AccountIndexes => {
|
||||
indicesCache = indices;
|
||||
|
||||
return indices;
|
||||
})
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -113,8 +113,8 @@ function retrieveIdentity (api: ApiInterfaceRx, accountId?: AccountId): Observab
|
||||
* @name info
|
||||
* @description Returns aux. info with regards to an account, current that includes the accountId, accountIndex and nickname
|
||||
*/
|
||||
export function info (api: ApiInterfaceRx): (address?: AccountIndex | AccountId | Address | string | null) => Observable<DeriveAccountInfo> {
|
||||
return memo((address?: AccountIndex | AccountId | Address | string | null): Observable<DeriveAccountInfo> =>
|
||||
export function info (instanceId: string, api: ApiInterfaceRx): (address?: AccountIndex | AccountId | Address | string | null) => Observable<DeriveAccountInfo> {
|
||||
return memo(instanceId, (address?: AccountIndex | AccountId | Address | string | null): Observable<DeriveAccountInfo> =>
|
||||
api.derive.accounts.idAndIndex(address).pipe(
|
||||
switchMap(([accountId, accountIndex]): Observable<[Partial<DeriveAccountInfo>, DeriveAccountRegistration, string?]> =>
|
||||
combineLatest([
|
||||
|
||||
@@ -23,7 +23,7 @@ function calcBalances (api: ApiInterfaceRx, [accountId, [freeBalance, reservedBa
|
||||
frozenFee,
|
||||
frozenMisc,
|
||||
reservedBalance,
|
||||
votingBalance: api.registry.createType('Balance', freeBalance.add(reservedBalance))
|
||||
votingBalance: api.registry.createType('Balance', freeBalance.toBn())
|
||||
};
|
||||
}
|
||||
|
||||
@@ -80,10 +80,10 @@ function queryCurrent (api: ApiInterfaceRx, accountId: AccountId): Observable<Re
|
||||
* });
|
||||
* ```
|
||||
*/
|
||||
export function account (api: ApiInterfaceRx): (address: AccountIndex | AccountId | Address | string) => Observable<DeriveBalancesAccount> {
|
||||
return memo((address: AccountIndex | AccountId | Address | string): Observable<DeriveBalancesAccount> =>
|
||||
api.derive.accounts.info(address).pipe(
|
||||
switchMap(({ accountId }): Observable<[AccountId, Result]> =>
|
||||
export function account (instanceId: string, api: ApiInterfaceRx): (address: AccountIndex | AccountId | Address | string) => Observable<DeriveBalancesAccount> {
|
||||
return memo(instanceId, (address: AccountIndex | AccountId | Address | string): Observable<DeriveBalancesAccount> =>
|
||||
api.derive.accounts.accountId(address).pipe(
|
||||
switchMap((accountId): Observable<[AccountId, Result]> =>
|
||||
(accountId
|
||||
? combineLatest([
|
||||
of(accountId),
|
||||
|
||||
@@ -17,18 +17,22 @@ import { memo } from '../util';
|
||||
type ResultBalance = [VestingInfo | null, (BalanceLock | BalanceLockTo212)[]];
|
||||
type Result = [DeriveBalancesAccount, BlockNumber, ResultBalance];
|
||||
|
||||
const VESTING_ID = '0x76657374696e6720';
|
||||
|
||||
function calcBalances (api: ApiInterfaceRx, [{ accountId, accountNonce, freeBalance, frozenFee, frozenMisc, reservedBalance, votingBalance }, bestNumber, [vesting, locks]]: Result): DeriveBalancesAll {
|
||||
let lockedBalance = api.registry.createType('Balance');
|
||||
let lockedBreakdown: (BalanceLock | BalanceLockTo212)[] = [];
|
||||
let vestingLocked = api.registry.createType('Balance');
|
||||
let allLocked = false;
|
||||
|
||||
if (Array.isArray(locks)) {
|
||||
// only get the locks that are valid until passed the current block
|
||||
lockedBreakdown = (locks as BalanceLockTo212[]).filter(({ until }): boolean => !until || (bestNumber && until.gt(bestNumber)));
|
||||
|
||||
const notAll = lockedBreakdown.filter(({ amount }): boolean => !amount.isMax());
|
||||
const notAll = lockedBreakdown.filter(({ amount }) => !amount.isMax());
|
||||
|
||||
allLocked = lockedBreakdown.some(({ amount }): boolean => amount.isMax());
|
||||
allLocked = lockedBreakdown.some(({ amount }) => amount.isMax());
|
||||
vestingLocked = api.registry.createType('Balance', lockedBreakdown.filter(({ id }) => id.eq(VESTING_ID)).reduce((result: BN, { amount }) => result.iadd(amount), new BN(0)));
|
||||
|
||||
// get the maximum of the locks according to https://github.com/paritytech/substrate/blob/master/srml/balances/src/lib.rs#L699
|
||||
if (notAll.length) {
|
||||
@@ -41,19 +45,12 @@ function calcBalances (api: ApiInterfaceRx, [{ accountId, accountNonce, freeBala
|
||||
// - perBlock is the unlock amount
|
||||
const { locked: vestingTotal, perBlock, startingBlock } = vesting || api.registry.createType('VestingInfo');
|
||||
const isStarted = bestNumber.gt(startingBlock);
|
||||
const vestedBalance = api.registry.createType('Balance', isStarted ? perBlock.mul(bestNumber.sub(startingBlock)) : 0);
|
||||
const isVesting = isStarted && vestedBalance.lt(vestingTotal);
|
||||
|
||||
// The available balance & vested has an interplay here
|
||||
// "
|
||||
// vesting is a guarantee that the account's balance will never go below a certain amount. so it functions in the opposite way, a bit like a lock that is monotonically decreasing rather than a liquid amount that is monotonically increasing.
|
||||
// locks function as the same guarantee - that a balance will not be lower than a particular amount.
|
||||
// because of this you can see that if there is a "vesting lock" that guarantees the balance cannot go below 200, and a "staking lock" that guarantees the balance cannot drop below 300, then we just have two guarantees of which the first is irrelevant.
|
||||
// i.e. (balance >= 200 && balance >= 300) == (balance >= 300)
|
||||
// ""
|
||||
const floating = freeBalance.sub(lockedBalance);
|
||||
const extraReceived = isVesting ? freeBalance.sub(vestingTotal) : new BN(0);
|
||||
const availableBalance = api.registry.createType('Balance', allLocked ? 0 : bnMax(new BN(0), isVesting && floating.gt(vestedBalance) ? vestedBalance.add(extraReceived) : floating));
|
||||
const vestedNow = isStarted ? perBlock.mul(bestNumber.sub(startingBlock)) : new BN(0);
|
||||
const vestedBalance = vestedNow.gt(vestingTotal) ? vestingTotal : api.registry.createType('Balance', vestedNow);
|
||||
const isVesting = isStarted && !vestingLocked.isZero();
|
||||
const vestedClaimable = api.registry.createType('Balance', isVesting ? vestingLocked.sub(vestingTotal.sub(vestedBalance)) : 0);
|
||||
const availableBalance = api.registry.createType('Balance', allLocked ? 0 : bnMax(new BN(0), freeBalance.sub(lockedBalance)));
|
||||
const vestingEndBlock = api.registry.createType('BlockNumber', isVesting ? vestingTotal.div(perBlock).add(startingBlock) : 0);
|
||||
|
||||
return {
|
||||
accountId,
|
||||
@@ -67,6 +64,10 @@ function calcBalances (api: ApiInterfaceRx, [{ accountId, accountNonce, freeBala
|
||||
lockedBreakdown,
|
||||
reservedBalance,
|
||||
vestedBalance,
|
||||
vestedClaimable,
|
||||
vestingEndBlock,
|
||||
vestingLocked,
|
||||
vestingPerBlock: perBlock,
|
||||
vestingTotal,
|
||||
votingBalance
|
||||
};
|
||||
@@ -127,15 +128,15 @@ function queryCurrent (api: ApiInterfaceRx, accountId: AccountId): Observable<Re
|
||||
* });
|
||||
* ```
|
||||
*/
|
||||
export function all (api: ApiInterfaceRx): (address: AccountIndex | AccountId | Address | string) => Observable<DeriveBalancesAll> {
|
||||
return memo((address: AccountIndex | AccountId | Address | string): Observable<DeriveBalancesAll> =>
|
||||
export function all (instanceId: string, api: ApiInterfaceRx): (address: AccountIndex | AccountId | Address | string) => Observable<DeriveBalancesAll> {
|
||||
return memo(instanceId, (address: AccountIndex | AccountId | Address | string): Observable<DeriveBalancesAll> =>
|
||||
api.derive.balances.account(address).pipe(
|
||||
switchMap((account): Observable<Result> =>
|
||||
(!account.accountId.isEmpty
|
||||
? combineLatest([
|
||||
of(account),
|
||||
api.derive.chain.bestNumber(),
|
||||
isFunction(api.query.balances.account)
|
||||
isFunction(api.query.system.account) || isFunction(api.query.balances.account)
|
||||
? queryCurrent(api, account.accountId)
|
||||
: queryOld(api, account.accountId)
|
||||
])
|
||||
|
||||
@@ -24,8 +24,8 @@ import { memo } from '../util';
|
||||
* });
|
||||
* ```
|
||||
*/
|
||||
export function fees (api: ApiInterfaceRx): () => Observable<DeriveFees> {
|
||||
return memo((): Observable<DeriveFees> =>
|
||||
export function fees (instanceId: string, api: ApiInterfaceRx): () => Observable<DeriveFees> {
|
||||
return memo(instanceId, (): Observable<DeriveFees> =>
|
||||
of([
|
||||
// deprecated - remove
|
||||
(api.consts.balances?.creationFee as unknown as Balance) || api.registry.createType('Balance'),
|
||||
|
||||
@@ -10,8 +10,8 @@ import { ApiInterfaceRx } from '@polkadot/api/types';
|
||||
|
||||
import { memo } from '../util';
|
||||
|
||||
export function votingBalances (api: ApiInterfaceRx): (addresses?: (AccountId | AccountIndex | Address | string)[]) => Observable<DeriveBalancesAccount[]> {
|
||||
return memo((addresses?: (AccountId | AccountIndex | Address | string)[]): Observable<DeriveBalancesAccount[]> =>
|
||||
export function votingBalances (instanceId: string, api: ApiInterfaceRx): (addresses?: (AccountId | AccountIndex | Address | string)[]) => Observable<DeriveBalancesAccount[]> {
|
||||
return memo(instanceId, (addresses?: (AccountId | AccountIndex | Address | string)[]): Observable<DeriveBalancesAccount[]> =>
|
||||
!addresses || !addresses.length
|
||||
? of([] as DeriveBalancesAccount[])
|
||||
: combineLatest(
|
||||
|
||||
@@ -22,8 +22,8 @@ import { memo } from '../util';
|
||||
* });
|
||||
* ```
|
||||
*/
|
||||
export function bestNumber (api: ApiInterfaceRx): () => Observable<BlockNumber> {
|
||||
return memo((): Observable<BlockNumber> =>
|
||||
export function bestNumber (instanceId: string, api: ApiInterfaceRx): () => Observable<BlockNumber> {
|
||||
return memo(instanceId, (): Observable<BlockNumber> =>
|
||||
api.derive.chain.subscribeNewHeads().pipe(
|
||||
map((header) => header.number.unwrap())
|
||||
));
|
||||
|
||||
@@ -23,8 +23,8 @@ import { memo } from '../util';
|
||||
* });
|
||||
* ```
|
||||
*/
|
||||
export function bestNumberFinalized (api: ApiInterfaceRx): () => Observable<BlockNumber> {
|
||||
return memo((): Observable<BlockNumber> =>
|
||||
export function bestNumberFinalized (instanceId: string, api: ApiInterfaceRx): () => Observable<BlockNumber> {
|
||||
return memo(instanceId, (): Observable<BlockNumber> =>
|
||||
api.rpc.chain.subscribeFinalizedHeads().pipe(
|
||||
map((header) => header.number.unwrap())
|
||||
));
|
||||
|
||||
@@ -23,8 +23,8 @@ import { memo } from '../util';
|
||||
* });
|
||||
* ```
|
||||
*/
|
||||
export function bestNumberLag (api: ApiInterfaceRx): () => Observable<BlockNumber> {
|
||||
return memo((): Observable<BlockNumber> =>
|
||||
export function bestNumberLag (instanceId: string, api: ApiInterfaceRx): () => Observable<BlockNumber> {
|
||||
return memo(instanceId, (): Observable<BlockNumber> =>
|
||||
combineLatest([
|
||||
api.derive.chain.bestNumber(),
|
||||
api.derive.chain.bestNumberFinalized()
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
// Copyright 2017-2020 @polkadot/api-derive authors & contributors
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the Apache-2.0 license. See the LICENSE file for details.
|
||||
|
||||
import { ApiInterfaceRx } from '@polkadot/api/types';
|
||||
|
||||
import { Observable, combineLatest, of } from 'rxjs';
|
||||
import { catchError, map } from 'rxjs/operators';
|
||||
|
||||
import { SignedBlockExtended } from '../type';
|
||||
import { memo } from '../util';
|
||||
|
||||
/**
|
||||
* @name getBlock
|
||||
* @param {( Uint8Array | string )} hash - A block hash as U8 array or string.
|
||||
* @description Get a specific block (e.g. rpc.chain.getBlock) and extend it with the author
|
||||
* @example
|
||||
* <BR>
|
||||
*
|
||||
* ```javascript
|
||||
* const { author, number } = await api.derive.chain.getHeader('0x123...456');
|
||||
*
|
||||
* console.log(`block #${number} was authored by ${author}`);
|
||||
* ```
|
||||
*/
|
||||
export function getHeader (instanceId: string, api: ApiInterfaceRx): (hash: Uint8Array | string) => Observable<SignedBlockExtended | undefined> {
|
||||
return memo(instanceId, (hash: Uint8Array | string): Observable<SignedBlockExtended | undefined> =>
|
||||
combineLatest([
|
||||
api.rpc.chain.getBlock(hash),
|
||||
api.query.session
|
||||
? api.query.session.validators.at(hash)
|
||||
: of([])
|
||||
]).pipe(
|
||||
map(([signedBlock, validators]): SignedBlockExtended =>
|
||||
new SignedBlockExtended(api.registry, signedBlock, validators)
|
||||
),
|
||||
catchError((): Observable<undefined> =>
|
||||
// where rpc.chain.getHeader throws, we will land here - it can happen that
|
||||
// we supplied an invalid hash. (Due to defaults, storeage will have an
|
||||
// empty value, so only the RPC is affected). So return undefined
|
||||
of()
|
||||
)
|
||||
));
|
||||
}
|
||||
@@ -11,7 +11,7 @@ import { HeaderExtended } from '../type';
|
||||
import { memo } from '../util';
|
||||
|
||||
/**
|
||||
* @name bestNumberFinalized
|
||||
* @name getHeader
|
||||
* @param {( Uint8Array | string )} hash - A block hash as U8 array or string.
|
||||
* @returns An array containing the block header and the block author
|
||||
* @description Get a specific block header and extend it with the author
|
||||
@@ -24,8 +24,8 @@ import { memo } from '../util';
|
||||
* console.log(`block #${number} was authored by ${author}`);
|
||||
* ```
|
||||
*/
|
||||
export function getHeader (api: ApiInterfaceRx): (hash: Uint8Array | string) => Observable<HeaderExtended | undefined> {
|
||||
return memo((hash: Uint8Array | string): Observable<HeaderExtended | undefined> =>
|
||||
export function getHeader (instanceId: string, api: ApiInterfaceRx): (hash: Uint8Array | string) => Observable<HeaderExtended | undefined> {
|
||||
return memo(instanceId, (hash: Uint8Array | string): Observable<HeaderExtended | undefined> =>
|
||||
combineLatest([
|
||||
api.rpc.chain.getHeader(hash),
|
||||
api.query.session
|
||||
|
||||
@@ -23,8 +23,8 @@ import { memo } from '../util';
|
||||
* });
|
||||
* ```
|
||||
*/
|
||||
export function subscribeNewHeads (api: ApiInterfaceRx): () => Observable<HeaderExtended> {
|
||||
return memo((): Observable<HeaderExtended> =>
|
||||
export function subscribeNewHeads (instanceId: string, api: ApiInterfaceRx): () => Observable<HeaderExtended> {
|
||||
return memo(instanceId, (): Observable<HeaderExtended> =>
|
||||
combineLatest([
|
||||
api.rpc.chain.subscribeNewHeads(),
|
||||
api.query.session
|
||||
|
||||
@@ -29,8 +29,8 @@ function parse ([hashes, proposals, votes]: Result): DeriveCollectiveProposal[]
|
||||
.filter((proposal): proposal is DeriveCollectiveProposal => !!proposal);
|
||||
}
|
||||
|
||||
export function proposals (api: ApiInterfaceRx, section: 'council' | 'technicalCommittee'): () => Observable<DeriveCollectiveProposal[]> {
|
||||
return memo((): Observable<DeriveCollectiveProposal[]> =>
|
||||
export function proposals (instanceId: string, api: ApiInterfaceRx, section: 'council' | 'technicalCommittee'): () => Observable<DeriveCollectiveProposal[]> {
|
||||
return memo(instanceId, (): Observable<DeriveCollectiveProposal[]> =>
|
||||
isFunction(api.query[section]?.proposals)
|
||||
? api.query[section].proposals().pipe(
|
||||
switchMap((hashes: Hash[]): Observable<Result> =>
|
||||
|
||||
@@ -11,23 +11,24 @@ import { map } from 'rxjs/operators';
|
||||
|
||||
import { memo } from '../util';
|
||||
|
||||
type ResultV2 = [BN, BN, BN, BN, BN, BN, BN, BN, BN];
|
||||
type ResultV2 = [BN, BN, BN, BN, BN, BN, BN, BN, BN, BN];
|
||||
|
||||
// query via constants (current applicable path)
|
||||
function queryConstants (api: ApiInterfaceRx): Observable<ResultV2> {
|
||||
return of([
|
||||
// deprecated
|
||||
api.consts.contracts.callBaseFee || api.registry.createType('Balance'),
|
||||
api.consts.contracts.contractFee || api.registry.createType('Balance'),
|
||||
api.consts.contracts.creationFee || api.registry.createType('Balance'),
|
||||
api.consts.contracts.transactionBaseFee || api.registry.createType('Balance'),
|
||||
api.consts.contracts.transactionByteFee || api.registry.createType('Balance'),
|
||||
api.consts.contracts.transferFee || api.registry.createType('Balance'),
|
||||
|
||||
// current
|
||||
api.consts.contracts.callBaseFee,
|
||||
api.consts.contracts.contractFee,
|
||||
api.consts.contracts.rentByteFee,
|
||||
api.consts.contracts.rentDepositOffset,
|
||||
api.consts.contracts.tombstoneDeposit,
|
||||
api.consts.contracts.transactionBaseFee,
|
||||
api.consts.contracts.transactionByteFee
|
||||
api.consts.contracts.surchargeReward,
|
||||
api.consts.contracts.tombstoneDeposit
|
||||
]) as unknown as Observable<ResultV2>;
|
||||
}
|
||||
|
||||
@@ -44,15 +45,16 @@ function queryConstants (api: ApiInterfaceRx): Observable<ResultV2> {
|
||||
* });
|
||||
* ```
|
||||
*/
|
||||
export function fees (api: ApiInterfaceRx): () => Observable<DeriveContractFees> {
|
||||
return memo((): Observable<DeriveContractFees> => {
|
||||
export function fees (instanceId: string, api: ApiInterfaceRx): () => Observable<DeriveContractFees> {
|
||||
return memo(instanceId, (): Observable<DeriveContractFees> => {
|
||||
return queryConstants(api).pipe(
|
||||
map(([creationFee, transferFee, callBaseFee, contractFee, rentByteFee, rentDepositOffset, tombstoneDeposit, transactionBaseFee, transactionByteFee]): DeriveContractFees => ({
|
||||
map(([callBaseFee, contractFee, creationFee, transactionBaseFee, transactionByteFee, transferFee, rentByteFee, rentDepositOffset, surchargeReward, tombstoneDeposit]): DeriveContractFees => ({
|
||||
callBaseFee,
|
||||
contractFee,
|
||||
creationFee,
|
||||
rentByteFee,
|
||||
rentDepositOffset,
|
||||
surchargeReward,
|
||||
tombstoneDeposit,
|
||||
transactionBaseFee,
|
||||
transactionByteFee,
|
||||
|
||||
@@ -9,6 +9,6 @@ import { Observable } from 'rxjs';
|
||||
import { proposals as collectiveProposals } from '../collective';
|
||||
import { memo } from '../util';
|
||||
|
||||
export function proposals (api: ApiInterfaceRx): () => Observable<DeriveCollectiveProposals> {
|
||||
return memo(collectiveProposals(api, 'council'));
|
||||
export function proposals (instanceId: string, api: ApiInterfaceRx): () => Observable<DeriveCollectiveProposals> {
|
||||
return memo(instanceId, collectiveProposals(instanceId, api, 'council'));
|
||||
}
|
||||
|
||||
@@ -81,8 +81,8 @@ function retrieveCurrent (api: ApiInterfaceRx): Observable<DeriveCouncilVotes> {
|
||||
);
|
||||
}
|
||||
|
||||
export function votes (api: ApiInterfaceRx): () => Observable<DeriveCouncilVotes> {
|
||||
return memo((): Observable<DeriveCouncilVotes> =>
|
||||
export function votes (instanceId: string, api: ApiInterfaceRx): () => Observable<DeriveCouncilVotes> {
|
||||
return memo(instanceId, (): Observable<DeriveCouncilVotes> =>
|
||||
(api.query.electionsPhragmen || api.query.elections).stakeOf
|
||||
? retrievePrev(api)
|
||||
: retrieveCurrent(api)
|
||||
|
||||
@@ -10,8 +10,8 @@ import { Observable } from 'rxjs';
|
||||
import { map } from 'rxjs/operators';
|
||||
import { memo } from '../util';
|
||||
|
||||
export function votesOf (api: ApiInterfaceRx): (accountId: string | Uint8Array | AccountId) => Observable<DeriveCouncilVote> {
|
||||
return memo((accountId: string | Uint8Array | AccountId): Observable<DeriveCouncilVote> =>
|
||||
export function votesOf (instanceId: string, api: ApiInterfaceRx): (accountId: string | Uint8Array | AccountId) => Observable<DeriveCouncilVote> {
|
||||
return memo(instanceId, (accountId: string | Uint8Array | AccountId): Observable<DeriveCouncilVote> =>
|
||||
api.derive.council.votes().pipe(
|
||||
map((votes): DeriveCouncilVote =>
|
||||
(
|
||||
|
||||
@@ -94,8 +94,8 @@ function queryScheduler (api: ApiInterfaceRx): Observable<DeriveDispatch[]> {
|
||||
);
|
||||
}
|
||||
|
||||
export function dispatchQueue (api: ApiInterfaceRx): () => Observable<DeriveDispatch[]> {
|
||||
return memo((): Observable<DeriveDispatch[]> =>
|
||||
export function dispatchQueue (instanceId: string, api: ApiInterfaceRx): () => Observable<DeriveDispatch[]> {
|
||||
return memo(instanceId, (): Observable<DeriveDispatch[]> =>
|
||||
isFunction(api.query.scheduler?.agenda)
|
||||
? queryScheduler(api)
|
||||
: api.query.democracy.dispatchQueue
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the Apache-2.0 license. See the LICENSE file for details.
|
||||
|
||||
import { AccountId, ReferendumInfo, ReferendumInfoTo239, VotingDirect, VotingDirectVote } from '@polkadot/types/interfaces';
|
||||
import { AccountId, ReferendumInfo, ReferendumInfoTo239, VotingDelegating, VotingDirect, VotingDirectVote } from '@polkadot/types/interfaces';
|
||||
import { ApiInterfaceRx } from '@polkadot/api/types';
|
||||
import { DeriveDemocracyLock } from '../types';
|
||||
|
||||
@@ -20,16 +20,37 @@ const ZERO = new BN(0);
|
||||
function parseLock (api: ApiInterfaceRx, [referendumId, accountVote]: VotingDirectVote, referendum: ReferendumInfo): DeriveDemocracyLock {
|
||||
const { balance, vote } = accountVote.asStandard;
|
||||
let unlockAt = ZERO;
|
||||
let referendumEnd = ZERO;
|
||||
|
||||
if (referendum.isFinished) {
|
||||
const { approved, end } = referendum.asFinished;
|
||||
|
||||
referendumEnd = end;
|
||||
|
||||
if ((approved.isTrue && vote.isAye) || (approved.isFalse && vote.isNay)) {
|
||||
unlockAt = end.add(api.consts.democracy.enactmentPeriod.muln(LOCKUPS[vote.conviction.index]));
|
||||
}
|
||||
}
|
||||
|
||||
return { balance, isFinished: referendum.isFinished, referendumId, unlockAt, vote };
|
||||
return { balance, isDelegated: false, isFinished: referendum.isFinished, referendumEnd, referendumId, unlockAt, vote };
|
||||
}
|
||||
|
||||
function delegateLocks (api: ApiInterfaceRx, { balance, conviction, target }: VotingDelegating): Observable<DeriveDemocracyLock[]> {
|
||||
return api.derive.democracy.locks(target).pipe(
|
||||
map((available): DeriveDemocracyLock[] =>
|
||||
available.map(({ isFinished, referendumEnd, referendumId, unlockAt, vote }): DeriveDemocracyLock => ({
|
||||
balance,
|
||||
isDelegated: true,
|
||||
isFinished,
|
||||
referendumEnd,
|
||||
referendumId,
|
||||
unlockAt: unlockAt.isZero()
|
||||
? unlockAt
|
||||
: referendumEnd.add(api.consts.democracy.enactmentPeriod.muln(LOCKUPS[conviction.index])),
|
||||
vote: api.registry.createType('Vote', { aye: vote.isAye, conviction })
|
||||
}))
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
function directLocks (api: ApiInterfaceRx, { votes }: VotingDirect): Observable<DeriveDemocracyLock[]> {
|
||||
@@ -53,13 +74,15 @@ function directLocks (api: ApiInterfaceRx, { votes }: VotingDirect): Observable<
|
||||
);
|
||||
}
|
||||
|
||||
export function locks (api: ApiInterfaceRx): (accountId: string | AccountId) => Observable<DeriveDemocracyLock[]> {
|
||||
return memo((accountId: string | AccountId): Observable<DeriveDemocracyLock[]> =>
|
||||
export function locks (instanceId: string, api: ApiInterfaceRx): (accountId: string | AccountId) => Observable<DeriveDemocracyLock[]> {
|
||||
return memo(instanceId, (accountId: string | AccountId): Observable<DeriveDemocracyLock[]> =>
|
||||
api.query.democracy.votingOf(accountId).pipe(
|
||||
switchMap((voting): Observable<DeriveDemocracyLock[]> =>
|
||||
voting.isDirect
|
||||
? directLocks(api, voting.asDirect)
|
||||
: of([])
|
||||
: voting.isDelegating
|
||||
? delegateLocks(api, voting.asDelegating)
|
||||
: of([])
|
||||
)
|
||||
)
|
||||
);
|
||||
|
||||
@@ -29,8 +29,8 @@ function withImage (api: ApiInterfaceRx, nextOpt: Option<ITuple<[Hash, VoteThres
|
||||
);
|
||||
}
|
||||
|
||||
export function nextExternal (api: ApiInterfaceRx): () => Observable<DeriveProposalExternal | null> {
|
||||
return memo((): Observable<DeriveProposalExternal | null> =>
|
||||
export function nextExternal (instanceId: string, api: ApiInterfaceRx): () => Observable<DeriveProposalExternal | null> {
|
||||
return memo(instanceId, (): Observable<DeriveProposalExternal | null> =>
|
||||
api.query.democracy?.nextExternal
|
||||
? api.query.democracy.nextExternal<Option<ITuple<[Hash, VoteThreshold]>>>().pipe(
|
||||
switchMap((nextOpt) => withImage(api, nextOpt))
|
||||
|
||||
@@ -16,8 +16,8 @@ import { parseImage } from './util';
|
||||
|
||||
type PreImage = Option<ITuple<[Bytes, AccountId, Balance, BlockNumber]>>;
|
||||
|
||||
export function preimage (api: ApiInterfaceRx): (hash: Hash) => Observable<DeriveProposalImage | undefined> {
|
||||
return memo((hash: Hash): Observable<DeriveProposalImage | undefined> =>
|
||||
export function preimage (instanceId: string, api: ApiInterfaceRx): (hash: Hash) => Observable<DeriveProposalImage | undefined> {
|
||||
return memo(instanceId, (hash: Hash): Observable<DeriveProposalImage | undefined> =>
|
||||
api.query.democracy.preimages<PreImage>(hash).pipe(
|
||||
map((imageOpt) => parseImage(api, imageOpt))
|
||||
)
|
||||
|
||||
@@ -16,8 +16,8 @@ import { parseImage } from './util';
|
||||
|
||||
type PreImage = Option<ITuple<[Bytes, AccountId, Balance, BlockNumber]>>;
|
||||
|
||||
export function preimages (api: ApiInterfaceRx): (hashes: Hash[]) => Observable<(DeriveProposalImage | undefined)[]> {
|
||||
return memo((hashes: Hash[]): Observable<(DeriveProposalImage | undefined)[]> =>
|
||||
export function preimages (instanceId: string, api: ApiInterfaceRx): (hashes: Hash[]) => Observable<(DeriveProposalImage | undefined)[]> {
|
||||
return memo(instanceId, (hashes: Hash[]): Observable<(DeriveProposalImage | undefined)[]> =>
|
||||
api.query.democracy.preimages.multi<PreImage>(hashes).pipe(
|
||||
map((images): (DeriveProposalImage | undefined)[] =>
|
||||
images.map((imageOpt) => parseImage(api, imageOpt))
|
||||
|
||||
@@ -49,8 +49,8 @@ function parse ([proposals, images, optDepositors]: Result): DeriveProposal[] {
|
||||
});
|
||||
}
|
||||
|
||||
export function proposals (api: ApiInterfaceRx): () => Observable<DeriveProposal[]> {
|
||||
return memo((): Observable<DeriveProposal[]> =>
|
||||
export function proposals (instanceId: string, api: ApiInterfaceRx): () => Observable<DeriveProposal[]> {
|
||||
return memo(instanceId, (): Observable<DeriveProposal[]> =>
|
||||
api.query.democracy?.publicProps && api.query.democracy?.preimages
|
||||
? api.query.democracy.publicProps<Proposals>().pipe(
|
||||
switchMap((proposals) =>
|
||||
|
||||
@@ -11,8 +11,8 @@ import { map } from 'rxjs/operators';
|
||||
|
||||
import { memo } from '../util';
|
||||
|
||||
export function referendumIds (api: ApiInterfaceRx): () => Observable<BN[]> {
|
||||
return memo((): Observable<BN[]> =>
|
||||
export function referendumIds (instanceId: string, api: ApiInterfaceRx): () => Observable<BN[]> {
|
||||
return memo(instanceId, (): Observable<BN[]> =>
|
||||
api.query.democracy?.lowestUnbaked
|
||||
? api.queryMulti<[ReferendumIndex, ReferendumIndex]>([
|
||||
api.query.democracy.lowestUnbaked,
|
||||
|
||||
@@ -10,8 +10,8 @@ import { map, switchMap } from 'rxjs/operators';
|
||||
|
||||
import { memo } from '../util';
|
||||
|
||||
export function referendums (api: ApiInterfaceRx): () => Observable<DeriveReferendumExt[]> {
|
||||
return memo((): Observable<DeriveReferendumExt[]> =>
|
||||
export function referendums (instanceId: string, api: ApiInterfaceRx): () => Observable<DeriveReferendumExt[]> {
|
||||
return memo(instanceId, (): Observable<DeriveReferendumExt[]> =>
|
||||
api.derive.democracy.referendumsActive().pipe(
|
||||
switchMap((referendums) =>
|
||||
combineLatest([
|
||||
|
||||
@@ -10,8 +10,8 @@ import { switchMap } from 'rxjs/operators';
|
||||
|
||||
import { memo } from '../util';
|
||||
|
||||
export function referendumsActive (api: ApiInterfaceRx): () => Observable<DeriveReferendum[]> {
|
||||
return memo((): Observable<DeriveReferendum[]> =>
|
||||
export function referendumsActive (instanceId: string, api: ApiInterfaceRx): () => Observable<DeriveReferendum[]> {
|
||||
return memo(instanceId, (): Observable<DeriveReferendum[]> =>
|
||||
api.derive.democracy.referendumIds().pipe(
|
||||
switchMap((ids): Observable<DeriveReferendum[]> =>
|
||||
ids.length
|
||||
|
||||
@@ -11,8 +11,8 @@ import { Option } from '@polkadot/types';
|
||||
|
||||
import { memo } from '../util';
|
||||
|
||||
export function referendumsFinished (api: ApiInterfaceRx): () => Observable<ReferendumInfoFinished[]> {
|
||||
return memo((): Observable<ReferendumInfoFinished[]> =>
|
||||
export function referendumsFinished (instanceId: string, api: ApiInterfaceRx): () => Observable<ReferendumInfoFinished[]> {
|
||||
return memo(instanceId, (): Observable<ReferendumInfoFinished[]> =>
|
||||
api.derive.democracy.referendumIds().pipe(
|
||||
switchMap((ids) => api.query.democracy.referendumInfoOf.multi<Option<ReferendumInfo>>(ids)),
|
||||
map((infos): ReferendumInfoFinished[] =>
|
||||
|
||||
@@ -92,8 +92,8 @@ function votesCurr (api: ApiInterfaceRx, referendumId: BN): Observable<DeriveRef
|
||||
);
|
||||
}
|
||||
|
||||
export function _referendumVotes (api: ApiInterfaceRx): (referendum: DeriveReferendum) => Observable<DeriveReferendumVotes> {
|
||||
return memo((referendum: DeriveReferendum): Observable<DeriveReferendumVotes> =>
|
||||
export function _referendumVotes (instanceId: string, api: ApiInterfaceRx): (referendum: DeriveReferendum) => Observable<DeriveReferendumVotes> {
|
||||
return memo(instanceId, (referendum: DeriveReferendum): Observable<DeriveReferendumVotes> =>
|
||||
combineLatest([
|
||||
api.derive.democracy.sqrtElectorate(),
|
||||
isFunction(api.query.democracy.votingOf)
|
||||
@@ -107,8 +107,8 @@ export function _referendumVotes (api: ApiInterfaceRx): (referendum: DeriveRefer
|
||||
);
|
||||
}
|
||||
|
||||
export function _referendumsVotes (api: ApiInterfaceRx): (referendums: DeriveReferendum[]) => Observable<DeriveReferendumVotes[]> {
|
||||
return memo((referendums: DeriveReferendum[]): Observable<DeriveReferendumVotes[]> =>
|
||||
export function _referendumsVotes (instanceId: string, api: ApiInterfaceRx): (referendums: DeriveReferendum[]) => Observable<DeriveReferendumVotes[]> {
|
||||
return memo(instanceId, (referendums: DeriveReferendum[]): Observable<DeriveReferendumVotes[]> =>
|
||||
referendums.length
|
||||
? combineLatest(
|
||||
referendums.map((referendum): Observable<DeriveReferendumVotes> =>
|
||||
@@ -119,8 +119,8 @@ export function _referendumsVotes (api: ApiInterfaceRx): (referendums: DeriveRef
|
||||
);
|
||||
}
|
||||
|
||||
export function _referendumInfo (api: ApiInterfaceRx): (index: BN, info: Option<ReferendumInfo | ReferendumInfoTo239>) => Observable<DeriveReferendum | null> {
|
||||
return memo((index: BN, info: Option<ReferendumInfo | ReferendumInfoTo239>): Observable<DeriveReferendum | null> => {
|
||||
export function _referendumInfo (instanceId: string, api: ApiInterfaceRx): (index: BN, info: Option<ReferendumInfo | ReferendumInfoTo239>) => Observable<DeriveReferendum | null> {
|
||||
return memo(instanceId, (index: BN, info: Option<ReferendumInfo | ReferendumInfoTo239>): Observable<DeriveReferendum | null> => {
|
||||
const status = getStatus(info);
|
||||
|
||||
return status
|
||||
@@ -136,8 +136,8 @@ export function _referendumInfo (api: ApiInterfaceRx): (index: BN, info: Option<
|
||||
});
|
||||
}
|
||||
|
||||
export function referendumsInfo (api: ApiInterfaceRx): (ids: BN[]) => Observable<DeriveReferendum[]> {
|
||||
return memo((ids: BN[]): Observable<DeriveReferendum[]> =>
|
||||
export function referendumsInfo (instanceId: string, api: ApiInterfaceRx): (ids: BN[]) => Observable<DeriveReferendum[]> {
|
||||
return memo(instanceId, (ids: BN[]): Observable<DeriveReferendum[]> =>
|
||||
ids.length
|
||||
? api.query.democracy.referendumInfoOf.multi<Option<ReferendumInfo>>(ids).pipe(
|
||||
switchMap((infos): Observable<(DeriveReferendum | null)[]> =>
|
||||
|
||||
@@ -11,8 +11,8 @@ import { bnSqrt } from '@polkadot/util';
|
||||
|
||||
import { memo } from '../util';
|
||||
|
||||
export function sqrtElectorate (api: ApiInterfaceRx): () => Observable<BN> {
|
||||
return memo((): Observable<BN> =>
|
||||
export function sqrtElectorate (instanceId: string, api: ApiInterfaceRx): () => Observable<BN> {
|
||||
return memo(instanceId, (): Observable<BN> =>
|
||||
api.query.balances.totalIssuance().pipe(
|
||||
map((totalIssuance) =>
|
||||
bnSqrt(totalIssuance)
|
||||
|
||||
@@ -9,19 +9,14 @@ import { Vec } from '@polkadot/types';
|
||||
|
||||
export interface DeriveDemocracyLock {
|
||||
balance: Balance;
|
||||
isDelegated: boolean;
|
||||
isFinished: boolean;
|
||||
referendumEnd: BN;
|
||||
referendumId: ReferendumIndex;
|
||||
unlockAt: BN;
|
||||
vote: Vote;
|
||||
}
|
||||
|
||||
export interface DeriveDispatch {
|
||||
at: BlockNumber;
|
||||
index: ReferendumIndex;
|
||||
imageHash: Hash;
|
||||
image?: DeriveProposalImage;
|
||||
}
|
||||
|
||||
export interface DeriveProposalImage {
|
||||
at: BlockNumber;
|
||||
balance: Balance;
|
||||
@@ -29,6 +24,13 @@ export interface DeriveProposalImage {
|
||||
proposer: AccountId;
|
||||
}
|
||||
|
||||
export interface DeriveDispatch {
|
||||
at: BlockNumber;
|
||||
index: ReferendumIndex;
|
||||
imageHash: Hash;
|
||||
image?: DeriveProposalImage;
|
||||
}
|
||||
|
||||
export interface DeriveProposal {
|
||||
balance?: Balance;
|
||||
index: PropIndex;
|
||||
|
||||
@@ -82,15 +82,15 @@ function calcVotesPrev (votesFor: DeriveReferendumVote[]): DeriveReferendumVoteS
|
||||
if (vote.isAye) {
|
||||
state.allAye.push(derived);
|
||||
state.voteCountAye++;
|
||||
state.votedAye = state.votedAye.add(counted);
|
||||
state.votedAye.iadd(counted);
|
||||
} else {
|
||||
state.allNay.push(derived);
|
||||
state.voteCountNay++;
|
||||
state.votedNay = state.votedNay.add(counted);
|
||||
state.votedNay.iadd(counted);
|
||||
}
|
||||
|
||||
state.voteCount++;
|
||||
state.votedTotal = state.votedTotal.add(counted);
|
||||
state.votedTotal.iadd(counted);
|
||||
|
||||
return state;
|
||||
}, {
|
||||
|
||||
@@ -4,13 +4,13 @@
|
||||
|
||||
import { AccountId, Balance, BlockNumber } from '@polkadot/types/interfaces';
|
||||
import { ITuple } from '@polkadot/types/types';
|
||||
import { DeriveElectionsInfo } from './types';
|
||||
|
||||
import { Observable } from 'rxjs';
|
||||
import { map } from 'rxjs/operators';
|
||||
import { ApiInterfaceRx } from '@polkadot/api/types';
|
||||
import { Vec, u32 } from '@polkadot/types';
|
||||
|
||||
import { DeriveElectionsInfo } from '../types';
|
||||
import { memo } from '../util';
|
||||
|
||||
function sortAccounts ([, balanceA]: ITuple<[AccountId, Balance]>, [, balanceB]: ITuple<[AccountId, Balance]>): number {
|
||||
@@ -30,6 +30,7 @@ function queryElections (api: ApiInterfaceRx): Observable<DeriveElectionsInfo> {
|
||||
candidacyBond: api.consts[section].candidacyBond as Balance,
|
||||
candidateCount: api.registry.createType('u32', candidates.length),
|
||||
candidates,
|
||||
desiredRunnersUp: api.consts[section].desiredRunnersUp as u32,
|
||||
desiredSeats: api.consts[section].desiredMembers as u32,
|
||||
members: members.length
|
||||
? members.sort(sortAccounts)
|
||||
@@ -54,6 +55,6 @@ function queryElections (api: ApiInterfaceRx): Observable<DeriveElectionsInfo> {
|
||||
* });
|
||||
* ```
|
||||
*/
|
||||
export function info (api: ApiInterfaceRx): () => Observable<DeriveElectionsInfo> {
|
||||
return memo((): Observable<DeriveElectionsInfo> => queryElections(api));
|
||||
export function info (instanceId: string, api: ApiInterfaceRx): () => Observable<DeriveElectionsInfo> {
|
||||
return memo(instanceId, (): Observable<DeriveElectionsInfo> => queryElections(api));
|
||||
}
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
// Copyright 2017-2020 @polkadot/api-derive authors & contributors
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the Apache-2.0 license. See the LICENSE file for details.
|
||||
|
||||
import { AccountId, Balance, BlockNumber, SetIndex, VoteIndex } from '@polkadot/types/interfaces';
|
||||
|
||||
import { u32 } from '@polkadot/types';
|
||||
|
||||
export interface DeriveElectionsInfo {
|
||||
candidates: AccountId[];
|
||||
candidateCount: u32;
|
||||
candidacyBond?: Balance;
|
||||
desiredRunnersUp: u32;
|
||||
desiredSeats: u32;
|
||||
members: [AccountId, Balance][];
|
||||
nextVoterSet?: SetIndex;
|
||||
runnersUp: [AccountId, Balance][];
|
||||
termDuration: BlockNumber;
|
||||
voteCount?: VoteIndex;
|
||||
voterCount?: SetIndex;
|
||||
votingBond?: Balance;
|
||||
}
|
||||
@@ -9,18 +9,39 @@ import { Observable, of, combineLatest } from 'rxjs';
|
||||
import { map, switchMap } from 'rxjs/operators';
|
||||
import { ApiInterfaceRx } from '@polkadot/api/types';
|
||||
import { Bytes, Option, u32 } from '@polkadot/types';
|
||||
import { BN_ZERO } from '@polkadot/util';
|
||||
|
||||
import { memo } from '../util';
|
||||
|
||||
function mapResult ([result, validators, heartbeats, numBlocks]: [DeriveHeartbeats, AccountId[], Option<Bytes>[], u32[]]): DeriveHeartbeats {
|
||||
validators.forEach((validator, index): void => {
|
||||
const validatorId = validator.toString();
|
||||
const blockCount = numBlocks[index];
|
||||
const hasMessage = !heartbeats[index].isEmpty;
|
||||
const prev = result[validatorId];
|
||||
|
||||
if (!prev || prev.hasMessage !== hasMessage || !prev.blockCount.eq(blockCount)) {
|
||||
result[validatorId] = {
|
||||
blockCount,
|
||||
hasMessage,
|
||||
isOnline: hasMessage || blockCount.gt(BN_ZERO)
|
||||
};
|
||||
}
|
||||
});
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Return a boolean array indicating whether the passed accounts had received heartbeats in the current session
|
||||
*/
|
||||
export function receivedHeartbeats (api: ApiInterfaceRx): () => Observable<DeriveHeartbeats> {
|
||||
return memo((): Observable<DeriveHeartbeats> =>
|
||||
export function receivedHeartbeats (instanceId: string, api: ApiInterfaceRx): () => Observable<DeriveHeartbeats> {
|
||||
return memo(instanceId, (): Observable<DeriveHeartbeats> =>
|
||||
api.query.imOnline?.receivedHeartbeats
|
||||
? api.derive.staking.overview().pipe(
|
||||
switchMap(({ currentIndex, validators }): Observable<[AccountId[], Option<Bytes>[], u32[]]> =>
|
||||
switchMap(({ currentIndex, validators }): Observable<[DeriveHeartbeats, AccountId[], Option<Bytes>[], u32[]]> =>
|
||||
combineLatest([
|
||||
of({}),
|
||||
of(validators),
|
||||
api.query.imOnline.receivedHeartbeats.multi<Option<Bytes>>(
|
||||
validators.map((_address, index) => [currentIndex, index])),
|
||||
@@ -28,16 +49,8 @@ export function receivedHeartbeats (api: ApiInterfaceRx): () => Observable<Deriv
|
||||
validators.map((address) => [currentIndex, address]))
|
||||
])
|
||||
),
|
||||
map(([validators, heartbeats, numBlocks]): DeriveHeartbeats =>
|
||||
validators.reduce((result: DeriveHeartbeats, validator, index): DeriveHeartbeats => ({
|
||||
...result,
|
||||
[validator.toString()]: {
|
||||
blockCount: numBlocks[index],
|
||||
hasMessage: !heartbeats[index].isEmpty,
|
||||
isOnline: !heartbeats[index].isEmpty || numBlocks[index].gtn(0)
|
||||
}
|
||||
}), {})
|
||||
)
|
||||
map(mapResult)
|
||||
)
|
||||
: of({}));
|
||||
: of({})
|
||||
);
|
||||
}
|
||||
|
||||
@@ -36,7 +36,7 @@ type DeriveAllSections<AllSections> = {
|
||||
[Section in keyof AllSections]: DeriveSection<AllSections[Section]>
|
||||
};
|
||||
|
||||
export type DeriveCustom = Record<string, Record<string, (api: ApiInterfaceRx) => (...args: any[]) => Observable<any>>>;
|
||||
export type DeriveCustom = Record<string, Record<string, (instanceId: string, api: ApiInterfaceRx) => (...args: any[]) => Observable<any>>>;
|
||||
|
||||
export type ExactDerive = DeriveAllSections<typeof derive>;
|
||||
|
||||
@@ -60,7 +60,7 @@ const deriveAvail: Record<string, string[]> = {
|
||||
* `allSections`, and keep the object architecture of `allSections`.
|
||||
*/
|
||||
/** @internal */
|
||||
function injectFunctions<AllSections> (api: ApiInterfaceRx, allSections: AllSections): DeriveAllSections<AllSections> {
|
||||
function injectFunctions<AllSections> (instanceId: string, api: ApiInterfaceRx, allSections: AllSections): DeriveAllSections<AllSections> {
|
||||
const queryKeys = Object.keys(api.query);
|
||||
|
||||
return Object
|
||||
@@ -77,7 +77,7 @@ function injectFunctions<AllSections> (api: ApiInterfaceRx, allSections: AllSect
|
||||
const methodName = _methodName as keyof typeof section;
|
||||
// Not sure what to do here, casting as any. Though the final types are good
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment,@typescript-eslint/no-unsafe-call
|
||||
const method = (section[methodName] as any)(api);
|
||||
const method = (section[methodName] as any)(instanceId, api);
|
||||
|
||||
// idem
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment,@typescript-eslint/no-unsafe-member-access
|
||||
@@ -93,9 +93,9 @@ function injectFunctions<AllSections> (api: ApiInterfaceRx, allSections: AllSect
|
||||
// FIXME The return type of this function should be {...ExactDerive, ...DeriveCustom}
|
||||
// For now we just drop the custom derive typings
|
||||
/** @internal */
|
||||
export default function decorateDerive (api: ApiInterfaceRx, custom: DeriveCustom = {}): ExactDerive {
|
||||
export default function decorateDerive (instanceId: string, api: ApiInterfaceRx, custom: DeriveCustom = {}): ExactDerive {
|
||||
return {
|
||||
...injectFunctions(api, derive),
|
||||
...injectFunctions(api, custom)
|
||||
...injectFunctions(instanceId, api, derive),
|
||||
...injectFunctions(instanceId, api, custom)
|
||||
};
|
||||
}
|
||||
|
||||
@@ -77,8 +77,8 @@ function parse (id: ParaId, [active, retryQueue, selectedThreads, didUpdate, inf
|
||||
};
|
||||
}
|
||||
|
||||
export function info (api: ApiInterfaceRx): (id: ParaId | number) => Observable<DeriveParachainFull | null> {
|
||||
return memo((id: ParaId | number): Observable<DeriveParachainFull | null> =>
|
||||
export function info (instanceId: string, api: ApiInterfaceRx): (id: ParaId | number) => Observable<DeriveParachainFull | null> {
|
||||
return memo(instanceId, (id: ParaId | number): Observable<DeriveParachainFull | null> =>
|
||||
api.query.registrar && api.query.parachains
|
||||
? api.queryMulti<Result>([
|
||||
api.query.registrar.active,
|
||||
|
||||
@@ -34,8 +34,8 @@ function parse ([ids, didUpdate, infos, pendingSwaps, relayDispatchQueueSizes]:
|
||||
});
|
||||
}
|
||||
|
||||
export function overview (api: ApiInterfaceRx): () => Observable<DeriveParachain[]> {
|
||||
return memo((): Observable<DeriveParachain[]> =>
|
||||
export function overview (instanceId: string, api: ApiInterfaceRx): () => Observable<DeriveParachain[]> {
|
||||
return memo(instanceId, (): Observable<DeriveParachain[]> =>
|
||||
api.query.registrar?.parachains && api.query.parachains
|
||||
? api.query.registrar.parachains<ParaId[]>().pipe(
|
||||
switchMap((paraIds) =>
|
||||
|
||||
@@ -10,8 +10,8 @@ import { ApiInterfaceRx } from '@polkadot/api/types';
|
||||
|
||||
import { memo } from '../util';
|
||||
|
||||
export function eraLength (api: ApiInterfaceRx): () => Observable<BlockNumber> {
|
||||
return memo((): Observable<BlockNumber> =>
|
||||
export function eraLength (instanceId: string, api: ApiInterfaceRx): () => Observable<BlockNumber> {
|
||||
return memo(instanceId, (): Observable<BlockNumber> =>
|
||||
api.derive.session.info().pipe(
|
||||
map((info) => info.eraLength)
|
||||
));
|
||||
|
||||
@@ -10,8 +10,8 @@ import { ApiInterfaceRx } from '@polkadot/api/types';
|
||||
|
||||
import { memo } from '../util';
|
||||
|
||||
export function eraProgress (api: ApiInterfaceRx): () => Observable<BlockNumber> {
|
||||
return memo((): Observable<BlockNumber> =>
|
||||
export function eraProgress (instanceId: string, api: ApiInterfaceRx): () => Observable<BlockNumber> {
|
||||
return memo(instanceId, (): Observable<BlockNumber> =>
|
||||
api.derive.session.progress().pipe(
|
||||
map((info) => info.eraProgress)
|
||||
));
|
||||
|
||||
@@ -13,10 +13,12 @@ import { isFunction } from '@polkadot/util';
|
||||
|
||||
import { memo } from '../util';
|
||||
|
||||
type Result = [EraIndex, Option<Moment>, EraIndex, SessionIndex, u32];
|
||||
function isEraOpt (era: Option<EraIndex> | EraIndex): era is Option<EraIndex> {
|
||||
return isFunction((era as Option<EraIndex>).unwrapOrDefault);
|
||||
}
|
||||
|
||||
// parse into Indexes
|
||||
function parse ([activeEra, activeEraStart, currentEra, currentIndex, validatorCount]: Result): DeriveSessionIndexes {
|
||||
function parse ([activeEra, activeEraStart, currentEra, currentIndex, validatorCount]: [EraIndex, Option<Moment>, EraIndex, SessionIndex, u32]): DeriveSessionIndexes {
|
||||
return {
|
||||
activeEra,
|
||||
activeEraStart,
|
||||
@@ -27,63 +29,67 @@ function parse ([activeEra, activeEraStart, currentEra, currentIndex, validatorC
|
||||
}
|
||||
|
||||
// query for previous V2
|
||||
function queryNoActive (api: ApiInterfaceRx): Observable<Result> {
|
||||
return api.queryMulti<[EraIndex, SessionIndex, u32]>([
|
||||
function queryNoActive (api: ApiInterfaceRx): Observable<DeriveSessionIndexes> {
|
||||
return api.queryMulti<[Option<EraIndex> | EraIndex, SessionIndex, u32]>([
|
||||
api.query.staking.currentEra,
|
||||
api.query.session.currentIndex,
|
||||
api.query.staking.validatorCount
|
||||
]).pipe(
|
||||
map(([currentEra, currentIndex, validatorCount]): Result => [
|
||||
currentEra,
|
||||
api.registry.createType('Option<Moment>'),
|
||||
currentEra,
|
||||
currentIndex,
|
||||
validatorCount
|
||||
])
|
||||
map(([currentEraOpt, currentIndex, validatorCount]): DeriveSessionIndexes => {
|
||||
const currentEra = isEraOpt(currentEraOpt)
|
||||
? currentEraOpt.unwrapOrDefault()
|
||||
: currentEraOpt;
|
||||
|
||||
return parse([
|
||||
currentEra,
|
||||
api.registry.createType('Option<Moment>'),
|
||||
currentEra,
|
||||
currentIndex,
|
||||
validatorCount
|
||||
]);
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
// query based on latest
|
||||
function query (api: ApiInterfaceRx): Observable<Result> {
|
||||
function query (api: ApiInterfaceRx): Observable<DeriveSessionIndexes> {
|
||||
return api.queryMulti<[Option<ActiveEraInfo>, Option<EraIndex>, SessionIndex, u32]>([
|
||||
api.query.staking.activeEra,
|
||||
api.query.staking.currentEra,
|
||||
api.query.session.currentIndex,
|
||||
api.query.staking.validatorCount
|
||||
]).pipe(
|
||||
map(([activeOpt, currentEra, currentIndex, validatorCount]): Result => {
|
||||
const { index: activeEra, start: activeEraStart } = activeOpt.unwrapOrDefault();
|
||||
map(([activeOpt, currentEra, currentIndex, validatorCount]): DeriveSessionIndexes => {
|
||||
const { index, start } = activeOpt.unwrapOrDefault();
|
||||
|
||||
return [
|
||||
activeEra,
|
||||
activeEraStart,
|
||||
currentEra.unwrapOr(api.registry.createType('EraIndex')),
|
||||
return parse([
|
||||
index,
|
||||
start,
|
||||
currentEra.unwrapOrDefault(),
|
||||
currentIndex,
|
||||
validatorCount
|
||||
];
|
||||
]);
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
// empty set when none is available
|
||||
function empty (api: ApiInterfaceRx): Observable<Result> {
|
||||
return of([
|
||||
function empty (api: ApiInterfaceRx): Observable<DeriveSessionIndexes> {
|
||||
return of(parse([
|
||||
api.registry.createType('EraIndex'),
|
||||
api.registry.createType('Option<Moment>'),
|
||||
api.registry.createType('EraIndex'),
|
||||
api.registry.createType('SessionIndex', 1),
|
||||
api.registry.createType('u32')
|
||||
]);
|
||||
]));
|
||||
}
|
||||
|
||||
export function indexes (api: ApiInterfaceRx): () => Observable<DeriveSessionIndexes> {
|
||||
return memo((): Observable<DeriveSessionIndexes> =>
|
||||
(
|
||||
api.query.session && api.query.staking
|
||||
? isFunction(api.query.staking.activeEra)
|
||||
? query(api)
|
||||
: queryNoActive(api)
|
||||
: empty(api)
|
||||
).pipe(map(parse))
|
||||
export function indexes (instanceId: string, api: ApiInterfaceRx): () => Observable<DeriveSessionIndexes> {
|
||||
return memo(instanceId, (): Observable<DeriveSessionIndexes> =>
|
||||
api.query.session && api.query.staking
|
||||
? isFunction(api.query.staking.activeEra)
|
||||
? query(api)
|
||||
: queryNoActive(api)
|
||||
: empty(api)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -62,8 +62,8 @@ function queryBabe (api: ApiInterfaceRx): Observable<DeriveSessionInfo> {
|
||||
/**
|
||||
* @description Retrieves all the session and era query and calculates specific values on it as the length of the session and eras
|
||||
*/
|
||||
export function info (api: ApiInterfaceRx): () => Observable<DeriveSessionInfo> {
|
||||
return memo((): Observable<DeriveSessionInfo> =>
|
||||
export function info (instanceId: string, api: ApiInterfaceRx): () => Observable<DeriveSessionInfo> {
|
||||
return memo(instanceId, (): Observable<DeriveSessionInfo> =>
|
||||
api.consts.babe
|
||||
? queryBabe(api)
|
||||
: queryAura(api)
|
||||
|
||||
@@ -17,9 +17,9 @@ type ResultSlots = [u64, u64, u64, Option<SessionIndex>];
|
||||
type ResultSlotsFlat = [u64, u64, u64, SessionIndex];
|
||||
|
||||
function createDerive (api: ApiInterfaceRx, info: DeriveSessionInfo, [currentSlot, epochIndex, epochOrGenesisStartSlot, activeEraStartSessionIndex]: ResultSlotsFlat): DeriveSessionProgress {
|
||||
const epochStartSlot = epochIndex.mul(info.sessionLength).add(epochOrGenesisStartSlot);
|
||||
const epochStartSlot = epochIndex.mul(info.sessionLength).iadd(epochOrGenesisStartSlot);
|
||||
const sessionProgress = currentSlot.sub(epochStartSlot);
|
||||
const eraProgress = info.currentIndex.sub(activeEraStartSessionIndex).mul(info.sessionLength).add(sessionProgress);
|
||||
const eraProgress = info.currentIndex.sub(activeEraStartSessionIndex).imul(info.sessionLength).iadd(sessionProgress);
|
||||
|
||||
return {
|
||||
...info,
|
||||
@@ -30,14 +30,11 @@ function createDerive (api: ApiInterfaceRx, info: DeriveSessionInfo, [currentSlo
|
||||
|
||||
function queryAura (api: ApiInterfaceRx): Observable<DeriveSessionProgress> {
|
||||
return api.derive.session.info().pipe(
|
||||
map((info): DeriveSessionProgress =>
|
||||
createDerive(api, info, [
|
||||
api.registry.createType('u64', 1),
|
||||
api.registry.createType('u64', 1),
|
||||
api.registry.createType('u64', 1),
|
||||
api.registry.createType('SessionIndex', 1)
|
||||
])
|
||||
)
|
||||
map((info): DeriveSessionProgress => ({
|
||||
...info,
|
||||
eraProgress: api.registry.createType('BlockNumber'),
|
||||
sessionProgress: api.registry.createType('BlockNumber')
|
||||
}))
|
||||
);
|
||||
}
|
||||
|
||||
@@ -75,8 +72,8 @@ function queryBabeNoHistory (api: ApiInterfaceRx): Observable<[DeriveSessionInfo
|
||||
/**
|
||||
* @description Retrieves all the session and era query and calculates specific values on it as the length of the session and eras
|
||||
*/
|
||||
export function progress (api: ApiInterfaceRx): () => Observable<DeriveSessionProgress> {
|
||||
return memo((): Observable<DeriveSessionProgress> =>
|
||||
export function progress (instanceId: string, api: ApiInterfaceRx): () => Observable<DeriveSessionProgress> {
|
||||
return memo(instanceId, (): Observable<DeriveSessionProgress> =>
|
||||
api.consts.babe
|
||||
? (
|
||||
isFunction(api.query.staking.erasStartSessionIndex)
|
||||
|
||||
@@ -10,8 +10,8 @@ import { ApiInterfaceRx } from '@polkadot/api/types';
|
||||
|
||||
import { memo } from '../util';
|
||||
|
||||
export function sessionProgress (api: ApiInterfaceRx): () => Observable<BlockNumber> {
|
||||
return memo((): Observable<BlockNumber> =>
|
||||
export function sessionProgress (instanceId: string, api: ApiInterfaceRx): () => Observable<BlockNumber> {
|
||||
return memo(instanceId, (): Observable<BlockNumber> =>
|
||||
api.derive.session.progress().pipe(
|
||||
map((info) => info.sessionProgress)
|
||||
));
|
||||
|
||||
@@ -19,8 +19,8 @@ type Result = [Bid[], ResultSuspend[]]
|
||||
/**
|
||||
* @description Get the candidate info for a society
|
||||
*/
|
||||
export function candidates (api: ApiInterfaceRx): () => Observable<DeriveSocietyCandidate[]> {
|
||||
return memo((): Observable<DeriveSocietyCandidate[]> =>
|
||||
export function candidates (instanceId: string, api: ApiInterfaceRx): () => Observable<DeriveSocietyCandidate[]> {
|
||||
return memo(instanceId, (): Observable<DeriveSocietyCandidate[]> =>
|
||||
api.query.society.candidates<Vec<Bid>>().pipe(
|
||||
switchMap((candidates: Vec<Bid>): Observable<Result> =>
|
||||
combineLatest([
|
||||
|
||||
@@ -17,8 +17,8 @@ type Result = [Vec<Bid>, Option<AccountId>, Option<AccountId>, Option<AccountId>
|
||||
/**
|
||||
* @description Get the overall info for a society
|
||||
*/
|
||||
export function info (api: ApiInterfaceRx): () => Observable<DeriveSociety> {
|
||||
return memo((): Observable<DeriveSociety> =>
|
||||
export function info (instanceId: string, api: ApiInterfaceRx): () => Observable<DeriveSociety> {
|
||||
return memo(instanceId, (): Observable<DeriveSociety> =>
|
||||
api.queryMulti<Result>([
|
||||
api.query.society.bids,
|
||||
api.query.society.defender,
|
||||
|
||||
@@ -18,8 +18,8 @@ type Result = [Vec<ITuple<[BlockNumber, Balance]>>, StrikeCount, Option<SocietyV
|
||||
/**
|
||||
* @description Get the member info for a society
|
||||
*/
|
||||
export function member (api: ApiInterfaceRx): (accountId: AccountId) => Observable<DeriveSocietyMember> {
|
||||
return memo((accountId: AccountId): Observable<DeriveSocietyMember> =>
|
||||
export function member (instanceId: string, api: ApiInterfaceRx): (accountId: AccountId) => Observable<DeriveSocietyMember> {
|
||||
return memo(instanceId, (accountId: AccountId): Observable<DeriveSocietyMember> =>
|
||||
api.queryMulti<Result>([
|
||||
[api.query.society.payouts, accountId],
|
||||
[api.query.society.strikes, accountId],
|
||||
|
||||
@@ -14,8 +14,8 @@ import { memo } from '../util';
|
||||
/**
|
||||
* @description Get the member info for a society
|
||||
*/
|
||||
export function members (api: ApiInterfaceRx): () => Observable<DeriveSocietyMember[]> {
|
||||
return memo((): Observable<DeriveSocietyMember[]> =>
|
||||
export function members (instanceId: string, api: ApiInterfaceRx): () => Observable<DeriveSocietyMember[]> {
|
||||
return memo(instanceId, (): Observable<DeriveSocietyMember[]> =>
|
||||
api.query.society.members<AccountId[]>().pipe(
|
||||
switchMap((members): Observable<DeriveSocietyMember[]> =>
|
||||
combineLatest(
|
||||
|
||||
@@ -4,97 +4,82 @@
|
||||
|
||||
import { ApiInterfaceRx } from '@polkadot/api/types';
|
||||
import { Balance, StakingLedger, UnlockChunk } from '@polkadot/types/interfaces';
|
||||
import { DeriveSessionInfo, DeriveStakingAccount, DeriveStakingQuery, DeriveUnlocking } from '../types';
|
||||
import { DeriveSessionInfo, DeriveStakingAccount, DeriveStakingKeys, DeriveStakingQuery, DeriveUnlocking } from '../types';
|
||||
|
||||
import BN from 'bn.js';
|
||||
import { Observable, combineLatest } from 'rxjs';
|
||||
import { combineLatest, Observable } from 'rxjs';
|
||||
import { map, switchMap } from 'rxjs/operators';
|
||||
|
||||
import { isUndefined } from '@polkadot/util';
|
||||
import { BN_ZERO } from '@polkadot/util';
|
||||
|
||||
import { memo } from '../util';
|
||||
|
||||
// groups the supplied chunks by era, i.e. { [era]: BN(total of values) }
|
||||
function groupByEra (list: UnlockChunk[]): Record<string, BN> {
|
||||
return list.reduce((map: Record<string, BN>, { era, value }): Record<string, BN> => {
|
||||
const key = era.toString();
|
||||
|
||||
map[key] = !map[key]
|
||||
? value.unwrap()
|
||||
: map[key].add(value.unwrap());
|
||||
map[key] = (map[key] || BN_ZERO).add(value.unwrap());
|
||||
|
||||
return map;
|
||||
}, {});
|
||||
}
|
||||
|
||||
function calculateUnlocking (api: ApiInterfaceRx, stakingLedger: StakingLedger | undefined, sessionInfo: DeriveSessionInfo): DeriveUnlocking[] | undefined {
|
||||
if (isUndefined(stakingLedger)) {
|
||||
return undefined;
|
||||
}
|
||||
const results = Object
|
||||
.entries(groupByEra(
|
||||
(stakingLedger?.unlocking || []).filter(({ era }) => era.unwrap().gt(sessionInfo.activeEra))
|
||||
))
|
||||
.map(([eraString, value]): DeriveUnlocking => ({
|
||||
remainingEras: new BN(eraString).isub(sessionInfo.activeEra),
|
||||
value: api.registry.createType('Balance', value)
|
||||
}));
|
||||
|
||||
const unlockingChunks = stakingLedger.unlocking.filter(({ era }): boolean =>
|
||||
era.unwrap().sub(sessionInfo.activeEra).gtn(0)
|
||||
);
|
||||
|
||||
if (!unlockingChunks.length) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
// group the unlock chunks that have the same era and sum their values
|
||||
const groupedResult = groupByEra(unlockingChunks);
|
||||
const results = Object.entries(groupedResult).map(([eraString, value]): DeriveUnlocking => ({
|
||||
remainingEras: new BN(eraString).sub(sessionInfo.activeEra),
|
||||
value: api.registry.createType('Balance', value)
|
||||
}));
|
||||
|
||||
return results.length ? results : undefined;
|
||||
return results.length
|
||||
? results
|
||||
: undefined;
|
||||
}
|
||||
|
||||
function redeemableSum (api: ApiInterfaceRx, stakingLedger: StakingLedger | undefined, sessionInfo: DeriveSessionInfo): Balance {
|
||||
if (isUndefined(stakingLedger)) {
|
||||
return api.registry.createType('Balance');
|
||||
}
|
||||
|
||||
return api.registry.createType('Balance', stakingLedger.unlocking.reduce((total, { era, value }): BN => {
|
||||
return api.registry.createType('Balance', (stakingLedger?.unlocking || [] as UnlockChunk[]).reduce((total, { era, value }): BN => {
|
||||
return sessionInfo.activeEra.gte(era.unwrap())
|
||||
? total.add(value.unwrap())
|
||||
? total.iadd(value.unwrap())
|
||||
: total;
|
||||
}, new BN(0)));
|
||||
}
|
||||
|
||||
function parseResult (api: ApiInterfaceRx, sessionInfo: DeriveSessionInfo, query: DeriveStakingQuery): DeriveStakingAccount {
|
||||
function parseResult (api: ApiInterfaceRx, sessionInfo: DeriveSessionInfo, keys: DeriveStakingKeys, query: DeriveStakingQuery): DeriveStakingAccount {
|
||||
return {
|
||||
...keys,
|
||||
...query,
|
||||
redeemable: redeemableSum(api, query.stakingLedger, sessionInfo),
|
||||
unlocking: calculateUnlocking(api, query.stakingLedger, sessionInfo)
|
||||
};
|
||||
}
|
||||
|
||||
export function _account (api: ApiInterfaceRx): (sessionInfo: DeriveSessionInfo, accountId: Uint8Array | string) => Observable<DeriveStakingAccount> {
|
||||
return memo((sessionInfo: DeriveSessionInfo, accountId: Uint8Array | string): Observable<DeriveStakingAccount> =>
|
||||
api.derive.staking.query(accountId).pipe(
|
||||
map((query) => parseResult(api, sessionInfo, query))
|
||||
));
|
||||
/**
|
||||
* @description From a list of stashes, fill in all the relevant staking details
|
||||
*/
|
||||
export function accounts (instanceId: string, api: ApiInterfaceRx): (accountIds: (Uint8Array | string)[]) => Observable<DeriveStakingAccount[]> {
|
||||
return memo(instanceId, (accountIds: (Uint8Array | string)[]): Observable<DeriveStakingAccount[]> =>
|
||||
api.derive.session.info().pipe(
|
||||
switchMap((sessionInfo) =>
|
||||
combineLatest([
|
||||
api.derive.staking.keysMulti(accountIds),
|
||||
api.derive.staking.queryMulti(accountIds)
|
||||
]).pipe(
|
||||
map(([keys, queries]) => queries.map((query, index) => parseResult(api, sessionInfo, keys[index], query)))
|
||||
)
|
||||
)
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @description From a stash, retrieve the controllerId and fill in all the relevant staking details
|
||||
*/
|
||||
export function account (api: ApiInterfaceRx): (accountId: Uint8Array | string) => Observable<DeriveStakingAccount> {
|
||||
return memo((accountId: Uint8Array | string): Observable<DeriveStakingAccount> =>
|
||||
api.derive.session.info().pipe(
|
||||
switchMap((sessionInfo) => api.derive.staking._account(sessionInfo, accountId))
|
||||
));
|
||||
}
|
||||
|
||||
/**
|
||||
* @description From a list of stashes, fill in all the relevant staking details
|
||||
*/
|
||||
export function accounts (api: ApiInterfaceRx): (accountIds: (Uint8Array | string)[]) => Observable<DeriveStakingAccount[]> {
|
||||
return memo((accountIds: (Uint8Array | string)[]): Observable<DeriveStakingAccount[]> =>
|
||||
api.derive.session.info().pipe(
|
||||
switchMap((sessionInfo) =>
|
||||
combineLatest(accountIds.map((accountId) => api.derive.staking._account(sessionInfo, accountId)))
|
||||
)
|
||||
));
|
||||
export function account (instanceId: string, api: ApiInterfaceRx): (accountId: Uint8Array | string) => Observable<DeriveStakingAccount> {
|
||||
return memo(instanceId, (accountId: Uint8Array | string): Observable<DeriveStakingAccount> =>
|
||||
api.derive.staking.accounts([accountId]).pipe(
|
||||
map(([first]) => first)
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -28,8 +28,8 @@ function retrievePointsPrev (api: ApiInterfaceRx, currentElected: AccountId[]):
|
||||
/**
|
||||
* @description Retrieve the staking overview, including elected and points earned
|
||||
*/
|
||||
export function currentPoints (api: ApiInterfaceRx): () => Observable<EraRewardPoints> {
|
||||
return memo((): Observable<EraRewardPoints> =>
|
||||
export function currentPoints (instanceId: string, api: ApiInterfaceRx): () => Observable<EraRewardPoints> {
|
||||
return memo(instanceId, (): Observable<EraRewardPoints> =>
|
||||
api.derive.staking.overview().pipe(
|
||||
switchMap(({ activeEra, nextElected }) =>
|
||||
api.query.staking.erasRewardPoints
|
||||
|
||||
@@ -3,29 +3,24 @@
|
||||
// of the Apache-2.0 license. See the LICENSE file for details.
|
||||
|
||||
import { ApiInterfaceRx } from '@polkadot/api/types';
|
||||
import { AccountId } from '@polkadot/types/interfaces';
|
||||
import { DeriveStakingQuery, DeriveStakingElected } from '../types';
|
||||
import { DeriveStakingElected } from '../types';
|
||||
|
||||
import { Observable, combineLatest, of } from 'rxjs';
|
||||
import { Observable } from 'rxjs';
|
||||
import { map, switchMap } from 'rxjs/operators';
|
||||
|
||||
import { memo } from '../util';
|
||||
|
||||
export function electedInfo (api: ApiInterfaceRx): () => Observable<DeriveStakingElected> {
|
||||
return memo((): Observable<DeriveStakingElected> =>
|
||||
export function electedInfo (instanceId: string, api: ApiInterfaceRx): () => Observable<DeriveStakingElected> {
|
||||
return memo(instanceId, (): Observable<DeriveStakingElected> =>
|
||||
api.derive.staking.validators().pipe(
|
||||
switchMap(({ nextElected }): Observable<[AccountId[], DeriveStakingQuery[]]> =>
|
||||
combineLatest([
|
||||
of(nextElected),
|
||||
combineLatest(
|
||||
nextElected.map((accountId) => api.derive.staking.query(accountId))
|
||||
)
|
||||
])
|
||||
),
|
||||
map(([nextElected, info]): DeriveStakingElected => ({
|
||||
info,
|
||||
nextElected
|
||||
}))
|
||||
switchMap(({ nextElected }): Observable<DeriveStakingElected> =>
|
||||
api.derive.staking.queryMulti(nextElected).pipe(
|
||||
map((info): DeriveStakingElected => ({
|
||||
info,
|
||||
nextElected
|
||||
}))
|
||||
)
|
||||
)
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -36,8 +36,8 @@ function mapStakers (era: EraIndex, stakers: KeysAndExposures): DeriveEraExposur
|
||||
return { era, nominators, validators };
|
||||
}
|
||||
|
||||
export function _eraExposure (api: ApiInterfaceRx): (era: EraIndex, withActive: boolean) => Observable<DeriveEraExposure> {
|
||||
return memo((era: EraIndex, withActive: boolean): Observable<DeriveEraExposure> => {
|
||||
export function _eraExposure (instanceId: string, api: ApiInterfaceRx): (era: EraIndex, withActive: boolean) => Observable<DeriveEraExposure> {
|
||||
return memo(instanceId, (era: EraIndex, withActive: boolean): Observable<DeriveEraExposure> => {
|
||||
const cacheKey = `${CACHE_KEY}-${era.toString()}`;
|
||||
const cached = withActive
|
||||
? undefined
|
||||
@@ -57,22 +57,22 @@ export function _eraExposure (api: ApiInterfaceRx): (era: EraIndex, withActive:
|
||||
});
|
||||
}
|
||||
|
||||
export function eraExposure (api: ApiInterfaceRx): (era: EraIndex) => Observable<DeriveEraExposure> {
|
||||
return memo((era: EraIndex): Observable<DeriveEraExposure> =>
|
||||
export function eraExposure (instanceId: string, api: ApiInterfaceRx): (era: EraIndex) => Observable<DeriveEraExposure> {
|
||||
return memo(instanceId, (era: EraIndex): Observable<DeriveEraExposure> =>
|
||||
api.derive.staking._eraExposure(era, true)
|
||||
);
|
||||
}
|
||||
|
||||
export function _erasExposure (api: ApiInterfaceRx): (eras: EraIndex[], withActive: boolean) => Observable<DeriveEraExposure[]> {
|
||||
return memo((eras: EraIndex[], withActive: boolean): Observable<DeriveEraExposure[]> =>
|
||||
export function _erasExposure (instanceId: string, api: ApiInterfaceRx): (eras: EraIndex[], withActive: boolean) => Observable<DeriveEraExposure[]> {
|
||||
return memo(instanceId, (eras: EraIndex[], withActive: boolean): Observable<DeriveEraExposure[]> =>
|
||||
eras.length
|
||||
? combineLatest(eras.map((era) => api.derive.staking._eraExposure(era, withActive)))
|
||||
: of([])
|
||||
);
|
||||
}
|
||||
|
||||
export function erasExposure (api: ApiInterfaceRx): (withActive?: boolean) => Observable<DeriveEraExposure[]> {
|
||||
return memo((withActive = false): Observable<DeriveEraExposure[]> =>
|
||||
export function erasExposure (instanceId: string, api: ApiInterfaceRx): (withActive?: boolean) => Observable<DeriveEraExposure[]> {
|
||||
return memo(instanceId, (withActive = false): Observable<DeriveEraExposure[]> =>
|
||||
api.derive.staking.erasHistoric(withActive).pipe(
|
||||
switchMap((eras) => api.derive.staking._erasExposure(eras, withActive))
|
||||
)
|
||||
|
||||
@@ -12,8 +12,8 @@ import { Option, u32 } from '@polkadot/types';
|
||||
|
||||
import { memo } from '../util';
|
||||
|
||||
export function erasHistoric (api: ApiInterfaceRx): (withActive?: boolean) => Observable<EraIndex[]> {
|
||||
return memo((withActive?: boolean): Observable<EraIndex[]> =>
|
||||
export function erasHistoric (instanceId: string, api: ApiInterfaceRx): (withActive: boolean) => Observable<EraIndex[]> {
|
||||
return memo(instanceId, (withActive: boolean): Observable<EraIndex[]> =>
|
||||
api.query.staking?.activeEra
|
||||
? api.queryMulti<[Option<ActiveEraInfo>, u32]>([
|
||||
api.query.staking.activeEra,
|
||||
|
||||
@@ -8,6 +8,7 @@ import { DeriveEraPoints, DeriveEraValPoints } from '../types';
|
||||
|
||||
import { Observable, of } from 'rxjs';
|
||||
import { map, switchMap } from 'rxjs/operators';
|
||||
import { BN_ZERO } from '@polkadot/util';
|
||||
|
||||
import { deriveCache, memo } from '../util';
|
||||
|
||||
@@ -15,7 +16,7 @@ const CACHE_KEY = 'eraPoints';
|
||||
|
||||
function mapValidators ({ individual }: EraRewardPoints): DeriveEraValPoints {
|
||||
return [...individual.entries()]
|
||||
.filter(([, points]): boolean => points.gtn(0))
|
||||
.filter(([, points]) => points.gt(BN_ZERO))
|
||||
.reduce((result: DeriveEraValPoints, [validatorId, points]): DeriveEraValPoints => {
|
||||
result[validatorId.toString()] = points;
|
||||
|
||||
@@ -31,8 +32,8 @@ function mapPoints (eras: EraIndex[], points: EraRewardPoints[]): DeriveEraPoint
|
||||
}));
|
||||
}
|
||||
|
||||
export function _erasPoints (api: ApiInterfaceRx): (eras: EraIndex[], withActive: boolean) => Observable<DeriveEraPoints[]> {
|
||||
return memo((eras: EraIndex[], withActive: boolean): Observable<DeriveEraPoints[]> => {
|
||||
export function _erasPoints (instanceId: string, api: ApiInterfaceRx): (eras: EraIndex[], withActive: boolean) => Observable<DeriveEraPoints[]> {
|
||||
return memo(instanceId, (eras: EraIndex[], withActive: boolean): Observable<DeriveEraPoints[]> => {
|
||||
if (!eras.length) {
|
||||
return of([]);
|
||||
}
|
||||
@@ -61,8 +62,8 @@ export function _erasPoints (api: ApiInterfaceRx): (eras: EraIndex[], withActive
|
||||
});
|
||||
}
|
||||
|
||||
export function erasPoints (api: ApiInterfaceRx): (withActive?: boolean) => Observable<DeriveEraPoints[]> {
|
||||
return memo((withActive = false): Observable<DeriveEraPoints[]> =>
|
||||
export function erasPoints (instanceId: string, api: ApiInterfaceRx): (withActive?: boolean) => Observable<DeriveEraPoints[]> {
|
||||
return memo(instanceId, (withActive = false): Observable<DeriveEraPoints[]> =>
|
||||
api.derive.staking.erasHistoric(withActive).pipe(
|
||||
switchMap((eras) => api.derive.staking._erasPoints(eras, withActive))
|
||||
)
|
||||
|
||||
@@ -24,8 +24,8 @@ function mapPrefs (era: EraIndex, all: [StorageKey, ValidatorPrefs][]): DeriveEr
|
||||
return { era, validators };
|
||||
}
|
||||
|
||||
export function _eraPrefs (api: ApiInterfaceRx): (era: EraIndex, withActive: boolean) => Observable<DeriveEraPrefs> {
|
||||
return memo((era: EraIndex, withActive: boolean): Observable<DeriveEraPrefs> => {
|
||||
export function _eraPrefs (instanceId: string, api: ApiInterfaceRx): (era: EraIndex, withActive: boolean) => Observable<DeriveEraPrefs> {
|
||||
return memo(instanceId, (era: EraIndex, withActive: boolean): Observable<DeriveEraPrefs> => {
|
||||
const cacheKey = `${CACHE_KEY}-${era.toString()}`;
|
||||
const cached = withActive
|
||||
? undefined
|
||||
@@ -45,22 +45,22 @@ export function _eraPrefs (api: ApiInterfaceRx): (era: EraIndex, withActive: boo
|
||||
});
|
||||
}
|
||||
|
||||
export function eraPrefs (api: ApiInterfaceRx): (era: EraIndex) => Observable<DeriveEraPrefs> {
|
||||
return memo((era: EraIndex): Observable<DeriveEraPrefs> =>
|
||||
export function eraPrefs (instanceId: string, api: ApiInterfaceRx): (era: EraIndex) => Observable<DeriveEraPrefs> {
|
||||
return memo(instanceId, (era: EraIndex): Observable<DeriveEraPrefs> =>
|
||||
api.derive.staking._eraPrefs(era, true)
|
||||
);
|
||||
}
|
||||
|
||||
export function _erasPrefs (api: ApiInterfaceRx): (eras: EraIndex[], withActive: boolean) => Observable<DeriveEraPrefs[]> {
|
||||
return memo((eras: EraIndex[], withActive: boolean): Observable<DeriveEraPrefs[]> =>
|
||||
export function _erasPrefs (instanceId: string, api: ApiInterfaceRx): (eras: EraIndex[], withActive: boolean) => Observable<DeriveEraPrefs[]> {
|
||||
return memo(instanceId, (eras: EraIndex[], withActive: boolean): Observable<DeriveEraPrefs[]> =>
|
||||
eras.length
|
||||
? combineLatest(eras.map((era) => api.derive.staking._eraPrefs(era, withActive)))
|
||||
: of([])
|
||||
);
|
||||
}
|
||||
|
||||
export function erasPrefs (api: ApiInterfaceRx): (withActive?: boolean) => Observable<DeriveEraPrefs[]> {
|
||||
return memo((withActive = false): Observable<DeriveEraPrefs[]> =>
|
||||
export function erasPrefs (instanceId: string, api: ApiInterfaceRx): (withActive?: boolean) => Observable<DeriveEraPrefs[]> {
|
||||
return memo(instanceId, (withActive = false): Observable<DeriveEraPrefs[]> =>
|
||||
api.derive.staking.erasHistoric(withActive).pipe(
|
||||
switchMap((eras) => api.derive.staking._erasPrefs(eras, withActive))
|
||||
)
|
||||
|
||||
@@ -21,8 +21,8 @@ function mapRewards (eras: EraIndex[], optRewards: Option<Balance>[]): DeriveEra
|
||||
}));
|
||||
}
|
||||
|
||||
export function _erasRewards (api: ApiInterfaceRx): (eras: EraIndex[], withActive: boolean) => Observable<DeriveEraRewards[]> {
|
||||
return memo((eras: EraIndex[], withActive: boolean): Observable<DeriveEraRewards[]> => {
|
||||
export function _erasRewards (instanceId: string, api: ApiInterfaceRx): (eras: EraIndex[], withActive: boolean) => Observable<DeriveEraRewards[]> {
|
||||
return memo(instanceId, (eras: EraIndex[], withActive: boolean): Observable<DeriveEraRewards[]> => {
|
||||
if (!eras.length) {
|
||||
return of([]);
|
||||
}
|
||||
@@ -53,8 +53,8 @@ export function _erasRewards (api: ApiInterfaceRx): (eras: EraIndex[], withActiv
|
||||
});
|
||||
}
|
||||
|
||||
export function erasRewards (api: ApiInterfaceRx): (withActive?: boolean) => Observable<DeriveEraRewards[]> {
|
||||
return memo((withActive = false): Observable<DeriveEraRewards[]> =>
|
||||
export function erasRewards (instanceId: string, api: ApiInterfaceRx): (withActive?: boolean) => Observable<DeriveEraRewards[]> {
|
||||
return memo(instanceId, (withActive = false): Observable<DeriveEraRewards[]> =>
|
||||
api.derive.staking.erasHistoric(withActive).pipe(
|
||||
switchMap((eras) => api.derive.staking._erasRewards(eras, withActive))
|
||||
)
|
||||
|
||||
@@ -30,8 +30,8 @@ function mapSlashes (era: EraIndex, noms: [StorageKey, Option<BalanceOf>][], val
|
||||
return { era, nominators, validators };
|
||||
}
|
||||
|
||||
export function _eraSlashes (api: ApiInterfaceRx): (era: EraIndex, withActive: boolean) => Observable<DeriveEraSlashes> {
|
||||
return memo((era: EraIndex, withActive: boolean): Observable<DeriveEraSlashes> => {
|
||||
export function _eraSlashes (instanceId: string, api: ApiInterfaceRx): (era: EraIndex, withActive: boolean) => Observable<DeriveEraSlashes> {
|
||||
return memo(instanceId, (era: EraIndex, withActive: boolean): Observable<DeriveEraSlashes> => {
|
||||
const cacheKey = `${CACHE_KEY}-${era.toString()}`;
|
||||
const cached = withActive
|
||||
? undefined
|
||||
@@ -54,14 +54,14 @@ export function _eraSlashes (api: ApiInterfaceRx): (era: EraIndex, withActive: b
|
||||
});
|
||||
}
|
||||
|
||||
export function eraSlashes (api: ApiInterfaceRx): (era: EraIndex) => Observable<DeriveEraSlashes> {
|
||||
return memo((era: EraIndex): Observable<DeriveEraSlashes> =>
|
||||
export function eraSlashes (instanceId: string, api: ApiInterfaceRx): (era: EraIndex) => Observable<DeriveEraSlashes> {
|
||||
return memo(instanceId, (era: EraIndex): Observable<DeriveEraSlashes> =>
|
||||
api.derive.staking._eraSlashes(era, true)
|
||||
);
|
||||
}
|
||||
|
||||
export function _erasSlashes (api: ApiInterfaceRx): (eras: EraIndex[], withActive: boolean) => Observable<DeriveEraSlashes[]> {
|
||||
return memo((eras: EraIndex[], withActive: boolean): Observable<DeriveEraSlashes[]> =>
|
||||
export function _erasSlashes (instanceId: string, api: ApiInterfaceRx): (eras: EraIndex[], withActive: boolean) => Observable<DeriveEraSlashes[]> {
|
||||
return memo(instanceId, (eras: EraIndex[], withActive: boolean): Observable<DeriveEraSlashes[]> =>
|
||||
eras.length
|
||||
? combineLatest(
|
||||
eras.map((era) => api.derive.staking._eraSlashes(era, withActive))
|
||||
@@ -70,8 +70,8 @@ export function _erasSlashes (api: ApiInterfaceRx): (eras: EraIndex[], withActiv
|
||||
);
|
||||
}
|
||||
|
||||
export function erasSlashes (api: ApiInterfaceRx): (withActive?: boolean) => Observable<DeriveEraSlashes[]> {
|
||||
return memo((withActive = false): Observable<DeriveEraSlashes[]> =>
|
||||
export function erasSlashes (instanceId: string, api: ApiInterfaceRx): (withActive?: boolean) => Observable<DeriveEraSlashes[]> {
|
||||
return memo(instanceId, (withActive = false): Observable<DeriveEraSlashes[]> =>
|
||||
api.derive.staking.erasHistoric(withActive).pipe(
|
||||
switchMap((eras) => api.derive.staking._erasSlashes(eras, withActive))
|
||||
)
|
||||
|
||||
@@ -11,13 +11,16 @@ export * from './erasPrefs';
|
||||
export * from './erasRewards';
|
||||
export * from './erasSlashes';
|
||||
export * from './electedInfo';
|
||||
export * from './keys';
|
||||
export * from './overview';
|
||||
export * from './ownExposure';
|
||||
export * from './ownSlashes';
|
||||
export * from './query';
|
||||
export * from './stakerExposure';
|
||||
export * from './stakerPoints';
|
||||
export * from './stakerPrefs';
|
||||
export * from './stakerRewards';
|
||||
export * from './stakerSlashes';
|
||||
export * from './stashes';
|
||||
export * from './validators';
|
||||
export * from './waitingInfo';
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
// Copyright 2017-2020 @polkadot/api-derive authors & contributors
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the Apache-2.0 license. See the LICENSE file for details.
|
||||
|
||||
import { ApiInterfaceRx } from '@polkadot/api/types';
|
||||
import { AccountId, Keys } from '@polkadot/types/interfaces';
|
||||
import { ITuple } from '@polkadot/types/types';
|
||||
import { DeriveStakingKeys } from './types';
|
||||
|
||||
import { Observable, combineLatest, of } from 'rxjs';
|
||||
import { map, switchMap } from 'rxjs/operators';
|
||||
import { Option, Vec } from '@polkadot/types';
|
||||
|
||||
import { memo } from '../util';
|
||||
|
||||
function extractsIds (stashId: Uint8Array | string, queuedKeys: [AccountId, Keys][], nextKeys: Option<Keys>): DeriveStakingKeys {
|
||||
const sessionIds = (queuedKeys.find(([currentId]) => currentId.eq(stashId)) || [undefined, [] as AccountId[]])[1];
|
||||
const nextSessionIds = nextKeys.unwrapOr([] as AccountId[]);
|
||||
|
||||
return {
|
||||
nextSessionIds,
|
||||
sessionIds
|
||||
};
|
||||
}
|
||||
|
||||
export function keys (instanceId: string, api: ApiInterfaceRx): (stashId: Uint8Array | string) => Observable<DeriveStakingKeys> {
|
||||
return memo(instanceId, (stashId: Uint8Array | string): Observable<DeriveStakingKeys> =>
|
||||
api.derive.staking.keysMulti([stashId]).pipe(
|
||||
map(([first]) => first)
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
export function keysMulti (instanceId: string, api: ApiInterfaceRx): (stashIds: (Uint8Array | string)[]) => Observable<DeriveStakingKeys[]> {
|
||||
return memo(instanceId, (stashIds: (Uint8Array | string)[]): Observable<DeriveStakingKeys[]> =>
|
||||
stashIds.length
|
||||
? api.query.session.queuedKeys<Vec<ITuple<[AccountId, Keys]>>>().pipe(
|
||||
switchMap((queuedKeys): Observable<[Vec<ITuple<[AccountId, Keys]>>, Option<Keys>[]]> =>
|
||||
combineLatest([
|
||||
of(queuedKeys),
|
||||
api.consts.session?.dedupKeyPrefix
|
||||
? api.query.session.nextKeys.multi<Option<Keys>>(stashIds.map((stashId) => [api.consts.session.dedupKeyPrefix, stashId]))
|
||||
: api.query.session.nextKeys.multi<Option<Keys>>(stashIds)
|
||||
])
|
||||
),
|
||||
map(([queuedKeys, nextKeys]) =>
|
||||
stashIds.map((stashId, index) => extractsIds(stashId, queuedKeys, nextKeys[index]))
|
||||
)
|
||||
)
|
||||
: of([])
|
||||
);
|
||||
}
|
||||
@@ -13,8 +13,8 @@ import { memo } from '../util';
|
||||
/**
|
||||
* @description Retrieve the staking overview, including elected and points earned
|
||||
*/
|
||||
export function overview (api: ApiInterfaceRx): () => Observable<DeriveStakingOverview> {
|
||||
return memo((): Observable<DeriveStakingOverview> =>
|
||||
export function overview (instanceId: string, api: ApiInterfaceRx): () => Observable<DeriveStakingOverview> {
|
||||
return memo(instanceId, (): Observable<DeriveStakingOverview> =>
|
||||
combineLatest([
|
||||
api.derive.session.indexes(),
|
||||
api.derive.staking.validators()
|
||||
|
||||
@@ -2,34 +2,62 @@
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the Apache-2.0 license. See the LICENSE file for details.
|
||||
|
||||
import { EraIndex, Exposure } from '@polkadot/types/interfaces';
|
||||
import { ApiInterfaceRx } from '@polkadot/api/types';
|
||||
import { DeriveOwnExposure } from '../types';
|
||||
|
||||
import { Observable, combineLatest, of } from 'rxjs';
|
||||
import { map, switchMap } from 'rxjs/operators';
|
||||
|
||||
import { memo } from '../util';
|
||||
import { deriveCache, memo } from '../util';
|
||||
|
||||
export function ownExposure (api: ApiInterfaceRx): (accountId: Uint8Array | string, withActive?: boolean) => Observable<DeriveOwnExposure[]> {
|
||||
return memo((accountId: Uint8Array | string, withActive?: boolean): Observable<DeriveOwnExposure[]> => {
|
||||
const CACHE_KEY = 'ownExposure';
|
||||
|
||||
export function _ownExposure (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]]
|
||||
]).pipe(
|
||||
map(([clipped, exposure]): DeriveOwnExposure => {
|
||||
const value = { clipped, era, exposure };
|
||||
|
||||
!withActive && deriveCache.set(cacheKey, value);
|
||||
|
||||
return value;
|
||||
})
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
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([])
|
||||
);
|
||||
}
|
||||
|
||||
export function ownExposures (instanceId: string, api: ApiInterfaceRx): (accountId: Uint8Array | string, withActive?: boolean) => Observable<DeriveOwnExposure[]> {
|
||||
return memo(instanceId, (accountId: Uint8Array | string, withActive = false): Observable<DeriveOwnExposure[]> => {
|
||||
return api.derive.staking.erasHistoric(withActive).pipe(
|
||||
switchMap((eras) =>
|
||||
eras.length
|
||||
? combineLatest(
|
||||
eras.map((era) => combineLatest([
|
||||
of(era),
|
||||
api.query.staking.erasStakersClipped(era, accountId),
|
||||
api.query.staking.erasStakers(era, accountId)
|
||||
]))
|
||||
)
|
||||
: of([])
|
||||
),
|
||||
map((result): DeriveOwnExposure[] =>
|
||||
result.map(([era, clipped, exposure]): DeriveOwnExposure => ({
|
||||
clipped,
|
||||
era,
|
||||
exposure
|
||||
}))
|
||||
api.derive.staking._ownExposures(accountId, eras, withActive)
|
||||
)
|
||||
);
|
||||
});
|
||||
|
||||
@@ -3,34 +3,68 @@
|
||||
// of the Apache-2.0 license. See the LICENSE file for details.
|
||||
|
||||
import { ApiInterfaceRx } from '@polkadot/api/types';
|
||||
import { BalanceOf, EraIndex, Perbill } from '@polkadot/types/interfaces';
|
||||
import { ITuple } from '@polkadot/types/types';
|
||||
import { DeriveStakerSlashes } from '../types';
|
||||
|
||||
import { Observable, combineLatest, of } from 'rxjs';
|
||||
import { map, switchMap } from 'rxjs/operators';
|
||||
import { Option } from '@polkadot/types';
|
||||
|
||||
import { memo } from '../util';
|
||||
import { deriveCache, memo } from '../util';
|
||||
|
||||
export function ownSlashes (api: ApiInterfaceRx): (accountId: Uint8Array | string, withActive?: boolean) => Observable<DeriveStakerSlashes[]> {
|
||||
return memo((accountId: Uint8Array | string, withActive = false): Observable<DeriveStakerSlashes[]> => {
|
||||
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]]
|
||||
]).pipe(
|
||||
map(([optNom, optVal]): DeriveStakerSlashes => {
|
||||
const value = {
|
||||
era,
|
||||
total: optVal.isSome
|
||||
? optVal.unwrap()[1]
|
||||
: optNom.unwrapOrDefault()
|
||||
};
|
||||
|
||||
!withActive && deriveCache.set(cacheKey, value);
|
||||
|
||||
return value;
|
||||
})
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
export function ownSlash (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([])
|
||||
);
|
||||
}
|
||||
|
||||
export function ownSlashes (instanceId: string, api: ApiInterfaceRx): (accountId: Uint8Array | string, withActive?: boolean) => Observable<DeriveStakerSlashes[]> {
|
||||
return memo(instanceId, (accountId: Uint8Array | string, withActive = false): Observable<DeriveStakerSlashes[]> => {
|
||||
return api.derive.staking.erasHistoric(withActive).pipe(
|
||||
switchMap((eras) =>
|
||||
eras.length
|
||||
? combineLatest(
|
||||
eras.map((era) => combineLatest([
|
||||
of(era),
|
||||
api.query.staking.nominatorSlashInEra(era, accountId),
|
||||
api.query.staking.validatorSlashInEra(era, accountId)
|
||||
]))
|
||||
)
|
||||
: of([])
|
||||
),
|
||||
map((result): DeriveStakerSlashes[] =>
|
||||
result.map(([era, optNom, optVal]): DeriveStakerSlashes => ({
|
||||
era,
|
||||
total: optVal.isSome
|
||||
? optVal.unwrap()[1]
|
||||
: optNom.unwrapOrDefault()
|
||||
}))
|
||||
api.derive.staking._ownSlashes(accountId, eras, withActive)
|
||||
)
|
||||
);
|
||||
});
|
||||
|
||||
@@ -3,28 +3,37 @@
|
||||
// of the Apache-2.0 license. See the LICENSE file for details.
|
||||
|
||||
import { ApiInterfaceRx } from '@polkadot/api/types';
|
||||
import { AccountId, Exposure, Keys, Nominations, RewardDestination, ValidatorPrefs } from '@polkadot/types/interfaces';
|
||||
import { AccountId, EraIndex, Exposure, Nominations, RewardDestination, StakingLedger, ValidatorPrefs } from '@polkadot/types/interfaces';
|
||||
import { ITuple } from '@polkadot/types/types';
|
||||
import { DeriveStakingQuery } from '../types';
|
||||
|
||||
import { Observable, combineLatest, of } from 'rxjs';
|
||||
import { map, switchMap } from 'rxjs/operators';
|
||||
import { Option, Vec } from '@polkadot/types';
|
||||
import { Option } from '@polkadot/types';
|
||||
import { isFunction } from '@polkadot/util';
|
||||
|
||||
import { memo } from '../util';
|
||||
|
||||
type MultiResult = [Option<AccountId>, Option<ITuple<[Nominations]> | Nominations>, RewardDestination, ITuple<[ValidatorPrefs]> | ValidatorPrefs, Option<Keys>, Exposure];
|
||||
type MultiResult = [Option<AccountId>, Option<ITuple<[Nominations]> | Nominations>, RewardDestination, ITuple<[ValidatorPrefs]> | ValidatorPrefs, Exposure];
|
||||
|
||||
function unwrapSessionIds (stashId: AccountId, queuedKeys: [AccountId, Keys][], nextKeys: Option<Keys>): { nextSessionIds: AccountId[]; sessionIds: AccountId[] } {
|
||||
const sessionIds = (queuedKeys.find(([currentId]): boolean =>
|
||||
currentId.eq(stashId)
|
||||
) || [undefined, [] as AccountId[]])[1];
|
||||
const nextSessionIds = nextKeys.unwrapOr([] as AccountId[]);
|
||||
function parseController (stashId: AccountId, [controllerIdOpt, nominatorsOpt, rewardDestination, validatorPrefs, exposure]: MultiResult, stakingLedgerOpt: Option<StakingLedger>): DeriveStakingQuery {
|
||||
const nominators = nominatorsOpt.unwrapOr(null);
|
||||
|
||||
return {
|
||||
nextSessionIds,
|
||||
sessionIds
|
||||
accountId: stashId,
|
||||
controllerId: controllerIdOpt.unwrapOr(null),
|
||||
exposure,
|
||||
nominators: nominators
|
||||
? Array.isArray(nominators)
|
||||
? nominators[0].targets
|
||||
: nominators.targets
|
||||
: [],
|
||||
rewardDestination,
|
||||
stakingLedger: stakingLedgerOpt.unwrapOrDefault(),
|
||||
stashId,
|
||||
validatorPrefs: Array.isArray(validatorPrefs)
|
||||
? validatorPrefs[0]
|
||||
: validatorPrefs
|
||||
};
|
||||
}
|
||||
|
||||
@@ -34,89 +43,80 @@ function retrievePrev (api: ApiInterfaceRx, stashId: AccountId): Observable<Mult
|
||||
[api.query.staking.nominators, stashId],
|
||||
[api.query.staking.payee, stashId],
|
||||
[api.query.staking.validators, stashId],
|
||||
[api.query.session.nextKeys, [api.consts.session.dedupKeyPrefix, stashId]],
|
||||
[api.query.staking.stakers, stashId]
|
||||
]);
|
||||
}
|
||||
|
||||
function retrieveCurr (api: ApiInterfaceRx, stashId: AccountId): Observable<MultiResult> {
|
||||
return api.derive.session.indexes().pipe(
|
||||
switchMap(({ activeEra }) =>
|
||||
api.queryMulti<MultiResult>([
|
||||
[api.query.staking.bonded, stashId],
|
||||
[api.query.staking.nominators, stashId],
|
||||
[api.query.staking.payee, stashId],
|
||||
[api.query.staking.validators, stashId],
|
||||
api.consts.session?.dedupKeyPrefix
|
||||
? [api.query.session.nextKeys, [api.consts.session.dedupKeyPrefix, stashId]]
|
||||
: [api.query.session.nextKeys, stashId],
|
||||
[api.query.staking.erasStakers, [activeEra, stashId]]
|
||||
])
|
||||
function retrieveCurr (api: ApiInterfaceRx, stashIds: AccountId[], activeEra: EraIndex): Observable<MultiResult[]> {
|
||||
return combineLatest([
|
||||
api.query.staking.bonded.multi<Option<AccountId>>(stashIds),
|
||||
api.query.staking.nominators
|
||||
? api.query.staking.nominators.multi<Option<Nominations>>(stashIds)
|
||||
: of(stashIds.map(() => api.registry.createType('Option<Nominations>'))),
|
||||
api.query.staking.payee.multi<RewardDestination>(stashIds),
|
||||
api.query.staking.validators.multi<ValidatorPrefs>(stashIds),
|
||||
api.query.staking.erasStakers.multi<Exposure>(stashIds.map((stashId) => [activeEra, stashId]))
|
||||
]).pipe(
|
||||
map(([controllerIdOpt, nominatorsOpt, rewardDestination, validatorPrefs, exposure]): MultiResult[] =>
|
||||
controllerIdOpt.map((controllerIdOpt, index): MultiResult =>
|
||||
[controllerIdOpt, nominatorsOpt[index], rewardDestination[index], validatorPrefs[index], exposure[index]]
|
||||
)
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
function retrieveController (api: ApiInterfaceRx, stashId: AccountId, queuedKeys: Vec<ITuple<[AccountId, Keys]>>, [controllerIdOpt, nominatorsOpt, rewardDestination, validatorPrefs, nextKeys, exposure]: MultiResult): Observable<DeriveStakingQuery> {
|
||||
const controllerId = controllerIdOpt.unwrapOr(null);
|
||||
const nominators = nominatorsOpt.unwrapOr(null);
|
||||
function retrieveControllers (api: ApiInterfaceRx, optControllerIds: Option<AccountId>[]): Observable<Option<StakingLedger>[]> {
|
||||
const ids = optControllerIds.filter((opt) => opt.isSome).map((opt) => opt.unwrap());
|
||||
|
||||
return controllerId
|
||||
? api.query.staking.ledger(controllerId).pipe(
|
||||
map((stakingLedgerOpt): DeriveStakingQuery => ({
|
||||
accountId: stashId,
|
||||
controllerId,
|
||||
exposure,
|
||||
nominators: nominators
|
||||
? Array.isArray(nominators)
|
||||
? nominators[0].targets
|
||||
: nominators.targets
|
||||
: [],
|
||||
rewardDestination,
|
||||
stakingLedger: stakingLedgerOpt.unwrapOr(undefined),
|
||||
stashId,
|
||||
validatorPrefs: Array.isArray(validatorPrefs)
|
||||
? validatorPrefs[0]
|
||||
: validatorPrefs,
|
||||
...unwrapSessionIds(stashId, queuedKeys, nextKeys)
|
||||
}))
|
||||
)
|
||||
: of({ accountId: stashId, nextSessionIds: [], sessionIds: [] });
|
||||
}
|
||||
if (!ids.length) {
|
||||
return of(optControllerIds.map(() => api.registry.createType('Option<StakingLedger>')));
|
||||
}
|
||||
|
||||
export function queryWithQueued (api: ApiInterfaceRx): (accountId: Uint8Array | string, queuedKeys: Vec<ITuple<[AccountId, Keys]>>) => Observable<DeriveStakingQuery> {
|
||||
return memo((accountId: Uint8Array | string, queuedKeys: Vec<ITuple<[AccountId, Keys]>>): Observable<DeriveStakingQuery> => {
|
||||
const stashId = api.registry.createType('AccountId', accountId);
|
||||
return api.query.staking.ledger.multi<Option<StakingLedger>>(ids).pipe(
|
||||
map((optLedgers): Option<StakingLedger>[] => {
|
||||
let offset = -1;
|
||||
|
||||
return (
|
||||
isFunction(api.query.staking.erasStakers)
|
||||
? retrieveCurr(api, stashId)
|
||||
: retrievePrev(api, stashId)
|
||||
).pipe(
|
||||
switchMap((result): Observable<DeriveStakingQuery> =>
|
||||
retrieveController(api, stashId, queuedKeys, result)
|
||||
)
|
||||
);
|
||||
});
|
||||
return optControllerIds.map((opt): Option<StakingLedger> =>
|
||||
opt.isSome
|
||||
? optLedgers[++offset]
|
||||
: api.registry.createType('Option<StakingLedger>')
|
||||
);
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @description From a stash, retrieve the controllerId and all relevant details
|
||||
*/
|
||||
export function query (api: ApiInterfaceRx): (accountId: Uint8Array | string) => Observable<DeriveStakingQuery> {
|
||||
return memo((accountId: Uint8Array | string): Observable<DeriveStakingQuery> =>
|
||||
api.query.session.queuedKeys<Vec<ITuple<[AccountId, Keys]>>>().pipe(
|
||||
switchMap((queuedKeys) => api.derive.staking.queryWithQueued(accountId, queuedKeys))
|
||||
export function query (instanceId: string, api: ApiInterfaceRx): (accountId: Uint8Array | string) => Observable<DeriveStakingQuery> {
|
||||
return memo(instanceId, (accountId: Uint8Array | string): Observable<DeriveStakingQuery> =>
|
||||
api.derive.staking.queryMulti([accountId]).pipe(
|
||||
map(([first]) => first)
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
export function queryMulti (api: ApiInterfaceRx): (accountIds: (Uint8Array | string)[]) => Observable<DeriveStakingQuery[]> {
|
||||
return memo((accountIds: (Uint8Array | string)[]): Observable<DeriveStakingQuery[]> =>
|
||||
export function queryMulti (instanceId: string, api: ApiInterfaceRx): (accountIds: (Uint8Array | string)[]) => Observable<DeriveStakingQuery[]> {
|
||||
return memo(instanceId, (accountIds: (Uint8Array | string)[]): Observable<DeriveStakingQuery[]> =>
|
||||
accountIds.length
|
||||
? api.query.session.queuedKeys<Vec<ITuple<[AccountId, Keys]>>>().pipe(
|
||||
switchMap((queuedKeys) => combineLatest(
|
||||
accountIds.map((acc) => api.derive.staking.queryWithQueued(acc, queuedKeys))
|
||||
))
|
||||
? api.derive.session.indexes().pipe(
|
||||
switchMap(({ activeEra }): Observable<DeriveStakingQuery[]> => {
|
||||
const stashIds = accountIds.map((accountId) => api.registry.createType('AccountId', accountId));
|
||||
|
||||
return (
|
||||
isFunction(api.query.staking.erasStakers)
|
||||
? retrieveCurr(api, stashIds, activeEra)
|
||||
: combineLatest(stashIds.map((stashId) => retrievePrev(api, stashId)))
|
||||
).pipe(
|
||||
switchMap((results): Observable<DeriveStakingQuery[]> =>
|
||||
retrieveControllers(api, results.map(([optController]) => optController)).pipe(
|
||||
map((stakingLedgerOpts) =>
|
||||
stashIds.map((stashId, index) => parseController(stashId, results[index], stakingLedgerOpts[index]))
|
||||
)
|
||||
)
|
||||
)
|
||||
);
|
||||
})
|
||||
)
|
||||
: of([])
|
||||
);
|
||||
|
||||
@@ -11,8 +11,8 @@ import { map, switchMap } from 'rxjs/operators';
|
||||
|
||||
import { memo } from '../util';
|
||||
|
||||
export function _stakerExposure (api: ApiInterfaceRx): (accountId: Uint8Array | string, eras: EraIndex[], withActive: boolean) => Observable<DeriveStakerExposure[]> {
|
||||
return memo((accountId: Uint8Array | string, eras: EraIndex[], withActive: boolean): Observable<DeriveStakerExposure[]> => {
|
||||
export function _stakerExposure (instanceId: string, api: ApiInterfaceRx): (accountId: Uint8Array | string, eras: EraIndex[], withActive: boolean) => Observable<DeriveStakerExposure[]> {
|
||||
return memo(instanceId, (accountId: Uint8Array | string, eras: EraIndex[], withActive: boolean): Observable<DeriveStakerExposure[]> => {
|
||||
const stakerId = api.registry.createType('AccountId', accountId).toString();
|
||||
|
||||
return api.derive.staking._erasExposure(eras, withActive).pipe(
|
||||
@@ -37,8 +37,8 @@ export function _stakerExposure (api: ApiInterfaceRx): (accountId: Uint8Array |
|
||||
});
|
||||
}
|
||||
|
||||
export function stakerExposure (api: ApiInterfaceRx): (accountId: Uint8Array | string, withActive?: boolean) => Observable<DeriveStakerExposure[]> {
|
||||
return memo((accountId: Uint8Array | string, withActive = false): Observable<DeriveStakerExposure[]> =>
|
||||
export function stakerExposure (instanceId: string, api: ApiInterfaceRx): (accountId: Uint8Array | string, withActive?: boolean) => Observable<DeriveStakerExposure[]> {
|
||||
return memo(instanceId, (accountId: Uint8Array | string, withActive = false): Observable<DeriveStakerExposure[]> =>
|
||||
api.derive.staking.erasHistoric(withActive).pipe(
|
||||
switchMap((eras) => api.derive.staking._stakerExposure(accountId, eras, withActive))
|
||||
)
|
||||
|
||||
@@ -11,8 +11,8 @@ import { map, switchMap } from 'rxjs/operators';
|
||||
|
||||
import { memo } from '../util';
|
||||
|
||||
export function _stakerPoints (api: ApiInterfaceRx): (accountId: Uint8Array | string, eras: EraIndex[], withActive: boolean) => Observable<DeriveStakerPoints[]> {
|
||||
return memo((accountId: Uint8Array | string, eras: EraIndex[], withActive: boolean): Observable<DeriveStakerPoints[]> => {
|
||||
export function _stakerPoints (instanceId: string, api: ApiInterfaceRx): (accountId: Uint8Array | string, eras: EraIndex[], withActive: boolean) => Observable<DeriveStakerPoints[]> {
|
||||
return memo(instanceId, (accountId: Uint8Array | string, eras: EraIndex[], withActive: boolean): Observable<DeriveStakerPoints[]> => {
|
||||
const stakerId = api.registry.createType('AccountId', accountId).toString();
|
||||
|
||||
return api.derive.staking._erasPoints(eras, withActive).pipe(
|
||||
@@ -27,8 +27,8 @@ export function _stakerPoints (api: ApiInterfaceRx): (accountId: Uint8Array | st
|
||||
});
|
||||
}
|
||||
|
||||
export function stakerPoints (api: ApiInterfaceRx): (accountId: Uint8Array | string, withActive?: boolean) => Observable<DeriveStakerPoints[]> {
|
||||
return memo((accountId: Uint8Array | string, withActive = false): Observable<DeriveStakerPoints[]> =>
|
||||
export function stakerPoints (instanceId: string, api: ApiInterfaceRx): (accountId: Uint8Array | string, withActive?: boolean) => Observable<DeriveStakerPoints[]> {
|
||||
return memo(instanceId, (accountId: Uint8Array | string, withActive = false): Observable<DeriveStakerPoints[]> =>
|
||||
api.derive.staking.erasHistoric(withActive).pipe(
|
||||
switchMap((eras) => api.derive.staking._stakerPoints(accountId, eras, withActive))
|
||||
)
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
// Copyright 2017-2020 @polkadot/api-derive authors & contributors
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the Apache-2.0 license. See the LICENSE file for details.
|
||||
|
||||
import { ApiInterfaceRx } from '@polkadot/api/types';
|
||||
import { EraIndex, ValidatorPrefs } from '@polkadot/types/interfaces';
|
||||
import { DeriveStakerPrefs } from '../types';
|
||||
|
||||
import { Observable } from 'rxjs';
|
||||
import { map, switchMap } from 'rxjs/operators';
|
||||
|
||||
import { memo } from '../util';
|
||||
|
||||
export function _stakerPrefs (instanceId: string, api: ApiInterfaceRx): (accountId: Uint8Array | string, eras: EraIndex[], withActive: boolean) => Observable<DeriveStakerPrefs[]> {
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
return memo(instanceId, (accountId: Uint8Array | string, eras: EraIndex[], _withActive: boolean): Observable<DeriveStakerPrefs[]> => {
|
||||
return api.query.staking.erasValidatorPrefs.multi<ValidatorPrefs>(eras.map((era) => [era, accountId])).pipe(
|
||||
map((all): DeriveStakerPrefs[] =>
|
||||
all.map((validatorPrefs, index): DeriveStakerPrefs => ({
|
||||
era: eras[index],
|
||||
validatorPrefs
|
||||
}))
|
||||
)
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
export function stakerPrefs (instanceId: string, api: ApiInterfaceRx): (accountId: Uint8Array | string, withActive?: boolean) => Observable<DeriveStakerPrefs[]> {
|
||||
return memo(instanceId, (accountId: Uint8Array | string, withActive = false): Observable<DeriveStakerPrefs[]> =>
|
||||
api.derive.staking.erasHistoric(withActive).pipe(
|
||||
switchMap((eras) => api.derive.staking._stakerPrefs(accountId, eras, withActive))
|
||||
)
|
||||
);
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user