Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f428a58006 | ||
|
|
fcce2ab340 | ||
|
|
877eb11717 | ||
|
|
4b55f1be93 | ||
|
|
f2a677634e | ||
|
|
eea4c8775e | ||
|
|
792bf0ec36 | ||
|
|
e3d13107a9 | ||
|
|
e5c2c6a228 | ||
|
|
d2be79132c | ||
|
|
76da2638c1 | ||
|
|
daf3912920 | ||
|
|
6dfebbb9fe | ||
|
|
e55c5f77f7 | ||
|
|
c7315ffb74 | ||
|
|
84eb806f07 | ||
|
|
2493442a2e | ||
|
|
77df7907c7 | ||
|
|
f1b6268784 | ||
|
|
9aa9380251 | ||
|
|
b4306cb60a | ||
|
|
1e83daf797 | ||
|
|
d46d32d9bc | ||
|
|
032a0a595c | ||
|
|
34101ec12b | ||
|
|
4e02b982d3 | ||
|
|
5b96d52fa6 | ||
|
|
735f2b835e | ||
|
|
646e64c286 | ||
|
|
fc9060caa8 | ||
|
|
503c2b3c63 | ||
|
|
168abc130f | ||
|
|
5c5db2709b | ||
|
|
5a4ff5420f | ||
|
|
a1655508ba | ||
|
|
64827a6114 | ||
|
|
2eb09374bc | ||
|
|
ddf67d5564 | ||
|
|
ad6b8280a2 | ||
|
|
682c6b6fb2 | ||
|
|
6a281211b4 | ||
|
|
6ef94b3c3b | ||
|
|
e900d1d657 | ||
|
|
7f1a3fa636 | ||
|
|
21802664b8 | ||
|
|
1492df11a7 | ||
|
|
00fed90da2 | ||
|
|
e6beb6554d | ||
|
|
099cf5a351 | ||
|
|
55e762a348 | ||
|
|
0ad146c607 | ||
|
|
4e7f3f5268 | ||
|
|
6a9e3d80f1 | ||
|
|
dee98fae55 | ||
|
|
ff52876920 | ||
|
|
4d01a09c54 | ||
|
|
7310ea825e | ||
|
|
15b80a47c3 | ||
|
|
622682b4ef | ||
|
|
56415df4ab | ||
|
|
8bea5e5a3b | ||
|
|
d6372ade44 | ||
|
|
f501994df8 | ||
|
|
b787a7d5a0 | ||
|
|
11d162a10d | ||
|
|
e2564dea17 | ||
|
|
2b9152871e | ||
|
|
70ecb03d14 | ||
|
|
a2f179acb1 | ||
|
|
c8cb97edef | ||
|
|
69d344c6c3 | ||
|
|
44cdf49b2c | ||
|
|
daaf4654a1 | ||
|
|
f8d4fcaf04 | ||
|
|
eb19a39d82 | ||
|
|
7ed958fb2d | ||
|
|
bbe9b94f26 | ||
|
|
6e83e6aaef | ||
|
|
1545bbf7c5 | ||
|
|
5bfc2cd534 | ||
|
|
b22d0a196f | ||
|
|
b174864804 | ||
|
|
e6834d60c5 | ||
|
|
97438bb2e8 | ||
|
|
f630d43a25 | ||
|
|
0187f1ff19 | ||
|
|
d8db866316 | ||
|
|
28aa9e18a7 | ||
|
|
3eaea97b8f | ||
|
|
ea0e5e4547 | ||
|
|
1256317b65 | ||
|
|
e0c3ed1b96 | ||
|
|
9f2c3016d7 | ||
|
|
938ace2342 | ||
|
|
e5d2607dff | ||
|
|
50b8db2263 | ||
|
|
91766a6885 | ||
|
|
4b1a9ab9e1 | ||
|
|
9a14c65336 | ||
|
|
4aa66fd4c6 | ||
|
|
3d9c62d538 | ||
|
|
4156eb44ab | ||
|
|
4b2d33693c | ||
|
|
e8b127e177 | ||
|
|
b052b03f31 | ||
|
|
6727e12468 | ||
|
|
c130285651 | ||
|
|
47fc4a2b3c | ||
|
|
97cb408f36 | ||
|
|
dde7c8085a | ||
|
|
8b02fafb99 | ||
|
|
393f46ba4a | ||
|
|
455f5ad834 | ||
|
|
674324e7f9 | ||
|
|
b0dc7cf451 | ||
|
|
cbe1b2b1ce | ||
|
|
4bd2f2fc32 | ||
|
|
053112470d | ||
|
|
acdf27a272 | ||
|
|
f70b32ba76 | ||
|
|
67a3376ef8 | ||
|
|
eb06bb6e93 | ||
|
|
f8f7e92da4 | ||
|
|
d0fd3eca25 | ||
|
|
dac1df35de | ||
|
|
597563d2bb | ||
|
|
f825c7f187 | ||
|
|
2e71a6160e | ||
|
|
c076c37119 | ||
|
|
0e18fdbccc | ||
|
|
c3eebd8fbe | ||
|
|
45786b31da | ||
|
|
f348e34de7 | ||
|
|
337de79bef | ||
|
|
a13b51b985 | ||
|
|
c5c77c9b52 | ||
|
|
2a033e5634 | ||
|
|
00ffb358cb | ||
|
|
66d1bbe4cb | ||
|
|
3baf36e9e6 | ||
|
|
e3abb95111 | ||
|
|
da281c9531 | ||
|
|
c0e3026772 | ||
|
|
757da68675 | ||
|
|
f145488314 | ||
|
|
0ce10d2938 | ||
|
|
6f2d62bb3b | ||
|
|
fc7c8310ae | ||
|
|
c9921f002f | ||
|
|
6b8a65eb31 | ||
|
|
0cf29719b3 | ||
|
|
abecabdaed | ||
|
|
0c5b69bea1 | ||
|
|
7b3f24b1f5 | ||
|
|
d1f8f8b5e8 | ||
|
|
3f060b9e0d | ||
|
|
fe69f70539 | ||
|
|
578c4ffb69 | ||
|
|
66aa38000b | ||
|
|
50ddff6907 | ||
|
|
14874f41f7 | ||
|
|
5a11b0c701 | ||
|
|
8491ab8ca6 | ||
|
|
4f5cb0f35e | ||
|
|
53d081df65 | ||
|
|
6b5dbb6948 | ||
|
|
3879986a75 | ||
|
|
378ca10580 | ||
|
|
d75d8bec0e | ||
|
|
6f6a32a7a2 | ||
|
|
226426e67e | ||
|
|
66e2a4d298 | ||
|
|
664151f829 | ||
|
|
49b00524b1 | ||
|
|
401784b7e6 | ||
|
|
99873e901a | ||
|
|
72d131f62f | ||
|
|
c412f7fa11 | ||
|
|
a1ad90c2b4 | ||
|
|
92f62bfa15 | ||
|
|
fa9c5778be | ||
|
|
e6f877621a | ||
|
|
5c35a70e9d | ||
|
|
a287096cc3 | ||
|
|
c35f31bfbd | ||
|
|
718afa91e3 | ||
|
|
102a06b0f2 | ||
|
|
58f0df1ef0 | ||
|
|
a458589222 | ||
|
|
deef4ce4c7 | ||
|
|
f5d2449407 | ||
|
|
8bb1d1259e | ||
|
|
abd860d548 | ||
|
|
25936d882f | ||
|
|
9deaff54e4 | ||
|
|
bc479a995b | ||
|
|
458b7fa7e4 | ||
|
|
2fc17a66e1 | ||
|
|
94f81db568 | ||
|
|
e83d97c849 | ||
|
|
4a497fa970 | ||
|
|
cb40d459b5 | ||
|
|
c70cdb351f | ||
|
|
001aa0d011 | ||
|
|
961d27ad46 | ||
|
|
1c09bb69dd | ||
|
|
174510a928 | ||
|
|
39ed76f2de | ||
|
|
7d1c93db59 | ||
|
|
e9b1b4ee77 | ||
|
|
2367978f6e | ||
|
|
e77050b9f5 | ||
|
|
844d1a2928 | ||
|
|
6a70beda0f | ||
|
|
05a834b822 | ||
|
|
6a3af506a4 | ||
|
|
c82b85ef79 | ||
|
|
91ab81ef60 | ||
|
|
3665690444 | ||
|
|
03dcefceb5 | ||
|
|
e84be032f4 | ||
|
|
033ff7a28c | ||
|
|
7c8b2abf92 | ||
|
|
5312ec1f3a | ||
|
|
cdfbf91ee6 | ||
|
|
14f2abdc37 | ||
|
|
04c8d49e9d | ||
|
|
722929d0d4 | ||
|
|
d1fae523ac | ||
|
|
ce9a92cdc0 | ||
|
|
3de09a2e27 | ||
|
|
f28479180f | ||
|
|
0d1d42f6c2 | ||
|
|
c93dad0bc5 | ||
|
|
e3d3a1ff71 | ||
|
|
1c8bd896e1 | ||
|
|
e0119c1873 | ||
|
|
defe81e560 | ||
|
|
932122cd21 | ||
|
|
40d035eca7 | ||
|
|
a135abaea2 | ||
|
|
00b8c10881 | ||
|
|
11e7b90918 | ||
|
|
ae74467e6a | ||
|
|
5a929d3810 | ||
|
|
63732f1456 | ||
|
|
ea6bb83c01 | ||
|
|
d6a443ca2a | ||
|
|
d983ee106c | ||
|
|
beed1df5bd | ||
|
|
426aef6088 | ||
|
|
9be9b3fb83 | ||
|
|
8676f30cbf | ||
|
|
154561c34c | ||
|
|
714b242ec0 | ||
|
|
32ce650ee1 | ||
|
|
3715df2f5b | ||
|
|
dd6e6ddfc1 | ||
|
|
9975f58cfb | ||
|
|
536369261f | ||
|
|
33165e93dc | ||
|
|
39a38a6c44 | ||
|
|
b18bdc37f9 | ||
|
|
79847aabf7 | ||
|
|
ab75863d94 | ||
|
|
c908a27b7d | ||
|
|
98c7e5d5ea | ||
|
|
fd4587a0bc | ||
|
|
e211ae1667 | ||
|
|
af735176fe | ||
|
|
9eb44d6e89 | ||
|
|
379e841808 | ||
|
|
5c16b8e8a1 | ||
|
|
96d7d9ff5a | ||
|
|
e9fbbbbd42 | ||
|
|
73750ddb7d | ||
|
|
4e1145c66f | ||
|
|
7f35fa22d5 | ||
|
|
da1daf5bd9 | ||
|
|
5afc87ce47 | ||
|
|
a2269cd999 | ||
|
|
201308c259 | ||
|
|
00490116dd | ||
|
|
1968c878f5 | ||
|
|
52ccb9fbbf | ||
|
|
03e21ea64b | ||
|
|
8c949bb3df | ||
|
|
e484e7cf35 | ||
|
|
7aac4c7936 | ||
|
|
933c8d48e2 | ||
|
|
d3d3bb9b5a | ||
|
|
f4d976c337 | ||
|
|
07c4037fcf | ||
|
|
52d73d8698 | ||
|
|
ccfab75f41 | ||
|
|
b8204b138d | ||
|
|
a97cb6e25d | ||
|
|
11534a1153 | ||
|
|
dd1fab5366 | ||
|
|
dbb3a5ccc2 | ||
|
|
fb08215e0d | ||
|
|
d7d7ab2f89 | ||
|
|
25393cd982 | ||
|
|
d6a6089e2d | ||
|
|
a3eaca0270 | ||
|
|
f9d1b4d653 | ||
|
|
f81712343a | ||
|
|
33e414be12 | ||
|
|
9387103558 | ||
|
|
3b7c1afa95 | ||
|
|
7e1fa8954b | ||
|
|
53c62f1542 | ||
|
|
5ed94a50e1 | ||
|
|
b1c047149b | ||
|
|
7a0efaf58c | ||
|
|
5acce98346 | ||
|
|
165179ebf2 | ||
|
|
def60dce9e | ||
|
|
c8f91fcf7a | ||
|
|
70a160cca0 | ||
|
|
9691fd5ba7 | ||
|
|
475cb4fa69 | ||
|
|
5c54b3cc92 | ||
|
|
55d8c58d95 | ||
|
|
edf8adaa88 | ||
|
|
1f8f6e54bd | ||
|
|
f6ca7b9a9d | ||
|
|
7732339fc0 | ||
|
|
5a8a8c7ecb | ||
|
|
05df087e73 | ||
|
|
5b71abfe80 | ||
|
|
1d6c33060a | ||
|
|
eae573e6a2 | ||
|
|
0f08031792 | ||
|
|
e0bde927d1 | ||
|
|
e569de520a | ||
|
|
a833dccdaf | ||
|
|
b58d772156 | ||
|
|
e5d9bbc264 | ||
|
|
3089529405 | ||
|
|
5ab24390c5 | ||
|
|
245047a41f | ||
|
|
8aa1bd5bd0 | ||
|
|
e0dde35621 | ||
|
|
9ba91a3851 | ||
|
|
351cb97667 | ||
|
|
afdb476796 | ||
|
|
3b67b65091 | ||
|
|
25580b2026 | ||
|
|
2db16e94b7 | ||
|
|
9184268c3d | ||
|
|
83a762af1e | ||
|
|
6a8e5370b6 | ||
|
|
9cd4bf7cf7 | ||
|
|
c4708dcfca | ||
|
|
041d06a6c8 | ||
|
|
2b4bd75499 | ||
|
|
c4c47a84e1 | ||
|
|
a241bd1c38 | ||
|
|
d420cede82 | ||
|
|
b869695e40 | ||
|
|
37caf4e710 | ||
|
|
134bc22463 | ||
|
|
39d142876e | ||
|
|
6d95eb418d | ||
|
|
e26a6a28ff | ||
|
|
d80d6f2a06 | ||
|
|
ff8dabb249 | ||
|
|
e7a01f9780 | ||
|
|
94938c7075 | ||
|
|
f37e729605 | ||
|
|
9cfde73ff8 | ||
|
|
f5c140d1c2 | ||
|
|
472e1022d3 | ||
|
|
f71211f5dc | ||
|
|
7e06974f1b | ||
|
|
f95384d9ff | ||
|
|
baedd5b689 | ||
|
|
9ec1cb194a | ||
|
|
d730310ea5 | ||
|
|
641fe5c380 | ||
|
|
c5a8d5e018 | ||
|
|
02d130f0a0 | ||
|
|
5554f17f05 | ||
|
|
69351ceb9e | ||
|
|
0cf9fa7405 | ||
|
|
8213fa7cb9 | ||
|
|
8ef983169f | ||
|
|
e392dd745e | ||
|
|
6b07a9c2a5 | ||
|
|
114ac59707 | ||
|
|
3c95bfe56e | ||
|
|
58de0b8b9c | ||
|
|
1f97c5e9e3 | ||
|
|
0dc46445bc | ||
|
|
7d3464ae2c | ||
|
|
295cd2a7e0 | ||
|
|
5a66ce5a87 | ||
|
|
d8d008108d | ||
|
|
491518405d | ||
|
|
7290b3d296 | ||
|
|
b6162a316f | ||
|
|
71c1d16dc4 | ||
|
|
204f592bea | ||
|
|
39c44bb5aa | ||
|
|
df0de49a67 | ||
|
|
0bdbf4b7a7 | ||
|
|
ef9cd6fc4b | ||
|
|
5ab0bf3998 | ||
|
|
e69d97619e | ||
|
|
6aa0d90fc0 | ||
|
|
d338fcb58c | ||
|
|
b9a60a2519 | ||
|
|
7b8b4e8078 | ||
|
|
50b551e4fc | ||
|
|
a4ea4d648a | ||
|
|
146360a454 | ||
|
|
2e83d92adc | ||
|
|
b77e5d079c | ||
|
|
0d067c9484 | ||
|
|
88519eff3f | ||
|
|
bb14471e60 | ||
|
|
97ab7fcf2f | ||
|
|
922cfb8759 | ||
|
|
717f33ca02 | ||
|
|
21a2b5f0b7 | ||
|
|
54efead9d7 | ||
|
|
c472a451a4 | ||
|
|
6ed2de43fc | ||
|
|
8976ded37f | ||
|
|
169a374544 | ||
|
|
6476d88e19 | ||
|
|
75de454619 | ||
|
|
851428aef9 | ||
|
|
dfc51ad300 | ||
|
|
e16d288644 | ||
|
|
a19928fef9 | ||
|
|
0906c7837a | ||
|
|
cb9831c4f8 | ||
|
|
620d3757ba | ||
|
|
601288b3ec | ||
|
|
efbeecc8f6 | ||
|
|
852e0d4f0b | ||
|
|
5c7f9f1c8a | ||
|
|
64f64c1001 | ||
|
|
15c3085511 | ||
|
|
27cd9b1ca4 | ||
|
|
1c2a95f820 | ||
|
|
8bf5e51725 | ||
|
|
493225aa9d | ||
|
|
a0979a9ce3 | ||
|
|
02849ae49b | ||
|
|
602bb1406b | ||
|
|
d70930587c | ||
|
|
8c011cdc86 | ||
|
|
eb3e7a0740 | ||
|
|
2071de517d | ||
|
|
205ae40f20 | ||
|
|
aa37e372dd | ||
|
|
8cdac77a8e | ||
|
|
7a7d6e9b8a | ||
|
|
7a1bdb18a8 | ||
|
|
39f22ca403 | ||
|
|
b3c6a5acc5 | ||
|
|
b3a6b3dcb5 | ||
|
|
0c0e4c4d7c | ||
|
|
9d67d711d4 | ||
|
|
f45d03fa17 | ||
|
|
af11444b72 | ||
|
|
f412a5ac86 | ||
|
|
c9dcd51ba6 | ||
|
|
5dca826429 | ||
|
|
8dc53e6339 | ||
|
|
5867f8ab0c | ||
|
|
6d3db2fb3f | ||
|
|
3a1634d67f | ||
|
|
53d18d874d | ||
|
|
044efbc6de | ||
|
|
27e3fbfd0f | ||
|
|
b7af4781ea | ||
|
|
c51e351117 | ||
|
|
e6afed9bb1 | ||
|
|
4b07d5511e | ||
|
|
a613308bdb | ||
|
|
a863e5eb95 | ||
|
|
623420ca3d | ||
|
|
9ea6053a42 | ||
|
|
73dce6bfd1 | ||
|
|
5a7811c80f | ||
|
|
1c529bdc6a | ||
|
|
3f4576f524 | ||
|
|
2619489ec3 | ||
|
|
f165845cc3 | ||
|
|
897f03e4c1 | ||
|
|
82c1e3f35a | ||
|
|
c06f260d3c | ||
|
|
63573ca0de | ||
|
|
bf1a5f0d91 | ||
|
|
1750522cb6 | ||
|
|
ed3b507ea6 | ||
|
|
f942510309 | ||
|
|
09a9153645 | ||
|
|
908d0fcf52 | ||
|
|
707c93a557 | ||
|
|
82addc4f6a | ||
|
|
d595eb440c | ||
|
|
e86fe5bab0 | ||
|
|
7187dca2f7 | ||
|
|
94a3b1f09a | ||
|
|
d88b300a6d | ||
|
|
dd217f82b2 | ||
|
|
3b4cee08e2 | ||
|
|
34be2399eb | ||
|
|
27d879a325 | ||
|
|
4093ef9ffa | ||
|
|
261eebee03 | ||
|
|
d9dad3566a | ||
|
|
3d0fdbd6da | ||
|
|
affa5d390c | ||
|
|
1659e672ae | ||
|
|
0fa6b99c9e | ||
|
|
ef9db7bf78 | ||
|
|
8c6505d870 | ||
|
|
48f83c7d5b | ||
|
|
f3c2c5c084 | ||
|
|
98e1cc3f73 | ||
|
|
4fd74a04c8 | ||
|
|
421594b0eb | ||
|
|
2e79c25da1 | ||
|
|
ca2a313aec | ||
|
|
693315dad3 | ||
|
|
c2f9ef7ca8 | ||
|
|
fc477b98bd | ||
|
|
b8cdfd226a | ||
|
|
a5725d7bd6 | ||
|
|
8995ef6ae2 | ||
|
|
742baa3dad | ||
|
|
3a37bf1e6b | ||
|
|
f4b51f6311 | ||
|
|
a09fc51693 | ||
|
|
1d8b6a79ef | ||
|
|
164a1b6867 | ||
|
|
032f2dc040 | ||
|
|
3dbe33378c | ||
|
|
bb08ac4a28 | ||
|
|
4656d32e22 | ||
|
|
60c982ed95 | ||
|
|
cacafab912 | ||
|
|
99d4806a0d | ||
|
|
59a194a48d | ||
|
|
d818f61dc8 | ||
|
|
f1cbfff5a6 | ||
|
|
92cdc6c840 | ||
|
|
1ff864ea2f | ||
|
|
071b5ba7cb | ||
|
|
2e6d89a093 | ||
|
|
049a1a59f5 | ||
|
|
201098e9f6 | ||
|
|
423227d385 | ||
|
|
c1facd8b1c | ||
|
|
842d371699 | ||
|
|
bcbd4b8d40 | ||
|
|
b526873837 | ||
|
|
6f85c6783e | ||
|
|
672983f6c1 | ||
|
|
3ee3fb05cc | ||
|
|
8ff32d9c1e | ||
|
|
8ad3d35dd2 | ||
|
|
cb5fdc9078 | ||
|
|
77d894dd00 | ||
|
|
5b40d95b0f | ||
|
|
385d157f3f | ||
|
|
81a2a51610 | ||
|
|
ff8383c5ed | ||
|
|
ca9f671553 | ||
|
|
eb17de0888 | ||
|
|
110c9d199d | ||
|
|
b5cc8f193e | ||
|
|
abebe9ef43 | ||
|
|
e55f69a009 | ||
|
|
9bf854445c | ||
|
|
17f7e4b753 | ||
|
|
0a6c6ec4c5 | ||
|
|
7456113cef | ||
|
|
7051e20d59 | ||
|
|
79dba43f0f | ||
|
|
6bb421dac6 | ||
|
|
0ce28c519f | ||
|
|
cdde702db7 | ||
|
|
6b4a76b54b | ||
|
|
57e2a9dc14 | ||
|
|
798f1e6e91 | ||
|
|
0e264a029e | ||
|
|
8745c059f7 | ||
|
|
adee447cd0 | ||
|
|
63c22414ce | ||
|
|
89992ea03e |
+5
-3
@@ -1,3 +1,5 @@
|
||||
19
|
||||
1.4.2
|
||||
1.4.2
|
||||
24
|
||||
1.4.2
|
||||
1.6.2
|
||||
1.11.2
|
||||
1.12.21.17.2
|
||||
@@ -1,3 +1,4 @@
|
||||
.eslintrc.js
|
||||
**/build/*
|
||||
**/coverage/*
|
||||
**/node_modules/*
|
||||
|
||||
@@ -2,110 +2,15 @@ name: PR
|
||||
on: [pull_request]
|
||||
|
||||
jobs:
|
||||
lint:
|
||||
name: Linting
|
||||
runs-on: ubuntu-latest
|
||||
pr:
|
||||
strategy:
|
||||
matrix:
|
||||
node-version: [12.x]
|
||||
steps:
|
||||
- uses: actions/checkout@v1
|
||||
- name: Use Node.js ${{ matrix.node-version }}
|
||||
uses: actions/setup-node@v1
|
||||
with:
|
||||
node-version: ${{ matrix.node-version }}
|
||||
- name: Config yarn cache
|
||||
id: yarn-cache-dir-path
|
||||
run: echo "::set-output name=dir::$(yarn cache dir)"
|
||||
- uses: actions/cache@v1
|
||||
id: yarn-cache
|
||||
with:
|
||||
path: ${{ steps.yarn-cache-dir-path.outputs.dir }}
|
||||
key: ${{ runner.os }}-yarn-${{ hashFiles('**/yarn.lock') }}
|
||||
restore-keys: |
|
||||
${{ runner.os }}-yarn-
|
||||
- name: lint
|
||||
run: |
|
||||
yarn install --immutable | grep -v 'YN0013'
|
||||
yarn lint
|
||||
|
||||
test:
|
||||
name: Testing
|
||||
step: ['lint', 'test', 'build', 'docs']
|
||||
name: ${{ matrix.step }}
|
||||
runs-on: ubuntu-latest
|
||||
strategy:
|
||||
matrix:
|
||||
node-version: [12.x]
|
||||
steps:
|
||||
- uses: actions/checkout@v1
|
||||
- name: Use Node.js ${{ matrix.node-version }}
|
||||
uses: actions/setup-node@v1
|
||||
with:
|
||||
node-version: ${{ matrix.node-version }}
|
||||
- name: Config yarn cache
|
||||
id: yarn-cache-dir-path
|
||||
run: echo "::set-output name=dir::$(yarn cache dir)"
|
||||
- uses: actions/cache@v1
|
||||
id: yarn-cache
|
||||
with:
|
||||
path: ${{ steps.yarn-cache-dir-path.outputs.dir }}
|
||||
key: ${{ runner.os }}-yarn-${{ hashFiles('**/yarn.lock') }}
|
||||
restore-keys: |
|
||||
${{ runner.os }}-yarn-
|
||||
- name: test
|
||||
- name: ${{ matrix.step }}
|
||||
run: |
|
||||
yarn install --immutable | grep -v 'YN0013'
|
||||
yarn test
|
||||
|
||||
build_code:
|
||||
name: Build Code
|
||||
runs-on: ubuntu-latest
|
||||
strategy:
|
||||
matrix:
|
||||
node-version: [12.x]
|
||||
steps:
|
||||
- uses: actions/checkout@v1
|
||||
- name: Use Node.js ${{ matrix.node-version }}
|
||||
uses: actions/setup-node@v1
|
||||
with:
|
||||
node-version: ${{ matrix.node-version }}
|
||||
- name: Config yarn cache
|
||||
id: yarn-cache-dir-path
|
||||
run: echo "::set-output name=dir::$(yarn cache dir)"
|
||||
- uses: actions/cache@v1
|
||||
id: yarn-cache
|
||||
with:
|
||||
path: ${{ steps.yarn-cache-dir-path.outputs.dir }}
|
||||
key: ${{ runner.os }}-yarn-${{ hashFiles('**/yarn.lock') }}
|
||||
restore-keys: |
|
||||
${{ runner.os }}-yarn-
|
||||
- name: build
|
||||
run: |
|
||||
yarn install --immutable | grep -v 'YN0013'
|
||||
yarn build
|
||||
|
||||
build_docs:
|
||||
name: Build Docs
|
||||
runs-on: ubuntu-latest
|
||||
strategy:
|
||||
matrix:
|
||||
node-version: [12.x]
|
||||
steps:
|
||||
- uses: actions/checkout@v1
|
||||
- name: Use Node.js ${{ matrix.node-version }}
|
||||
uses: actions/setup-node@v1
|
||||
with:
|
||||
node-version: ${{ matrix.node-version }}
|
||||
- name: Config yarn cache
|
||||
id: yarn-cache-dir-path
|
||||
run: echo "::set-output name=dir::$(yarn cache dir)"
|
||||
- uses: actions/cache@v1
|
||||
id: yarn-cache
|
||||
with:
|
||||
path: ${{ steps.yarn-cache-dir-path.outputs.dir }}
|
||||
key: ${{ runner.os }}-yarn-${{ hashFiles('**/yarn.lock') }}
|
||||
restore-keys: |
|
||||
${{ runner.os }}-yarn-
|
||||
- name: build
|
||||
run: |
|
||||
yarn install --immutable | grep -v 'YN0013'
|
||||
yarn docs
|
||||
yarn ${{ matrix.step }}
|
||||
|
||||
@@ -5,82 +5,30 @@ on:
|
||||
- master
|
||||
|
||||
jobs:
|
||||
build_code:
|
||||
name: Build Code
|
||||
if: "! contains(github.event.head_commit.message, '[CI Skip]')"
|
||||
runs-on: ubuntu-latest
|
||||
master:
|
||||
strategy:
|
||||
matrix:
|
||||
node-version: [12.x]
|
||||
step: ['build:release', 'docs:release']
|
||||
name: ${{ matrix.step }}
|
||||
if: "! startsWith(github.event.head_commit.message, '[CI Skip]') && github.repository == 'polkadot-js/api'"
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v1
|
||||
with:
|
||||
token: ${{ secrets.GH_PAT }}
|
||||
- name: Use Node.js ${{ matrix.node-version }}
|
||||
uses: actions/setup-node@v1
|
||||
with:
|
||||
node-version: ${{ matrix.node-version }}
|
||||
- name: Config yarn cache
|
||||
id: yarn-cache-dir-path
|
||||
run: echo "::set-output name=dir::$(yarn cache dir)"
|
||||
- uses: actions/cache@v1
|
||||
id: yarn-cache
|
||||
with:
|
||||
path: ${{ steps.yarn-cache-dir-path.outputs.dir }}
|
||||
key: ${{ runner.os }}-yarn-${{ hashFiles('**/yarn.lock') }}
|
||||
restore-keys: |
|
||||
${{ runner.os }}-yarn-
|
||||
- name: build
|
||||
- name: ${{ matrix.step }}
|
||||
env:
|
||||
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 polkadot-ci-ghact-build
|
||||
|
||||
build_docs:
|
||||
name: Build Docs
|
||||
if: "! contains(github.event.head_commit.message, '[CI Skip]')"
|
||||
runs-on: ubuntu-latest
|
||||
strategy:
|
||||
matrix:
|
||||
node-version: [12.x]
|
||||
steps:
|
||||
- uses: actions/checkout@v1
|
||||
- name: Use Node.js ${{ matrix.node-version }}
|
||||
uses: actions/setup-node@v1
|
||||
with:
|
||||
node-version: ${{ matrix.node-version }}
|
||||
- name: Config yarn cache
|
||||
id: yarn-cache-dir-path
|
||||
run: echo "::set-output name=dir::$(yarn cache dir)"
|
||||
- uses: actions/cache@v1
|
||||
id: yarn-cache
|
||||
with:
|
||||
path: ${{ steps.yarn-cache-dir-path.outputs.dir }}
|
||||
key: ${{ runner.os }}-yarn-${{ hashFiles('**/yarn.lock') }}
|
||||
restore-keys: |
|
||||
${{ runner.os }}-yarn-
|
||||
- name: build
|
||||
env:
|
||||
GH_PAT: ${{ secrets.GH_PAT }}
|
||||
GH_TOKEN: ${{ secrets.GH_PAT }}
|
||||
GH_PAGES_SRC: build-docs
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
run: |
|
||||
yarn install --immutable | grep -v 'YN0013'
|
||||
yarn polkadot-ci-ghact-docs
|
||||
yarn ${{ matrix.step }}
|
||||
|
||||
dummy:
|
||||
name: Dummy
|
||||
if: "contains(github.event.head_commit.message, '[CI Skip]')"
|
||||
runs-on: ubuntu-latest
|
||||
strategy:
|
||||
matrix:
|
||||
node-version: [12.x]
|
||||
steps:
|
||||
- name: dummy
|
||||
run: |
|
||||
|
||||
Vendored
-58
File diff suppressed because one or more lines are too long
+56
File diff suppressed because one or more lines are too long
+2
-1
@@ -1,4 +1,5 @@
|
||||
enableImmutableInstalls: false
|
||||
|
||||
enableProgressBars: false
|
||||
|
||||
nodeLinker: node-modules
|
||||
@@ -7,4 +8,4 @@ plugins:
|
||||
- path: .yarn/plugins/@yarnpkg/plugin-interactive-tools.js
|
||||
spec: "@yarnpkg/plugin-interactive-tools"
|
||||
|
||||
yarnPath: .yarn/releases/yarn-berry.js
|
||||
yarnPath: .yarn/releases/yarn-rc.js
|
||||
|
||||
+279
-67
@@ -1,4 +1,216 @@
|
||||
# 1.5.1 Mar 06, 2020
|
||||
# CHANGELOG
|
||||
|
||||
## 1.21.1 Jun 23, 2020
|
||||
|
||||
- Fix subscriptions never unsubscribing after the id swap in 1.18.1 (Thanks to https://github.com/dillu24 for testing iterations)
|
||||
- Add support for `CheckMortality` signed extension (old `CheckEra` is now an alias)
|
||||
- Promise API will default to using `getStorage` on non-subscription calls, reducing RPC overhead
|
||||
- Optimize derive BN allocations, using in-place operators as applicable
|
||||
- Add new substrate types for Babe EquivocationProof
|
||||
- Adjust `Releases` enum to use a shared instance
|
||||
|
||||
## 1.20.1 Jun 22, 2020
|
||||
|
||||
- **Important** RPC for `account_nextIndex` has been moved to `system_accountNextIndex` (Aligning with Substrate as a primary alias)
|
||||
- Cleanup map entries support with only Substrate 2.0-era RPCs (when introduced)
|
||||
- Add `system_dryRun` RPC
|
||||
- Optimize `derive.staking.queryMulti` retrievals with additional per-type batching
|
||||
- Add `derive.staking.waitingInfo` (same as `electedInfo` for waiting validators)
|
||||
- Adjust types & metadata for latest Substrate
|
||||
- `@polkadot/util` 2.15
|
||||
|
||||
## 1.19.1 Jun 16, 2020
|
||||
|
||||
- Improve typing on `.entries()` queries (Thanks to https://github.com/monitz87)
|
||||
- Align metadata and types with latest Substrate
|
||||
- Update Polkadot types for current evolution of parachains
|
||||
- Allow for type aliasing on events (aligning with calls & queries)
|
||||
- `@polkadot/util` 2.14
|
||||
|
||||
## 1.18.1 Jun 8, 2020
|
||||
|
||||
- Expand docs on node-template types (Thanks to https://github.com/g2udevelopment)
|
||||
- Update contract fees to current impl. (Thanks to https://github.com/djuanit0x)
|
||||
- Allow `Option` types in enum/Result type generation (Thanks to http://github.com/xlc)
|
||||
- Add `.entriesPaged` and `.keysPaged` methods for state maps (https://github.com/monitz87)
|
||||
- Add types for new Substrate proxy module
|
||||
- Adjust types for new Substrate (renamed) npos-elections module
|
||||
- `Call` now exposes `method` & `section` fields (aligned with `toHuman()` representation)
|
||||
- Cater for new Substrate string subscription ids (with backwards compatibility)
|
||||
- `@polkadot/util` 2.13
|
||||
|
||||
## 1.17.2 Jun 2, 2020
|
||||
|
||||
- Ensure subscription promise resolves before first result
|
||||
|
||||
## 1.17.1 Jun 2, 2020
|
||||
|
||||
- Fix `ElectionSize` type (Thanks to https://github.com/arjanz)
|
||||
- Allow `BTreeSet` decoding from Array/JSON inputs
|
||||
- Adjust Call-only metadata output to trim documentation to first full line
|
||||
- Safeguard against divide-by-zero for total era points (expired reward eras)
|
||||
- Internal derive optimizations with combining calls
|
||||
- Support for latest Substrate types & metadata
|
||||
- `@polkadot/util` 2.12
|
||||
|
||||
## 1.16.1 May 26, 2020
|
||||
|
||||
- Support for Polkadot CC1 types & signed extensions
|
||||
- Add support for Babe VRF secondary digests (author extraction)
|
||||
- Adjust `Perbill/Permill` `toHuman()` formatting to output percentage
|
||||
- Support for latest Substrate types & metadata
|
||||
- Update to latest TypeScript, eslint & typescript-eslint
|
||||
- `@polkadot/util` 2.11
|
||||
|
||||
## 1.15.1 May 23, 2020
|
||||
|
||||
- Adjust `keyPrefix()` with DoubleMap args (Thanks to https://github.com/KiChjang)
|
||||
- Added `WeightToFeeCoefficient` type (Thanks to https://github.com/danforbes)
|
||||
- Spelling fixes for console logs (Thanks to https://github.com/JoshOrndorff)
|
||||
- Spelling fixes in cookbook (Thanks to https://github.com/pawelnguyen)
|
||||
- Add `transactionVersion` getter in payloads (Thanks to https://github.com/amaurymartiny)
|
||||
- Adjust `stakerRewards` derive ordering for improved on-payout refreshes
|
||||
- Baseline implementation for derive caching infrastructure
|
||||
- Adjust `Multiplier` type to `Fixed128` (as per latest Substrate)
|
||||
- Updated to latest Substrate metadata & add new types
|
||||
|
||||
## 1.14.1 May 14, 2020
|
||||
|
||||
- **Important** `DispatchInfo` changed `paysFee` to an enum, if using an older version use, `DispatchInfo: 'DispatchInfoTo244'`
|
||||
- Align imOnline `Heartbeat` with Substrate (Thanks to https://github.com/arjanz)
|
||||
- Adust EVM types to include `Vicinity` (Thanks to https://github.com/drewstone)
|
||||
- Add `derive.democracy.locks` to return extended lock info based on votes
|
||||
- Ensure metadata is only requested once upon startup (bypass on upgrade subscriptions)
|
||||
- Expand testing around `ExtrinsicEra` construction
|
||||
- Expand `Registry` to direct access to available signed extensions (in addition to exposed types)
|
||||
- Cater for new `CheckSpecVersion` and `CheckTxVersion` signed extensions (with `SignerPayload` adjustments)
|
||||
- Cater for new `PrevalidateAttests` signed extensions (Polkadot claims)
|
||||
- Don't re-calculate submittable extrinsic hash on status checks (optimization)
|
||||
- Support for both old/new Tuples in `democracy.depositOf` in derives
|
||||
- Fix democracy `ProxyState` types
|
||||
- Extends types for Polkadot claims
|
||||
- Update `@polkadot/util` to 2.10
|
||||
|
||||
## 1.13.1 May 6, 2020
|
||||
|
||||
- Add support for ECDSA keypairs in extrinsic signers (Thanks to https://github.com/akru)
|
||||
- Rework type generation to use templating for better maintenance (Thanks to https://github.com/xlc)
|
||||
- Adjust extrinsic `sign/signAsync` signature to optional options (Thanks to https://github.com/KiChjang)
|
||||
- Support round-robin endpoints in the `WsProvider` with array of urls (Thanks to https://github.com/hoani)
|
||||
- Remove static test-only metadata for Polkadot dev chains (not updated regularly, Substrate dev to remain)
|
||||
- Revert error swallow for wrong preimage data (temp. override for Kusama upgrade with no migration)
|
||||
- Fix `.encodedLength` calculation on `[Type; N]` types
|
||||
- Add new `rpc.grandpa.roundState` RPC
|
||||
- Update types & metadata as per latest Substrate master
|
||||
- Adjust Centrifuge starting version
|
||||
|
||||
## 1.12.2 Apr 30, 2020
|
||||
|
||||
- Update `@polkadot/util` to stable 2.9.1 (sadly missed in the previous version, stable should match to stable)
|
||||
|
||||
## 1.12.1 Apr 29, 2020
|
||||
|
||||
- Fix `CompactAssignments` types (Thanks to https://github.com/arjanz)
|
||||
- Provider ayo-connect now allows for interval config (Thanks to https://github.com/jnaviask)
|
||||
- Cleanup generation for c-like enums (Thanks to https://github.com/monitz87)
|
||||
- Allow subscription to all storage keys, alignment with Substrate (Thanks to https://github.com/xlc)
|
||||
- Cater for vote delegations in democracy derives
|
||||
- Cleanup account derive flags where to allow for optional council modules
|
||||
- Allow generic types in ApiPromise.combineLatest
|
||||
- Update to latest substrate metadata
|
||||
|
||||
## 1.11.2 Apr 22, 2020
|
||||
|
||||
- Small patch to add missing Polkadot master types (will be in next Kusama update)
|
||||
|
||||
## 1.11.1 Apr 21, 2020
|
||||
|
||||
- **Important** Substrate master has an updated `Weight` (to `u64`), on older chains apply `Weight: 'u32'` (This does affect event decoding if wrongly set)
|
||||
- Allow user type augmentation to work with different versions of rxjs (Thanks to https://github.com/monitz87)
|
||||
- Align augmented generation with camelCase (Thanks to https://github.com/monitz87)
|
||||
- Fix bitfield endian encoding (Thanks to investigation by https://github.com/xlc)
|
||||
- Add account flag derives via `accounts.flags(accountId)` (Thanks to https://github.com/kwingram25)
|
||||
- Fix entries decoding for `Option<Number>` (& simplify, decoding correctly on rpc layer)
|
||||
- Add `system.{localPeerId, localListenAddresses}` & `state.getReadProof` RPCs
|
||||
- Ensure proper propagation of `api.runtimeVersion` (used for signing) after upgrade
|
||||
- Field ordering fix for deprecated `Linkage` (used in linked maps)
|
||||
- `derive.account.info` now returns all field enum types decoded (not only raw)
|
||||
- Add banner with FAQ entries for node-template to aid with common issues
|
||||
- `Digest` has been moved to definitions, removal of `GenericDigest` type
|
||||
- Support `Fixed128` type
|
||||
- Add `transactionVersion` to `RuntimeVersion` struct
|
||||
- Enhance API support for non-subscription providers (skip subscription to runtimeVersion)
|
||||
- Adjust types for Kusama 1057 (notably the new `StakingLedger`)
|
||||
|
||||
## 1.10.1 Apr 13, 2020
|
||||
|
||||
- **Important** Substrate master has updated staking, on older chains apply `StakingLedger: 'StakingLedgerTo240'`
|
||||
- Add `rpc.system.chainType` to retrieve the chain type (Development. Local, Live & Custom)
|
||||
- Adjust types for Westend after the reset
|
||||
- Adjust democracy derives, including the support of the frame-scheduler for scheduled deployments
|
||||
- Allow staking derives to work with new staking payouts, specifically `tx.staking.payoutStakers`
|
||||
- Cleanups to derives for democracy & staking to be more performant
|
||||
- Add Centrifuge base types to `@polkadot/types-known`
|
||||
- Adjust with all the latest substrate master types
|
||||
- Internally all private/protected methods/variables are now `_` prefixed (Aligning with the `private/protected` indicators in the TS definitions)
|
||||
- Update metadata/docs-from-metadata to the latest Substrate
|
||||
|
||||
## 1.9.1 Apr 1, 2020
|
||||
|
||||
- **Breaking change** (TypeScript with derives only) The return type names for `api.derive.*` have been adjusted for consistency, all starting with `Derive*` (previously a mixture of `Derived*` and `Derive*`)
|
||||
- **Breaking change** (derives only) Additional cleanups of democracy proposal & referenda derives, including support for new Polkadot/Substrate vote retrievals
|
||||
- Tx signing via `signAndSend` & `signAsync` now tries to use the last finalized block (depending on finalized drift)
|
||||
- Add support for `api.rpc.childstate.*` Substrate RPCs, older nodes with still populate `api.rpc.state.*` with the child methods
|
||||
- Adjust `Error.message` on RPC failures to not include the (already known) method signature
|
||||
- Split `@polkadot/types/known` into `@polkadot/types-known`, allowing for base API overrides
|
||||
- Extended `api.derive.democracy` to cater for dispatchQueue and externals
|
||||
- Extended `api.derive.council` to cater for new phragmen elections
|
||||
- Use new `queryStorageAt` for query `.entries`, removing unneeded subscriptions (use as available)
|
||||
- Fix `BTreeSet` initialization when it forms part of query interfaces
|
||||
- Fix encoding for `Vec<u8>`-related types as part of constants
|
||||
- Internal adjustment of interface type locations (no impact on imports via `@polkadot/types/interfaces`)
|
||||
|
||||
## 1.8.1 Mar 22, 2020
|
||||
|
||||
- **Breaking change** The format for any custom RPCs have been changed (alongside API-internal changes) to allow for better RPC management. If you are currently using custom RPCs (or planning to do so), look at the [updated documentation](https://polkadot.js.org/api/start/rpc.custom.html)
|
||||
- **Breaking change** Alongside API RPC changes, the `@polkadot/jsonrpc` package has been removed. Since it was never documented and only used internally, this should not have adverse impacts. All RPC definitions itself has now been moved to the relevant modules inside `@polkadot/types/interfaces`
|
||||
- **Important** Substrate has an updated democracy module. If using an older chain add the `ReferendumInfo: 'ReferendumInfoTo239'` type when using referendums
|
||||
- The `isRetracted` Extrinsic status is now a warning, not a fatal error, correctly aligning with Polkadot/Substrate
|
||||
- The Substrate extrinsic phase definitions has been expanded with `Initialization` to align with the latest versions
|
||||
- Add support for all known substrate RPC methods
|
||||
- Extend account derives to include status flags, e.g. `isCouncil`, `isSudo`, ...
|
||||
- Adjusted referendum derives to cater for bot new/old democracy. Derived `referendumInfo` now includes `status` field, not `info`
|
||||
- Add `initWasm` flag to API options. When set to `false` does not init the WASM portion (leaving it to the user elsewhere)
|
||||
|
||||
## 1.7.1 Mar 17, 2020
|
||||
|
||||
- **Important** Current versions of Polkadot/Substrate have dropped support for linked maps on storage entries. If you are using these queries to retrieve all entries, for instance `staking.{nominators,validators}()` and using an upgraded chain, you need to swap to retrieving entries via `.entries()` or `.keys()` for the keys.
|
||||
- Pull in support and types for latest Polkadot/Substrate
|
||||
- Add support for the new Substrate `state_getKeysPaged` RPC, including use in storage keys
|
||||
- Move `derive.staking.controllers` to `derive.staking.stashes`, reflecting actual content
|
||||
- Cater for adjusted storage (non-linked mapped) for `derive.staking.stashes` queries (with old-compat)
|
||||
- Expanded `derive.staking.*` derives, including addition of `derive.staking.own*`
|
||||
- Re-add fixed (with tests) checks for query args, previously disabled in 1.6.2
|
||||
|
||||
## 1.6.2 Mar 12, 2020
|
||||
|
||||
- Revert checks for query args, not working on `.at()` queries (proper fix in next version)
|
||||
|
||||
## 1.6.1 Mar 12, 2020
|
||||
|
||||
- **Breaking change** `api.rpc.state.queryStorage(...)` now fully decodes the `Vec<StorageChangeSet>` and returns a decoded `[Hash, Codec[]][]` when using this RPC.
|
||||
- `StorageKey` now has an `.args` property, decoded from meta where `twox64_concat` or `blake128_concat` are used on maps
|
||||
- Fix `api.query.*.*.entries` type conversions to return exact types (not `Option` in some cases)
|
||||
- Add `api.query.*.*.keys` to retrieve only the storage keys, similar to `.entries`
|
||||
- Full linked map retrievals will now use direct getStorage queries for faster operation
|
||||
- Underlying rpc-core interfaces now unwraps `Error("...")` when found in responses
|
||||
- Added `derive.eras*` interfaces for queries to new Substrate staking interfaces
|
||||
- Update `derive.account` to cater for new indices module storage (detected with fallbacks)
|
||||
- Adjust derive queries for session without module prefix (DoubleMap -> Map), detected on use
|
||||
- Add runtime validation for map arguments to `api.query.*`
|
||||
- TypeScript interfaces for linked maps now correctly generates as `[Type, Linkage<Next>]`
|
||||
|
||||
## 1.5.1 Mar 06, 2020
|
||||
|
||||
- **Important** Substrate master has updated staking, on older chains supply `StakingLedger: 'StakingLedgerTo223'`
|
||||
- **Important** Substrate master has updated collective, on older chains supply `Votes: 'VotesTo230'`
|
||||
@@ -18,11 +230,11 @@
|
||||
- Add additional derives to `api.derive.staking` to handle lazy-payout retrievals
|
||||
- Update `@polkadot/{util, util-crypto, keyring}` to 1.6.1 & `@polkadot/wasm` to 1.2.1
|
||||
|
||||
# 1.4.2 Feb 27, 2020
|
||||
## 1.4.2 Feb 27, 2020
|
||||
|
||||
- Fix `api.tx(<extrinsic>): Submittable` decoration (non-working in 1.4.1, now with proper test)
|
||||
|
||||
# 1.4.1 Feb 26, 2020
|
||||
## 1.4.1 Feb 26, 2020
|
||||
|
||||
- **Breaking change** (TypeScript only) The `*.d.ts` files now contain TypeScript 3.8 features (specifically `#private`), which is not usable in TS versions < 3.8
|
||||
- **Breaking change** - `api.derive.staking.*` has updated result types and detects support for lazy payouts queries
|
||||
@@ -48,7 +260,7 @@
|
||||
- Cleanup augmentation and generation scripts for type definitions, aligning with api augmentation
|
||||
- Bump to `@polkadot/{util, util-crypto, keyring}` 2.5.1
|
||||
|
||||
# 1.3.1 Feb 18, 2020
|
||||
## 1.3.1 Feb 18, 2020
|
||||
|
||||
- Add `@types/bn.js` as a normal dependency, exposed in `*.d.ts` (Thanks to https://github.com/monitz87)
|
||||
- Type generation scripts (including `polkadot-types-from-{chain,defs}`) has been moved to the `@polkadot/typegen` package
|
||||
@@ -56,7 +268,7 @@
|
||||
- Expose chain properties on registry (and use for API type formatting)
|
||||
- Add `toHuman(isExtended?: boolean)` to all codec types, formatting into a human-readable structure
|
||||
|
||||
# 1.2.1 Feb 16, 2020
|
||||
## 1.2.1 Feb 16, 2020
|
||||
|
||||
- **Important** Update RPC status codes (latest Substrate 2), with the `isInBlock` (`isFinalized` now indicates finality)
|
||||
- Storage `.entries(arg?: any)` now has the correct argument type for DoubleMap (Thanks to https://github.com/monitz87)
|
||||
@@ -74,7 +286,7 @@
|
||||
- Cleanup `codec/Date` tests to make it run properly on all timezones
|
||||
- Add explicit dependencies to all packages and move TypeScript `@types/*` to dev deps
|
||||
|
||||
# 1.1.1 Feb 06, 2020
|
||||
## 1.1.1 Feb 06, 2020
|
||||
|
||||
- **Important** Chains without `balances.account` or `system.account` should supply `"BalanceLock": "BalanceLockTo212"` to their types to use the previous-generation `BalanceLock` (when querying locks)
|
||||
- Add support for `balances.account` in all applicable derives (incl. `vesting` module)
|
||||
@@ -88,7 +300,7 @@
|
||||
- Adjust balances fees derivation with optional transfer and creation fees (removed in Substrate)
|
||||
- Adjust enum `.toJSON()` to return type name as specified
|
||||
|
||||
# 1.0.1 Jan 30, 2020
|
||||
## 1.0.1 Jan 30, 2020
|
||||
|
||||
- **Breaking change** Drop support for Substrate v1 chain in all derives
|
||||
- Return unsub functions from provider .on emitters (Thanks to https://github.com/jak-pan)
|
||||
@@ -107,7 +319,7 @@
|
||||
- Remove support for un-deployed metadata
|
||||
- Remove old known types for Substrate V1
|
||||
|
||||
# 0.100.1 Jan 13, 2020
|
||||
## 0.100.1 Jan 13, 2020
|
||||
|
||||
- **Important** This will the the last API version with Substrate 1.x support. Although you will still be able to use subsequent versions with older chains, dependent libraries such as sr25519 may not be compatible.
|
||||
- Add support for the Substrate identity module
|
||||
@@ -118,7 +330,7 @@
|
||||
- Add support for latest Polkadot/Substrate types
|
||||
- Add `paymentInfo` to submittables to calculate fees
|
||||
|
||||
# 0.99.1 Dec 13, 2019
|
||||
## 0.99.1 Dec 13, 2019
|
||||
|
||||
- **Breaking change** The `Data` and `U8a` type has been renamed and just replaced with the `Raw` type
|
||||
- **Breaking change** The `api.derive.staking.info` has been split into 2 - `staking.query` for non-balance related information (more effective) and `staking.account` that enhances query for all the information previously found `.info`
|
||||
@@ -127,7 +339,7 @@
|
||||
- Add additional derives for both council & treasury
|
||||
- Alignment with latest Polkadot/Substrate master branch types
|
||||
|
||||
# 0.98.1 Dec 04, 2019
|
||||
## 0.98.1 Dec 04, 2019
|
||||
|
||||
- Make the TypeScript generation script mor re-usable (Thanks to https://github.com/xlc)
|
||||
- Add `.entries()` for all map-types, returning storage keys and values
|
||||
@@ -136,7 +348,7 @@
|
||||
- Support for new Substrate democracy with preimages in derive
|
||||
- Alignment of types with Substrate/Polkadot master branches
|
||||
|
||||
# 0.97.1 Nov 29, 2019
|
||||
## 0.97.1 Nov 29, 2019
|
||||
|
||||
- **Breaking change** Add the passing on an explicit `Registry` to all calls to `createType` as well as all codec classes. If you are upgrading form an older version, use the [migration guide](UPGRADING.md) to walk through the changes required.
|
||||
- **Breaking change** The metadata classes have been moved from `@polkadot/types` into `@polkadot/metadata`. If you explicitly create `Metadata` classes, you now would need to do so with the `import Metadata from '@polkadot/metadata';` This is a decorated class, where the previous metadata is now available on `Metadata.metadata`, alongside decorated `consts.*`', `tx.*` and `query.*`.
|
||||
@@ -148,7 +360,7 @@
|
||||
- Support for Metadata V9, which adjusts the hashing methods of storage entries
|
||||
- Support for Metadata V10 (still un-released), which includes prefixed map support
|
||||
|
||||
# 0.96.1 Nov 09, 2019
|
||||
## 0.96.1 Nov 09, 2019
|
||||
|
||||
- Updated types for latest Kusama
|
||||
- Add `filterRecords` (in addition to `findRecord`) on submittable results
|
||||
@@ -158,11 +370,11 @@
|
||||
- Update council derives for the latest Substrate master support (with constants)
|
||||
- Derive cleanups, including sharing of instances between the API and internal to derives
|
||||
|
||||
# 0.95.2 Oct 25, 2019
|
||||
## 0.95.2 Oct 25, 2019
|
||||
|
||||
- Temporary removal of `account_nextIndex` use, will be re-added in a future release
|
||||
|
||||
# 0.95.1 Oct 25, 2019
|
||||
## 0.95.1 Oct 25, 2019
|
||||
|
||||
- Support Extrinsic V4 with additional signature indicator (Latest Polkadot/Substrate/Kusama)
|
||||
- Adjust subscription update checks to avoid duplicated data updates
|
||||
@@ -172,7 +384,7 @@
|
||||
- All latest Polkadot & Substrate types (as per master branches)
|
||||
- **Breaking change** `Call.injectMethods` is moved to `Call.injectMetadata` to align with `Events` (This _should_ not be used externally, however mentioned as breaking here)
|
||||
|
||||
# 0.94.1 Oct 07, 2019
|
||||
## 0.94.1 Oct 07, 2019
|
||||
|
||||
- Add handling of `Result<Ok, Error>` definitions
|
||||
- Adjust API cloning now takes RPC filters from source into account
|
||||
@@ -184,7 +396,7 @@
|
||||
- Add documentation for custom extrinsic formats (advanced chains)
|
||||
- Update to latest substrate master metadata
|
||||
|
||||
# 0.93.1 Sep 26, 2019
|
||||
## 0.93.1 Sep 26, 2019
|
||||
|
||||
- Support for Kusama CC2
|
||||
- In extrinsic submission, use `rpc.account.nextIndex` to retrieve the nonce when available
|
||||
@@ -194,7 +406,7 @@
|
||||
- Support recursive type registration (self-referencing via `Box`) in addition to better sanitation of user-defined-types
|
||||
- Documentation and example updates (thanks mostly to contributions)
|
||||
|
||||
# 0.92.1 Sep 12, 2019
|
||||
## 0.92.1 Sep 12, 2019
|
||||
|
||||
- The API now correctly sets the ss58 prefix as retrieved from the chain properties via `ss58Format`
|
||||
- Bump to `@polkadot/util` 1.4.1, removing use of `ExtError`
|
||||
@@ -202,7 +414,7 @@
|
||||
- Support the latest Polkadot & Substrate master branches (incl. metadata updates)
|
||||
- Getting started documentation has been made available
|
||||
|
||||
# 0.91.1 Sep 09, 2019
|
||||
## 0.91.1 Sep 09, 2019
|
||||
|
||||
- This release was focussed on stability, with a number of cleanups and bug-fixes
|
||||
- Adjustments for Substrate 1.x chain detection (with auto-types) and Substrate 2.x support has been extended with all latest types
|
||||
@@ -216,7 +428,7 @@
|
||||
- **Breaking change** `SignerPayload` is renamed to `SignerPayloadJSON`
|
||||
- **Breaking change** `SignerPayloadJSON`, `SignerPayloadRawBase` and `SignerPayloadRaw` are all moved to `@polkadot/types`
|
||||
|
||||
# 0.90.1 Aug 24, 2019
|
||||
## 0.90.1 Aug 24, 2019
|
||||
|
||||
If you are upgrading form an older version, use the CHANGELOG hand-in-hand with the [migration guide](UPGRADING.md).
|
||||
|
||||
@@ -234,7 +446,7 @@ If you are upgrading form an older version, use the CHANGELOG hand-in-hand with
|
||||
- The `types/codec/createType` has been moved to `types/codec/create` with the same exports. If you explicitly imported from here (and not doing the suggested `import { createType } from '@polkadot/types`), the reference needs to be updated
|
||||
|
||||
|
||||
# 0.82.0-beta.x Jul 28, 2019
|
||||
## 0.82.0-beta.x Jul 28, 2019
|
||||
|
||||
- Support for substrate 2.x (master) has been extended,
|
||||
- Additional types have been addedd for the modules
|
||||
@@ -253,7 +465,7 @@ If you are upgrading form an older version, use the CHANGELOG hand-in-hand with
|
||||
- The `ContractsAbi` type has been moved from `@polkadot/types` to `import { Abi } from '@polkadot/api-contract`. This paves the way for an enhanced contracts interface, instead of dealing with low-level API calls.
|
||||
|
||||
|
||||
# 0.81.1 Jun 14, 2019
|
||||
## 0.81.1 Jun 14, 2019
|
||||
|
||||
- The dependency on `@polkadot/keyring` has been removed - if you relied on the API to provide this, you would now need to manually add it
|
||||
- `createType` allows for the creation of `[u8; <length>]` types (opening the door for contract support)
|
||||
@@ -273,7 +485,7 @@ If you are upgrading form an older version, use the CHANGELOG hand-in-hand with
|
||||
- Add `off` method to `Api` (Base, for both `ApiPromise` & `ApiRx`) to remove an event listener
|
||||
|
||||
|
||||
# 0.80.1 Jun 04, 2019
|
||||
## 0.80.1 Jun 04, 2019
|
||||
|
||||
- Support for mortal transactions
|
||||
- Better DoubleMap storage support
|
||||
@@ -283,7 +495,7 @@ If you are upgrading form an older version, use the CHANGELOG hand-in-hand with
|
||||
- Misc. cleanups and fixes
|
||||
|
||||
|
||||
# 0.79.1 May 22, 2019
|
||||
## 0.79.1 May 22, 2019
|
||||
|
||||
- DoubleMap query support
|
||||
- Support latest EventRecord metadata (substrate master)
|
||||
@@ -295,7 +507,7 @@ If you are upgrading form an older version, use the CHANGELOG hand-in-hand with
|
||||
- Add `toRawType` on all type classes (breakdown into primitive types)
|
||||
|
||||
|
||||
# 0.78.1 May 08, 2019
|
||||
## 0.78.1 May 08, 2019
|
||||
|
||||
- Fix linked-maps (not working since 0.77.1)
|
||||
- Convert Usize to U32 (as found in WASM environments)
|
||||
@@ -306,13 +518,13 @@ If you are upgrading form an older version, use the CHANGELOG hand-in-hand with
|
||||
- Metadata updates for substrate (WithdrawReasons, ContractInfo)
|
||||
|
||||
|
||||
# 0.77.1 Apr 25, 2019
|
||||
## 0.77.1 Apr 25, 2019
|
||||
|
||||
- Support Metadata v4, which introduces the use of a custom hasher to hash storage map keys.
|
||||
- Add TreasuryProposal (not the same as democracy, type aliased)
|
||||
|
||||
|
||||
# 0.76.1 Apr 03, 2019
|
||||
## 0.76.1 Apr 03, 2019
|
||||
|
||||
- Caching improvements (duplicate queries, no duplicate subscriptions)
|
||||
- Experimental contract API
|
||||
@@ -320,12 +532,12 @@ If you are upgrading form an older version, use the CHANGELOG hand-in-hand with
|
||||
- Update @polkadot/util-crypto with smaller footprint
|
||||
|
||||
|
||||
# 0.75.1 Mar 29, 2019
|
||||
## 0.75.1 Mar 29, 2019
|
||||
|
||||
- Start journey to 1.0
|
||||
|
||||
|
||||
# 0.53.1 Mar 29, 2019
|
||||
## 0.53.1 Mar 29, 2019
|
||||
|
||||
- Change spelling to US English as per substrate master (1.0-rc1). Breaking changes as a result:
|
||||
- For extrinsic status results, if you have checked the type returns, i.e. `result.type === 'Finalised'` now check on the status for `result.status.isFinalized` or `result.status.isBroadcast`, ... (the `type` property is now accessible only on `result.status.type`)
|
||||
@@ -336,7 +548,7 @@ If you are upgrading form an older version, use the CHANGELOG hand-in-hand with
|
||||
- All examples have been updated with sr25519 addresses (with the new checksums)
|
||||
|
||||
|
||||
# 0.52.1 Mar 28, 2019
|
||||
## 0.52.1 Mar 28, 2019
|
||||
|
||||
- Support queries to linked mapped storage (found in new staking interfaces)
|
||||
- Add `derive.staking.controllers` to retrieve all active staking controllers
|
||||
@@ -346,42 +558,42 @@ If you are upgrading form an older version, use the CHANGELOG hand-in-hand with
|
||||
- Check for single instances for api and types as they are loaded (assertSingletonPackage)
|
||||
|
||||
|
||||
# 0.51.1 Mar 25, 2019
|
||||
## 0.51.1 Mar 25, 2019
|
||||
|
||||
- Support metadata V2 as per latest substrate master
|
||||
- Update metadata with new types as per latest substrate master
|
||||
|
||||
|
||||
# 0.50.1 Mar 23, 2019
|
||||
## 0.50.1 Mar 23, 2019
|
||||
|
||||
- Latest util-crypto (usage of WASM with JS fallbacks if not available)
|
||||
- Update upstream @polkadot dependencies (for new crypto)
|
||||
|
||||
|
||||
# 0.49.1 Mar 20, 2019
|
||||
## 0.49.1 Mar 20, 2019
|
||||
|
||||
- Fix large message signing on non-known nodes (default is now hashing, there has been enough time between upgrades)
|
||||
|
||||
|
||||
# 0.48.1 Mar 18, 2019
|
||||
## 0.48.1 Mar 18, 2019
|
||||
|
||||
- Pull in new sr25519 capable keyring for dev nodes
|
||||
- When using dev mode, it assumes that the node is the latest with derived sr25519 keys
|
||||
|
||||
|
||||
# 0.47.1 Mar 14, 2019
|
||||
## 0.47.1 Mar 14, 2019
|
||||
|
||||
- Swap to publishing -beta.x on merge (non-breaking testing)
|
||||
|
||||
|
||||
# 0.46.1 Mar 01, 2019
|
||||
## 0.46.1 Mar 01, 2019
|
||||
|
||||
- Extended type registration to now handle internal types as well. Additionally the built-in Extrinsic type can now we overridden with a custom version.
|
||||
- Where `Extrinsic` and `Method` is used as types, consider importing `{ IMethod, IExtrinsic }` from `@polkadot/types/types`, especially in the cases where this is used from a `SubmittableExtrinsic`
|
||||
- The `typeRegistry` constant is now `getTypeRegistry()` as a function
|
||||
|
||||
|
||||
# 0.45.1 Feb 19, 2019
|
||||
## 0.45.1 Feb 19, 2019
|
||||
|
||||
- Storage with option values now correctly return `Option<Type>` and is indicated as such in the documentation
|
||||
|
||||
@@ -398,7 +610,7 @@ console.log('llo', llo.unwrapOr('not set') /* Option<BlockNumber> */)
|
||||
```
|
||||
|
||||
|
||||
# 0.44.1 Feb 19, 2019
|
||||
## 0.44.1 Feb 19, 2019
|
||||
|
||||
- Split primitives and types into separate folders. This should not affect external use since the exports remain the same, however does have an impact where classes are referenced directly. e.g.
|
||||
|
||||
@@ -416,45 +628,45 @@ import { Method, Signature } from '@polkadot/types';
|
||||
```
|
||||
|
||||
|
||||
# 0.43.1 Feb 14, 2019
|
||||
## 0.43.1 Feb 14, 2019
|
||||
|
||||
- Introduces support for the new keyring with sr25519 support in addition to ed25519. While this does not change the exposed API, it is considered breaking since @polkadot/keyring has interface changes. (Unless needed, don't rush the upgrade)
|
||||
|
||||
|
||||
# 0.42.1 Jan 31, 2019
|
||||
## 0.42.1 Jan 31, 2019
|
||||
|
||||
- Support for substrate hash signing with implVersion >= 18
|
||||
- Changed signatures for Extrinsic signing, this should not have (much) of an impact since it is generally not used directly. SubmittableExtrinsic (as exposed by the API), supports the old-style use.
|
||||
|
||||
|
||||
# 0.41.1 Jan 26, 2019
|
||||
## 0.41.1 Jan 26, 2019
|
||||
|
||||
- Support the V1 metadata specification from Substrate in addition to the currently testnet active V0 version
|
||||
|
||||
|
||||
# 0.40.1 Jan 16, 2019
|
||||
## 0.40.1 Jan 16, 2019
|
||||
|
||||
- The API interfaces now require a WS-compatible provider, e.g. subscription support is a must. Previously the HTTPProvider could be use (although it was very limited in the interactions).
|
||||
|
||||
|
||||
# 0.39.1 Jan 11, 2019
|
||||
## 0.39.1 Jan 11, 2019
|
||||
|
||||
- The Promise API now returns a `Promise<UnsubFunction>` instead of `UnsubFunction` when making subscriptions.
|
||||
|
||||
|
||||
# 0.38.1 Jan 08, 2019
|
||||
## 0.38.1 Jan 08, 2019
|
||||
|
||||
Substrate has been updated with a breaking new transaction format where the Index/Nonce is now encoded as a Compact. This change is being rolled out to both Alexander (Polkadot testnet) as well as Charred Cherry (Substrate testnet) - transactions between old and new are not compatible.
|
||||
|
||||
|
||||
# 0.37.1 Jan 04, 2019
|
||||
## 0.37.1 Jan 04, 2019
|
||||
|
||||
api-observable has been removed. This was only used in /apps and inconsistent with the api/rx and api/promise APIs. Future work will include derives like was included in api-observable into the base.
|
||||
|
||||
Tuples now return single types when only one type is available, i.e. `(AccountId)` would now resolve as `AccountId`. The extra type wrapper adds no benefit to users here.
|
||||
|
||||
|
||||
# 0.36.1 Jan 03, 2019
|
||||
## 0.36.1 Jan 03, 2019
|
||||
|
||||
Api Promise has been updated in the way we deal with subscriptions. Previously a subscription returned `Promise<number>` where the caller was to keep track of the id and use it in subsequent unsubscribes. Now any subscriptions return an unsubscribe/destroy function `(): void`, that is use for removing the subscriptions, e.g.
|
||||
|
||||
@@ -465,51 +677,51 @@ unsubscribe(); // here we destroy the subscription
|
||||
```
|
||||
|
||||
|
||||
# 0.35.1 Dec 20, 2018
|
||||
## 0.35.1 Dec 20, 2018
|
||||
|
||||
Swapped to new metadata structures from Substrate. If the API is not working with your node, update Substrate to latest master branch. (Or 0.9.1 for Charred Cherry). Dropped support for old metadata as found as far back as BBQ Birch.
|
||||
|
||||
|
||||
# 0.34.1 Dec 18, 2018
|
||||
## 0.34.1 Dec 18, 2018
|
||||
|
||||
Changed the send signature (for future expansion of eg. events) to return `result: { status: ExtrinsicStatus }` instead of `status: ExtrinsicStatus`. For most cases where only status `type` checks are used, i.e. `status.type === 'Finalised'` this should not be a breaking change. Deep inspection of the status object however will need to adapt.
|
||||
|
||||
# 0.33.1 Dec 06, 2018
|
||||
## 0.33.1 Dec 06, 2018
|
||||
|
||||
# 0.32.1 Nov 21, 2018
|
||||
## 0.32.1 Nov 21, 2018
|
||||
|
||||
# 0.31.1 Oct 10, 2018
|
||||
## 0.31.1 Oct 10, 2018
|
||||
|
||||
# 0.30.1 Sep 27, 2018
|
||||
## 0.30.1 Sep 27, 2018
|
||||
|
||||
# 0.29.1 Sep 14, 2018
|
||||
## 0.29.1 Sep 14, 2018
|
||||
|
||||
# 0.28.1 Aug 11, 2018
|
||||
## 0.28.1 Aug 11, 2018
|
||||
|
||||
# 0.15.1 Aug 07, 2018
|
||||
## 0.15.1 Aug 07, 2018
|
||||
|
||||
# 0.14.1 Jun 23, 2018
|
||||
## 0.14.1 Jun 23, 2018
|
||||
|
||||
# 0.13.1 May 29, 2018
|
||||
## 0.13.1 May 29, 2018
|
||||
|
||||
# 0.12.1 May 18, 2018
|
||||
## 0.12.1 May 18, 2018
|
||||
|
||||
# 0.11.1 May 16, 2018
|
||||
## 0.11.1 May 16, 2018
|
||||
|
||||
# 0.10.1 May 07, 2018
|
||||
## 0.10.1 May 07, 2018
|
||||
|
||||
# 0.9.1 Apr 24, 2018
|
||||
## 0.9.1 Apr 24, 2018
|
||||
|
||||
# 0.8.1 Mar 15, 2018
|
||||
## 0.8.1 Mar 15, 2018
|
||||
|
||||
# 0.7.1 Jan 25, 2018
|
||||
## 0.7.1 Jan 25, 2018
|
||||
|
||||
# 0.6.1 Dec 03, 2017
|
||||
## 0.6.1 Dec 03, 2017
|
||||
|
||||
# 0.5.1 Nov 28, 2017
|
||||
## 0.5.1 Nov 28, 2017
|
||||
|
||||
# 0.4.1 Nov 19, 2017
|
||||
## 0.4.1 Nov 19, 2017
|
||||
|
||||
# 0.3.1 Nov 19, 2017
|
||||
## 0.3.1 Nov 19, 2017
|
||||
|
||||
# 0.2.1 Nov 18, 2017
|
||||
## 0.2.1 Nov 18, 2017
|
||||
|
||||
@@ -1 +1,5 @@
|
||||
// Copyright 2017-2020 @polkadot/api authors & contributors
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the Apache-2.0 license. See the LICENSE file for details.
|
||||
|
||||
module.exports = require('@polkadot/dev/config/babel');
|
||||
|
||||
+2
-2
@@ -1,4 +1,4 @@
|
||||
#!/bin/bash
|
||||
#!/usr/bin/env bash
|
||||
|
||||
function copy_folder () {
|
||||
SRC="packages/$1/build"
|
||||
@@ -18,6 +18,6 @@ copy_folder "api-derive"
|
||||
copy_folder "metadata"
|
||||
copy_folder "rpc-core"
|
||||
copy_folder "rpc-provider"
|
||||
copy_folder "jsonrpc"
|
||||
copy_folder "types"
|
||||
copy_folder "types-known"
|
||||
copy_folder "typegen"
|
||||
|
||||
@@ -20,7 +20,8 @@ module.exports = {
|
||||
},
|
||||
{ text: 'GitHub', link: 'https://github.com/polkadot-js/api' }
|
||||
],
|
||||
search: false,
|
||||
search: true,
|
||||
searchMaxSuggestions: 10,
|
||||
sidebar: [
|
||||
{
|
||||
title: 'Getting started',
|
||||
@@ -43,12 +44,24 @@ module.exports = {
|
||||
['start/api.tx.wrap.md', 'Complex transactions'],
|
||||
['start/types.basics.md', 'Type basics'],
|
||||
['start/types.extend.md', 'Extending types'],
|
||||
['start/rpc.custom.md', 'Custom RPC'],
|
||||
['start/types.create.md', 'Creating types'],
|
||||
['start/typescript.md', 'TypeScript interfaces'],
|
||||
['start/typescript.user.md', 'TypeScript user generated'],
|
||||
['start/FAQ.md', 'FAQ']
|
||||
]
|
||||
},
|
||||
{
|
||||
title: 'Cookbook',
|
||||
path: '/cookbook/',
|
||||
collapsable: false,
|
||||
sidebarDepth: 0,
|
||||
children: [
|
||||
['cookbook/blocks.md', 'Blocks'],
|
||||
['cookbook/storage.md', 'Storage'],
|
||||
['cookbook/tx.md', 'Transactions']
|
||||
]
|
||||
},
|
||||
{
|
||||
title: 'Examples (Promise API)',
|
||||
path: '/examples/promise/',
|
||||
@@ -85,5 +98,10 @@ module.exports = {
|
||||
['/types/', '@polkadot/types'],
|
||||
'/CONTRIBUTING.md'
|
||||
]
|
||||
}
|
||||
},
|
||||
plugins: [
|
||||
['@vuepress/search', {
|
||||
searchMaxSuggestions: 10
|
||||
}]
|
||||
]
|
||||
};
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
$accentColor = #fd8824
|
||||
$textColor = #2c3e50
|
||||
$borderColor = #eaecef
|
||||
$codeBgColor = #282c34
|
||||
$arrowBgColor = #ccc
|
||||
|
||||
.home .hero .description,
|
||||
.home .feature h2,
|
||||
|
||||
+2
-9
@@ -13,7 +13,7 @@ features:
|
||||
- title: Types
|
||||
details: Various type interfaces to make using returned values from API calls transparent in your code.
|
||||
|
||||
footer: Apache-2 Licensed | Copyright © 2017-2019 polkadot-js authors and contributors
|
||||
footer: Apache-2 Licensed | Copyright © 2017-2020 polkadot-js authors and contributors
|
||||
---
|
||||
|
||||
## Welcome
|
||||
@@ -21,16 +21,9 @@ footer: Apache-2 Licensed | Copyright © 2017-2019 polkadot-js authors and contr
|
||||
The API provides application developers the ability to query a node and interact with the Polkadot or Substrate chains using Javascript. Here you will find documentation and examples to get you started.
|
||||
|
||||
::: tip Getting started & Examples
|
||||
[Jump right in](/start/) and get an overview on using the API in your projects, from installation all the way through to making it do magic. Already understand how things work and just want the examples? [The ApiPromise examples](/examples/promise/) provide some basic recipies.
|
||||
[Jump right in](/start/) and get an overview on using the API in your projects, from installation all the way through to making it do magic. Have things working and want tips? The [cookbook](/cookbook/) provides some tips and tricks. Getting started and want some full examples? [The ApiPromise examples](/examples/promise/) provide some basic examples.
|
||||
:::
|
||||
|
||||
## Available packages
|
||||
|
||||
This repository split up into a number of internal packages, namely -
|
||||
|
||||
- [api](api/README.md) Promise and RxJS-based APIs
|
||||
- [types](types/README.md) Type encoding and decoding wrappers
|
||||
|
||||
## The Polkadot Project
|
||||
|
||||
You can read more about the Polkadot Network at [https://polkadot.network/](https://polkadot.network/) and more about the polkadot-js projects at [https://polkadot.js.org](https://polkadot.js.org)
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
# Cookbook
|
||||
|
||||
The cookbook hosts small code snippets in a question-answer format. It does not walk you through the whole setup, like the [basic examples](../examples/), but rather aims to answer some questions around specific uses. It also does not replace the [getting started FAQ](../start/FAQ.md), rather this is focussed explicitly on code samples, instead of general trouble-shooting for common mishaps.
|
||||
|
||||
These questions are added as they do come up and the hope is that the snippets here is will be useful to others, instead of just the original person who asked on a specific use-case. As of today, it is only making a start and not fully comprehensive yet - check back early, check back often.
|
||||
|
||||
## Sections
|
||||
|
||||
The following cookbook sections are available -
|
||||
|
||||
- [Blocks](blocks.md) - Snippets around working with blocks and headers
|
||||
- [Storage](storage.md) - Snippets for working with storage
|
||||
- [Transactions](tx.md) - Snippets for working with transactions
|
||||
|
||||
... more to come.
|
||||
|
||||
## Contribute
|
||||
|
||||
And as always, if you have an addition to make, or a question to ask any [any PRs](https://github.com/polkadot-js/api/tree/master/docs) or [issues](https://github.com/polkadot-js/api/issues) are appreciated. The initial content was generate from exactly such questions, either in Riot chat or as submitted as issues.
|
||||
@@ -0,0 +1,44 @@
|
||||
# Blocks
|
||||
|
||||
The building blocks for each blockchain. As such there are a number of examples for working with blocks and headers, that could be useful.
|
||||
|
||||
## How do I retrieve the header/extrinsic hash from blocks?
|
||||
|
||||
A block hash refers to the hash over the header, the extrinsic hash refers to the hash of the encoded extrinsic. Since all objects returned by the API implements the `.hash => Hash` getter, we can simply use this to view the actual hash.
|
||||
|
||||
```js
|
||||
// returns Hash
|
||||
const blockHash = await this.api.rpc.chain.getBlockHash(blockNumber);
|
||||
// returns SignedBlock
|
||||
const signedBlock = await this.api.rpc.chain.getBlock(blockHash);
|
||||
|
||||
// the hash for the block, always via header (Hash -> toHex()) - will be
|
||||
// the same as blockHash above (also available on any header retrieved,
|
||||
// subscription or once-off)
|
||||
console.log(signedBlock.header.hash.toHex());
|
||||
|
||||
// the hash for each extrinsic in the block
|
||||
signedBlock.block.extrinsics.forEach((ex, index) => {
|
||||
console.log(index, ex.hash.toHex());
|
||||
});
|
||||
```
|
||||
|
||||
## How do I extract the block author?
|
||||
|
||||
The block author is encoded inside the consensus logs for the block. To extract, you need to decode the log (which the API does do) and then map the index of the validator to the list of session validators. This extraction is however available on the api derive for new head subscriptions, which returns an extended header with the author populated (assuming that the digest logs are known).
|
||||
|
||||
```js
|
||||
// subscribe to all new headers (with extended info)
|
||||
api.derive.chain.subscribeNewHeads((header) => {
|
||||
console.log(`#${header.number}: ${header.author}`);
|
||||
});
|
||||
```
|
||||
|
||||
For a single header only, the derives also contain a `getHeader`, which once again returns a header extended with the author -
|
||||
|
||||
```js
|
||||
// retrieve the last header (hash optional)
|
||||
const header = await api.derive.chain.getHeader();
|
||||
|
||||
console.log(`#${header.number}: ${header.author}`);
|
||||
```
|
||||
@@ -0,0 +1,55 @@
|
||||
# Storage
|
||||
|
||||
Here you will find snippets for working with storage.
|
||||
|
||||
## How do I check for storage existence?
|
||||
|
||||
In the metadata, for each storage item a fallback is provided. This means that when an entry does not exist, the fallback (which is the default value for the type) will be provided. This means, that querying for a non-existent key (unless an option), will yield a value -
|
||||
|
||||
```js
|
||||
// retrieve Option<StakingLedger>
|
||||
const ledger = await api.query.staking.ledger('EoukLS2Rzh6dZvMQSkqFy4zGvqeo14ron28Ue3yopVc8e3Q');
|
||||
// retrieve ValidatorPrefs (will yield the default value)
|
||||
const prefs = await api.query.staking.validators('EoukLS2Rzh6dZvMQSkqFy4zGvqeo14ron28Ue3yopVc8e3Q');
|
||||
|
||||
console.log(ledger.isNone, ledger.isSome); // true, false
|
||||
console.log(JSON.stringify(prefs.toHuman())); // {"commission":"0"}
|
||||
```
|
||||
|
||||
In the second case, the non-existent prefs returns the default/fallback value for the storage item. So in this case we don't know if the value is set to 0 or unset. Existence can be checked by using the storage size, which would be zero if nothing is stored.
|
||||
|
||||
```js
|
||||
// exists
|
||||
const sizeY = await api.query.staking.validators.size('DB2mp5nNhbFN86J9hxoAog8JALMhDXgwvWMxrRMLNUFMEY4');
|
||||
// non existent
|
||||
const sizeN = await api.query.staking.validators.size('EoukLS2Rzh6dZvMQSkqFy4zGvqeo14ron28Ue3yopVc8e3Q');
|
||||
|
||||
console.log(sizeY.isZero(), sizeY.toNumber()); // false 4
|
||||
console.log(sizeN.isZero(), sizeY.toNumber()); // true 0
|
||||
```
|
||||
|
||||
## How do I use .entries()/.keys() on double maps?
|
||||
|
||||
As [explained elsewhere](../start/api.query.other.md#map-keys-entries) each map-type storage entry exposes the entries/keys helpers to retrieve the whole list. In the case of double maps, with the addition of a single argument, you can retrieve either all entries or a subset based on the first map key.
|
||||
|
||||
In both these cases, entries/keys operate the same way, `.entries()` retrieving `(StorageKey, Codec)[]` and `.keys()` retrieving `StorageKey[]`
|
||||
|
||||
```js
|
||||
// Retrieves the entries for all slashes, in all eras (no arg)
|
||||
const allEntries = await api.query.staking.nominatorSlashInEra.entries();
|
||||
|
||||
// nominatorSlashInEra(EraIndex, AccountId) for the types of the key args
|
||||
allEntries.forEach(([{ args: [era, nominatorId] }, value]) => {
|
||||
console.log(`${era}: ${nominatorId} slashed ${value.toHuman()}`);
|
||||
});
|
||||
```
|
||||
|
||||
While we can retrieve only the keys for a specific era, using a argument for the first part of the doublemap (as defined here, an `EraIndex`) -
|
||||
|
||||
```js
|
||||
// Retrieves the keys for the slashed validators in era 652
|
||||
const slashedKeys = await api.query.staking.nominatorSlashInEra.keys(652);
|
||||
|
||||
// key args still contains [EraIndex, AccountId] decoded
|
||||
console.log(`slashed: ${slashedKeys.map(({ args: [era, nominatorId] }) => nominatorId)`);
|
||||
```
|
||||
@@ -0,0 +1,112 @@
|
||||
# Transactions
|
||||
|
||||
A blockchain is no fun if you are not submitting transactions. Or at least if somebody is not submitting any. Here you will find some snippets for dealing with some common issues.
|
||||
|
||||
## How do I estimate the transaction fees?
|
||||
|
||||
In addition to the `signAndSend` helper on transactions, `.paymentInfo` (with the exact same parameters) are also exposed. Using the same sender, it applies a dummy signature to the transaction and then gets the fee estimation via RPC.
|
||||
|
||||
```js
|
||||
// estimate the fees as RuntimeDispatchInfo, using the signer (either
|
||||
// address or locked/unlocked keypair) (When overrides are applied, e.g
|
||||
// nonce, the format would be `paymentInfo(sender, { nonce })`)
|
||||
const info = await api.tx.balances
|
||||
.transfer(recipient, 123)
|
||||
.paymentInfo(sender);
|
||||
|
||||
// log relevant info, partialFee is Balance, estimated for current
|
||||
console.log(`
|
||||
class=${class.toString()},
|
||||
weight=${weight.toString()},
|
||||
partialFee=${partialFee.toHuman()}
|
||||
`);
|
||||
```
|
||||
|
||||
## How do I get the decoded enum for an ExtrinsicFailed event?
|
||||
|
||||
Assuming you are sending a tx via `.signAndSend`, the callback yields information around the tx pool status as well as any events when `isInBlock` or `isFinalized`. If an extrinsic fails via `system.ExtrinsicFailed` event, you can retrieve the error, if defined as an enum on a module.
|
||||
|
||||
```js
|
||||
api.tx.balances
|
||||
.transfer(recipient, 123)
|
||||
.signAndSend(sender, ({ status, events }) => {
|
||||
if (status.isInBlock || status.isFinalized) {
|
||||
events
|
||||
// find/filter for failed events
|
||||
.filter(({ section, method }) =>
|
||||
section === 'system' &&
|
||||
method === 'ExtrinsicFailed'
|
||||
)
|
||||
// we know that data for system.ExtrinsicFailed is
|
||||
// (DispatchError, DispatchInfo)
|
||||
.forEach(({ data: [error, info] }) => {
|
||||
if (error.isModule) {
|
||||
// for module errors, we have the section indexed, lookup
|
||||
const decoded = api.registry.findMetaError(error.asModule);
|
||||
const { documentation, method, section } = decoded;
|
||||
|
||||
console.log(`${section}.${method}: ${documentation.join(' ')}`);
|
||||
} else {
|
||||
// Other, CannotLookup, BadOrigin, no extra info
|
||||
console.log(error.toString());
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
```
|
||||
|
||||
## How do I send an unsigned extrinsic?
|
||||
|
||||
For most runtime modules, transactions need to be signed and validation for this happens node-side. There are however modules that accepts unsigned extrinsics, an example would be the Polkadot/Kusama token claims (which is here used as an example).
|
||||
|
||||
```js
|
||||
// construct the transaction, exactly as per normal
|
||||
const utx = api.tx.claims.claim(beneficiary, ethSignature);
|
||||
|
||||
// send it without calling sign, pass callback with status/events
|
||||
tx.send(({ status }) => {
|
||||
if (status.isInBlock) {
|
||||
console.log(`included in ${status.asInBlock}`);
|
||||
}
|
||||
});
|
||||
```
|
||||
|
||||
The signing is indicated by the first byte in the transaction, so in this case we have called `.send` on it (no `.sign` or `.signAndSend`), so it will be sent using the unsigned state, without signature attached.
|
||||
|
||||
## How can I batch transactions?
|
||||
|
||||
Polkadot/Substrate provides a `utility.batch` method that can be used to send a number of transactions at once. These are then executed from a single sender (single nonce specified) in sequence. This is very useful in a number of cases, for instance if you wish to create a payout for a validator for multiple eras, you can use this method. Likewise, you can send a number of transfers at once. Or even batch different types of transactions.
|
||||
|
||||
```js
|
||||
// construct a list of transactions we want to batch
|
||||
const txs = [
|
||||
api.tx.balances.transfer(addrBob, 12345),
|
||||
api.tx.balances.transfer(addrEve, 12345),
|
||||
api.tx.staking.unbond(12345)
|
||||
];
|
||||
|
||||
// construct the batch and send the transactions
|
||||
api.tx.utility
|
||||
.batch(txs)
|
||||
.signAndSend(sender, ({ status }) => {
|
||||
if (status.isInBlock) {
|
||||
console.log(`included in ${status.asInBlock}`);
|
||||
}
|
||||
});
|
||||
```
|
||||
|
||||
## 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`.
|
||||
|
||||
```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);
|
||||
|
||||
// send, just retrieving the hash, not waiting on status
|
||||
const txhash = await api.tx.balances
|
||||
.transfer(recipient, 123)
|
||||
.signAndSend(sender, { nonce });
|
||||
}
|
||||
```
|
||||
@@ -1,6 +1,7 @@
|
||||
/* eslint-disable header/header */
|
||||
/* eslint-disable @typescript-eslint/require-await */
|
||||
/* eslint-disable @typescript-eslint/unbound-method */
|
||||
/* eslint-disable @typescript-eslint/no-var-requires */
|
||||
|
||||
// Required imports
|
||||
const { ApiPromise, WsProvider } = require('@polkadot/api');
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
/* eslint-disable header/header */
|
||||
/* eslint-disable @typescript-eslint/require-await */
|
||||
/* eslint-disable @typescript-eslint/unbound-method */
|
||||
/* eslint-disable @typescript-eslint/no-var-requires */
|
||||
|
||||
// Import the API
|
||||
const { ApiPromise } = require('@polkadot/api');
|
||||
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
/* eslint-disable header/header */
|
||||
/* eslint-disable @typescript-eslint/require-await */
|
||||
/* eslint-disable @typescript-eslint/unbound-method */
|
||||
/* eslint-disable @typescript-eslint/no-var-requires */
|
||||
/* eslint-disable @typescript-eslint/no-floating-promises */
|
||||
|
||||
// Import the API
|
||||
const { ApiPromise } = require('@polkadot/api');
|
||||
|
||||
@@ -13,13 +15,13 @@ async function main () {
|
||||
|
||||
// Retrieve the initial balance. Since the call has no callback, it is simply a promise
|
||||
// that resolves to the current on-chain value
|
||||
let { nonce: previousNonce, data: { free: previousFree } } = await api.query.system.account(Alice);
|
||||
let { data: { free: previousFree }, nonce: previousNonce } = await api.query.system.account(Alice);
|
||||
|
||||
console.log(`${Alice} has a balance of ${previousFree}, nonce ${previousNonce}`);
|
||||
console.log(`You may leave this example running and start example 06 or transfer any value to ${Alice}`);
|
||||
|
||||
// Here we subscribe to any balance changes and update the on-screen value
|
||||
api.query.system.account(Alice, ({ nonce: currentNonce, data: { free: currentFree } }) => {
|
||||
api.query.system.account(Alice, ({ data: { free: currentFree }, nonce: currentNonce }) => {
|
||||
// Calculate the delta
|
||||
const change = currentFree.sub(previousFree);
|
||||
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
/* eslint-disable header/header */
|
||||
/* eslint-disable @typescript-eslint/require-await */
|
||||
/* eslint-disable @typescript-eslint/unbound-method */
|
||||
/* eslint-disable @typescript-eslint/no-var-requires */
|
||||
/* eslint-disable @typescript-eslint/no-floating-promises */
|
||||
|
||||
// Import the API
|
||||
const { ApiPromise } = require('@polkadot/api');
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
/* eslint-disable header/header */
|
||||
/* eslint-disable @typescript-eslint/require-await */
|
||||
/* eslint-disable @typescript-eslint/unbound-method */
|
||||
/* eslint-disable @typescript-eslint/no-var-requires */
|
||||
|
||||
// Import the API
|
||||
const { ApiPromise } = require('@polkadot/api');
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
/* eslint-disable header/header */
|
||||
/* eslint-disable @typescript-eslint/require-await */
|
||||
/* eslint-disable @typescript-eslint/unbound-method */
|
||||
/* eslint-disable @typescript-eslint/no-var-requires */
|
||||
|
||||
// Import the API
|
||||
const { ApiPromise } = require('@polkadot/api');
|
||||
|
||||
@@ -24,7 +25,7 @@ async function main () {
|
||||
if (validators && validators.length > 0) {
|
||||
// Retrieve the balances for all validators
|
||||
const validatorBalances = await Promise.all(
|
||||
validators.map(authorityId =>
|
||||
validators.map((authorityId) =>
|
||||
api.query.system.account(authorityId)
|
||||
)
|
||||
);
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
/* eslint-disable header/header */
|
||||
/* eslint-disable @typescript-eslint/require-await */
|
||||
/* eslint-disable @typescript-eslint/unbound-method */
|
||||
/* eslint-disable @typescript-eslint/no-var-requires */
|
||||
|
||||
// Import the API
|
||||
const { ApiPromise } = require('@polkadot/api');
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
/* eslint-disable header/header */
|
||||
/* eslint-disable @typescript-eslint/require-await */
|
||||
/* eslint-disable @typescript-eslint/unbound-method */
|
||||
/* eslint-disable @typescript-eslint/no-var-requires */
|
||||
|
||||
// Import the API, Keyring and some utility functions
|
||||
const { ApiPromise } = require('@polkadot/api');
|
||||
const { Keyring } = require('@polkadot/keyring');
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
/* eslint-disable header/header */
|
||||
/* eslint-disable @typescript-eslint/require-await */
|
||||
/* eslint-disable @typescript-eslint/unbound-method */
|
||||
/* eslint-disable @typescript-eslint/no-var-requires */
|
||||
|
||||
// Import the API, Keyring and some utility functions
|
||||
const { ApiPromise } = require('@polkadot/api');
|
||||
const { Keyring } = require('@polkadot/keyring');
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
/* eslint-disable header/header */
|
||||
/* eslint-disable @typescript-eslint/require-await */
|
||||
/* eslint-disable @typescript-eslint/unbound-method */
|
||||
/* eslint-disable @typescript-eslint/no-var-requires */
|
||||
/* eslint-disable @typescript-eslint/no-floating-promises */
|
||||
|
||||
// Import the API
|
||||
const { ApiPromise } = require('@polkadot/api');
|
||||
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
/* eslint-disable header/header */
|
||||
/* eslint-disable @typescript-eslint/require-await */
|
||||
/* eslint-disable @typescript-eslint/unbound-method */
|
||||
/* eslint-disable @typescript-eslint/no-var-requires */
|
||||
/* eslint-disable @typescript-eslint/no-floating-promises */
|
||||
|
||||
// Import the API & Provider and some utility functions
|
||||
const { ApiPromise } = require('@polkadot/api');
|
||||
|
||||
@@ -44,7 +46,7 @@ async function main () {
|
||||
console.log('Included at block hash', status.asInBlock.toHex());
|
||||
console.log('Events:');
|
||||
|
||||
events.forEach(({ phase, event: { data, method, section } }) => {
|
||||
events.forEach(({ event: { data, method, section }, phase }) => {
|
||||
console.log('\t', phase.toString(), `: ${section}.${method}`, data.toString());
|
||||
});
|
||||
} else if (status.isFinalized) {
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
/* eslint-disable header/header */
|
||||
/* eslint-disable @typescript-eslint/require-await */
|
||||
/* eslint-disable @typescript-eslint/unbound-method */
|
||||
/* eslint-disable @typescript-eslint/no-var-requires */
|
||||
/* eslint-disable @typescript-eslint/no-floating-promises */
|
||||
|
||||
// Import the API & Provider and some utility functions
|
||||
const { ApiPromise, WsProvider } = require('@polkadot/api');
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
/* eslint-disable header/header */
|
||||
/* eslint-disable @typescript-eslint/require-await */
|
||||
/* eslint-disable @typescript-eslint/unbound-method */
|
||||
/* eslint-disable @typescript-eslint/no-var-requires */
|
||||
|
||||
// Required imports
|
||||
const { zip } = require('rxjs');
|
||||
const { ApiRx } = require('@polkadot/api');
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
/* eslint-disable header/header */
|
||||
/* eslint-disable @typescript-eslint/require-await */
|
||||
/* eslint-disable @typescript-eslint/unbound-method */
|
||||
/* eslint-disable @typescript-eslint/no-var-requires */
|
||||
|
||||
// Import the API
|
||||
const { ApiRx } = require('@polkadot/api');
|
||||
const { switchMap } = require('rxjs/operators');
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
/* eslint-disable header/header */
|
||||
/* eslint-disable @typescript-eslint/require-await */
|
||||
/* eslint-disable @typescript-eslint/unbound-method */
|
||||
/* eslint-disable @typescript-eslint/no-var-requires */
|
||||
|
||||
// Import the API and operators from RxJs
|
||||
const { ApiRx } = require('@polkadot/api');
|
||||
const { pairwise, startWith } = require('rxjs/operators');
|
||||
@@ -27,6 +28,7 @@ async function main () {
|
||||
// then balance[1] is the initial value of Alice account.
|
||||
console.log(`Alice ${Alice} has a balance of ${balance[1].data.free}`);
|
||||
console.log('You may leave this example running and start the "Make a transfer" example or transfer any value to Alice address');
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
/* eslint-disable header/header */
|
||||
/* eslint-disable @typescript-eslint/require-await */
|
||||
/* eslint-disable @typescript-eslint/unbound-method */
|
||||
/* eslint-disable @typescript-eslint/no-var-requires */
|
||||
|
||||
// Import the API
|
||||
const { ApiRx } = require('@polkadot/api');
|
||||
const { switchMap } = require('rxjs/operators');
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
/* eslint-disable header/header */
|
||||
/* eslint-disable @typescript-eslint/require-await */
|
||||
/* eslint-disable @typescript-eslint/unbound-method */
|
||||
/* eslint-disable @typescript-eslint/no-var-requires */
|
||||
|
||||
// Import the API
|
||||
const { ApiRx } = require('@polkadot/api');
|
||||
const { combineLatest, of } = require('rxjs');
|
||||
@@ -22,7 +23,7 @@ function main () {
|
||||
// In the next step, we're checking if the node has active validators.
|
||||
// If it does, we're making another call to the api to get the balances for all validators
|
||||
const balances = (validators && validators.length > 0)
|
||||
? combineLatest(validators.map(authorityId => api.query.system.account(authorityId).pipe(first())))
|
||||
? combineLatest(validators.map((authorityId) => api.query.system.account(authorityId).pipe(first())))
|
||||
: of(null);
|
||||
|
||||
// We're combining the results together with the emitted value 'validators',
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
|
||||
/* eslint-disable header/header */
|
||||
/* eslint-disable @typescript-eslint/require-await */
|
||||
/* eslint-disable @typescript-eslint/unbound-method */
|
||||
/* eslint-disable @typescript-eslint/no-var-requires */
|
||||
|
||||
// Import the API, Keyring and some utility functions
|
||||
const { ApiRx } = require('@polkadot/api');
|
||||
const { Keyring } = require('@polkadot/keyring');
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
/* eslint-disable header/header */
|
||||
/* eslint-disable @typescript-eslint/require-await */
|
||||
/* eslint-disable @typescript-eslint/unbound-method */
|
||||
/* eslint-disable @typescript-eslint/no-var-requires */
|
||||
|
||||
// Import the API and selected RxJs operators
|
||||
const { switchMap } = require('rxjs/operators');
|
||||
const { ApiRx } = require('@polkadot/api');
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
/* eslint-disable header/header */
|
||||
/* eslint-disable @typescript-eslint/require-await */
|
||||
/* eslint-disable @typescript-eslint/unbound-method */
|
||||
/* eslint-disable @typescript-eslint/no-var-requires */
|
||||
|
||||
// Import the API and some utility functions
|
||||
const { ApiRx } = require('@polkadot/api');
|
||||
|
||||
@@ -48,7 +49,7 @@ async function main () {
|
||||
console.log('Included at block hash', status.asInBlock.toHex());
|
||||
console.log('Events:');
|
||||
|
||||
events.forEach(({ phase, event: { data, method, section } }) => {
|
||||
events.forEach(({ event: { data, method, section }, phase }) => {
|
||||
console.log('\t', phase.toString(), `: ${section}.${method}`, data.toString());
|
||||
});
|
||||
} else if (status.isFinalized) {
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
/* eslint-disable header/header */
|
||||
/* eslint-disable @typescript-eslint/require-await */
|
||||
/* eslint-disable @typescript-eslint/unbound-method */
|
||||
/* eslint-disable @typescript-eslint/no-var-requires */
|
||||
|
||||
// Import the API & Provider and some utility functions
|
||||
const { ApiRx, WsProvider } = require('@polkadot/api');
|
||||
// Import the test keyring (already has dev keys for Alice, Bob, Charlie, Eve & Ferdie)
|
||||
|
||||
@@ -1,5 +0,0 @@
|
||||
... somewhere also need a signer injection section, something along the lines of the singlesigner or this https://github.com/polkadot-js/tools/blob/master/packages/signer-cli/src/cmdSubmit.ts#L12
|
||||
|
||||
... DoubleMap & LinkedMap examples
|
||||
|
||||
... api.derive
|
||||
+32
-2
@@ -20,6 +20,9 @@ All data transferred between the API and the Node is in a SCALE-encoded binary f
|
||||
|
||||
To fix this, you should look at the specific `api.tx.*` params and adjust the type definitions for those param types to match what is found on the node side. In some rare cases the cause could be extrinsic formatting related, to track these make an `api.tx.system.remark(data: Bytes)` call, if it fails, the API and node cannot agree on [an extrinsic format and adjustments are required](types.extend.md#impact-on-extrinsics).
|
||||
|
||||
If you are using a node-template based version of substrate and you changed the specName you need to add these typings(In addition to other custom types) `{"Address": "AccountId","LookupSource": "AccountId"}`. This is also the case when you use [polkadot-js/apps](https://github.com/polkadot-js/apps) to connect to your node. When the specName stays node-template the API is smart enough to add the custom typings.
|
||||
|
||||
|
||||
## I would like to sign transactions offline
|
||||
|
||||
The API itself is independent on where the signature comes from and how it is injected. Additionally it implements a signer interface, that can be used for external signing - an example of this is the [polkadot-js/apps](https://github.com/polkadot-js/apps) support for signing via extensions and even the [polkadot-js/extension](https://github.com/polkadot-js/extension) support for tools such as the [Parity Signer](https://github.com/paritytech/parity-signer).
|
||||
@@ -34,13 +37,13 @@ To submit these transactions, it needs to be send as a [wrapped transaction](api
|
||||
|
||||
## How do I call a function with a Tuple input
|
||||
|
||||
Tuples, as defined in the Polkadot/Substrate types appear as `(TypeA, TypeB)`. For instance we may have an `(AccountId, u64)` input as defined in the metadata or as part of the user types. To specify a Tuple as an input, wrap it is an array format, for instance to call `query.module.get((u32, u64))` where a `(u32, u64)` Tuple input is expected, you would do `query.module.get([123, 456])`
|
||||
Tuples, as defined in the Polkadot/Substrate types appear as `(TypeA, TypeB)`. For instance we may have an `(AccountId, u64)` input as defined in the metadata or as part of the user types. To specify a Tuple as an input, wrap it in an array format, for instance to call `query.module.get((u32, u64))` where a `(u32, u64)` Tuple input is expected, you would do `query.module.get([123, 456])`
|
||||
|
||||
## How long do transactions live
|
||||
|
||||
Polkadot/Substrate supports both immortal and mortal transactions. For immortal, this means that the transaction has an infinite lifetime, for mortals, the transactions expire after a defined period. By default the API sends mortal transactions when no explicit extrinsic era has been specified. This means that all transaction has a limited lifetime and will expire if not included in the period set.
|
||||
|
||||
The length for this transaction validity is set to 50 blocks, which translates to 5 minutes assuming a default of 6 second blocktimes. (10 blocks per minute in this default configuration).
|
||||
The length for this transaction validity is set to 5 minutes, calculated based on the blocktime for the chain. (10 blocks per minute in this default 6s Substrate configuration).
|
||||
|
||||
## My chain does not support system.account queries
|
||||
|
||||
@@ -49,3 +52,30 @@ The API always tracks the latest Substrate master in terms of examples. This mea
|
||||
It is possible that you are connecting to an older chain that has not been upgraded yet. For these chains, this storage entry won't be available (yet). To query the nonce on older chains, you can do a query to `api.query.system.accountNonce(<account>)` and balances can be retrieved via `api.query.balances.freeBalance(<account>)`.
|
||||
|
||||
Likewise, if your chain has been upgraded recently and you are still using the old `system.accountNonce` or `balances.freeBalance` queries in your code (which is now not available in the chain metadata), you need to update it to query the new location.
|
||||
|
||||
## I cannot send transactions from my node-template-based chain
|
||||
|
||||
The API always injects the default type definitions as specified by the Substrate master fully-featured node. This means that any customizations to chains needs needs to be applied as types, should there be differences in specific user-implementations.
|
||||
|
||||
The Substrate node-template has added customizations for some types in the default template, specifically around the `Address` and `Lookup` types, removing any lookups based on indices. This means that the transaction payload saves 2 bytes for a transfer and is an approach followed by other chains as well, notably Polkadot & Kusama.
|
||||
|
||||
Due to these customizations and differences that bleed through to the transaction formats, out-of-the-box chains based on the node-template will have issues when sending transactions. To fix this, you would need to add [the customized Address types into your API](types.extend.md#impact-on-extrinsics) instances (or UIs), allowing the API to have the information required to adjust the encoding.
|
||||
|
||||
## Using a non-current-master node, I have issues parsing events
|
||||
|
||||
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
|
||||
|
||||
@@ -23,7 +23,7 @@ A couple of items to note in the example above: we don't call `account` directly
|
||||
...
|
||||
|
||||
// Retrieve a snapshot of the validators
|
||||
const validators = await api.query.session.validators();
|
||||
const validatorKeys = await api.query.session.validators.keys();
|
||||
|
||||
// Subscribe to the balances for these accounts
|
||||
const unsub = await api.query.balances.account.multi(validators, (balances) => {
|
||||
|
||||
@@ -22,7 +22,7 @@ const [{ data: balanceNow }, { data: balancePrev }] = await Promise.all([
|
||||
console.log(`The delta was ${balanceNow.free.sub(balancePrev.free)}`);
|
||||
```
|
||||
|
||||
In the above example, we introduce the `.at(<hash>[, ...params])` query. For all `.at` queries, the first parameter is always the block hash at which we want to make the query, in our example we use both the last retrieved block and the parent thereof. The params are optional as per the type of query made, for instance to retrieve the timestamp for a previous block, it would be -
|
||||
In the above example, we introduce the `.at(<hash>[, ...params]): Type` query. For all `.at` queries, the first parameter is always the block hash at which we want to make the query, in our example we use both the last retrieved block and the parent thereof. The params are optional as per the type of query made, for instance to retrieve the timestamp for a previous block, it would be -
|
||||
|
||||
```js
|
||||
...
|
||||
@@ -35,6 +35,61 @@ The `.at` queries are all single-shot, i.e. there are no subscription option to
|
||||
|
||||
An additional point to take care of (briefly mentioned above), is state pruning. By default a Polkadot/Substrate node will only keep state for the last 256 blocks, unless it is explicitly run in archive mode. This means that querying state further back than the pruning period will result in an error returned from the Node. (Generally most public RPC nodes only run with default settings, which includes aggressive state pruning)
|
||||
|
||||
## State for a range of blocks
|
||||
|
||||
In addition to the `.at` queries, you can also query state starting at a specific historic block and up to either a specified or the latest blocks. This is done via the `.range([from, to?], <...opt params>): [Hash, Type][]` query. As an example -
|
||||
|
||||
```js
|
||||
...
|
||||
// Retrieve the current block header
|
||||
const lastHdr = await api.rpc.chain.getHeader();
|
||||
const startHdr = await api.rpc.chain.getBlockHash(lastHdr.number.unwrap().subn(500));
|
||||
|
||||
// retrieve the range of changes
|
||||
const changes = await api.query.system.account.range([startHdr]);
|
||||
|
||||
changes.forEach(([hash, value]) => {
|
||||
console.log(hash.toHex(), value.toHuman());
|
||||
});
|
||||
```
|
||||
|
||||
## Map keys & entries
|
||||
|
||||
When working maps and double-maps, it is possible to retrieve a list of all the keys and entries for the map. For this we can use the `.entries(<args>): [StorageKey, Type][]` queries. For example we may want to know the current list of validator exposures at a current era in the staking module -
|
||||
|
||||
```js
|
||||
...
|
||||
// Retrieve the active era
|
||||
const activeEra = await api.query.staking.activeEra();
|
||||
|
||||
// retrieve all exposures for the active era
|
||||
const exposures = await api.query.staking.erasStakers.entries(activeEra.index);
|
||||
|
||||
exposures.forEach(([key, exposure]) => {
|
||||
console.log('key arguments:', key.args.map((k) => k.toHuman()));
|
||||
console.log(' exposure:', exposure.toHuman());
|
||||
});
|
||||
```
|
||||
|
||||
To understand the usage of the `key.args`, you need to understand that map/doublemap keys are stored alongside their lookups. This means that the raw key has hashed parts as well as the raw data. The API will decode the keys and provide the raw key arguments in args. This would mean -
|
||||
|
||||
- if we are querying `api.query.staking.validators(validatorId: AccountId)` via `entries`, the `key.args` would be `[AccountId]`
|
||||
- if we are querying `api.query.staking.erasStakers(era: EraIndex, validatorId: AccountId)` via `entries`, the `key.args` would be `[EraIndex, AccountId]`
|
||||
|
||||
the same applies to `.keys()` - here the list of keys also have the decoded args, as specified. You can think of `.args` as a tuple with the same types as the types required to retrieve a single entry in the map.
|
||||
|
||||
In the first example we are querying a double-map, so we supply 1 argument. No arguments on double-maps will be very costly, retrieving all the eras and associated entries. In the same way as above we can simply do `.keys(activeEra.index): StorageKey[]` to retrieve all the keys here, including the individual keys args (available on maps with decodable hashing functions) -
|
||||
|
||||
```js
|
||||
// retrieve all the nominator keys
|
||||
const keys = await api.query.staking.nominators.keys();
|
||||
|
||||
// extract the first key argument [AccountId] as string
|
||||
const nominatorIds = keys.map(({ args: [nominatorId] }) => nominatorId);
|
||||
|
||||
console.log('all nominators:', nominatorIds.join(', '));
|
||||
```
|
||||
|
||||
## State entries
|
||||
|
||||
In addition to using `api.query` to make actual on-chain queries, it can also be used to retrieve some information on the state entries. For instance to retrieve both the hash and size of an existing entry, we can make the following calls -
|
||||
|
||||
@@ -26,7 +26,7 @@ If we had a query with parameters, i.e. where we wish to perform a query for a s
|
||||
|
||||
// Subscribe to balance changes for our account
|
||||
const unsub = await api.query.system.account(ADDR, ({ nonce, data: balance }) => {
|
||||
console.log(`free balance is ${balance.freee} with ${balance.reserved} reserved and a nonce of ${nonce}`);
|
||||
console.log(`free balance is ${balance.free} with ${balance.reserved} reserved and a nonce of ${nonce}`);
|
||||
});
|
||||
```
|
||||
|
||||
|
||||
@@ -62,6 +62,23 @@ const unsub = await api.tx.balances
|
||||
|
||||
Be aware that when a transaction status is `isFinalized`, it means it is included, but it may still have failed - for instance if you try to send a larger amount that you have free, the transaction is included in a block, however from a end-user perspective the transaction failed since the transfer did not occur. In these cases a `system.ExtrinsicFailed` event will be available in the events array.
|
||||
|
||||
## Payment information
|
||||
|
||||
The Polkadot/Substrate RPC endpoints exposes weight/payment information that takes an encoded extrinsic and calculates the on-chain weight fees for it. A wrapper for this is available on the tx itself, taking exactly the same parameters as you would pass to a normal `.signAndSend` operation, specifically `.paymentInfo(sender, <any options>)`. To expand on our previous example -
|
||||
|
||||
```js
|
||||
// construct a transaction
|
||||
const transfer = api.tx.balances.transfer(BOB, 12345);
|
||||
|
||||
// retrieve the payment info
|
||||
const { partialFee, weight } = await transfer.paymentInfo(alice);
|
||||
|
||||
console.log(`transaction will have a weight of ${weight}, with ${partialFee.toHuman()} weight fees`);
|
||||
|
||||
// send the tx
|
||||
transfer.signAndSend(alice, ({ events = [], status }) => { ... });
|
||||
```
|
||||
|
||||
## Complex transactions
|
||||
|
||||
In many cases transactions can carry quite complex information, be it for passing objects or proposing changes. In the next section we will take a dive [into complex transactions, including those wrapped for sudo](api.tx.wrap.md).
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
# Custom RPC
|
||||
|
||||
In previous sections we looked at the injection of types, as in use and defined in modules from the node. Another area that can be customized is RPC definitions, and like with the types, the API provides the capability to add user-defined RPCs (in addition to the Polkadot/Substrate base) to allow use of these RPCs via the API.
|
||||
|
||||
## Custom definitions
|
||||
|
||||
RPCs are exposed as a method on a specific module, this means that once available you can call any rpc via the `api.rpc.<module>.<method>(...params[])` endpoints. To extend with user-defined RPCs, the injection can happen at the time of API creation with the addition of the `rpc` key (in addition to any other params, such as `types` or `provider`) -
|
||||
|
||||
```js
|
||||
...
|
||||
const api = await ApiPromise.create({
|
||||
rpc: {
|
||||
firstModule: {
|
||||
testMethod: {
|
||||
description: 'Just a test method',
|
||||
params: [
|
||||
{
|
||||
name: 'index',
|
||||
type: 'u64'
|
||||
},
|
||||
{
|
||||
name: 'at',
|
||||
type: 'Hash',
|
||||
isOptional: true
|
||||
}
|
||||
],
|
||||
type: 'Balance'
|
||||
},
|
||||
anotherMethod: { ... },
|
||||
...
|
||||
},
|
||||
anotherModule: { ... },
|
||||
...
|
||||
},
|
||||
...
|
||||
});
|
||||
```
|
||||
|
||||
In the above example we have defined a new method, which is now available on the RPCs as `api.rpc.firstModule.testMethod(index: u64, at?: Hash) => Promise<Balance>`. In the case of optional params, we have added the `isOptional: true` flag alongside the `name` & `type` in the param definition.
|
||||
|
||||
Be aware that while defined, the method will only appear on the API if it is in the list as returned by `api.rpc.rpc.methods()`, which is the list of known RPCs the node exposes. When making changes to the node, always ensure that it does expose the RPC method correctly, otherwise it will not be decorated.
|
||||
|
||||
## 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,
|
||||
|
||||
```js
|
||||
...
|
||||
const api = await ApiPromise.create({
|
||||
rpc: {
|
||||
firstModule: { ... },
|
||||
testModule: { ... }
|
||||
}
|
||||
});
|
||||
```
|
||||
|
||||
Inside the specific module definitions, the key is the actual expose RPC method. As we have seen in the first example, we expose a `testMethod` on `firstModule`. For the method definitions, apart from the description, we have definitions for the params and return a single result `type`.
|
||||
|
||||
Params itself, as an array, contains fields for `name`, `type` and an optional flag `isOptional` that indicates that the field is not required when making the call. (And example of this use would be in cases such as `state.getStorage(key, blockHash?)` where the last param is optional)
|
||||
|
||||
## Type creation
|
||||
|
||||
While the API always converts all the inputs into the underlying type required by the operation, be it for RPC, query or transaction, in some cases you may want to [create an instance of a type](types.create.md) yourself.
|
||||
@@ -57,7 +57,7 @@ Be aware that in the JS version naming defaults to `camelCase` where names of fi
|
||||
|
||||
Each enum has additional getters which are injected based on the fields wrapped. These take the form of `.is<Name>` and `.as<Name>` to allow you to check is the enum is a certain value or to retrieve the underlying value as a specific type.
|
||||
|
||||
As a real-world example, when an extrinsic is applied, the `Phase` enum has one of two states, `ApplyExtrinsic(u32)` or `Finalization`. In this case `.isApplyExtrinsic` would be `true` when an extrinsic is being applied, and `.asApplyExtrinsic` would return the value as a `u32` (which is the index of the extrinsic in the block, as it is being applied). When `isisApplyExtrinsic` is `false` and `asApplyExtrinsic` is called, the getter will throw.
|
||||
As a real-world example, when an extrinsic is applied, the `Phase` enum has one of two states, `ApplyExtrinsic(u32)` or `Finalization`. In this case `.isApplyExtrinsic` would be `true` when an extrinsic is being applied, and `.asApplyExtrinsic` would return the value as a `u32` (which is the index of the extrinsic in the block, as it is being applied). When `isApplyExtrinsic` is `false` and `asApplyExtrinsic` is called, the getter will throw.
|
||||
|
||||
## Working with Option<Type>
|
||||
|
||||
@@ -67,6 +67,7 @@ An `Option<Type>` attempts to mimic the Rust approach of having `None` and `Some
|
||||
- `.isSome` - this is `true` is a value is wrapped, i.e. if a `Option<u32>` has an actual underlying `u32`
|
||||
- `.unwrap()` - when `isSome`, this will return the wrapped value, i.e. for `Option<u32>`, this would return the `u32`. When the value is `isNone`, this call will throw an exception.
|
||||
- `.unwrapOr(<default value>)` - this extends `unwrap()`, returning the wrapped value when `isSome` and in the case of `isNone` it will return the `<default value>` passed.
|
||||
- `.unwrapOrDefault()` - returns either the rapped value when `isSome`, or the default for the type when `isNone`
|
||||
|
||||
## Working with Tuples
|
||||
|
||||
|
||||
@@ -26,6 +26,15 @@ const api = await ApiPromise.create({
|
||||
|
||||
The above introduces the `types` registry, effectively allowing overrides and the definition of new types. The override above would mean that immediately the API will treat all occurrences of `Balance` not as the default, but rather as the defined size.
|
||||
|
||||
## Field ordering
|
||||
|
||||
When defining any custom structures or types, it is critical that the following rules are applied -
|
||||
|
||||
- Map exactly to what is defined in the Rust code, i.e. defining a `SaleType` cannot be `u16` on the one end and `u32` on the other end. If mismatches occur, the serialization will fail.
|
||||
- Ensure that the field order is maintained in all definitions. The SCALE serialization is binary and contains no field names in the serialization, only the encoded values. Any decoding is therefore done based on the size of the type and the order thereof in the definitions.
|
||||
|
||||
These rules apply everywhere. Always ensure that the types match exactly between the environments and that the ordering is maintained, be it for structs, tuples or enums.
|
||||
|
||||
## User-defined structs
|
||||
|
||||
Registration also applies to any type that can be found on a specific chain, i.e. we can add any types that is available on a specific node -
|
||||
@@ -201,6 +210,6 @@ const api = await ApiPromise.create({
|
||||
|
||||
Always look at customization and understand the impacts, replicating these changes between the node and the API. For the above the `Address` type is used in the construction of the `UncheckedExtrinsic` type, while the lookup type is applicable on transactions such as `balances.transfer(to: LookupSource, value: Balance)`
|
||||
|
||||
## Type creation
|
||||
## Custom RPC
|
||||
|
||||
While the API always converts all the inputs into the underlying type required by the operation, in some cases you may want to [create an instance of a type](types.create.md) yourself.
|
||||
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.
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
# 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 onw definitions and chain types.
|
||||
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.
|
||||
|
||||
## Definitions
|
||||
|
||||
A large part of the type definitions are defined not as classes, but rather as structures from which type definitions are extracted and that can be used as-is to let the API know how to decode a type. By now you should be familiar with [type extensions](types.extend.md), but effectively the [types library does exactly the same](https://github.com/polkadot-js/api/tree/master/packages/types/src/interfaces).
|
||||
A large part of the type definitions are defined not as classes, but rather as structures from which type definitions are extracted and that can be used as-is to let the API know how to decode a type. By now you should be familiar with [type extensions](types.extend.md) and the [rules around fields](types.extend.md#field-ordering), but effectively the [types library does exactly the same](https://github.com/polkadot-js/api/tree/master/packages/types/src/interfaces).
|
||||
|
||||
To create TypeScript-aware definitions and keep your files in a single place, you can follow the same approach. Assuming you have a package named `@MeInc/stuff` where you have the definitions in an `stuff/interfaces` folder. Each sub-folder would indicate a runtime module, e.g.
|
||||
|
||||
|
||||
+9
-15
@@ -1,36 +1,30 @@
|
||||
/* eslint-disable @typescript-eslint/camelcase */
|
||||
/* eslint-disable @typescript-eslint/no-var-requires */
|
||||
// Copyright 2017-2020 @polkadot/api authors & contributors
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the Apache-2.0 license. See the LICENSE file for details.
|
||||
|
||||
const config = require('@polkadot/dev/config/jest');
|
||||
|
||||
module.exports = Object.assign({}, config, {
|
||||
moduleNameMapper: {
|
||||
'@polkadot/api-contract(.*)$': '<rootDir>/packages/api-contract/src/$1',
|
||||
'@polkadot/api-derive(.*)$': '<rootDir>/packages/api-derive/src/$1',
|
||||
// eslint-disable-next-line sort-keys
|
||||
'@polkadot/api(.*)$': '<rootDir>/packages/api/src/$1',
|
||||
'@polkadot/jsonrpc(.*)$': '<rootDir>/packages/jsonrpc/src/$1',
|
||||
'@polkadot/metadata(.*)$': '<rootDir>/packages/metadata/src/$1',
|
||||
'@polkadot/rpc-(core|provider)(.*)$': '<rootDir>/packages/rpc-$1/src/$2',
|
||||
'@polkadot/types-known(.*)$': '<rootDir>/packages/types-known/src/$1',
|
||||
// eslint-disable-next-line sort-keys
|
||||
'@polkadot/types(.*)$': '<rootDir>/packages/types/src/$1'
|
||||
},
|
||||
modulePathIgnorePatterns: [
|
||||
'<rootDir>/packages/api/build',
|
||||
'<rootDir>/packages/api-derive/build',
|
||||
'<rootDir>/packages/api-contract/build',
|
||||
'<rootDir>/packages/jsonrpc/build',
|
||||
'<rootDir>/packages/metadata/build',
|
||||
'<rootDir>/packages/rpc-core/build',
|
||||
'<rootDir>/packages/rpc-provider/build',
|
||||
'<rootDir>/packages/types/build'
|
||||
'<rootDir>/packages/types/build',
|
||||
'<rootDir>/packages/types-known/build'
|
||||
],
|
||||
globals: {
|
||||
ws_local: 'ws://127.0.0.1:9944/',
|
||||
ws_local_substrate_master: 'ws://127.0.0.1:9945/',
|
||||
ws_local_substrate_1: 'ws://127.0.0.1:9946/',
|
||||
ws_local_substrate_2: 'ws://127.0.0.1:9947/',
|
||||
ws_local_polkadot_master: 'ws://127.0.0.1:9948/',
|
||||
ws_local_polkadot_alex: 'ws://127.0.0.1:9949/',
|
||||
ws_substrate_1: 'wss://substrate-rpc.parity.io/',
|
||||
ws_polkadot_alex: 'wss://poc3-rpc.polkadot.io/'
|
||||
},
|
||||
resolver: './jest.resolver.js'
|
||||
});
|
||||
|
||||
+1
-2
@@ -1,8 +1,7 @@
|
||||
// Copyright 2017-2020 @polkadot/util authors & contributors
|
||||
// Copyright 2017-2020 @polkadot/api authors & contributors
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the Apache-2.0 license. See the LICENSE file for details.
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-var-requires
|
||||
const path = require('path');
|
||||
|
||||
module.exports = function resolver (file, config) {
|
||||
|
||||
+1
-1
@@ -9,5 +9,5 @@
|
||||
"packages": [
|
||||
"packages/*"
|
||||
],
|
||||
"version": "1.5.1"
|
||||
"version": "1.21.1"
|
||||
}
|
||||
|
||||
+13
-8
@@ -7,12 +7,14 @@
|
||||
"packages/*"
|
||||
],
|
||||
"resolutions": {
|
||||
"typescript": "^3.8.3"
|
||||
"babel-core": "^7.0.0-bridge.0"
|
||||
},
|
||||
"scripts": {
|
||||
"build": "yarn build:interfaces && polkadot-dev-build-ts && (cd packages/typegen && copyfiles scripts/* build)",
|
||||
"build:interfaces": "polkadot-types-internal-interfaces",
|
||||
"build:release": "polkadot-ci-ghact-build",
|
||||
"docs": "polkadot-types-internal-metadata && polkadot-dev-build-docs",
|
||||
"docs:release": "polkadot-ci-ghact-docs",
|
||||
"chain:info": "polkadot-types-chain-info",
|
||||
"lint": "polkadot-dev-run-lint",
|
||||
"clean": "polkadot-dev-clean-build",
|
||||
@@ -22,12 +24,15 @@
|
||||
"test:watch": "polkadot-dev-run-test --watch"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@babel/core": "^7.8.4",
|
||||
"@babel/register": "^7.8.3",
|
||||
"@babel/runtime": "^7.8.4",
|
||||
"@polkadot/dev": "^0.50.27",
|
||||
"@polkadot/ts": "^0.3.7",
|
||||
"@babel/core": "^7.10.3",
|
||||
"@babel/register": "^7.10.3",
|
||||
"@babel/runtime": "^7.10.3",
|
||||
"@polkadot/dev": "^0.55.12",
|
||||
"@polkadot/ts": "^0.3.26",
|
||||
"@polkadot/typegen": "workspace:packages/typegen",
|
||||
"copyfiles": "^2.2.0"
|
||||
}
|
||||
"@types/jest": "^26.0.0",
|
||||
"@vuepress/plugin-search": "^1.5.2",
|
||||
"copyfiles": "^2.3.0"
|
||||
},
|
||||
"version": "1.21.1"
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@polkadot/api-contract",
|
||||
"version": "1.5.1",
|
||||
"version": "1.21.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.8.4",
|
||||
"@polkadot/api": "1.5.1",
|
||||
"@polkadot/rpc-core": "1.5.1",
|
||||
"@polkadot/types": "1.5.1",
|
||||
"@polkadot/util": "^2.6.1",
|
||||
"bn.js": "^5.1.1",
|
||||
"rxjs": "^6.5.4"
|
||||
"@babel/runtime": "^7.10.3",
|
||||
"@polkadot/api": "1.21.1",
|
||||
"@polkadot/rpc-core": "1.21.1",
|
||||
"@polkadot/types": "1.21.1",
|
||||
"@polkadot/util": "^2.15.1",
|
||||
"bn.js": "^5.1.2",
|
||||
"rxjs": "^6.5.5"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -18,10 +18,10 @@ export default class ContractAbi extends ContractRegistry implements InterfaceAb
|
||||
|
||||
constructor (registry: Registry, abi: ContractABIPre) {
|
||||
super(registry, abi);
|
||||
[this.abi, this.constructors, this.messages] = this.decodeAbi(abi);
|
||||
[this.abi, this.constructors, this.messages] = this._decodeAbi(abi);
|
||||
}
|
||||
|
||||
private decodeAbi (abiPre: ContractABIPre): [ContractABI, ContractABIFn[], AbiMessages] {
|
||||
private _decodeAbi (abiPre: ContractABIPre): [ContractABI, ContractABIFn[], AbiMessages] {
|
||||
this.validateAbi(abiPre);
|
||||
|
||||
const abi = this.convertAbi(abiPre);
|
||||
|
||||
@@ -19,7 +19,7 @@ function parseSelector (registry: Registry, fnname: string, input: ContractABIMe
|
||||
return registry.createType('u32', hexToU8a(input));
|
||||
} else if (typeof input === 'string') {
|
||||
try {
|
||||
const array = JSON.parse(input);
|
||||
const array = JSON.parse(input) as unknown[];
|
||||
|
||||
assert(array.length === 4, `${fnname}: Invalid selector length`);
|
||||
|
||||
@@ -61,7 +61,7 @@ export default class ContractRegistry extends MetaRegistry {
|
||||
const unknownKeys = Object.keys(arg).filter((key): boolean => !['name', 'type'].includes(key));
|
||||
|
||||
assert(unknownKeys.length === 0, `Unknown keys ${unknownKeys.join(', ')} found in ABI args for ${name}`);
|
||||
assert(isNumber(arg.name) && isString(this.stringAt(arg.name)), `${name} args should have valid name `);
|
||||
assert(isNumber(arg.name) && isString(this._stringAt(arg.name)), `${name} args should have valid name `);
|
||||
assert(isNumber(arg.type.ty) && isObject(this.typeDefAt(arg.type.ty)), `${name} args should have valid type`);
|
||||
});
|
||||
}
|
||||
@@ -83,9 +83,9 @@ export default class ContractRegistry extends MetaRegistry {
|
||||
|
||||
assert(unknownKeys.length === 0, `Unknown keys ${unknownKeys.join(', ')} found in ABI args for messages.${message.name}`);
|
||||
|
||||
const { name, selector, return_type: returnType } = message;
|
||||
const { name, return_type: returnType, selector } = message;
|
||||
|
||||
assert(isNumber(name) && isString(this.stringAt(name)), `Expected name for ${fnname}`);
|
||||
assert(isNumber(name) && isString(this._stringAt(name)), `Expected name for ${fnname}`);
|
||||
assert(isNull(returnType) || (isNumber(returnType.ty) && isObject(this.typeDefAt(returnType.ty))), `Expected return_type for ${fnname}`);
|
||||
|
||||
parseSelector(this.registry, fnname, selector);
|
||||
@@ -100,7 +100,7 @@ export default class ContractRegistry extends MetaRegistry {
|
||||
|
||||
const { contract: { constructors, messages, name } } = abi;
|
||||
|
||||
assert(constructors && messages && isString(this.stringAt(name)), 'ABI should have constructors, messages & name sections');
|
||||
assert(constructors && messages && isString(this._stringAt(name)), 'ABI should have constructors, messages & name sections');
|
||||
|
||||
this.validateConstructors(abi);
|
||||
this.validateMessages(abi);
|
||||
@@ -108,14 +108,17 @@ export default class ContractRegistry extends MetaRegistry {
|
||||
|
||||
public createMessage (name: string, message: Partial<ContractABIMessage> & ContractABIMessageBase): ContractABIFn {
|
||||
const args = message.args.map(({ name, type }): ContractABIFnArg => {
|
||||
assert(isObject(type), `Invalid type at index ${type}`);
|
||||
assert(isObject(type), `Invalid type at index ${type.toString()}`);
|
||||
|
||||
return {
|
||||
name: stringCamelCase(name),
|
||||
type
|
||||
};
|
||||
});
|
||||
|
||||
const Clazz = createArgClass(this.registry, args, isUndefined(message.selector) ? {} : { __selector: 'u32' });
|
||||
const baseStruct: { [index: string]: any } = { __selector: isUndefined(message.selector) ? undefined : parseSelector(this.registry, name, message.selector) };
|
||||
|
||||
const encoder = (...params: CodecArg[]): Uint8Array => {
|
||||
assert(params.length === args.length, `Expected ${args.length} arguments to contract ${name}, found ${params.length}`);
|
||||
|
||||
@@ -136,6 +139,7 @@ export default class ContractRegistry extends MetaRegistry {
|
||||
fn.args = args;
|
||||
fn.isConstant = !(message.mutates || false);
|
||||
fn.type = message.returnType || null;
|
||||
|
||||
return fn;
|
||||
}
|
||||
|
||||
@@ -147,21 +151,22 @@ export default class ContractRegistry extends MetaRegistry {
|
||||
}
|
||||
|
||||
public convertArgs (args: ContractABIArgBasePre[]): any[] {
|
||||
return args.map(({ name, type, ...arg }) => ({ ...arg, name: this.stringAt(name), type: this.convertType(type) }));
|
||||
return args.map(({ name, type, ...arg }) => ({ ...arg, name: this._stringAt(name), type: this.convertType(type) }));
|
||||
}
|
||||
|
||||
public convertType ({ ty, display_name: displayNameIndices }: ContractABITypePre): TypeDef {
|
||||
public convertType ({ display_name: displayNameIndices, ty }: ContractABITypePre): TypeDef {
|
||||
const displayName = this.stringsAt(displayNameIndices).join('::');
|
||||
|
||||
return this.typeDefAt(ty, { displayName });
|
||||
}
|
||||
|
||||
public convertContract ({ constructors, messages, name, events, ...contract }: ContractABIContractPre): ContractABIContract {
|
||||
public convertContract ({ constructors, events, messages, name, ...contract }: ContractABIContractPre): ContractABIContract {
|
||||
return {
|
||||
constructors: this.convertConstructors(constructors),
|
||||
messages: messages.map(message => this.convertMessage(message)),
|
||||
name: this.stringAt(name),
|
||||
messages: messages.map((message) => this.convertMessage(message)),
|
||||
name: this._stringAt(name),
|
||||
...(events
|
||||
? { events: events.map(event => this.convertEvent(event)) }
|
||||
? { events: events.map((event) => this.convertEvent(event)) }
|
||||
: {}),
|
||||
...contract
|
||||
};
|
||||
@@ -178,14 +183,16 @@ export default class ContractRegistry extends MetaRegistry {
|
||||
public convertMessage ({ args, name, return_type: returnType, ...message }: ContractABIMessagePre): ContractABIMessage {
|
||||
return {
|
||||
...message,
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
|
||||
args: this.convertArgs(args),
|
||||
name: this.stringAt(name),
|
||||
name: this._stringAt(name),
|
||||
returnType: returnType ? this.convertType(returnType) : null
|
||||
};
|
||||
}
|
||||
|
||||
public convertEvent ({ args }: ContractABIEventPre): ContractABIEvent {
|
||||
return {
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
|
||||
args: this.convertArgs(args)
|
||||
};
|
||||
}
|
||||
@@ -202,13 +209,13 @@ export default class ContractRegistry extends MetaRegistry {
|
||||
}
|
||||
}
|
||||
|
||||
public convertStorageStruct ({ 'struct.type': structType, 'struct.fields': structFields }: ContractABIStorageStructPre): ContractABIStorageStruct {
|
||||
public convertStorageStruct ({ 'struct.fields': structFields, 'struct.type': structType }: ContractABIStorageStructPre): ContractABIStorageStruct {
|
||||
return {
|
||||
'struct.type': this.typeDefAt(structType),
|
||||
'struct.fields': structFields.map(({ name, layout }) => ({
|
||||
name: this.stringAt(name),
|
||||
layout: this.convertStorageLayout(layout)
|
||||
}))
|
||||
'struct.fields': structFields.map(({ layout, name }) => ({
|
||||
layout: this.convertStorageLayout(layout),
|
||||
name: this._stringAt(name)
|
||||
})),
|
||||
'struct.type': this.typeDefAt(structType)
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -7,11 +7,11 @@ import { MetaRegistryItem, MetaRegistryJson, MetaTypeDefClikeEnum, MetaType, Met
|
||||
import { assert } from '@polkadot/util';
|
||||
import { displayType, withTypeString } from '@polkadot/types';
|
||||
|
||||
const builtinMap: [(id: any) => boolean, MetaTypeInfo][] = [
|
||||
[(id: any): boolean => typeof id === 'string', MetaTypeInfo.BuiltinPlain],
|
||||
[(id: any): boolean => Array.isArray(id), MetaTypeInfo.BuiltinTuple],
|
||||
[(id: any): boolean => !!(id['array.type']), MetaTypeInfo.BuiltinVecFixed],
|
||||
[(id: any): boolean => !!(id['slice.type']), MetaTypeInfo.BuiltinVec]
|
||||
const builtinMap: [(id: unknown | unknown[] | { 'array.type': unknown } | { 'slice.type': unknown }) => boolean, MetaTypeInfo][] = [
|
||||
[(id: any) => typeof id === 'string', MetaTypeInfo.BuiltinPlain],
|
||||
[(id: any) => Array.isArray(id), MetaTypeInfo.BuiltinTuple],
|
||||
[(id: any) => !!((id as { 'array.type': unknown })['array.type']), MetaTypeInfo.BuiltinVecFixed],
|
||||
[(id: any) => !!((id as { 'slice.type': unknown })['slice.type']), MetaTypeInfo.BuiltinVec]
|
||||
];
|
||||
|
||||
const typeMap: [string, MetaTypeInfo][] = [
|
||||
@@ -25,8 +25,8 @@ function detectedType ({ def, id }: MetaType): MetaTypeInfo {
|
||||
assert(!(def as MetaTypeDefUnion)['union.fields'], 'Invalid union type definition found');
|
||||
|
||||
const lookup = def === 'builtin'
|
||||
? builtinMap.find(([test]): boolean => test(id))
|
||||
: typeMap.find(([test]): boolean => !!(def as any)[test]);
|
||||
? builtinMap.find(([test]) => test(id))
|
||||
: typeMap.find(([test]) => !!(def as unknown as Record<string, unknown>)[test]);
|
||||
|
||||
return lookup
|
||||
? lookup[1]
|
||||
@@ -48,7 +48,7 @@ class MetadataRegistryLookup {
|
||||
this._types = types;
|
||||
}
|
||||
|
||||
protected hasItemAt (index: number, variant: MetaRegistryItem): boolean {
|
||||
protected _hasItemAt (index: number, variant: MetaRegistryItem): boolean {
|
||||
switch (variant) {
|
||||
case MetaRegistryItem.String:
|
||||
return this._strings && !!this._strings[index - 1];
|
||||
@@ -59,8 +59,8 @@ class MetadataRegistryLookup {
|
||||
}
|
||||
}
|
||||
|
||||
protected itemAt (index: number, variant: MetaRegistryItem): any {
|
||||
assert(this.hasItemAt(index, variant), `MetaRegistry: Invalid ${variant} index ${index} found in metadata`);
|
||||
protected _itemAt (index: number, variant: MetaRegistryItem): string | MetaType | TypeDef {
|
||||
assert(this._hasItemAt(index, variant), `MetaRegistry: Invalid ${variant} index ${index} found in metadata`);
|
||||
|
||||
switch (variant) {
|
||||
case MetaRegistryItem.String:
|
||||
@@ -72,33 +72,33 @@ class MetadataRegistryLookup {
|
||||
}
|
||||
}
|
||||
|
||||
protected itemsAt (indices: number[], variant: MetaRegistryItem): any[] {
|
||||
return indices.map((index: number): string => this.itemAt(index, variant));
|
||||
protected _itemsAt (indices: number[], variant: MetaRegistryItem): (string | MetaType | TypeDef)[] {
|
||||
return indices.map((index: number) => this._itemAt(index, variant));
|
||||
}
|
||||
|
||||
protected stringAt (index: StringIndex): string {
|
||||
return this.itemAt(index, MetaRegistryItem.String);
|
||||
protected _stringAt (index: StringIndex): string {
|
||||
return this._itemAt(index, MetaRegistryItem.String) as string;
|
||||
}
|
||||
|
||||
public stringsAt (indices: StringIndex[]): string[] {
|
||||
return this.itemsAt(indices, MetaRegistryItem.String);
|
||||
return this._itemsAt(indices, MetaRegistryItem.String) as string[];
|
||||
}
|
||||
|
||||
public typeAt (index: TypeIndex): MetaType {
|
||||
return this.itemAt(index, MetaRegistryItem.Type);
|
||||
return this._itemAt(index, MetaRegistryItem.Type) as MetaType;
|
||||
}
|
||||
|
||||
public typesAt (indices: TypeIndex[]): MetaType[] {
|
||||
return this.itemsAt(indices, MetaRegistryItem.Type);
|
||||
return this._itemsAt(indices, MetaRegistryItem.Type) as MetaType[];
|
||||
}
|
||||
|
||||
public hasTypeDefAt (index: TypeIndex): boolean {
|
||||
return this.hasItemAt(index, MetaRegistryItem.TypeDef);
|
||||
return this._hasItemAt(index, MetaRegistryItem.TypeDef);
|
||||
}
|
||||
|
||||
public typeDefAt (index: TypeIndex, extra: Pick<TypeDef, never> = {}): TypeDef {
|
||||
return {
|
||||
...this.itemAt(index, MetaRegistryItem.TypeDef),
|
||||
...this._itemAt(index, MetaRegistryItem.TypeDef) as TypeDef,
|
||||
...extra
|
||||
};
|
||||
}
|
||||
@@ -116,7 +116,7 @@ export default class MetaRegistry extends MetadataRegistryLookup {
|
||||
this.typeDefs[typeIndex - 1] = this.typeDefFromMetaType(this.typeAt(typeIndex), typeIndex);
|
||||
}
|
||||
|
||||
private typeDefIdFields ({ id }: MetaType): Pick<TypeDef, never> {
|
||||
private _typeDefIdFields ({ id }: MetaType): Pick<TypeDef, never> {
|
||||
const { 'custom.name': nameIndex, 'custom.namespace': namespaceIndices, 'custom.params': paramsIndices } = id as MetaTypeIdCustom;
|
||||
|
||||
if (!nameIndex) {
|
||||
@@ -124,7 +124,7 @@ export default class MetaRegistry extends MetadataRegistryLookup {
|
||||
}
|
||||
|
||||
return {
|
||||
name: this.stringAt(nameIndex),
|
||||
name: this._stringAt(nameIndex),
|
||||
...(namespaceIndices && namespaceIndices.length
|
||||
? { namespace: this.stringsAt(namespaceIndices).join('::') }
|
||||
: {}
|
||||
@@ -136,33 +136,33 @@ export default class MetaRegistry extends MetadataRegistryLookup {
|
||||
};
|
||||
}
|
||||
|
||||
private typeDefDefFields (metaType: MetaType, typeIndex?: TypeIndex): Pick<TypeDef, never> {
|
||||
private _typeDefDefFields (metaType: MetaType, typeIndex: TypeIndex = -1): Pick<TypeDef, never> {
|
||||
let typeDef;
|
||||
|
||||
switch (detectedType(metaType)) {
|
||||
case MetaTypeInfo.BuiltinPlain:
|
||||
typeDef = this.typeDefForBuiltinPlain(metaType.id as string);
|
||||
typeDef = this._typeDefForBuiltinPlain(metaType.id as string);
|
||||
break;
|
||||
case MetaTypeInfo.BuiltinTuple:
|
||||
typeDef = this.typeDefForBuiltinTuple(metaType.id as TypeIndex[]);
|
||||
typeDef = this._typeDefForBuiltinTuple(metaType.id as TypeIndex[]);
|
||||
break;
|
||||
case MetaTypeInfo.BuiltinVec:
|
||||
typeDef = this.typeDefForBuiltinVec(metaType.id as MetaTypeIdVec, typeIndex);
|
||||
typeDef = this._typeDefForBuiltinVec(metaType.id as MetaTypeIdVec, typeIndex);
|
||||
break;
|
||||
case MetaTypeInfo.BuiltinVecFixed:
|
||||
typeDef = this.typeDefForBuiltinVecFixed(metaType.id as MetaTypeIdVecFixed, typeIndex);
|
||||
typeDef = this._typeDefForBuiltinVecFixed(metaType.id as MetaTypeIdVecFixed, typeIndex);
|
||||
break;
|
||||
case MetaTypeInfo.Enum:
|
||||
typeDef = this.typeDefForEnum(metaType.def as MetaTypeDefEnum, metaType.id as MetaTypeIdCustom, typeIndex);
|
||||
typeDef = this._typeDefForEnum(metaType.def as MetaTypeDefEnum, metaType.id as MetaTypeIdCustom, typeIndex);
|
||||
break;
|
||||
case MetaTypeInfo.ClikeEnum:
|
||||
typeDef = this.typeDefForClikeEnum(metaType.def as MetaTypeDefClikeEnum);
|
||||
typeDef = this._typeDefForClikeEnum(metaType.def as MetaTypeDefClikeEnum);
|
||||
break;
|
||||
case MetaTypeInfo.Struct:
|
||||
typeDef = this.typeDefForStruct(metaType.def as MetaTypeDefStruct);
|
||||
break;
|
||||
case MetaTypeInfo.TupleStruct:
|
||||
typeDef = this.typeDefForTupleStruct(metaType.def as MetaTypeDefTupleStruct);
|
||||
typeDef = this._typeDefForTupleStruct(metaType.def as MetaTypeDefTupleStruct);
|
||||
break;
|
||||
case MetaTypeInfo.Null:
|
||||
default:
|
||||
@@ -176,8 +176,8 @@ export default class MetaRegistry extends MetadataRegistryLookup {
|
||||
return withTypeString({
|
||||
info: TypeDefInfo.Null,
|
||||
type: '',
|
||||
...this.typeDefDefFields(metaType, typeIndex),
|
||||
...this.typeDefIdFields(metaType)
|
||||
...this._typeDefDefFields(metaType, typeIndex),
|
||||
...this._typeDefIdFields(metaType)
|
||||
}) as TypeDef;
|
||||
}
|
||||
|
||||
@@ -189,13 +189,13 @@ export default class MetaRegistry extends MetadataRegistryLookup {
|
||||
return this.typeDefAt(typeIndex);
|
||||
}
|
||||
|
||||
private typeDefForEnumVariant (variant: MetaTypeDefEnumVariant): Pick<TypeDef, any> {
|
||||
private _typeDefForEnumVariant (variant: MetaTypeDefEnumVariant): Pick<TypeDef, any> {
|
||||
const { 'unit_variant.name': unitNameIndex } = variant as MetaTypeDefEnumVariantUnit;
|
||||
|
||||
if (unitNameIndex) {
|
||||
return {
|
||||
info: TypeDefInfo.Plain,
|
||||
name: this.stringAt(unitNameIndex),
|
||||
name: this._stringAt(unitNameIndex),
|
||||
type: 'Null'
|
||||
};
|
||||
}
|
||||
@@ -203,7 +203,7 @@ export default class MetaRegistry extends MetadataRegistryLookup {
|
||||
const { 'tuple_struct_variant.name': tupleStructVariantNameIndex } = variant as MetaTypeDefEnumVariantTupleStruct;
|
||||
|
||||
if (tupleStructVariantNameIndex) {
|
||||
return this.typeDefForTupleStruct(variant as MetaTypeDefEnumVariantTupleStruct);
|
||||
return this._typeDefForTupleStruct(variant as MetaTypeDefEnumVariantTupleStruct);
|
||||
}
|
||||
|
||||
const { 'struct_variant.name': structVariantNameIndex } = variant as MetaTypeDefEnumVariantStruct;
|
||||
@@ -218,14 +218,14 @@ export default class MetaRegistry extends MetadataRegistryLookup {
|
||||
};
|
||||
}
|
||||
|
||||
private typeDefForBuiltinPlain (id: string): Pick<TypeDef, never> {
|
||||
private _typeDefForBuiltinPlain (id: string): Pick<TypeDef, never> {
|
||||
return {
|
||||
info: TypeDefInfo.Plain,
|
||||
type: id
|
||||
};
|
||||
}
|
||||
|
||||
private typeDefForBuiltinTuple (id: TypeIndex[]): Pick<TypeDef, never> {
|
||||
private _typeDefForBuiltinTuple (id: TypeIndex[]): Pick<TypeDef, never> {
|
||||
const sub = id.map((tupleTypeIndex: number): TypeDef => this.typeDefFromMetaTypeAt(tupleTypeIndex));
|
||||
|
||||
return {
|
||||
@@ -234,48 +234,52 @@ export default class MetaRegistry extends MetadataRegistryLookup {
|
||||
};
|
||||
}
|
||||
|
||||
private typeDefForBuiltinVec (id: MetaTypeIdVec, typeIndex?: TypeIndex): Pick<TypeDef, never> {
|
||||
private _typeDefForBuiltinVec (id: MetaTypeIdVec, typeIndex: TypeIndex = -1): Pick<TypeDef, never> {
|
||||
const { 'slice.type': vecTypeIndex } = id;
|
||||
|
||||
assert(!typeIndex || vecTypeIndex !== typeIndex, `MetaRegistry: self-referencing registry type at index ${typeIndex}`);
|
||||
|
||||
const type = displayType(this.typeDefFromMetaTypeAt(vecTypeIndex));
|
||||
|
||||
assert(type && type.length > 0, `MetaRegistry: Invalid builtin Vec type found at index ${typeIndex}`);
|
||||
|
||||
return {
|
||||
info: TypeDefInfo.Vec,
|
||||
type: `Vec<${type}>`,
|
||||
sub: this.typeDefFromMetaTypeAt(vecTypeIndex)
|
||||
sub: this.typeDefFromMetaTypeAt(vecTypeIndex),
|
||||
type: `Vec<${type}>`
|
||||
};
|
||||
}
|
||||
|
||||
private typeDefForBuiltinVecFixed (id: MetaTypeIdVecFixed, typeIndex?: TypeIndex): Pick<TypeDef, never> {
|
||||
const { 'array.type': vecTypeIndex, 'array.len': vecLength } = id;
|
||||
private _typeDefForBuiltinVecFixed (id: MetaTypeIdVecFixed, typeIndex: TypeIndex = -1): Pick<TypeDef, never> {
|
||||
const { 'array.len': vecLength, 'array.type': vecTypeIndex } = id;
|
||||
|
||||
assert(!vecLength || vecLength <= 256, 'MetaRegistry: Only support for [Type; <length>], where length <= 256');
|
||||
assert(!typeIndex || vecTypeIndex !== typeIndex, `MetaRegistry: self-referencing registry type at index ${typeIndex}`);
|
||||
|
||||
const type = displayType(this.typeDefFromMetaTypeAt(vecTypeIndex));
|
||||
|
||||
assert(type && type.length > 0, `MetaRegistry: Invalid vector type found at index ${typeIndex}`);
|
||||
|
||||
return {
|
||||
info: TypeDefInfo.VecFixed,
|
||||
length: vecLength, // ex: { type: type }
|
||||
type: `[${type};${vecLength}]`,
|
||||
sub: this.typeDefFromMetaTypeAt(vecTypeIndex)
|
||||
sub: this.typeDefFromMetaTypeAt(vecTypeIndex),
|
||||
type: `[${type};${vecLength}]`
|
||||
};
|
||||
}
|
||||
|
||||
private typeDefForEnum (def: MetaTypeDefEnum, id: MetaTypeIdCustom, typeIndex?: TypeIndex): Pick<TypeDef, any> {
|
||||
const name = id && this.stringAt(id['custom.name']);
|
||||
private _typeDefForEnum (def: MetaTypeDefEnum, id: MetaTypeIdCustom, typeIndex?: TypeIndex): Pick<TypeDef, any> {
|
||||
const name = id && this._stringAt(id['custom.name']);
|
||||
|
||||
switch (name) {
|
||||
case 'Option':
|
||||
return this.typeDefForOption(id, typeIndex);
|
||||
|
||||
case 'Result':
|
||||
return this.typeDefForResult(id, typeIndex);
|
||||
|
||||
default: {
|
||||
const sub = def['enum.variants'].map(variant => this.typeDefForEnumVariant(variant));
|
||||
const sub = def['enum.variants'].map((variant) => this._typeDefForEnumVariant(variant));
|
||||
|
||||
return {
|
||||
info: TypeDefInfo.Enum,
|
||||
@@ -285,19 +289,19 @@ export default class MetaRegistry extends MetadataRegistryLookup {
|
||||
}
|
||||
}
|
||||
|
||||
private typeDefForClikeEnum (def: MetaTypeDefClikeEnum): Pick<TypeDef, never> {
|
||||
private _typeDefForClikeEnum (def: MetaTypeDefClikeEnum): Pick<TypeDef, never> {
|
||||
return {
|
||||
info: TypeDefInfo.Enum,
|
||||
sub: def['clike_enum.variants'].map(({ name: nameIndex, discriminant }): TypeDef => ({
|
||||
sub: def['clike_enum.variants'].map(({ discriminant, name: nameIndex }): TypeDef => ({
|
||||
ext: { discriminant },
|
||||
info: TypeDefInfo.Plain,
|
||||
name: this.stringAt(nameIndex),
|
||||
name: this._stringAt(nameIndex),
|
||||
type: 'Null'
|
||||
}))
|
||||
};
|
||||
}
|
||||
|
||||
public typeDefForOption (id: MetaTypeIdCustom, typeIndex?: TypeIndex): Pick<TypeDef, any> {
|
||||
public typeDefForOption (id: MetaTypeIdCustom, typeIndex: TypeIndex = -1): Pick<TypeDef, any> {
|
||||
assert(id['custom.params'] && id['custom.params'][0], `Invalid Option type defined at index ${typeIndex}`);
|
||||
|
||||
return {
|
||||
@@ -306,7 +310,7 @@ export default class MetaRegistry extends MetadataRegistryLookup {
|
||||
};
|
||||
}
|
||||
|
||||
public typeDefForResult (id: MetaTypeIdCustom, typeIndex?: TypeIndex): Pick<TypeDef, any> {
|
||||
public typeDefForResult (id: MetaTypeIdCustom, typeIndex: TypeIndex = -1): Pick<TypeDef, any> {
|
||||
assert(id['custom.params'] && id['custom.params'][0] && id['custom.params'][1], `Invalid Result type defined at index ${typeIndex}`);
|
||||
|
||||
return {
|
||||
@@ -322,24 +326,24 @@ export default class MetaRegistry extends MetadataRegistryLookup {
|
||||
return withTypeString({
|
||||
info: TypeDefInfo.Struct,
|
||||
...(structNameIndex
|
||||
? { name: this.stringAt(structNameIndex) }
|
||||
? { name: this._stringAt(structNameIndex) }
|
||||
: {}
|
||||
),
|
||||
sub: structFields.map((field: MetaTypeDefStructField): TypeDef => ({
|
||||
...this.typeDefFromMetaTypeAt(field.type),
|
||||
name: this.stringAt(field.name)
|
||||
name: this._stringAt(field.name)
|
||||
}))
|
||||
});
|
||||
}
|
||||
|
||||
private typeDefForTupleStruct (def: MetaTypeDefTupleStruct | MetaTypeDefEnumVariantTupleStruct): Pick<TypeDef, any> {
|
||||
private _typeDefForTupleStruct (def: MetaTypeDefTupleStruct | MetaTypeDefEnumVariantTupleStruct): Pick<TypeDef, any> {
|
||||
const tupleStructTypes = (def as MetaTypeDefTupleStruct)['tuple_struct.types'] || (def as MetaTypeDefEnumVariantTupleStruct)['tuple_struct_variant.types'];
|
||||
const tupleStructNameIndex = (def as MetaTypeDefEnumVariantTupleStruct)['tuple_struct_variant.name'];
|
||||
|
||||
return withTypeString({
|
||||
info: TypeDefInfo.Tuple,
|
||||
...(tupleStructNameIndex
|
||||
? { name: this.stringAt(tupleStructNameIndex) }
|
||||
? { name: this._stringAt(tupleStructNameIndex) }
|
||||
: {}
|
||||
),
|
||||
sub: tupleStructTypes.map((fieldIndex: number, index: number): TypeDef => ({
|
||||
|
||||
@@ -47,18 +47,19 @@ export default class Blueprint<ApiType extends ApiTypes> extends BaseWithTx<ApiT
|
||||
assert(!!this.abi.constructors[constructorIndex], `Specified constructor index ${constructorIndex} does not exist`);
|
||||
|
||||
return {
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
|
||||
signAndSend: this.decorateMethod(
|
||||
(account: IKeyringPair | string | AccountId | Address): BlueprintCreateResultSubscription<ApiType> => {
|
||||
return this.apiContracts
|
||||
return this._apiContracts
|
||||
.create(endowment, maxGas, this.codeHash, this.abi.constructors[constructorIndex](...params))
|
||||
.signAndSend(account)
|
||||
.pipe(map(this.createResult));
|
||||
.pipe(map(this._createResult));
|
||||
}
|
||||
)
|
||||
};
|
||||
}
|
||||
|
||||
private createResult = (result: SubmittableResult): BlueprintCreateResult<ApiType> => {
|
||||
private _createResult = (result: SubmittableResult): BlueprintCreateResult<ApiType> => {
|
||||
let contract: Contract<ApiType> | undefined;
|
||||
|
||||
if (result.isInBlock) {
|
||||
|
||||
@@ -19,7 +19,6 @@ import { BaseWithTx } from './util';
|
||||
|
||||
type CodePutCodeResultSubscription<ApiType extends ApiTypes> = Observable<CodePutCodeResult<ApiType>>;
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/interface-name-prefix
|
||||
export interface CodePutCode<ApiType extends ApiTypes> {
|
||||
signAndSend (account: IKeyringPair | string | AccountId | Address): CodePutCodeResultSubscription<ApiType>;
|
||||
}
|
||||
@@ -46,17 +45,18 @@ export default class Code<ApiType extends ApiTypes> extends BaseWithTx<ApiType>
|
||||
|
||||
public createBlueprint = (maxGas: number | BN): CodePutCode<ApiType> => {
|
||||
return {
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
|
||||
signAndSend: this.decorateMethod(
|
||||
(account: IKeyringPair | string | AccountId | Address): CodePutCodeResultSubscription<ApiType> =>
|
||||
this.apiContracts
|
||||
this._apiContracts
|
||||
.putCode(maxGas, compactAddLength(this.code))
|
||||
.signAndSend(account)
|
||||
.pipe(map(this.createResult))
|
||||
.pipe(map(this._createResult))
|
||||
)
|
||||
};
|
||||
}
|
||||
|
||||
private createResult = (result: ISubmittableResult): CodePutCodeResult<ApiType> => {
|
||||
private _createResult = (result: ISubmittableResult): CodePutCodeResult<ApiType> => {
|
||||
let blueprint: Blueprint<ApiType> | undefined;
|
||||
|
||||
if (result.isInBlock) {
|
||||
|
||||
@@ -21,7 +21,6 @@ type ContractCallResultSubscription<ApiType extends ApiTypes, CallType extends C
|
||||
? Observable<ContractCallResult<CallType>>
|
||||
: Promise<ObsInnerType<ContractCallResult<CallType>>>;
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/interface-name-prefix
|
||||
export interface ContractCall<ApiType extends ApiTypes, CallType extends ContractCallTypes> {
|
||||
send (account: IKeyringPair | string | AccountId | Address): ContractCallResultSubscription<ApiType, CallType>;
|
||||
}
|
||||
@@ -33,35 +32,42 @@ export type ContractCallResult<CallType extends ContractCallTypes> = CallType ex
|
||||
export default class Contract<ApiType extends ApiTypes> extends BaseWithTxAndRpcCall<ApiType> {
|
||||
public readonly address: Address;
|
||||
|
||||
constructor (api: ApiObject<ApiType>, abi: ContractABIPre | Abi, decorateMethod: DecorateMethod<ApiType>, address: string | AccountId | Address) {
|
||||
super(api, abi, decorateMethod);
|
||||
|
||||
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> {
|
||||
const { fn, def } = this.getMessage(message);
|
||||
const { def, fn } = this.getMessage(message);
|
||||
|
||||
return {
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
|
||||
send: this.decorateMethod(
|
||||
as === 'rpc' && this.hasRpcContractsCall
|
||||
? (account: IKeyringPair | string | AccountId | Address): ContractCallResult<'rpc'> =>
|
||||
this.rpcContractsCall(
|
||||
this._rpcContractsCall(
|
||||
this.registry.createType('ContractCallRequest', {
|
||||
origin: account,
|
||||
dest: this.address.toString(),
|
||||
value,
|
||||
gasLimit,
|
||||
inputData: fn(...params)
|
||||
inputData: fn(...params),
|
||||
origin: account,
|
||||
value
|
||||
})
|
||||
).pipe(map((result: ContractExecResult): ContractCallOutcome =>
|
||||
this.createOutcome(result, this.registry.createType('AccountId', account), def, params)
|
||||
this._createOutcome(result, this.registry.createType('AccountId', account), def, params)
|
||||
))
|
||||
: (account: IKeyringPair | string | AccountId | Address): ContractCallResult<'tx'> =>
|
||||
this.apiContracts
|
||||
this._apiContracts
|
||||
.call(this.address, value, gasLimit, fn(...params))
|
||||
.signAndSend(account)
|
||||
)
|
||||
};
|
||||
}
|
||||
|
||||
private createOutcome (result: ContractExecResult, origin: AccountId, message: ContractABIMessage, params: any[]): ContractCallOutcome {
|
||||
private _createOutcome (result: ContractExecResult, origin: AccountId, message: ContractABIMessage, params: any[]): ContractCallOutcome {
|
||||
let output: Codec | null = null;
|
||||
|
||||
if (result.isSuccess) {
|
||||
@@ -73,19 +79,13 @@ export default class Contract<ApiType extends ApiTypes> extends BaseWithTxAndRpc
|
||||
}
|
||||
|
||||
return {
|
||||
time: Date.now(),
|
||||
isSuccess: result.isSuccess,
|
||||
message,
|
||||
origin,
|
||||
output,
|
||||
params,
|
||||
result,
|
||||
isSuccess: result.isSuccess,
|
||||
output
|
||||
time: Date.now()
|
||||
};
|
||||
}
|
||||
|
||||
constructor (api: ApiObject<ApiType>, abi: ContractABIPre | Abi, decorateMethod: DecorateMethod<ApiType>, address: string | AccountId | Address) {
|
||||
super(api, abi, decorateMethod);
|
||||
|
||||
this.address = this.registry.createType('Address', address);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -31,9 +31,9 @@ export abstract class Base<ApiType extends ApiTypes> implements ContractBase<Api
|
||||
public get messages (): ContractMessage[] {
|
||||
return this.abi.abi.contract.messages.map(
|
||||
(def: ContractABIMessage, index): ContractMessage => ({
|
||||
index,
|
||||
def,
|
||||
fn: this.abi.messages[def.name] || this.abi.messages[stringCamelCase(name)]
|
||||
fn: this.abi.messages[def.name] || this.abi.messages[stringCamelCase(name)],
|
||||
index
|
||||
})
|
||||
);
|
||||
}
|
||||
@@ -46,15 +46,16 @@ export abstract class Base<ApiType extends ApiTypes> implements ContractBase<Api
|
||||
: 0;
|
||||
const def = this.abi.abi.contract.messages[index];
|
||||
|
||||
assert(!!def, `Attempted to access a contract message that does not exist: ${typeof nameOrIndex === 'number' ? `index ${nameOrIndex}` : nameOrIndex}`);
|
||||
assert(!!def, `Attempted to access a contract message that does not exist: ${typeof nameOrIndex === 'number' ? `index ${nameOrIndex}` : (nameOrIndex || 'unknown')}`);
|
||||
|
||||
const fn = this.abi.messages[def.name] || this.abi.messages[stringCamelCase(def.name)];
|
||||
return { index, def, fn };
|
||||
|
||||
return { def, fn, index };
|
||||
}
|
||||
}
|
||||
|
||||
export abstract class BaseWithTx<ApiType extends ApiTypes> extends Base<ApiType> {
|
||||
protected get apiContracts (): SubmittableModuleExtrinsics<'rxjs'> {
|
||||
protected get _apiContracts (): SubmittableModuleExtrinsics<'rxjs'> {
|
||||
return this.api.rx.tx.contracts;
|
||||
}
|
||||
|
||||
@@ -70,7 +71,7 @@ export abstract class BaseWithTxAndRpcCall<ApiType extends ApiTypes> extends Bas
|
||||
return isFunction(this.api.rx.rpc.contracts?.call);
|
||||
}
|
||||
|
||||
protected get rpcContractsCall (): DecoratedRpc<'rxjs', RpcInterface>['contracts']['call'] {
|
||||
protected get _rpcContractsCall (): DecoratedRpc<'rxjs', RpcInterface>['contracts']['call'] {
|
||||
assert(this.hasRpcContractsCall, 'You need to connect to a node with the contracts.call RPC method.');
|
||||
|
||||
return this.api.rx.rpc.contracts.call;
|
||||
|
||||
@@ -7,7 +7,6 @@ import { AccountId, Address, ContractExecResult } from '@polkadot/types/interfac
|
||||
import { Codec, CodecArg } from '@polkadot/types/types';
|
||||
import { MetaRegistryJson, StringIndex, TypeIndex, TypeDef } from '@polkadot/types/create/types';
|
||||
|
||||
// import { Observable } from 'rxjs';
|
||||
import { ApiPromise, ApiRx } from '@polkadot/api';
|
||||
|
||||
export type ApiObject<ApiType extends ApiTypes> = ApiType extends 'rxjs'
|
||||
@@ -24,6 +23,7 @@ export interface ContractBase<ApiType extends ApiTypes> {
|
||||
|
||||
export interface ContractABITypePre {
|
||||
ty: TypeIndex;
|
||||
// eslint-disable-next-line camelcase
|
||||
display_name: StringIndex[];
|
||||
}
|
||||
|
||||
@@ -57,6 +57,7 @@ export interface ContractABIMessageCommon {
|
||||
|
||||
export interface ContractABIMessagePre extends ContractABIMessageCommon, ContractABIMessageBasePre {
|
||||
name: StringIndex;
|
||||
// eslint-disable-next-line camelcase
|
||||
return_type: ContractABITypePre | null;
|
||||
}
|
||||
|
||||
@@ -188,6 +189,7 @@ export interface InterfaceAbi {
|
||||
}
|
||||
|
||||
export interface InterfaceContractCalls {
|
||||
// eslint-disable-next-line @typescript-eslint/ban-types
|
||||
[index: string]: Function;
|
||||
}
|
||||
|
||||
|
||||
@@ -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 { Codec, Registry, TypeDefInfo, TypeDef } from '@polkadot/types/types';
|
||||
import { Codec, Registry, TypeDef, TypeDefInfo } from '@polkadot/types/types';
|
||||
|
||||
import { Option, Raw, createClass, createTypeUnsafe } from '@polkadot/types';
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@polkadot/api-derive",
|
||||
"version": "1.5.1",
|
||||
"version": "1.21.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.8.4",
|
||||
"@polkadot/api": "1.5.1",
|
||||
"@polkadot/rpc-core": "1.5.1",
|
||||
"@polkadot/rpc-provider": "1.5.1",
|
||||
"@polkadot/types": "1.5.1",
|
||||
"@polkadot/util": "^2.6.1",
|
||||
"@polkadot/util-crypto": "^2.6.1",
|
||||
"bn.js": "^5.1.1",
|
||||
"@babel/runtime": "^7.10.3",
|
||||
"@polkadot/api": "1.21.1",
|
||||
"@polkadot/rpc-core": "1.21.1",
|
||||
"@polkadot/rpc-provider": "1.21.1",
|
||||
"@polkadot/types": "1.21.1",
|
||||
"@polkadot/util": "^2.15.1",
|
||||
"@polkadot/util-crypto": "^2.15.1",
|
||||
"bn.js": "^5.1.2",
|
||||
"memoizee": "^0.4.14",
|
||||
"rxjs": "^6.5.4"
|
||||
"rxjs": "^6.5.5"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@polkadot/keyring": "^2.6.1"
|
||||
"@polkadot/keyring": "^2.15.1"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
// 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, Address, Balance } from '@polkadot/types/interfaces';
|
||||
import { ITuple } from '@polkadot/types/types';
|
||||
import { DeriveAccountFlags } from '../types';
|
||||
|
||||
import { Observable, combineLatest, of } from 'rxjs';
|
||||
import { map } from 'rxjs/operators';
|
||||
import { Vec } from '@polkadot/types';
|
||||
|
||||
import { memo } from '../util';
|
||||
|
||||
type FlagsIntermediate = [
|
||||
Vec<ITuple<[AccountId, Balance]>> | undefined,
|
||||
AccountId[],
|
||||
AccountId[],
|
||||
AccountId[],
|
||||
AccountId | undefined
|
||||
];
|
||||
|
||||
function isIncludedFn (accountId: AccountId | Address | string): (_: AccountId | Address |string) => boolean {
|
||||
return function (id: AccountId | Address | string): boolean {
|
||||
return id.toString() === accountId.toString();
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* @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> => {
|
||||
const councilSection = api.query.electionsPhragmen ? 'electionsPhragmen' : 'elections';
|
||||
|
||||
return (
|
||||
combineLatest([
|
||||
address && api.query[councilSection]?.members
|
||||
? api.query[councilSection].members()
|
||||
: of(undefined),
|
||||
address && api.query.council?.members
|
||||
? api.query.council.members()
|
||||
: of([]),
|
||||
address && api.query.technicalCommittee?.members
|
||||
? api.query.technicalCommittee.members()
|
||||
: of([]),
|
||||
address && api.query.society?.members
|
||||
? api.query.society.members()
|
||||
: of([]),
|
||||
address && api.query.sudo?.key
|
||||
? api.query.sudo.key()
|
||||
: of(undefined)
|
||||
]) as Observable<FlagsIntermediate>
|
||||
).pipe(
|
||||
map(([electionsMembers, councilMembers, technicalCommitteeMembers, societyMembers, sudoKey]): DeriveAccountFlags => {
|
||||
const isIncluded = address ? isIncludedFn(address) : (): boolean => false;
|
||||
|
||||
return {
|
||||
isCouncil: (electionsMembers?.map(([id]: ITuple<[AccountId, Balance]>) => id) || councilMembers || []).some(isIncluded),
|
||||
isSociety: (societyMembers || []).some(isIncluded),
|
||||
isSudo: sudoKey?.toString() === address?.toString(),
|
||||
isTechCommittee: (technicalCommitteeMembers || []).some(isIncluded)
|
||||
};
|
||||
})
|
||||
);
|
||||
});
|
||||
}
|
||||
@@ -3,18 +3,16 @@
|
||||
// of the Apache-2.0 license. See the LICENSE file for details.
|
||||
|
||||
import { AccountId, AccountIndex, Address } from '@polkadot/types/interfaces';
|
||||
import { AccountIdAndIndex } from '../types';
|
||||
|
||||
import { Observable, of } from 'rxjs';
|
||||
import { map } from 'rxjs/operators';
|
||||
import { ApiInterfaceRx } from '@polkadot/api/types';
|
||||
import { createType } from '@polkadot/types';
|
||||
import { isU8a } from '@polkadot/util';
|
||||
import { decodeAddress } from '@polkadot/util-crypto';
|
||||
|
||||
import { memo } from '../util';
|
||||
|
||||
export type AccountIdAndIndex = [AccountId?, AccountIndex?];
|
||||
|
||||
function retrieve (api: ApiInterfaceRx, address: Address | AccountId | AccountIndex | string | null | undefined): Observable<AccountIdAndIndex> {
|
||||
try {
|
||||
// yes, this can fail, don't care too much, catch will catch it
|
||||
@@ -23,14 +21,14 @@ function retrieve (api: ApiInterfaceRx, address: Address | AccountId | AccountIn
|
||||
: decodeAddress((address || '').toString());
|
||||
|
||||
if (decoded.length === 32) {
|
||||
const accountId = createType(api.registry, 'AccountId', decoded);
|
||||
const accountId = api.registry.createType('AccountId', decoded);
|
||||
|
||||
return api.derive.accounts.idToIndex(accountId).pipe(
|
||||
map((accountIndex): AccountIdAndIndex => [accountId, accountIndex])
|
||||
);
|
||||
}
|
||||
|
||||
const accountIndex = createType(api.registry, 'AccountIndex', decoded);
|
||||
const accountIndex = api.registry.createType('AccountIndex', decoded);
|
||||
|
||||
return api.derive.accounts.indexToId(accountIndex).pipe(
|
||||
map((accountId): AccountIdAndIndex => [accountId, accountIndex])
|
||||
|
||||
@@ -6,7 +6,7 @@ import { AccountId, AccountIndex } from '@polkadot/types/interfaces';
|
||||
import { AccountIndexes } from '../types';
|
||||
|
||||
import { Observable } from 'rxjs';
|
||||
import { map, startWith } from 'rxjs/operators';
|
||||
import { map } from 'rxjs/operators';
|
||||
import { ApiInterfaceRx } from '@polkadot/api/types';
|
||||
|
||||
import { memo } from '../util';
|
||||
@@ -28,7 +28,6 @@ import { memo } from '../util';
|
||||
export function idToIndex (api: ApiInterfaceRx): (accountId: AccountId | string) => Observable<AccountIndex | undefined> {
|
||||
return memo((accountId: AccountId | string): Observable<AccountIndex | undefined> =>
|
||||
api.derive.accounts.indexes().pipe(
|
||||
startWith({}),
|
||||
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 './flags';
|
||||
export * from './idAndIndex';
|
||||
export * from './idToIndex';
|
||||
export * from './indexToId';
|
||||
|
||||
@@ -9,14 +9,15 @@ import { Observable, of } from 'rxjs';
|
||||
import { map, startWith } from 'rxjs/operators';
|
||||
import { ApiInterfaceRx } from '@polkadot/api/types';
|
||||
import { ENUMSET_SIZE } from '@polkadot/types/generic/AccountIndex';
|
||||
import { Option, Vec, createType } from '@polkadot/types';
|
||||
import { Option, Vec } from '@polkadot/types';
|
||||
import { isFunction } from '@polkadot/util';
|
||||
|
||||
import { memo } from '../util';
|
||||
|
||||
function queryEnumSet (api: ApiInterfaceRx, _accountIndex: AccountIndex | string): Observable<AccountId | undefined> {
|
||||
const accountIndex = _accountIndex instanceof api.registry.createClass('AccountIndex')
|
||||
? _accountIndex
|
||||
: createType(api.registry, 'AccountIndex', _accountIndex);
|
||||
: api.registry.createType('AccountIndex', _accountIndex);
|
||||
|
||||
return api.query.indices.enumSet<Vec<AccountId>>(accountIndex.div(ENUMSET_SIZE)).pipe(
|
||||
startWith([]),
|
||||
@@ -51,7 +52,7 @@ function query (api: ApiInterfaceRx, accountIndex: AccountIndex | string): Obser
|
||||
export function indexToId (api: ApiInterfaceRx): (accountIndex: AccountIndex | string) => Observable<AccountId | undefined> {
|
||||
return memo((accountIndex: AccountIndex | string): Observable<AccountId | undefined> =>
|
||||
api.query.indices
|
||||
? api.query.indices.accounts
|
||||
? isFunction(api.query.indices.accounts)
|
||||
? query(api, accountIndex)
|
||||
: queryEnumSet(api, accountIndex)
|
||||
: of(undefined)
|
||||
|
||||
@@ -7,9 +7,10 @@ import { AccountId, AccountIndex } from '@polkadot/types/interfaces';
|
||||
import { AccountIndexes } from '../types';
|
||||
|
||||
import { Observable, of } from 'rxjs';
|
||||
import { map, switchMap } from 'rxjs/operators';
|
||||
import { map, startWith, switchMap } from 'rxjs/operators';
|
||||
import { ENUMSET_SIZE } from '@polkadot/types/generic/AccountIndex';
|
||||
import { Vec, createType } from '@polkadot/types';
|
||||
import { Vec } from '@polkadot/types';
|
||||
import { isFunction } from '@polkadot/util';
|
||||
|
||||
import { memo } from '../util';
|
||||
|
||||
@@ -25,24 +26,33 @@ function queryEnumSet (api: ApiInterfaceRx): Observable<AccountIndexes> {
|
||||
api.query.indices.enumSet.multi<Vec<AccountId>>([...Array(next.toNumber() + 1).keys()])
|
||||
),
|
||||
map((all: AccountId[][]): AccountIndexes =>
|
||||
all.reduce((result: AccountIndexes, list, outerIndex): AccountIndexes => {
|
||||
all.reduce((indexes: AccountIndexes, list, outerIndex): AccountIndexes => {
|
||||
(list || []).forEach((accountId, innerIndex): void => {
|
||||
// re-create the index based on position 0 is [0][0] and likewise
|
||||
// 64 (0..63 in first) is [1][0] (the first index value in set 2)
|
||||
const index = (outerIndex * enumsetSize) + innerIndex;
|
||||
|
||||
result[accountId.toString()] = createType(api.registry, 'AccountIndex', index);
|
||||
indexes[accountId.toString()] = api.registry.createType('AccountIndex', index);
|
||||
});
|
||||
|
||||
return result;
|
||||
return indexes;
|
||||
}, {})
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
// TODO Reverse lookup (via query keys)
|
||||
function query (): Observable<AccountIndexes> {
|
||||
return of({} as AccountIndexes);
|
||||
function queryAccounts (api: ApiInterfaceRx): Observable<AccountIndexes> {
|
||||
return api.query.indices.accounts.entries().pipe(
|
||||
map((entries): AccountIndexes =>
|
||||
entries.reduce((indexes: AccountIndexes, [key, idOpt]): AccountIndexes => {
|
||||
if (idOpt.isSome) {
|
||||
indexes[idOpt.unwrap()[0].toString()] = key.args[0] as AccountIndex;
|
||||
}
|
||||
|
||||
return indexes;
|
||||
}, {})
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -62,10 +72,11 @@ function query (): Observable<AccountIndexes> {
|
||||
*/
|
||||
export function indexes (api: ApiInterfaceRx): () => Observable<AccountIndexes> {
|
||||
return memo((): Observable<AccountIndexes> =>
|
||||
api.query.indices
|
||||
? api.query.indices.accounts
|
||||
? query()
|
||||
(api.query.indices
|
||||
? isFunction(api.query.indices.accounts)
|
||||
? queryAccounts(api)
|
||||
: queryEnumSet(api)
|
||||
: of({} as AccountIndexes)
|
||||
).pipe(startWith({}))
|
||||
);
|
||||
}
|
||||
|
||||
@@ -17,9 +17,9 @@ import { memo } from '../util';
|
||||
function dataAsString (data: Data): string | undefined {
|
||||
return data.isRaw
|
||||
? u8aToString(data.asRaw.toU8a(true))
|
||||
: data.isSha256
|
||||
? data.asSha256.toHex()
|
||||
: undefined;
|
||||
: data.isNone
|
||||
? undefined
|
||||
: data.toHex();
|
||||
}
|
||||
|
||||
function retrieveNick (api: ApiInterfaceRx, accountId?: AccountId): Observable<string | undefined> {
|
||||
@@ -53,6 +53,7 @@ function extractIdentity (identityOfOpt?: Option<Registration>, superOf?: [Accou
|
||||
: undefined,
|
||||
email: dataAsString(info.email),
|
||||
image: dataAsString(info.image),
|
||||
judgements,
|
||||
legal: dataAsString(info.legal),
|
||||
other: info.additional.reduce((other: Record<string, string>, [_key, _value]): Record<string, string> => {
|
||||
const key = dataAsString(_key);
|
||||
@@ -72,8 +73,7 @@ function extractIdentity (identityOfOpt?: Option<Registration>, superOf?: [Accou
|
||||
: undefined,
|
||||
riot: dataAsString(info.riot),
|
||||
twitter: dataAsString(info.twitter),
|
||||
web: dataAsString(info.web),
|
||||
judgements
|
||||
web: dataAsString(info.web)
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
// 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, RegistrationJudgement } from '@polkadot/types/interfaces';
|
||||
|
||||
export type AccountIdAndIndex = [AccountId?, AccountIndex?];
|
||||
|
||||
export type AccountIndexes = Record<string, AccountIndex>;
|
||||
|
||||
export interface DeriveAccountRegistration {
|
||||
display?: string;
|
||||
displayParent?: string;
|
||||
email?: string;
|
||||
image?: string;
|
||||
legal?: string;
|
||||
other?: Record<string, string>;
|
||||
parent?: AccountId;
|
||||
pgp?: string;
|
||||
riot?: string;
|
||||
twitter?: string;
|
||||
web?: string;
|
||||
judgements: RegistrationJudgement[];
|
||||
}
|
||||
|
||||
export interface DeriveAccountFlags {
|
||||
isCouncil: boolean;
|
||||
isSociety: boolean;
|
||||
isSudo: boolean;
|
||||
isTechCommittee: boolean;
|
||||
}
|
||||
|
||||
export interface DeriveAccountInfo {
|
||||
accountId?: AccountId;
|
||||
accountIndex?: AccountIndex;
|
||||
identity: DeriveAccountRegistration;
|
||||
nickname?: string;
|
||||
}
|
||||
@@ -4,18 +4,18 @@
|
||||
|
||||
import { AccountId, AccountData, AccountIndex, AccountInfo, Address, Balance, Index } from '@polkadot/types/interfaces';
|
||||
import { ITuple } from '@polkadot/types/types';
|
||||
import { DerivedBalancesAccount } from '../types';
|
||||
import { DeriveBalancesAccount } from '../types';
|
||||
|
||||
import { combineLatest, of, Observable } from 'rxjs';
|
||||
import { Observable, combineLatest, of } from 'rxjs';
|
||||
import { map, switchMap } from 'rxjs/operators';
|
||||
import { ApiInterfaceRx } from '@polkadot/api/types';
|
||||
import { createType } from '@polkadot/types';
|
||||
import { isFunction } from '@polkadot/util';
|
||||
|
||||
import { memo } from '../util';
|
||||
|
||||
type Result = [Balance, Balance, Balance, Balance, Index];
|
||||
|
||||
function calcBalances (api: ApiInterfaceRx, [accountId, [freeBalance, reservedBalance, frozenFee, frozenMisc, accountNonce]]: [AccountId, Result]): DerivedBalancesAccount {
|
||||
function calcBalances (api: ApiInterfaceRx, [accountId, [freeBalance, reservedBalance, frozenFee, frozenMisc, accountNonce]]: [AccountId, Result]): DeriveBalancesAccount {
|
||||
return {
|
||||
accountId,
|
||||
accountNonce,
|
||||
@@ -23,7 +23,7 @@ function calcBalances (api: ApiInterfaceRx, [accountId, [freeBalance, reservedBa
|
||||
frozenFee,
|
||||
frozenMisc,
|
||||
reservedBalance,
|
||||
votingBalance: createType(api.registry, 'Balance', freeBalance.add(reservedBalance))
|
||||
votingBalance: api.registry.createType('Balance', freeBalance.add(reservedBalance))
|
||||
};
|
||||
}
|
||||
|
||||
@@ -35,7 +35,7 @@ function queryBalancesFree (api: ApiInterfaceRx, accountId: AccountId): Observab
|
||||
[api.query.system.accountNonce, accountId]
|
||||
]).pipe(
|
||||
map(([freeBalance, reservedBalance, accountNonce]): Result =>
|
||||
[freeBalance, reservedBalance, createType(api.registry, 'Balance'), createType(api.registry, 'Balance'), accountNonce]
|
||||
[freeBalance, reservedBalance, api.registry.createType('Balance'), api.registry.createType('Balance'), accountNonce]
|
||||
)
|
||||
);
|
||||
}
|
||||
@@ -45,7 +45,7 @@ function queryBalancesAccount (api: ApiInterfaceRx, accountId: AccountId): Obser
|
||||
[api.query.balances.account, accountId],
|
||||
[api.query.system.accountNonce, accountId]
|
||||
]).pipe(
|
||||
map(([{ free, reserved, miscFrozen, feeFrozen }, accountNonce]): Result =>
|
||||
map(([{ feeFrozen, free, miscFrozen, reserved }, accountNonce]): Result =>
|
||||
[free, reserved, feeFrozen, miscFrozen, accountNonce]
|
||||
)
|
||||
);
|
||||
@@ -55,7 +55,7 @@ function queryCurrent (api: ApiInterfaceRx, accountId: AccountId): Observable<Re
|
||||
// AccountInfo is current, support old, eg. Edgeware
|
||||
return api.query.system.account<AccountInfo | ITuple<[Index, AccountData]>>(accountId).pipe(
|
||||
map((infoOrTuple): Result => {
|
||||
const { free, reserved, miscFrozen, feeFrozen } = (infoOrTuple as AccountInfo).nonce
|
||||
const { feeFrozen, free, miscFrozen, reserved } = (infoOrTuple as AccountInfo).nonce
|
||||
? (infoOrTuple as AccountInfo).data
|
||||
: (infoOrTuple as [Index, AccountData])[1];
|
||||
const accountNonce = (infoOrTuple as AccountInfo).nonce || (infoOrTuple as [Index, AccountData])[0];
|
||||
@@ -80,22 +80,22 @@ function queryCurrent (api: ApiInterfaceRx, accountId: AccountId): Observable<Re
|
||||
* });
|
||||
* ```
|
||||
*/
|
||||
export function account (api: ApiInterfaceRx): (address: AccountIndex | AccountId | Address | string) => Observable<DerivedBalancesAccount> {
|
||||
return memo((address: AccountIndex | AccountId | Address | string): Observable<DerivedBalancesAccount> =>
|
||||
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]> =>
|
||||
(accountId
|
||||
? combineLatest([
|
||||
of(accountId),
|
||||
api.query.system.account
|
||||
isFunction(api.query.system.account)
|
||||
? queryCurrent(api, accountId)
|
||||
: api.query.balances.account
|
||||
: isFunction(api.query.balances.account)
|
||||
? queryBalancesAccount(api, accountId)
|
||||
: queryBalancesFree(api, accountId)
|
||||
])
|
||||
: of([createType(api.registry, 'AccountId'), [createType(api.registry, 'Balance'), createType(api.registry, 'Balance'), createType(api.registry, 'Balance'), createType(api.registry, 'Balance'), createType(api.registry, 'Index')]])
|
||||
: of([api.registry.createType('AccountId'), [api.registry.createType('Balance'), api.registry.createType('Balance'), api.registry.createType('Balance'), api.registry.createType('Balance'), api.registry.createType('Index')]])
|
||||
)
|
||||
),
|
||||
map((result): DerivedBalancesAccount => calcBalances(api, result))
|
||||
map((result): DeriveBalancesAccount => calcBalances(api, result))
|
||||
));
|
||||
}
|
||||
|
||||
@@ -3,23 +3,24 @@
|
||||
// of the Apache-2.0 license. See the LICENSE file for details.
|
||||
|
||||
import { AccountId, AccountIndex, Address, Balance, BalanceLock, BalanceLockTo212, BlockNumber, VestingInfo, VestingSchedule } from '@polkadot/types/interfaces';
|
||||
import { DerivedBalancesAccount, DerivedBalancesAll } from '../types';
|
||||
import { DeriveBalancesAccount, DeriveBalancesAll } from '../types';
|
||||
|
||||
import BN from 'bn.js';
|
||||
import { combineLatest, of, Observable } from 'rxjs';
|
||||
import { Observable, combineLatest, of } from 'rxjs';
|
||||
import { map, switchMap } from 'rxjs/operators';
|
||||
import { ApiInterfaceRx } from '@polkadot/api/types';
|
||||
import { Option, Vec, createType } from '@polkadot/types';
|
||||
import { bnMax } from '@polkadot/util';
|
||||
import { Option, Vec } from '@polkadot/types';
|
||||
import { bnMax, isFunction } from '@polkadot/util';
|
||||
|
||||
import { memo } from '../util';
|
||||
|
||||
type ResultBalance = [VestingInfo | null, (BalanceLock | BalanceLockTo212)[]];
|
||||
type Result = [DerivedBalancesAccount, BlockNumber, ResultBalance];
|
||||
type Result = [DeriveBalancesAccount, BlockNumber, ResultBalance];
|
||||
|
||||
function calcBalances (api: ApiInterfaceRx, [{ accountId, accountNonce, freeBalance, frozenFee, frozenMisc, reservedBalance, votingBalance }, bestNumber, [vesting, locks]]: Result): DerivedBalancesAll {
|
||||
let lockedBalance = createType(api.registry, 'Balance');
|
||||
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 allLocked = false;
|
||||
|
||||
if (Array.isArray(locks)) {
|
||||
// only get the locks that are valid until passed the current block
|
||||
@@ -27,18 +28,20 @@ function calcBalances (api: ApiInterfaceRx, [{ accountId, accountNonce, freeBala
|
||||
|
||||
const notAll = lockedBreakdown.filter(({ amount }): boolean => !amount.isMax());
|
||||
|
||||
allLocked = lockedBreakdown.some(({ amount }): boolean => amount.isMax());
|
||||
|
||||
// get the maximum of the locks according to https://github.com/paritytech/substrate/blob/master/srml/balances/src/lib.rs#L699
|
||||
if (notAll.length) {
|
||||
lockedBalance = createType(api.registry, 'Balance', bnMax(...notAll.map(({ amount }): Balance => amount)));
|
||||
lockedBalance = api.registry.createType('Balance', bnMax(...notAll.map(({ amount }): Balance => amount)));
|
||||
}
|
||||
}
|
||||
|
||||
// Calculate the vesting balances,
|
||||
// - offset = balance locked at startingBlock
|
||||
// - perBlock is the unlock amount
|
||||
const { locked: vestingTotal, perBlock, startingBlock } = vesting || createType(api.registry, 'VestingInfo');
|
||||
const { locked: vestingTotal, perBlock, startingBlock } = vesting || api.registry.createType('VestingInfo');
|
||||
const isStarted = bestNumber.gt(startingBlock);
|
||||
const vestedBalance = createType(api.registry, 'Balance', isStarted ? perBlock.mul(bestNumber.sub(startingBlock)) : 0);
|
||||
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
|
||||
@@ -50,7 +53,7 @@ function calcBalances (api: ApiInterfaceRx, [{ accountId, accountNonce, freeBala
|
||||
// ""
|
||||
const floating = freeBalance.sub(lockedBalance);
|
||||
const extraReceived = isVesting ? freeBalance.sub(vestingTotal) : new BN(0);
|
||||
const availableBalance = createType(api.registry, 'Balance', bnMax(new BN(0), isVesting && floating.gt(vestedBalance) ? vestedBalance.add(extraReceived) : floating));
|
||||
const availableBalance = api.registry.createType('Balance', allLocked ? 0 : bnMax(new BN(0), isVesting && floating.gt(vestedBalance) ? vestedBalance.add(extraReceived) : floating));
|
||||
|
||||
return {
|
||||
accountId,
|
||||
@@ -81,7 +84,7 @@ function queryOld (api: ApiInterfaceRx, accountId: AccountId): Observable<Result
|
||||
if (optVesting.isSome) {
|
||||
const { offset: locked, perBlock, startingBlock } = optVesting.unwrap();
|
||||
|
||||
vestingNew = createType(api.registry, 'VestingInfo', { locked, perBlock, startingBlock });
|
||||
vestingNew = api.registry.createType('VestingInfo', { locked, perBlock, startingBlock });
|
||||
}
|
||||
|
||||
return [vestingNew, locks];
|
||||
@@ -99,7 +102,7 @@ function queryCurrent (api: ApiInterfaceRx, accountId: AccountId): Observable<Re
|
||||
])
|
||||
: api.query.balances.locks(accountId).pipe(
|
||||
map((locks): [Vec<BalanceLock>, Option<VestingInfo>] =>
|
||||
[locks, createType(api.registry, 'Option<VestingInfo>')]
|
||||
[locks, api.registry.createType('Option<VestingInfo>')]
|
||||
)
|
||||
)
|
||||
).pipe(
|
||||
@@ -124,21 +127,21 @@ function queryCurrent (api: ApiInterfaceRx, accountId: AccountId): Observable<Re
|
||||
* });
|
||||
* ```
|
||||
*/
|
||||
export function all (api: ApiInterfaceRx): (address: AccountIndex | AccountId | Address | string) => Observable<DerivedBalancesAll> {
|
||||
return memo((address: AccountIndex | AccountId | Address | string): Observable<DerivedBalancesAll> =>
|
||||
export function all (api: ApiInterfaceRx): (address: AccountIndex | AccountId | Address | string) => Observable<DeriveBalancesAll> {
|
||||
return memo((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(),
|
||||
api.query.balances.account
|
||||
isFunction(api.query.balances.account)
|
||||
? queryCurrent(api, account.accountId)
|
||||
: queryOld(api, account.accountId)
|
||||
])
|
||||
: of([account, createType(api.registry, 'BlockNumber'), [null, createType(api.registry, 'Vec<BalanceLock>')]])
|
||||
: of([account, api.registry.createType('BlockNumber'), [null, api.registry.createType('Vec<BalanceLock>')]])
|
||||
)
|
||||
),
|
||||
map((result): DerivedBalancesAll => calcBalances(api, result))
|
||||
map((result): DeriveBalancesAll => calcBalances(api, result))
|
||||
));
|
||||
}
|
||||
|
||||
@@ -4,11 +4,10 @@
|
||||
|
||||
import { ApiInterfaceRx } from '@polkadot/api/types';
|
||||
import { Balance } from '@polkadot/types/interfaces';
|
||||
import { DerivedFees } from '../types';
|
||||
import { DeriveFees } from '../types';
|
||||
|
||||
import { Observable, of } from 'rxjs';
|
||||
import { map } from 'rxjs/operators';
|
||||
import { createType } from '@polkadot/types';
|
||||
|
||||
import { memo } from '../util';
|
||||
|
||||
@@ -25,19 +24,19 @@ import { memo } from '../util';
|
||||
* });
|
||||
* ```
|
||||
*/
|
||||
export function fees (api: ApiInterfaceRx): () => Observable<DerivedFees> {
|
||||
return memo((): Observable<DerivedFees> =>
|
||||
export function fees (api: ApiInterfaceRx): () => Observable<DeriveFees> {
|
||||
return memo((): Observable<DeriveFees> =>
|
||||
of([
|
||||
// deprecated - remove
|
||||
(api.consts.balances.creationFee as Balance) || createType(api.registry, 'Balance'),
|
||||
(api.consts.balances.transferFee as Balance) || createType(api.registry, 'Balance'),
|
||||
(api.consts.balances?.creationFee as unknown as Balance) || api.registry.createType('Balance'),
|
||||
(api.consts.balances?.transferFee as unknown as Balance) || api.registry.createType('Balance'),
|
||||
|
||||
// current
|
||||
api.consts.balances.existentialDeposit,
|
||||
api.consts.transactionPayment.transactionBaseFee,
|
||||
api.consts.transactionPayment.transactionByteFee
|
||||
(api.consts.balances?.existentialDeposit as Balance) || api.registry.createType('Balance'),
|
||||
(api.consts.transactionPayment?.transactionBaseFee as unknown as Balance) || api.registry.createType('Balance'),
|
||||
(api.consts.transactionPayment?.transactionByteFee as Balance) || api.registry.createType('Balance')
|
||||
]).pipe(
|
||||
map(([creationFee, transferFee, existentialDeposit, transactionBaseFee, transactionByteFee]): DerivedFees => ({
|
||||
map(([creationFee, transferFee, existentialDeposit, transactionBaseFee, transactionByteFee]): DeriveFees => ({
|
||||
creationFee,
|
||||
existentialDeposit,
|
||||
transactionBaseFee,
|
||||
|
||||
@@ -3,20 +3,21 @@
|
||||
// of the Apache-2.0 license. See the LICENSE file for details.
|
||||
|
||||
import { AccountId, AccountIndex, Address } from '@polkadot/types/interfaces';
|
||||
import { DerivedBalancesAccount } from '../types';
|
||||
import { DeriveBalancesAccount } from '../types';
|
||||
|
||||
import { combineLatest, Observable, of } from 'rxjs';
|
||||
import { Observable, combineLatest, of } from 'rxjs';
|
||||
import { ApiInterfaceRx } from '@polkadot/api/types';
|
||||
|
||||
import { memo } from '../util';
|
||||
|
||||
export function votingBalances (api: ApiInterfaceRx): (addresses?: (AccountId | AccountIndex | Address | string)[]) => Observable<DerivedBalancesAccount[]> {
|
||||
return memo((addresses?: (AccountId | AccountIndex | Address | string)[]): Observable<DerivedBalancesAccount[]> =>
|
||||
export function votingBalances (api: ApiInterfaceRx): (addresses?: (AccountId | AccountIndex | Address | string)[]) => Observable<DeriveBalancesAccount[]> {
|
||||
return memo((addresses?: (AccountId | AccountIndex | Address | string)[]): Observable<DeriveBalancesAccount[]> =>
|
||||
!addresses || !addresses.length
|
||||
? of([] as DerivedBalancesAccount[])
|
||||
? of([] as DeriveBalancesAccount[])
|
||||
: combineLatest(
|
||||
addresses.map((accountId): Observable<DerivedBalancesAccount> =>
|
||||
api.derive.balances.account(accountId))
|
||||
addresses.map((accountId): Observable<DeriveBalancesAccount> =>
|
||||
api.derive.balances.account(accountId)
|
||||
)
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -7,7 +7,6 @@ import { BlockNumber } from '@polkadot/types/interfaces';
|
||||
import { Observable, combineLatest } from 'rxjs';
|
||||
import { map } from 'rxjs/operators';
|
||||
import { ApiInterfaceRx } from '@polkadot/api/types';
|
||||
import { createType } from '@polkadot/types';
|
||||
|
||||
import { memo } from '../util';
|
||||
|
||||
@@ -31,7 +30,7 @@ export function bestNumberLag (api: ApiInterfaceRx): () => Observable<BlockNumbe
|
||||
api.derive.chain.bestNumberFinalized()
|
||||
]).pipe(
|
||||
map(([bestNumber, bestNumberFinalized]): BlockNumber =>
|
||||
createType(api.registry, 'BlockNumber', bestNumber.sub(bestNumberFinalized))
|
||||
api.registry.createType('BlockNumber', bestNumber.sub(bestNumberFinalized))
|
||||
)
|
||||
));
|
||||
}
|
||||
|
||||
@@ -4,17 +4,20 @@
|
||||
|
||||
import { ApiInterfaceRx } from '@polkadot/api/types';
|
||||
import { Hash, Proposal, Votes } from '@polkadot/types/interfaces';
|
||||
import { DerivedCollectiveProposal } from '../types';
|
||||
import { DeriveCollectiveProposal } from '../types';
|
||||
|
||||
import { combineLatest, Observable, of } from 'rxjs';
|
||||
import { Observable, combineLatest, of } from 'rxjs';
|
||||
import { map, switchMap } from 'rxjs/operators';
|
||||
import { Option } from '@polkadot/types';
|
||||
import { isFunction } from '@polkadot/util';
|
||||
|
||||
import { memo } from '../util';
|
||||
|
||||
type Result = [Hash[], Option<Proposal>[], Option<Votes>[]];
|
||||
|
||||
function parse ([hashes, proposals, votes]: Result): DerivedCollectiveProposal[] {
|
||||
function parse ([hashes, proposals, votes]: Result): DeriveCollectiveProposal[] {
|
||||
return proposals
|
||||
.map((proposalOpt, index): DerivedCollectiveProposal | null =>
|
||||
.map((proposalOpt, index): DeriveCollectiveProposal | null =>
|
||||
proposalOpt.isSome
|
||||
? {
|
||||
hash: hashes[index],
|
||||
@@ -23,12 +26,12 @@ function parse ([hashes, proposals, votes]: Result): DerivedCollectiveProposal[]
|
||||
}
|
||||
: null
|
||||
)
|
||||
.filter((proposal): proposal is DerivedCollectiveProposal => !!proposal);
|
||||
.filter((proposal): proposal is DeriveCollectiveProposal => !!proposal);
|
||||
}
|
||||
|
||||
export function proposals (api: ApiInterfaceRx, section: 'council' | 'technicalCommittee'): () => Observable<DerivedCollectiveProposal[]> {
|
||||
return (): Observable<DerivedCollectiveProposal[]> =>
|
||||
api.query[section]
|
||||
export function proposals (api: ApiInterfaceRx, section: 'council' | 'technicalCommittee'): () => Observable<DeriveCollectiveProposal[]> {
|
||||
return memo((): Observable<DeriveCollectiveProposal[]> =>
|
||||
isFunction(api.query[section]?.proposals)
|
||||
? api.query[section].proposals().pipe(
|
||||
switchMap((hashes: Hash[]): Observable<Result> =>
|
||||
hashes.length
|
||||
@@ -41,5 +44,6 @@ export function proposals (api: ApiInterfaceRx, section: 'council' | 'technicalC
|
||||
),
|
||||
map(parse)
|
||||
)
|
||||
: of([] as DerivedCollectiveProposal[]);
|
||||
: of([] as DeriveCollectiveProposal[])
|
||||
);
|
||||
}
|
||||
|
||||
@@ -3,32 +3,32 @@
|
||||
// of the Apache-2.0 license. See the LICENSE file for details.
|
||||
|
||||
import { ApiInterfaceRx } from '@polkadot/api/types';
|
||||
import { DerivedContractFees } from '../types';
|
||||
import { DeriveContractFees } from '../types';
|
||||
|
||||
import BN from 'bn.js';
|
||||
import { Observable, of } from 'rxjs';
|
||||
import { map } from 'rxjs/operators';
|
||||
import { createType } from '@polkadot/types';
|
||||
|
||||
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.creationFee || createType(api.registry, 'Balance'),
|
||||
api.consts.contracts.transferFee || createType(api.registry, 'Balance'),
|
||||
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>;
|
||||
}
|
||||
|
||||
@@ -45,15 +45,16 @@ function queryConstants (api: ApiInterfaceRx): Observable<ResultV2> {
|
||||
* });
|
||||
* ```
|
||||
*/
|
||||
export function fees (api: ApiInterfaceRx): () => Observable<DerivedContractFees> {
|
||||
return memo((): Observable<DerivedContractFees> => {
|
||||
export function fees (api: ApiInterfaceRx): () => Observable<DeriveContractFees> {
|
||||
return memo((): Observable<DeriveContractFees> => {
|
||||
return queryConstants(api).pipe(
|
||||
map(([creationFee, transferFee, callBaseFee, contractFee, rentByteFee, rentDepositOffset, tombstoneDeposit, transactionBaseFee, transactionByteFee]): DerivedContractFees => ({
|
||||
map(([callBaseFee, contractFee, creationFee, transactionBaseFee, transactionByteFee, transferFee, rentByteFee, rentDepositOffset, surchargeReward, tombstoneDeposit]): DeriveContractFees => ({
|
||||
callBaseFee,
|
||||
contractFee,
|
||||
creationFee,
|
||||
rentByteFee,
|
||||
rentDepositOffset,
|
||||
surchargeReward,
|
||||
tombstoneDeposit,
|
||||
transactionBaseFee,
|
||||
transactionByteFee,
|
||||
|
||||
@@ -3,3 +3,5 @@
|
||||
// of the Apache-2.0 license. See the LICENSE file for details.
|
||||
|
||||
export * from './proposals';
|
||||
export * from './votes';
|
||||
export * from './votesOf';
|
||||
|
||||
@@ -3,12 +3,12 @@
|
||||
// of the Apache-2.0 license. See the LICENSE file for details.
|
||||
|
||||
import { ApiInterfaceRx } from '@polkadot/api/types';
|
||||
import { DerivedCollectiveProposals } from '../types';
|
||||
import { DeriveCollectiveProposals } from '../types';
|
||||
|
||||
import { Observable } from 'rxjs';
|
||||
import { proposals as collectiveProposals } from '../collective';
|
||||
import { memo } from '../util';
|
||||
|
||||
export function proposals (api: ApiInterfaceRx): () => Observable<DerivedCollectiveProposals> {
|
||||
export function proposals (api: ApiInterfaceRx): () => Observable<DeriveCollectiveProposals> {
|
||||
return memo(collectiveProposals(api, 'council'));
|
||||
}
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
// 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 } from '@polkadot/types/interfaces';
|
||||
|
||||
export interface DeriveCouncilVote {
|
||||
stake: Balance;
|
||||
votes: AccountId[];
|
||||
}
|
||||
|
||||
export type DeriveCouncilVotes = [AccountId, DeriveCouncilVote][];
|
||||
@@ -0,0 +1,90 @@
|
||||
// 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 } from '@polkadot/types/interfaces';
|
||||
import { ITuple } from '@polkadot/types/types';
|
||||
import { ApiInterfaceRx } from '@polkadot/api/types';
|
||||
import { DeriveCouncilVote, DeriveCouncilVotes } from '../types';
|
||||
|
||||
import { Observable, combineLatest } from 'rxjs';
|
||||
import { map } from 'rxjs/operators';
|
||||
import { Vec } from '@polkadot/types';
|
||||
|
||||
import { memo } from '../util';
|
||||
|
||||
function retrieveStakeOf (api: ApiInterfaceRx): Observable<[AccountId, Balance][]> {
|
||||
const elections = (api.query.electionsPhragmen || api.query.elections);
|
||||
|
||||
return elections.stakeOf.creator.meta.type.asMap.linked.isTrue
|
||||
? elections.stakeOf<ITuple<[Vec<AccountId>, Vec<Balance>]>>().pipe(
|
||||
map(([voters, stake]) =>
|
||||
voters.map((voter, index): [AccountId, Balance] => [voter, stake[index]])
|
||||
)
|
||||
)
|
||||
: elections.stakeOf.entries<Balance>().pipe(
|
||||
map((entries) =>
|
||||
entries.map(([key, stake]) => [key.args[0] as AccountId, stake])
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
function retrieveVoteOf (api: ApiInterfaceRx): Observable<[AccountId, AccountId[]][]> {
|
||||
const elections = (api.query.electionsPhragmen || api.query.elections);
|
||||
|
||||
return elections.votesOf.creator.meta.type.asMap.linked.isTrue
|
||||
? elections.votesOf<ITuple<[Vec<AccountId>, Vec<Vec<AccountId>>]>>().pipe(
|
||||
map(([voters, votes]) =>
|
||||
voters.map((voter, index) => [voter, votes[index]])
|
||||
)
|
||||
)
|
||||
: elections.votesOf.entries<Vec<AccountId>>().pipe(
|
||||
map((entries) =>
|
||||
entries.map(([key, votes]) => [key.args[0] as AccountId, votes])
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
function retrievePrev (api: ApiInterfaceRx): Observable<DeriveCouncilVotes> {
|
||||
return combineLatest([retrieveStakeOf(api), retrieveVoteOf(api)]).pipe(
|
||||
map(([stakes, votes]): DeriveCouncilVotes => {
|
||||
const result: DeriveCouncilVotes = [];
|
||||
|
||||
votes.forEach(([voter, votes]): void => {
|
||||
result.push([voter, { stake: api.registry.createType('Balance'), votes }]);
|
||||
});
|
||||
|
||||
stakes.forEach(([staker, stake]): void => {
|
||||
const entry = result.find(([voter]) => voter.eq(staker));
|
||||
|
||||
if (entry) {
|
||||
entry[1].stake = stake;
|
||||
} else {
|
||||
result.push([staker, { stake, votes: [] }]);
|
||||
}
|
||||
});
|
||||
|
||||
return result;
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
function retrieveCurrent (api: ApiInterfaceRx): Observable<DeriveCouncilVotes> {
|
||||
const elections = (api.query.electionsPhragmen || api.query.elections);
|
||||
|
||||
return elections.voting.entries<ITuple<[Balance, Vec<AccountId>]>>().pipe(
|
||||
map((entries): DeriveCouncilVotes =>
|
||||
entries.map(([key, [stake, votes]]): [AccountId, DeriveCouncilVote] =>
|
||||
[key.args[0] as AccountId, { stake, votes }]
|
||||
)
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
export function votes (api: ApiInterfaceRx): () => Observable<DeriveCouncilVotes> {
|
||||
return memo((): Observable<DeriveCouncilVotes> =>
|
||||
(api.query.electionsPhragmen || api.query.elections).stakeOf
|
||||
? retrievePrev(api)
|
||||
: retrieveCurrent(api)
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
// 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 } from '@polkadot/types/interfaces';
|
||||
import { ApiInterfaceRx } from '@polkadot/api/types';
|
||||
import { DeriveCouncilVote } from '../types';
|
||||
|
||||
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> =>
|
||||
api.derive.council.votes().pipe(
|
||||
map((votes): DeriveCouncilVote =>
|
||||
(
|
||||
votes.find(([from]) => from.eq(accountId)) ||
|
||||
[null, { stake: api.registry.createType('Balance'), votes: [] as AccountId[] }]
|
||||
)[1]
|
||||
)
|
||||
)
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
// 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 { BlockNumber, Hash, ReferendumIndex, Scheduled } from '@polkadot/types/interfaces';
|
||||
import { ITuple } from '@polkadot/types/types';
|
||||
import { DeriveDispatch, DeriveProposalImage } from '../types';
|
||||
|
||||
import { Observable, combineLatest, of } from 'rxjs';
|
||||
import { map, switchMap } from 'rxjs/operators';
|
||||
import { ApiInterfaceRx } from '@polkadot/api/types';
|
||||
import { Option, Vec, u64 } from '@polkadot/types';
|
||||
import { isFunction, stringToHex } from '@polkadot/util';
|
||||
|
||||
import { memo } from '../util';
|
||||
|
||||
const DEMOCRACY_ID = stringToHex('democrac');
|
||||
|
||||
interface SchedulerInfo {
|
||||
at: BlockNumber;
|
||||
imageHash: Hash;
|
||||
index: ReferendumIndex;
|
||||
}
|
||||
|
||||
function queryQueue (api: ApiInterfaceRx): Observable<DeriveDispatch[]> {
|
||||
return api.query.democracy.dispatchQueue<Vec<ITuple<[BlockNumber, Hash, ReferendumIndex]>>>().pipe(
|
||||
switchMap((dispatches) =>
|
||||
combineLatest([
|
||||
of(dispatches),
|
||||
api.derive.democracy.preimages(
|
||||
dispatches.map(([, hash]) => hash))
|
||||
])
|
||||
),
|
||||
map(([dispatches, images]) =>
|
||||
dispatches.map(([at, imageHash, index], dispatchIndex): DeriveDispatch => ({
|
||||
at,
|
||||
image: images[dispatchIndex],
|
||||
imageHash,
|
||||
index
|
||||
}))
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
function schedulerEntries (api: ApiInterfaceRx): Observable<[BlockNumber[], Option<Scheduled>[][]]> {
|
||||
// We don't get entries, but rather we get the keys (triggered via finished referendums) and
|
||||
// the subscribe to those keys - this means we pickup when the schedulers actually executes
|
||||
// at a block, the entry for that block will become empty
|
||||
return api.derive.democracy.referendumsFinished().pipe(
|
||||
switchMap(() =>
|
||||
api.query.scheduler.agenda.keys()
|
||||
),
|
||||
switchMap((keys) => {
|
||||
const blockNumbers = keys.map((key) => key.args[0] as BlockNumber);
|
||||
|
||||
return combineLatest([
|
||||
of(blockNumbers),
|
||||
api.query.scheduler.agenda.multi<Vec<Option<Scheduled>>>(blockNumbers)
|
||||
]);
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
function queryScheduler (api: ApiInterfaceRx): Observable<DeriveDispatch[]> {
|
||||
return schedulerEntries(api).pipe(
|
||||
switchMap(([blockNumbers, agendas]): Observable<[SchedulerInfo[], (DeriveProposalImage | undefined)[]]> => {
|
||||
const result: SchedulerInfo[] = [];
|
||||
|
||||
blockNumbers.forEach((at, index): void => {
|
||||
agendas[index].filter((optScheduled) => optScheduled.isSome).forEach((optScheduled): void => {
|
||||
const scheduled = optScheduled.unwrap();
|
||||
|
||||
if (scheduled.maybeId.isSome) {
|
||||
const id = scheduled.maybeId.unwrap().toHex();
|
||||
|
||||
if (id.startsWith(DEMOCRACY_ID)) {
|
||||
const [, index] = api.registry.createType('(u64, ReferendumIndex)' as any, id) as ITuple<[u64, ReferendumIndex]>;
|
||||
const imageHash = scheduled.call.args[0] as Hash;
|
||||
|
||||
result.push({ at, imageHash, index });
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
return combineLatest([
|
||||
of(result),
|
||||
api.derive.democracy.preimages(result.map(({ imageHash }) => imageHash))
|
||||
]);
|
||||
}),
|
||||
map(([infos, images]): DeriveDispatch[] =>
|
||||
infos.map((info, index) => ({ ...info, image: images[index] }))
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
export function dispatchQueue (api: ApiInterfaceRx): () => Observable<DeriveDispatch[]> {
|
||||
return memo((): Observable<DeriveDispatch[]> =>
|
||||
isFunction(api.query.scheduler?.agenda)
|
||||
? queryScheduler(api)
|
||||
: api.query.democracy.dispatchQueue
|
||||
? queryQueue(api)
|
||||
: of([])
|
||||
);
|
||||
}
|
||||
@@ -2,8 +2,15 @@
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the Apache-2.0 license. See the LICENSE file for details.
|
||||
|
||||
export * from './dispatchQueue';
|
||||
export * from './locks';
|
||||
export * from './nextExternal';
|
||||
export * from './preimage';
|
||||
export * from './preimages';
|
||||
export * from './proposals';
|
||||
export * from './referendumInfos';
|
||||
export * from './referendumIds';
|
||||
export * from './referendums';
|
||||
export * from './referendumVotesFor';
|
||||
export * from './votes';
|
||||
export * from './referendumsActive';
|
||||
export * from './referendumsFinished';
|
||||
export * from './referendumsInfo';
|
||||
export * from './sqrtElectorate';
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
// Copyright 2017-2020 @polkadot/api-derive authors & contributors
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the Apache-2.0 license. See the LICENSE file for details.
|
||||
|
||||
import { AccountId, ReferendumInfo, ReferendumInfoTo239, VotingDirect, VotingDirectVote } from '@polkadot/types/interfaces';
|
||||
import { ApiInterfaceRx } from '@polkadot/api/types';
|
||||
import { DeriveDemocracyLock } from '../types';
|
||||
|
||||
import BN from 'bn.js';
|
||||
import { Observable, of } from 'rxjs';
|
||||
import { map, switchMap } from 'rxjs/operators';
|
||||
import { Option } from '@polkadot/types';
|
||||
import { isUndefined } from '@polkadot/util';
|
||||
|
||||
import { memo } from '../util';
|
||||
|
||||
const LOCKUPS = [0, 1, 2, 4, 8, 16, 32];
|
||||
const ZERO = new BN(0);
|
||||
|
||||
function parseLock (api: ApiInterfaceRx, [referendumId, accountVote]: VotingDirectVote, referendum: ReferendumInfo): DeriveDemocracyLock {
|
||||
const { balance, vote } = accountVote.asStandard;
|
||||
let unlockAt = ZERO;
|
||||
|
||||
if (referendum.isFinished) {
|
||||
const { approved, end } = referendum.asFinished;
|
||||
|
||||
if ((approved.isTrue && vote.isAye) || (approved.isFalse && vote.isNay)) {
|
||||
unlockAt = end.add(api.consts.democracy.enactmentPeriod.muln(LOCKUPS[vote.conviction.index]));
|
||||
}
|
||||
}
|
||||
|
||||
return { balance, isFinished: referendum.isFinished, referendumId, unlockAt, vote };
|
||||
}
|
||||
|
||||
function directLocks (api: ApiInterfaceRx, { votes }: VotingDirect): Observable<DeriveDemocracyLock[]> {
|
||||
if (!votes.length) {
|
||||
return of([]);
|
||||
}
|
||||
|
||||
return api.query.democracy.referendumInfoOf.multi<Option<ReferendumInfo | ReferendumInfoTo239>>(votes.map(([referendumId]) => referendumId)).pipe(
|
||||
map((referendums) =>
|
||||
votes
|
||||
.map((vote, index): [VotingDirectVote, ReferendumInfo | ReferendumInfoTo239 | null] =>
|
||||
[vote, referendums[index].unwrapOr(null)]
|
||||
)
|
||||
.filter((item): item is [VotingDirectVote, ReferendumInfo] =>
|
||||
!!item[1] && isUndefined((item[1] as ReferendumInfoTo239).end) && item[0][1].isStandard
|
||||
)
|
||||
.map(([directVote, referendum]) =>
|
||||
parseLock(api, directVote, referendum)
|
||||
)
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
export function locks (api: ApiInterfaceRx): (accountId: string | AccountId) => Observable<DeriveDemocracyLock[]> {
|
||||
return memo((accountId: string | AccountId): Observable<DeriveDemocracyLock[]> =>
|
||||
api.query.democracy.votingOf(accountId).pipe(
|
||||
switchMap((voting): Observable<DeriveDemocracyLock[]> =>
|
||||
voting.isDirect
|
||||
? directLocks(api, voting.asDirect)
|
||||
: of([])
|
||||
)
|
||||
)
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
// 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 { Hash, VoteThreshold } from '@polkadot/types/interfaces';
|
||||
import { ITuple } from '@polkadot/types/types';
|
||||
import { DeriveProposalExternal } from '../types';
|
||||
|
||||
import { Observable, of } from 'rxjs';
|
||||
import { map, switchMap } from 'rxjs/operators';
|
||||
import { ApiInterfaceRx } from '@polkadot/api/types';
|
||||
import { Option } from '@polkadot/types';
|
||||
|
||||
import { memo } from '../util';
|
||||
|
||||
function withImage (api: ApiInterfaceRx, nextOpt: Option<ITuple<[Hash, VoteThreshold]>>): Observable<DeriveProposalExternal | null> {
|
||||
if (nextOpt.isNone) {
|
||||
return of(null);
|
||||
}
|
||||
|
||||
const [imageHash, threshold] = nextOpt.unwrap();
|
||||
|
||||
return api.derive.democracy.preimage(imageHash).pipe(
|
||||
map((image): DeriveProposalExternal => ({
|
||||
image,
|
||||
imageHash,
|
||||
threshold
|
||||
}))
|
||||
);
|
||||
}
|
||||
|
||||
export function nextExternal (api: ApiInterfaceRx): () => Observable<DeriveProposalExternal | null> {
|
||||
return memo((): Observable<DeriveProposalExternal | null> =>
|
||||
api.query.democracy?.nextExternal
|
||||
? api.query.democracy.nextExternal<Option<ITuple<[Hash, VoteThreshold]>>>().pipe(
|
||||
switchMap((nextOpt) => withImage(api, nextOpt))
|
||||
)
|
||||
: of(null)
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
// 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, Hash } from '@polkadot/types/interfaces';
|
||||
import { ITuple } from '@polkadot/types/types';
|
||||
import { ApiInterfaceRx } from '@polkadot/api/types';
|
||||
import { DeriveProposalImage } from '../types';
|
||||
|
||||
import { Observable } from 'rxjs';
|
||||
import { map } from 'rxjs/operators';
|
||||
import { Bytes, Option } from '@polkadot/types';
|
||||
|
||||
import { memo } from '../util';
|
||||
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> =>
|
||||
api.query.democracy.preimages<PreImage>(hash).pipe(
|
||||
map((imageOpt) => parseImage(api, imageOpt))
|
||||
)
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
// 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, Hash } from '@polkadot/types/interfaces';
|
||||
import { ITuple } from '@polkadot/types/types';
|
||||
import { ApiInterfaceRx } from '@polkadot/api/types';
|
||||
import { DeriveProposalImage } from '../types';
|
||||
|
||||
import { Observable } from 'rxjs';
|
||||
import { map } from 'rxjs/operators';
|
||||
import { Bytes, Option } from '@polkadot/types';
|
||||
|
||||
import { memo } from '../util';
|
||||
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)[]> =>
|
||||
api.query.democracy.preimages.multi<PreImage>(hashes).pipe(
|
||||
map((images): (DeriveProposalImage | undefined)[] =>
|
||||
images.map((imageOpt) => parseImage(api, imageOpt))
|
||||
)
|
||||
)
|
||||
);
|
||||
}
|
||||
@@ -2,82 +2,68 @@
|
||||
// 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, Hash, PropIndex, Proposal } from '@polkadot/types/interfaces';
|
||||
import { AccountId, Balance, Hash, PropIndex } from '@polkadot/types/interfaces';
|
||||
import { ITuple } from '@polkadot/types/types';
|
||||
import { DeriveProposal } from '../types';
|
||||
import { DeriveProposalImage, DeriveProposal } from '../types';
|
||||
|
||||
import { Observable, combineLatest, of } from 'rxjs';
|
||||
import { map, switchMap } from 'rxjs/operators';
|
||||
import { ApiInterfaceRx } from '@polkadot/api/types';
|
||||
import { Bytes, Option, Vec, createType } from '@polkadot/types';
|
||||
import { Option, Vec } from '@polkadot/types';
|
||||
import { isFunction } from '@polkadot/util';
|
||||
|
||||
import { memo } from '../util';
|
||||
|
||||
export type PreImage = Option<ITuple<[Bytes, AccountId, Balance, BlockNumber]>>;
|
||||
|
||||
type Depositors = Option<ITuple<[Balance, Vec<AccountId>]>>;
|
||||
type DepositorsNew = Option<ITuple<[Vec<AccountId>, Balance]>>;
|
||||
type DepositorsOld = Option<ITuple<[Balance, Vec<AccountId>]>>;
|
||||
type Depositors = DepositorsNew | DepositorsOld;
|
||||
type Proposals = Vec<ITuple<[PropIndex, Hash, AccountId]>>;
|
||||
type Result = [Proposals, (DeriveProposalImage | undefined)[], Depositors[]];
|
||||
|
||||
interface Result {
|
||||
depositors: Depositors[];
|
||||
preimages: PreImage[];
|
||||
proposals: Proposals;
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
function isNewDepositors (depositors: ITuple<[Vec<AccountId>, Balance]> | ITuple<[Balance, Vec<AccountId>]>): depositors is ITuple<[Vec<AccountId>, Balance]> {
|
||||
// Detect balance...
|
||||
// eslint-disable-next-line @typescript-eslint/unbound-method
|
||||
return isFunction((depositors[1] as Balance).mul);
|
||||
}
|
||||
|
||||
function parse (api: ApiInterfaceRx, { depositors, proposals, preimages }: Result): DeriveProposal[] {
|
||||
function parse ([proposals, images, optDepositors]: Result): DeriveProposal[] {
|
||||
return proposals
|
||||
.filter(([, , proposer], index): boolean =>
|
||||
!!(depositors[index]?.isSome) && !proposer.isEmpty
|
||||
!!(optDepositors[index]?.isSome) && !proposer.isEmpty
|
||||
)
|
||||
.map(([propIndex, hash, proposer], index): DeriveProposal => {
|
||||
const preimage = preimages[index].unwrapOr(null);
|
||||
const depositor = depositors[index].unwrap();
|
||||
let proposal: undefined | Proposal;
|
||||
|
||||
// we could end up in a situation where the proposal is non-decodable, e.g. after an upgrade
|
||||
if (preimage) {
|
||||
try {
|
||||
proposal = createType(api.registry, 'Proposal', preimage[0].toU8a(true));
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
}
|
||||
}
|
||||
.map(([index, imageHash, proposer], proposalIndex): DeriveProposal => {
|
||||
const depositors = optDepositors[proposalIndex].unwrap();
|
||||
|
||||
return {
|
||||
balance: depositor[0],
|
||||
hash,
|
||||
index: propIndex,
|
||||
preimage: preimage
|
||||
? {
|
||||
at: preimage[3],
|
||||
balance: preimage[2],
|
||||
proposer: preimage[1]
|
||||
}
|
||||
: undefined,
|
||||
proposal,
|
||||
proposer,
|
||||
seconds: depositor[1]
|
||||
...(
|
||||
isNewDepositors(depositors)
|
||||
? { balance: depositors[1], seconds: depositors[0] }
|
||||
: { balance: depositors[0], seconds: depositors[1] }
|
||||
),
|
||||
image: images[proposalIndex],
|
||||
imageHash,
|
||||
index,
|
||||
proposer
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
export function proposals (api: ApiInterfaceRx): () => Observable<DeriveProposal[]> {
|
||||
return memo((): Observable<DeriveProposal[]> =>
|
||||
api.query.democracy?.publicProps
|
||||
api.query.democracy?.publicProps && api.query.democracy?.preimages
|
||||
? api.query.democracy.publicProps<Proposals>().pipe(
|
||||
switchMap((proposals) =>
|
||||
combineLatest([
|
||||
of(proposals),
|
||||
api.query.democracy.preimages.multi<PreImage>(
|
||||
api.derive.democracy.preimages(
|
||||
proposals.map(([, hash]): Hash => hash)),
|
||||
api.query.democracy.depositOf.multi<Depositors>(
|
||||
proposals.map(([index]): PropIndex => index))
|
||||
])
|
||||
),
|
||||
map(([proposals, preimages, depositors]): DeriveProposal[] =>
|
||||
parse(api, { depositors, proposals, preimages })
|
||||
)
|
||||
map(parse)
|
||||
)
|
||||
: of([] as DeriveProposal[])
|
||||
: of([])
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
// 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 { ReferendumIndex } from '@polkadot/types/interfaces';
|
||||
|
||||
import BN from 'bn.js';
|
||||
import { Observable, of } from 'rxjs';
|
||||
import { map } from 'rxjs/operators';
|
||||
|
||||
import { memo } from '../util';
|
||||
|
||||
export function referendumIds (api: ApiInterfaceRx): () => Observable<BN[]> {
|
||||
return memo((): Observable<BN[]> =>
|
||||
api.query.democracy?.lowestUnbaked
|
||||
? api.queryMulti<[ReferendumIndex, ReferendumIndex]>([
|
||||
api.query.democracy.lowestUnbaked,
|
||||
api.query.democracy.referendumCount
|
||||
]).pipe(
|
||||
map(([first, total]): BN[] =>
|
||||
total.gt(first)
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
|
||||
? [...Array(total.sub(first).toNumber())].map((_, i): BN => first.addn(i))
|
||||
: []
|
||||
)
|
||||
)
|
||||
: of([])
|
||||
);
|
||||
}
|
||||
@@ -1,64 +0,0 @@
|
||||
// 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 { ReferendumInfo } from '@polkadot/types/interfaces/democracy';
|
||||
import { DerivedReferendum } from '../types';
|
||||
import { PreImage } from './proposals';
|
||||
|
||||
import BN from 'bn.js';
|
||||
import { Observable, of } from 'rxjs';
|
||||
import { map, switchMap } from 'rxjs/operators';
|
||||
import { ApiInterfaceRx } from '@polkadot/api/types';
|
||||
import { Option, createType } from '@polkadot/types';
|
||||
|
||||
import { memo } from '../util';
|
||||
|
||||
function constructInfo (api: ApiInterfaceRx, index: BN | number, _info: Option<ReferendumInfo>, _preimage?: PreImage): DerivedReferendum | null {
|
||||
const preImage = _preimage?.isSome
|
||||
? _preimage.unwrap()
|
||||
: null;
|
||||
const info = _info.unwrapOr(null);
|
||||
|
||||
if (!info) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return {
|
||||
index: createType(api.registry, 'PropIndex', index),
|
||||
info,
|
||||
hash: info.proposalHash,
|
||||
proposal: preImage
|
||||
? createType(api.registry, 'Proposal', preImage[0].toU8a(true))
|
||||
: undefined,
|
||||
preimage: preImage
|
||||
? {
|
||||
at: preImage[3],
|
||||
balance: preImage[2],
|
||||
proposer: preImage[1]
|
||||
}
|
||||
: undefined
|
||||
};
|
||||
}
|
||||
|
||||
export function retrieveInfo (api: ApiInterfaceRx, index: BN | number, info: Option<ReferendumInfo>): Observable<DerivedReferendum | null> {
|
||||
return ((
|
||||
info?.isSome
|
||||
? api.query.democracy.preimages(info.unwrap().proposalHash)
|
||||
: of(undefined)
|
||||
) as Observable<PreImage | undefined>).pipe(
|
||||
map((preimage?: PreImage): DerivedReferendum | null =>
|
||||
constructInfo(api, index, info, preimage)
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
export function referendumInfo (api: ApiInterfaceRx): (index: BN | number) => Observable<DerivedReferendum | null> {
|
||||
return memo((index: BN | number): Observable<DerivedReferendum | null> =>
|
||||
api.query.democracy.referendumInfoOf<Option<ReferendumInfo>>(index).pipe(
|
||||
switchMap((info): Observable<DerivedReferendum | null> =>
|
||||
retrieveInfo(api, index, info)
|
||||
)
|
||||
)
|
||||
);
|
||||
}
|
||||
@@ -1,35 +0,0 @@
|
||||
// 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 { ReferendumInfo } from '@polkadot/types/interfaces/democracy';
|
||||
import { DerivedReferendum } from '../types';
|
||||
|
||||
import BN from 'bn.js';
|
||||
import { Observable, combineLatest, of } from 'rxjs';
|
||||
import { map, switchMap } from 'rxjs/operators';
|
||||
import { ApiInterfaceRx } from '@polkadot/api/types';
|
||||
import { Option } from '@polkadot/types';
|
||||
|
||||
import { memo } from '../util';
|
||||
import { retrieveInfo } from './referendumInfo';
|
||||
|
||||
export function referendumInfos (api: ApiInterfaceRx): (ids?: (BN | number)[]) => Observable<DerivedReferendum[]> {
|
||||
return memo((ids: (BN | number)[] = []): Observable<DerivedReferendum[]> =>
|
||||
(
|
||||
!ids?.length
|
||||
? of([] as Option<ReferendumInfo>[])
|
||||
: api.query.democracy.referendumInfoOf.multi<Option<ReferendumInfo>>(ids)
|
||||
).pipe(
|
||||
switchMap((infos): Observable<(DerivedReferendum | null)[]> =>
|
||||
combineLatest(
|
||||
...ids.map((id, index): Observable<DerivedReferendum | null> =>
|
||||
retrieveInfo(api, id, infos[index])
|
||||
)
|
||||
)
|
||||
),
|
||||
map((infos): DerivedReferendum[] =>
|
||||
infos.filter((referendum): referendum is DerivedReferendum => !!referendum)
|
||||
)
|
||||
));
|
||||
}
|
||||
@@ -1,34 +0,0 @@
|
||||
// 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, Vote } from '@polkadot/types/interfaces';
|
||||
|
||||
import BN from 'bn.js';
|
||||
import { combineLatest, Observable, of } from 'rxjs';
|
||||
import { map, switchMap } from 'rxjs/operators';
|
||||
import { ApiInterfaceRx } from '@polkadot/api/types';
|
||||
import { Vec, createType } from '@polkadot/types';
|
||||
|
||||
import { DerivedBalancesAccount, DerivedReferendumVote } from '../types';
|
||||
import { memo } from '../util';
|
||||
|
||||
export function referendumVotesFor (api: ApiInterfaceRx): (referendumId: BN | number) => Observable<DerivedReferendumVote[]> {
|
||||
return memo((referendumId: BN | number): Observable<DerivedReferendumVote[]> =>
|
||||
api.query.democracy.votersFor<Vec<AccountId>>(referendumId).pipe(
|
||||
switchMap((votersFor): Observable<[Vec<AccountId>, Vote[], DerivedBalancesAccount[]]> =>
|
||||
combineLatest([
|
||||
of(votersFor),
|
||||
api.derive.democracy.votes(referendumId, votersFor),
|
||||
api.derive.balances.votingBalances(votersFor)
|
||||
])
|
||||
),
|
||||
map(([votersFor, votes, balances]): DerivedReferendumVote[] =>
|
||||
votersFor.map((accountId, index): DerivedReferendumVote => ({
|
||||
accountId,
|
||||
balance: balances[index].votingBalance || createType(api.registry, 'Balance'),
|
||||
vote: votes[index] || createType(api.registry, 'Vote')
|
||||
} as DerivedReferendumVote))
|
||||
)
|
||||
));
|
||||
}
|
||||
@@ -2,33 +2,29 @@
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the Apache-2.0 license. See the LICENSE file for details.
|
||||
|
||||
import { ReferendumIndex } from '@polkadot/types/interfaces/democracy';
|
||||
import { DerivedReferendum } from '../types';
|
||||
|
||||
import BN from 'bn.js';
|
||||
import { Observable, of } from 'rxjs';
|
||||
import { switchMap } from 'rxjs/operators';
|
||||
import { ApiInterfaceRx } from '@polkadot/api/types';
|
||||
import { DeriveReferendumExt } from '../types';
|
||||
|
||||
import { Observable, combineLatest, of } from 'rxjs';
|
||||
import { map, switchMap } from 'rxjs/operators';
|
||||
|
||||
import { memo } from '../util';
|
||||
|
||||
export function referendums (api: ApiInterfaceRx): () => Observable<DerivedReferendum[]> {
|
||||
return memo((): Observable<DerivedReferendum[]> =>
|
||||
api.query.democracy?.lowestUnbaked
|
||||
? api.queryMulti<[ReferendumIndex, ReferendumIndex]>([
|
||||
api.query.democracy.lowestUnbaked,
|
||||
api.query.democracy.referendumCount
|
||||
]).pipe(
|
||||
switchMap(([earliest, referendumCount]): Observable<DerivedReferendum[]> =>
|
||||
referendumCount?.gt(earliest) && referendumCount?.gtn(0)
|
||||
? api.derive.democracy.referendumInfos(
|
||||
[...Array(referendumCount.sub(earliest).toNumber())].map((_, i): BN =>
|
||||
earliest.addn(i)
|
||||
)
|
||||
)
|
||||
: of([])
|
||||
)
|
||||
export function referendums (api: ApiInterfaceRx): () => Observable<DeriveReferendumExt[]> {
|
||||
return memo((): Observable<DeriveReferendumExt[]> =>
|
||||
api.derive.democracy.referendumsActive().pipe(
|
||||
switchMap((referendums) =>
|
||||
combineLatest([
|
||||
of(referendums),
|
||||
api.derive.democracy._referendumsVotes(referendums)
|
||||
])
|
||||
),
|
||||
map(([referendums, votes]) =>
|
||||
referendums.map((referendum, index): DeriveReferendumExt => ({
|
||||
...referendum,
|
||||
...votes[index]
|
||||
}))
|
||||
)
|
||||
: of([] as DerivedReferendum[])
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
// 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 { DeriveReferendum } from '../types';
|
||||
|
||||
import { Observable, of } from 'rxjs';
|
||||
import { switchMap } from 'rxjs/operators';
|
||||
|
||||
import { memo } from '../util';
|
||||
|
||||
export function referendumsActive (api: ApiInterfaceRx): () => Observable<DeriveReferendum[]> {
|
||||
return memo((): Observable<DeriveReferendum[]> =>
|
||||
api.derive.democracy.referendumIds().pipe(
|
||||
switchMap((ids): Observable<DeriveReferendum[]> =>
|
||||
ids.length
|
||||
? api.derive.democracy.referendumsInfo(ids)
|
||||
: of([])
|
||||
)
|
||||
)
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
// 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 { ReferendumInfo, ReferendumInfoFinished } from '@polkadot/types/interfaces';
|
||||
|
||||
import { Observable } from 'rxjs';
|
||||
import { map, switchMap } from 'rxjs/operators';
|
||||
import { Option } from '@polkadot/types';
|
||||
|
||||
import { memo } from '../util';
|
||||
|
||||
export function referendumsFinished (api: ApiInterfaceRx): () => Observable<ReferendumInfoFinished[]> {
|
||||
return memo((): Observable<ReferendumInfoFinished[]> =>
|
||||
api.derive.democracy.referendumIds().pipe(
|
||||
switchMap((ids) => api.query.democracy.referendumInfoOf.multi<Option<ReferendumInfo>>(ids)),
|
||||
map((infos): ReferendumInfoFinished[] =>
|
||||
infos
|
||||
.filter((optInfo) => optInfo.isSome)
|
||||
.map((optInfo) => optInfo.unwrap())
|
||||
.filter((info) => info.isFinished)
|
||||
.map((info) => info.asFinished)
|
||||
)
|
||||
)
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,156 @@
|
||||
// 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, ReferendumInfo, ReferendumInfoTo239, Vote, Voting, VotingDirectVote, VotingDelegating } from '@polkadot/types/interfaces';
|
||||
import { DeriveBalancesAccount, DeriveReferendum, DeriveReferendumVote, DeriveReferendumVotes } from '../types';
|
||||
|
||||
import BN from 'bn.js';
|
||||
import { Observable, of, combineLatest } from 'rxjs';
|
||||
import { map, switchMap } from 'rxjs/operators';
|
||||
import { Option, Vec } from '@polkadot/types';
|
||||
import { isFunction } from '@polkadot/util';
|
||||
|
||||
import { memo } from '../util';
|
||||
import { calcVotes, getStatus, parseImage } from './util';
|
||||
|
||||
function votesPrev (api: ApiInterfaceRx, referendumId: BN): Observable<DeriveReferendumVote[]> {
|
||||
return api.query.democracy.votersFor<Vec<AccountId>>(referendumId).pipe(
|
||||
switchMap((votersFor): Observable<[Vec<AccountId>, Vote[], DeriveBalancesAccount[]]> =>
|
||||
combineLatest([
|
||||
of(votersFor),
|
||||
votersFor.length
|
||||
? api.query.democracy.voteOf.multi<Vote>(
|
||||
votersFor.map((accountId): [BN | number, AccountId] =>
|
||||
[referendumId, accountId]
|
||||
)
|
||||
)
|
||||
: of([]),
|
||||
api.derive.balances.votingBalances(votersFor)
|
||||
])
|
||||
),
|
||||
map(([votersFor, votes, balances]): DeriveReferendumVote[] =>
|
||||
votersFor.map((accountId, index): DeriveReferendumVote => ({
|
||||
accountId,
|
||||
balance: balances[index].votingBalance || api.registry.createType('Balance'),
|
||||
isDelegating: false,
|
||||
vote: votes[index] || api.registry.createType('Vote')
|
||||
}))
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
function votesCurr (api: ApiInterfaceRx, referendumId: BN): Observable<DeriveReferendumVote[]> {
|
||||
return api.query.democracy.votingOf.entries<Voting>().pipe(
|
||||
map((allVoting): DeriveReferendumVote[] => {
|
||||
const mapped = allVoting.map(([key, voting]): [AccountId, Voting] => [key.args[0] as AccountId, voting]);
|
||||
const votes = mapped
|
||||
.filter(([, voting]) => voting.isDirect)
|
||||
.map(([accountId, voting]): [AccountId, VotingDirectVote[]] => [
|
||||
accountId,
|
||||
voting.asDirect.votes.filter(([idx]) => idx.eq(referendumId))
|
||||
])
|
||||
.filter(([, directVotes]) => !!directVotes.length)
|
||||
.reduce((result: DeriveReferendumVote[], [accountId, votes]) =>
|
||||
// FIXME We are ignoring split votes
|
||||
votes.reduce((result: DeriveReferendumVote[], [, vote]): DeriveReferendumVote[] => {
|
||||
if (vote.isStandard) {
|
||||
result.push({
|
||||
accountId,
|
||||
isDelegating: false,
|
||||
...vote.asStandard
|
||||
});
|
||||
}
|
||||
|
||||
return result;
|
||||
}, result), []
|
||||
);
|
||||
const delegations = mapped
|
||||
.filter(([, voting]) => voting.isDelegating)
|
||||
.map(([accountId, voting]): [AccountId, VotingDelegating] => [accountId, voting.asDelegating]);
|
||||
|
||||
// add delegations
|
||||
delegations.forEach(([accountId, { balance, conviction, target }]): void => {
|
||||
// Are we delegating to a delegator
|
||||
const toDelegator = delegations.find(([accountId]) => accountId.eq(target));
|
||||
const to = votes.find(({ accountId }) => accountId.eq(toDelegator ? toDelegator[0] : target));
|
||||
|
||||
// this delegation has a target
|
||||
if (to) {
|
||||
votes.push({
|
||||
accountId,
|
||||
balance,
|
||||
isDelegating: true,
|
||||
vote: api.registry.createType('Vote', { aye: to.vote.isAye, conviction })
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
return votes;
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
export function _referendumVotes (api: ApiInterfaceRx): (referendum: DeriveReferendum) => Observable<DeriveReferendumVotes> {
|
||||
return memo((referendum: DeriveReferendum): Observable<DeriveReferendumVotes> =>
|
||||
combineLatest([
|
||||
api.derive.democracy.sqrtElectorate(),
|
||||
isFunction(api.query.democracy.votingOf)
|
||||
? votesCurr(api, referendum.index)
|
||||
: votesPrev(api, referendum.index)
|
||||
]).pipe(
|
||||
map(([sqrtElectorate, votes]) =>
|
||||
calcVotes(sqrtElectorate, referendum, votes)
|
||||
)
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
export function _referendumsVotes (api: ApiInterfaceRx): (referendums: DeriveReferendum[]) => Observable<DeriveReferendumVotes[]> {
|
||||
return memo((referendums: DeriveReferendum[]): Observable<DeriveReferendumVotes[]> =>
|
||||
referendums.length
|
||||
? combineLatest(
|
||||
referendums.map((referendum): Observable<DeriveReferendumVotes> =>
|
||||
api.derive.democracy._referendumVotes(referendum)
|
||||
)
|
||||
)
|
||||
: of([])
|
||||
);
|
||||
}
|
||||
|
||||
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> => {
|
||||
const status = getStatus(info);
|
||||
|
||||
return status
|
||||
? api.query.democracy.preimages(status.proposalHash).pipe(
|
||||
map((preimage): DeriveReferendum => ({
|
||||
image: parseImage(api, preimage),
|
||||
imageHash: status.proposalHash,
|
||||
index: api.registry.createType('ReferendumIndex', index),
|
||||
status
|
||||
}))
|
||||
)
|
||||
: of(null);
|
||||
});
|
||||
}
|
||||
|
||||
export function referendumsInfo (api: ApiInterfaceRx): (ids: BN[]) => Observable<DeriveReferendum[]> {
|
||||
return memo((ids: BN[]): Observable<DeriveReferendum[]> =>
|
||||
ids.length
|
||||
? api.query.democracy.referendumInfoOf.multi<Option<ReferendumInfo>>(ids).pipe(
|
||||
switchMap((infos): Observable<(DeriveReferendum | null)[]> =>
|
||||
combineLatest(
|
||||
ids.map((id, index): Observable<DeriveReferendum | null> =>
|
||||
api.derive.democracy._referendumInfo(id, infos[index])
|
||||
)
|
||||
)
|
||||
),
|
||||
map((infos) =>
|
||||
infos.filter((referendum): referendum is DeriveReferendum => !!referendum)
|
||||
)
|
||||
)
|
||||
: of([])
|
||||
);
|
||||
}
|
||||
@@ -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 { ApiInterfaceRx } from '@polkadot/api/types';
|
||||
|
||||
import BN from 'bn.js';
|
||||
import { Observable } from 'rxjs';
|
||||
import { map } from 'rxjs/operators';
|
||||
import { bnSqrt } from '@polkadot/util';
|
||||
|
||||
import { memo } from '../util';
|
||||
|
||||
export function sqrtElectorate (api: ApiInterfaceRx): () => Observable<BN> {
|
||||
return memo((): Observable<BN> =>
|
||||
api.query.balances.totalIssuance().pipe(
|
||||
map((totalIssuance) =>
|
||||
bnSqrt(totalIssuance)
|
||||
)
|
||||
)
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
// 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 type BN from 'bn.js';
|
||||
import { AccountId, Balance, BlockNumber, Hash, Proposal, PropIndex, ReferendumInfoTo239, ReferendumStatus, Vote, ReferendumIndex, VoteThreshold } from '@polkadot/types/interfaces';
|
||||
|
||||
import { Vec } from '@polkadot/types';
|
||||
|
||||
export interface DeriveDemocracyLock {
|
||||
balance: Balance;
|
||||
isFinished: boolean;
|
||||
referendumId: ReferendumIndex;
|
||||
unlockAt: BN;
|
||||
vote: Vote;
|
||||
}
|
||||
|
||||
export interface DeriveDispatch {
|
||||
at: BlockNumber;
|
||||
index: ReferendumIndex;
|
||||
imageHash: Hash;
|
||||
image?: DeriveProposalImage;
|
||||
}
|
||||
|
||||
export interface DeriveProposalImage {
|
||||
at: BlockNumber;
|
||||
balance: Balance;
|
||||
proposal?: Proposal;
|
||||
proposer: AccountId;
|
||||
}
|
||||
|
||||
export interface DeriveProposal {
|
||||
balance?: Balance;
|
||||
index: PropIndex;
|
||||
image?: DeriveProposalImage;
|
||||
imageHash: Hash;
|
||||
proposer: AccountId;
|
||||
seconds: Vec<AccountId>;
|
||||
}
|
||||
|
||||
export interface DeriveProposalExternal {
|
||||
image?: DeriveProposalImage;
|
||||
imageHash: Hash;
|
||||
threshold: VoteThreshold;
|
||||
}
|
||||
|
||||
export interface DeriveReferendum {
|
||||
index: ReferendumIndex;
|
||||
image?: DeriveProposalImage;
|
||||
imageHash: Hash;
|
||||
status: ReferendumStatus | ReferendumInfoTo239;
|
||||
}
|
||||
|
||||
export interface DeriveReferendumVote {
|
||||
accountId: AccountId;
|
||||
balance: Balance;
|
||||
isDelegating: boolean;
|
||||
vote: Vote;
|
||||
}
|
||||
|
||||
export interface DeriveReferendumVoteState {
|
||||
allAye: DeriveReferendumVote[];
|
||||
allNay: DeriveReferendumVote[];
|
||||
voteCount: number;
|
||||
voteCountAye: number;
|
||||
voteCountNay: number;
|
||||
votedAye: BN;
|
||||
votedNay: BN;
|
||||
votedTotal: BN;
|
||||
}
|
||||
|
||||
export interface DeriveReferendumVotes extends DeriveReferendumVoteState {
|
||||
isPassing: boolean;
|
||||
votes: DeriveReferendumVote[];
|
||||
}
|
||||
|
||||
export interface DeriveReferendumExt extends DeriveReferendum, DeriveReferendumVotes {
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user