@ledgerhq/coin-polkadot 0.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (181) hide show
  1. package/.eslintrc.js +57 -0
  2. package/.turbo/turbo-build.log +4 -0
  3. package/CHANGELOG.md +12 -0
  4. package/jest.config.js +10 -0
  5. package/lib/account.d.ts +15 -0
  6. package/lib/account.d.ts.map +1 -0
  7. package/lib/account.js +133 -0
  8. package/lib/account.js.map +1 -0
  9. package/lib/address.d.ts +7 -0
  10. package/lib/address.d.ts.map +1 -0
  11. package/lib/address.js +28 -0
  12. package/lib/address.js.map +1 -0
  13. package/lib/api/bisontrails.d.ts +11 -0
  14. package/lib/api/bisontrails.d.ts.map +1 -0
  15. package/lib/api/bisontrails.js +351 -0
  16. package/lib/api/bisontrails.js.map +1 -0
  17. package/lib/api/common.d.ts +12 -0
  18. package/lib/api/common.d.ts.map +1 -0
  19. package/lib/api/common.js +41 -0
  20. package/lib/api/common.js.map +1 -0
  21. package/lib/api/index.d.ts +3 -0
  22. package/lib/api/index.d.ts.map +1 -0
  23. package/lib/api/index.js +53 -0
  24. package/lib/api/index.js.map +1 -0
  25. package/lib/api/sidecar.d.ts +193 -0
  26. package/lib/api/sidecar.d.ts.map +1 -0
  27. package/lib/api/sidecar.js +844 -0
  28. package/lib/api/sidecar.js.map +1 -0
  29. package/lib/api/sidecar.types.d.ts +163 -0
  30. package/lib/api/sidecar.types.d.ts.map +1 -0
  31. package/lib/api/sidecar.types.js +3 -0
  32. package/lib/api/sidecar.types.js.map +1 -0
  33. package/lib/api/subscan.d.ts +6 -0
  34. package/lib/api/subscan.d.ts.map +1 -0
  35. package/lib/api/subscan.js +375 -0
  36. package/lib/api/subscan.js.map +1 -0
  37. package/lib/api/websocket.d.ts +92 -0
  38. package/lib/api/websocket.d.ts.map +1 -0
  39. package/lib/api/websocket.js +759 -0
  40. package/lib/api/websocket.js.map +1 -0
  41. package/lib/bridge/js.d.ts +6 -0
  42. package/lib/bridge/js.d.ts.map +1 -0
  43. package/lib/bridge/js.js +120 -0
  44. package/lib/bridge/js.js.map +1 -0
  45. package/lib/bridge.integration.test.d.ts +4 -0
  46. package/lib/bridge.integration.test.d.ts.map +1 -0
  47. package/lib/bridge.integration.test.js +795 -0
  48. package/lib/bridge.integration.test.js.map +1 -0
  49. package/lib/cache.d.ts +65 -0
  50. package/lib/cache.d.ts.map +1 -0
  51. package/lib/cache.js +182 -0
  52. package/lib/cache.js.map +1 -0
  53. package/lib/cli-transaction.d.ts +44 -0
  54. package/lib/cli-transaction.d.ts.map +1 -0
  55. package/lib/cli-transaction.js +148 -0
  56. package/lib/cli-transaction.js.map +1 -0
  57. package/lib/deviceTransactionConfig.d.ts +16 -0
  58. package/lib/deviceTransactionConfig.d.ts.map +1 -0
  59. package/lib/deviceTransactionConfig.js +171 -0
  60. package/lib/deviceTransactionConfig.js.map +1 -0
  61. package/lib/errors.d.ts +37 -0
  62. package/lib/errors.d.ts.map +1 -0
  63. package/lib/errors.js +17 -0
  64. package/lib/errors.js.map +1 -0
  65. package/lib/hw-getAddress.d.ts +4 -0
  66. package/lib/hw-getAddress.d.ts.map +1 -0
  67. package/lib/hw-getAddress.js +64 -0
  68. package/lib/hw-getAddress.js.map +1 -0
  69. package/lib/js-buildTransaction.d.ts +25 -0
  70. package/lib/js-buildTransaction.d.ts.map +1 -0
  71. package/lib/js-buildTransaction.js +265 -0
  72. package/lib/js-buildTransaction.js.map +1 -0
  73. package/lib/js-createTransaction.d.ts +9 -0
  74. package/lib/js-createTransaction.d.ts.map +1 -0
  75. package/lib/js-createTransaction.js +22 -0
  76. package/lib/js-createTransaction.js.map +1 -0
  77. package/lib/js-estimateMaxSpendable.d.ts +15 -0
  78. package/lib/js-estimateMaxSpendable.d.ts.map +1 -0
  79. package/lib/js-estimateMaxSpendable.js +89 -0
  80. package/lib/js-estimateMaxSpendable.js.map +1 -0
  81. package/lib/js-getFeesForTransaction.d.ts +14 -0
  82. package/lib/js-getFeesForTransaction.d.ts.map +1 -0
  83. package/lib/js-getFeesForTransaction.js +94 -0
  84. package/lib/js-getFeesForTransaction.js.map +1 -0
  85. package/lib/js-getTransactionStatus.d.ts +18 -0
  86. package/lib/js-getTransactionStatus.d.ts.map +1 -0
  87. package/lib/js-getTransactionStatus.js +316 -0
  88. package/lib/js-getTransactionStatus.js.map +1 -0
  89. package/lib/js-prepareTransaction.d.ts +9 -0
  90. package/lib/js-prepareTransaction.d.ts.map +1 -0
  91. package/lib/js-prepareTransaction.js +83 -0
  92. package/lib/js-prepareTransaction.js.map +1 -0
  93. package/lib/js-signOperation.d.ts +27 -0
  94. package/lib/js-signOperation.d.ts.map +1 -0
  95. package/lib/js-signOperation.js +235 -0
  96. package/lib/js-signOperation.js.map +1 -0
  97. package/lib/js-synchronisation.d.ts +3 -0
  98. package/lib/js-synchronisation.d.ts.map +1 -0
  99. package/lib/js-synchronisation.js +104 -0
  100. package/lib/js-synchronisation.js.map +1 -0
  101. package/lib/logic.d.ts +107 -0
  102. package/lib/logic.d.ts.map +1 -0
  103. package/lib/logic.js +242 -0
  104. package/lib/logic.js.map +1 -0
  105. package/lib/platformAdapter.d.ts +11 -0
  106. package/lib/platformAdapter.d.ts.map +1 -0
  107. package/lib/platformAdapter.js +25 -0
  108. package/lib/platformAdapter.js.map +1 -0
  109. package/lib/platformAdapter.test.d.ts +2 -0
  110. package/lib/platformAdapter.test.d.ts.map +1 -0
  111. package/lib/platformAdapter.test.js +51 -0
  112. package/lib/platformAdapter.test.js.map +1 -0
  113. package/lib/polkadot-crypto.d.ts +2 -0
  114. package/lib/polkadot-crypto.d.ts.map +1 -0
  115. package/lib/polkadot-crypto.js +14 -0
  116. package/lib/polkadot-crypto.js.map +1 -0
  117. package/lib/preload.d.ts +14 -0
  118. package/lib/preload.d.ts.map +1 -0
  119. package/lib/preload.js +173 -0
  120. package/lib/preload.js.map +1 -0
  121. package/lib/serialization.d.ts +4 -0
  122. package/lib/serialization.d.ts.map +1 -0
  123. package/lib/serialization.js +51 -0
  124. package/lib/serialization.js.map +1 -0
  125. package/lib/specs.d.ts +7 -0
  126. package/lib/specs.d.ts.map +1 -0
  127. package/lib/specs.js +274 -0
  128. package/lib/specs.js.map +1 -0
  129. package/lib/speculos-deviceActions.d.ts +4 -0
  130. package/lib/speculos-deviceActions.d.ts.map +1 -0
  131. package/lib/speculos-deviceActions.js +85 -0
  132. package/lib/speculos-deviceActions.js.map +1 -0
  133. package/lib/transaction.d.ts +15 -0
  134. package/lib/transaction.d.ts.map +1 -0
  135. package/lib/transaction.js +51 -0
  136. package/lib/transaction.js.map +1 -0
  137. package/lib/types.d.ts +96 -0
  138. package/lib/types.d.ts.map +1 -0
  139. package/lib/types.js +3 -0
  140. package/lib/types.js.map +1 -0
  141. package/lib/validators.d.ts +3 -0
  142. package/lib/validators.d.ts.map +1 -0
  143. package/lib/validators.js +7 -0
  144. package/lib/validators.js.map +1 -0
  145. package/package.json +95 -0
  146. package/src/account.ts +170 -0
  147. package/src/address.ts +28 -0
  148. package/src/api/bisontrails.ts +343 -0
  149. package/src/api/common.ts +52 -0
  150. package/src/api/index.ts +38 -0
  151. package/src/api/sidecar.ts +735 -0
  152. package/src/api/sidecar.types.ts +162 -0
  153. package/src/api/subscan.ts +362 -0
  154. package/src/api/websocket.ts +535 -0
  155. package/src/bridge/js.ts +81 -0
  156. package/src/bridge.integration.test.ts +764 -0
  157. package/src/cache.ts +202 -0
  158. package/src/cli-transaction.ts +184 -0
  159. package/src/deviceTransactionConfig.ts +209 -0
  160. package/src/errors.ts +39 -0
  161. package/src/hw-getAddress.ts +14 -0
  162. package/src/js-buildTransaction.ts +206 -0
  163. package/src/js-createTransaction.ts +22 -0
  164. package/src/js-estimateMaxSpendable.ts +37 -0
  165. package/src/js-getFeesForTransaction.ts +41 -0
  166. package/src/js-getTransactionStatus.ts +350 -0
  167. package/src/js-prepareTransaction.ts +27 -0
  168. package/src/js-signOperation.ts +232 -0
  169. package/src/js-synchronisation.ts +57 -0
  170. package/src/logic.ts +266 -0
  171. package/src/platformAdapter.test.ts +61 -0
  172. package/src/platformAdapter.ts +29 -0
  173. package/src/polkadot-crypto.ts +10 -0
  174. package/src/preload.ts +148 -0
  175. package/src/serialization.ts +48 -0
  176. package/src/specs.ts +305 -0
  177. package/src/speculos-deviceActions.ts +84 -0
  178. package/src/transaction.ts +64 -0
  179. package/src/types.ts +118 -0
  180. package/src/validators.ts +2 -0
  181. package/tsconfig.json +21 -0
@@ -0,0 +1,759 @@
1
+ "use strict";
2
+ /*
3
+ THIS FILE IS UNUSED AND PROVIDED AS EXAMPLE FOR USING POLKADOT'S WEBSOCKET API DIRECTLY
4
+
5
+ POLKADOT.JS API VERSION 2.5.1
6
+ */
7
+ var __assign = (this && this.__assign) || function () {
8
+ __assign = Object.assign || function(t) {
9
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
10
+ s = arguments[i];
11
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
12
+ t[p] = s[p];
13
+ }
14
+ return t;
15
+ };
16
+ return __assign.apply(this, arguments);
17
+ };
18
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
19
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
20
+ return new (P || (P = Promise))(function (resolve, reject) {
21
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
22
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
23
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
24
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
25
+ });
26
+ };
27
+ var __generator = (this && this.__generator) || function (thisArg, body) {
28
+ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
29
+ return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
30
+ function verb(n) { return function (v) { return step([n, v]); }; }
31
+ function step(op) {
32
+ if (f) throw new TypeError("Generator is already executing.");
33
+ while (g && (g = 0, op[0] && (_ = 0)), _) try {
34
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
35
+ if (y = 0, t) op = [op[0] & 2, t.value];
36
+ switch (op[0]) {
37
+ case 0: case 1: t = op; break;
38
+ case 4: _.label++; return { value: op[1], done: false };
39
+ case 5: _.label++; y = op[1]; op = [0]; continue;
40
+ case 7: op = _.ops.pop(); _.trys.pop(); continue;
41
+ default:
42
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
43
+ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
44
+ if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
45
+ if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
46
+ if (t[2]) _.ops.pop();
47
+ _.trys.pop(); continue;
48
+ }
49
+ op = body.call(thisArg, _);
50
+ } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
51
+ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
52
+ }
53
+ };
54
+ var __read = (this && this.__read) || function (o, n) {
55
+ var m = typeof Symbol === "function" && o[Symbol.iterator];
56
+ if (!m) return o;
57
+ var i = m.call(o), r, ar = [], e;
58
+ try {
59
+ while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
60
+ }
61
+ catch (error) { e = { error: error }; }
62
+ finally {
63
+ try {
64
+ if (r && !r.done && (m = i["return"])) m.call(i);
65
+ }
66
+ finally { if (e) throw e.error; }
67
+ }
68
+ return ar;
69
+ };
70
+ var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
71
+ if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
72
+ if (ar || !(i in from)) {
73
+ if (!ar) ar = Array.prototype.slice.call(from, 0, i);
74
+ ar[i] = from[i];
75
+ }
76
+ }
77
+ return to.concat(ar || Array.prototype.slice.call(from));
78
+ };
79
+ var __importDefault = (this && this.__importDefault) || function (mod) {
80
+ return (mod && mod.__esModule) ? mod : { "default": mod };
81
+ };
82
+ exports.__esModule = true;
83
+ exports.getRegistry = exports.getStakingProgress = exports.getValidators = exports.fetchIdentities = exports.fetchRewardPoints = exports.paymentInfo = exports.submitExtrinsic = exports.getTransactionParams = exports.getNominations = exports.getStakingInfo = exports.getBalances = exports.getAccount = exports.verifyValidatorAddresses = exports.isControllerAddress = exports.isNewAccount = exports.isElectionClosed = exports.disconnect = void 0;
84
+ /* eslint-disable */
85
+ /* istanbul ignore file */
86
+ var uniq_1 = __importDefault(require("lodash/uniq"));
87
+ var compact_1 = __importDefault(require("lodash/compact"));
88
+ var bignumber_js_1 = require("bignumber.js");
89
+ var env_1 = require("@ledgerhq/coin-framework/env");
90
+ //@ts-expect-error
91
+ var api_1 = require("@polkadot/api");
92
+ var util_1 = require("@polkadot/util");
93
+ var VALIDATOR_COMISSION_RATIO = 1000000000;
94
+ var getWsUrl = function () { return (0, env_1.getEnv)("API_POLKADOT_NODE"); };
95
+ var WEBSOCKET_DEBOUNCE_DELAY = 30000;
96
+ var api;
97
+ var pendingQueries = [];
98
+ var apiDisconnectTimeout;
99
+ /**
100
+ * Connects to Substrate Node, executes calls then disconnects
101
+ *
102
+ * @param {*} execute - the calls to execute on api
103
+ */
104
+ function withApi(execute) {
105
+ return __awaiter(this, void 0, void 0, function () {
106
+ var err_1, wsProvider, query, res;
107
+ return __generator(this, function (_a) {
108
+ switch (_a.label) {
109
+ case 0:
110
+ if (!api) return [3 /*break*/, 4];
111
+ _a.label = 1;
112
+ case 1:
113
+ _a.trys.push([1, 3, , 4]);
114
+ return [4 /*yield*/, api.isReadyOrError];
115
+ case 2:
116
+ _a.sent();
117
+ return [3 /*break*/, 4];
118
+ case 3:
119
+ err_1 = _a.sent();
120
+ // definitely not connected...
121
+ api = null;
122
+ pendingQueries = [];
123
+ return [3 /*break*/, 4];
124
+ case 4:
125
+ if (!!api) return [3 /*break*/, 6];
126
+ wsProvider = new api_1.WsProvider(getWsUrl(),
127
+ /* autoConnectMs = */
128
+ false);
129
+ wsProvider.connect();
130
+ return [4 /*yield*/, new api_1.ApiPromise({
131
+ provider: wsProvider
132
+ }).isReadyOrError];
133
+ case 5:
134
+ api = _a.sent();
135
+ _a.label = 6;
136
+ case 6:
137
+ cancelDebouncedDisconnect();
138
+ _a.label = 7;
139
+ case 7:
140
+ _a.trys.push([7, , 9, 10]);
141
+ query = execute(api);
142
+ pendingQueries.push(query["catch"](function (err) { return err; }));
143
+ return [4 /*yield*/, query];
144
+ case 8:
145
+ res = _a.sent();
146
+ return [2 /*return*/, res];
147
+ case 9:
148
+ debouncedDisconnect();
149
+ return [7 /*endfinally*/];
150
+ case 10: return [2 /*return*/];
151
+ }
152
+ });
153
+ });
154
+ }
155
+ /**
156
+ * Disconnects Websocket API client after all pending queries are flushed.
157
+ */
158
+ var disconnect = function () { return __awaiter(void 0, void 0, void 0, function () {
159
+ var disconnecting, pending_1;
160
+ return __generator(this, function (_a) {
161
+ switch (_a.label) {
162
+ case 0:
163
+ cancelDebouncedDisconnect();
164
+ if (!api) return [3 /*break*/, 3];
165
+ disconnecting = api;
166
+ pending_1 = pendingQueries;
167
+ api = undefined;
168
+ pendingQueries = [];
169
+ return [4 /*yield*/, Promise.all(pending_1)];
170
+ case 1:
171
+ _a.sent();
172
+ return [4 /*yield*/, disconnecting.disconnect()];
173
+ case 2:
174
+ _a.sent();
175
+ _a.label = 3;
176
+ case 3: return [2 /*return*/];
177
+ }
178
+ });
179
+ }); };
180
+ exports.disconnect = disconnect;
181
+ var cancelDebouncedDisconnect = function () {
182
+ if (apiDisconnectTimeout) {
183
+ clearTimeout(apiDisconnectTimeout);
184
+ apiDisconnectTimeout = null;
185
+ }
186
+ };
187
+ /**
188
+ * Disconnects Websocket client after a delay.
189
+ */
190
+ var debouncedDisconnect = function () {
191
+ cancelDebouncedDisconnect();
192
+ apiDisconnectTimeout = setTimeout(exports.disconnect, WEBSOCKET_DEBOUNCE_DELAY);
193
+ };
194
+ /**
195
+ * Returns true if ElectionStatus is Close. If ElectionStatus is Open, some features must be disabled.
196
+ */
197
+ var isElectionClosed = function () { return __awaiter(void 0, void 0, void 0, function () {
198
+ return __generator(this, function (_a) {
199
+ return [2 /*return*/, withApi(function (api) { return __awaiter(void 0, void 0, void 0, function () {
200
+ var status, res;
201
+ return __generator(this, function (_a) {
202
+ switch (_a.label) {
203
+ case 0: return [4 /*yield*/, api.query.staking.eraElectionStatus()];
204
+ case 1:
205
+ status = _a.sent();
206
+ res = status.isClose;
207
+ return [2 /*return*/, !!res];
208
+ }
209
+ });
210
+ }); })];
211
+ });
212
+ }); };
213
+ exports.isElectionClosed = isElectionClosed;
214
+ /**
215
+ * Returns true if the address is a new account with no balance
216
+ *
217
+ * @param {*} addr
218
+ */
219
+ var isNewAccount = function (address) { return __awaiter(void 0, void 0, void 0, function () {
220
+ return __generator(this, function (_a) {
221
+ return [2 /*return*/, withApi(function (api) { return __awaiter(void 0, void 0, void 0, function () {
222
+ var _a, nonce, free;
223
+ return __generator(this, function (_b) {
224
+ switch (_b.label) {
225
+ case 0: return [4 /*yield*/, api.query.system.account(address)];
226
+ case 1:
227
+ _a = _b.sent(), nonce = _a.nonce, free = _a.data.free;
228
+ return [2 /*return*/, (new bignumber_js_1.BigNumber(0).isEqualTo(nonce) && new bignumber_js_1.BigNumber(0).isEqualTo(free))];
229
+ }
230
+ });
231
+ }); })];
232
+ });
233
+ }); };
234
+ exports.isNewAccount = isNewAccount;
235
+ /**
236
+ * Returns true if the address is a new account with no balance
237
+ *
238
+ * @param {*} addr
239
+ */
240
+ var isControllerAddress = function (address) { return __awaiter(void 0, void 0, void 0, function () {
241
+ return __generator(this, function (_a) {
242
+ return [2 /*return*/, withApi(function (api) { return __awaiter(void 0, void 0, void 0, function () {
243
+ var ledgetOpt;
244
+ return __generator(this, function (_a) {
245
+ switch (_a.label) {
246
+ case 0: return [4 /*yield*/, api.query.staking.ledger(address)];
247
+ case 1:
248
+ ledgetOpt = _a.sent();
249
+ return [2 /*return*/, ledgetOpt.isSome];
250
+ }
251
+ });
252
+ }); })];
253
+ });
254
+ }); };
255
+ exports.isControllerAddress = isControllerAddress;
256
+ /**
257
+ * Get all validators addresses to check for validity.
258
+ */
259
+ var getValidatorsStashesAddresses = function () { return __awaiter(void 0, void 0, void 0, function () {
260
+ return __generator(this, function (_a) {
261
+ return [2 /*return*/, withApi(function (api) { return __awaiter(void 0, void 0, void 0, function () {
262
+ var list;
263
+ return __generator(this, function (_a) {
264
+ switch (_a.label) {
265
+ case 0: return [4 /*yield*/, api.derive.staking.stashes()];
266
+ case 1:
267
+ list = _a.sent();
268
+ return [2 /*return*/, list.map(function (v) { return v.toString(); })];
269
+ }
270
+ });
271
+ }); })];
272
+ });
273
+ }); };
274
+ /**
275
+ * Returns all addresses that are not validators
276
+ */
277
+ var verifyValidatorAddresses = function (validators) { return __awaiter(void 0, void 0, void 0, function () {
278
+ var allValidators;
279
+ return __generator(this, function (_a) {
280
+ switch (_a.label) {
281
+ case 0: return [4 /*yield*/, getValidatorsStashesAddresses()];
282
+ case 1:
283
+ allValidators = _a.sent();
284
+ return [2 /*return*/, validators.filter(function (v) { return !allValidators.includes(v); })];
285
+ }
286
+ });
287
+ }); };
288
+ exports.verifyValidatorAddresses = verifyValidatorAddresses;
289
+ /**
290
+ * Get all account-related data
291
+ *
292
+ * @param {*} addr
293
+ */
294
+ var getAccount = function (addr) { return __awaiter(void 0, void 0, void 0, function () {
295
+ return __generator(this, function (_a) {
296
+ return [2 /*return*/, withApi(function () { return __awaiter(void 0, void 0, void 0, function () {
297
+ var balances, stakingInfo, nominations;
298
+ return __generator(this, function (_a) {
299
+ switch (_a.label) {
300
+ case 0: return [4 /*yield*/, (0, exports.getBalances)(addr)];
301
+ case 1:
302
+ balances = _a.sent();
303
+ return [4 /*yield*/, (0, exports.getStakingInfo)(addr)];
304
+ case 2:
305
+ stakingInfo = _a.sent();
306
+ return [4 /*yield*/, (0, exports.getNominations)(addr)];
307
+ case 3:
308
+ nominations = _a.sent();
309
+ return [2 /*return*/, __assign(__assign(__assign({}, balances), stakingInfo), { nominations: nominations })];
310
+ }
311
+ });
312
+ }); })];
313
+ });
314
+ }); };
315
+ exports.getAccount = getAccount;
316
+ /**
317
+ * Returns all the balances for an account
318
+ *
319
+ * @param {*} addr - the account address
320
+ */
321
+ var getBalances = function (addr) { return __awaiter(void 0, void 0, void 0, function () {
322
+ return __generator(this, function (_a) {
323
+ return [2 /*return*/, withApi(function (api) { return __awaiter(void 0, void 0, void 0, function () {
324
+ var _a, finalizedHash, balances, number;
325
+ return __generator(this, function (_b) {
326
+ switch (_b.label) {
327
+ case 0: return [4 /*yield*/, Promise.all([
328
+ api.rpc.chain.getFinalizedHead(),
329
+ api.derive.balances.all(addr),
330
+ ])];
331
+ case 1:
332
+ _a = __read.apply(void 0, [_b.sent(), 2]), finalizedHash = _a[0], balances = _a[1];
333
+ return [4 /*yield*/, api.rpc.chain.getHeader(finalizedHash)];
334
+ case 2:
335
+ number = (_b.sent()).number;
336
+ return [2 /*return*/, {
337
+ blockHeight: number.toNumber(),
338
+ balance: new bignumber_js_1.BigNumber(balances.freeBalance),
339
+ spendableBalance: new bignumber_js_1.BigNumber(balances.availableBalance),
340
+ nonce: balances.accountNonce.toNumber(),
341
+ lockedBalance: new bignumber_js_1.BigNumber(balances.lockedBalance)
342
+ }];
343
+ }
344
+ });
345
+ }); })];
346
+ });
347
+ }); };
348
+ exports.getBalances = getBalances;
349
+ /**
350
+ * Returns all staking-related data for an account
351
+ *
352
+ * @param {*} addr
353
+ */
354
+ var getStakingInfo = function (addr) { return __awaiter(void 0, void 0, void 0, function () {
355
+ return __generator(this, function (_a) {
356
+ return [2 /*return*/, withApi(function (api) { return __awaiter(void 0, void 0, void 0, function () {
357
+ var _a, controlledLedgerOpt, bonded, stash, controller, _b, activeOpt, ledgerOpt, now, _c, index, start, activeEraIndex, activeEraStart, blockTime, epochDuration, eraLength, ledger, unlockings, unlocked, unlockingBalance, unlockedBalance;
358
+ return __generator(this, function (_d) {
359
+ switch (_d.label) {
360
+ case 0: return [4 /*yield*/, Promise.all([
361
+ api.query.staking.ledger(addr),
362
+ api.query.staking.bonded(addr),
363
+ ])];
364
+ case 1:
365
+ _a = __read.apply(void 0, [_d.sent(), 2]), controlledLedgerOpt = _a[0], bonded = _a[1];
366
+ stash = controlledLedgerOpt.isSome
367
+ ? controlledLedgerOpt.unwrap().stash.toString()
368
+ : null;
369
+ controller = bonded.isSome ? bonded.unwrap().toString() : null;
370
+ // If account is not a stash, no need to fetch corresponding ledger
371
+ if (!controller) {
372
+ return [2 /*return*/, {
373
+ controller: null,
374
+ stash: stash || null,
375
+ unlockedBalance: new bignumber_js_1.BigNumber(0),
376
+ unlockingBalance: new bignumber_js_1.BigNumber(0),
377
+ unlockings: []
378
+ }];
379
+ }
380
+ return [4 /*yield*/, Promise.all([
381
+ api.query.staking.activeEra(),
382
+ api.query.staking.ledger(controller),
383
+ ])];
384
+ case 2:
385
+ _b = __read.apply(void 0, [_d.sent(), 2]), activeOpt = _b[0], ledgerOpt = _b[1];
386
+ now = new Date();
387
+ _c = activeOpt.unwrapOrDefault(), index = _c.index, start = _c.start;
388
+ activeEraIndex = index.toNumber();
389
+ activeEraStart = start.unwrap().toNumber();
390
+ blockTime = api.consts.babe.expectedBlockTime;
391
+ epochDuration = api.consts.babe.epochDuration;
392
+ eraLength = api.consts.staking.sessionsPerEra // 6 sessions
393
+ .mul(epochDuration)
394
+ .mul(blockTime)
395
+ .toNumber();
396
+ ledger = ledgerOpt.isSome ? ledgerOpt.unwrap() : null;
397
+ unlockings = ledger
398
+ ? ledger.unlocking.map(function (lock) { return ({
399
+ amount: new bignumber_js_1.BigNumber(lock.value),
400
+ completionDate: new Date(activeEraStart + (lock.era - activeEraIndex) * eraLength)
401
+ }); })
402
+ : [];
403
+ unlocked = unlockings.filter(function (lock) { return lock.completionDate <= now; });
404
+ unlockingBalance = unlockings.reduce(function (sum, lock) { return sum.plus(lock.amount); }, new bignumber_js_1.BigNumber(0));
405
+ unlockedBalance = unlocked.reduce(function (sum, lock) { return sum.plus(lock.amount); }, new bignumber_js_1.BigNumber(0));
406
+ return [2 /*return*/, {
407
+ controller: controller,
408
+ stash: stash,
409
+ unlockedBalance: unlockedBalance,
410
+ unlockingBalance: unlockingBalance,
411
+ unlockings: unlockings
412
+ }];
413
+ }
414
+ });
415
+ }); })];
416
+ });
417
+ }); };
418
+ exports.getStakingInfo = getStakingInfo;
419
+ /**
420
+ * Returns nominations for an account including validator address, status and associated stake.
421
+ *
422
+ * @param {*} addr
423
+ */
424
+ var getNominations = function (addr) { return __awaiter(void 0, void 0, void 0, function () {
425
+ return __generator(this, function (_a) {
426
+ return [2 /*return*/, withApi(function (api) { return __awaiter(void 0, void 0, void 0, function () {
427
+ var _a, activeEra, nominationsOpt, targets, _b, exposures, stashes, allStashes;
428
+ return __generator(this, function (_c) {
429
+ switch (_c.label) {
430
+ case 0: return [4 /*yield*/, Promise.all([
431
+ api.derive.session.indexes(),
432
+ api.query.staking.nominators(addr),
433
+ ])];
434
+ case 1:
435
+ _a = __read.apply(void 0, [_c.sent(), 2]), activeEra = _a[0].activeEra, nominationsOpt = _a[1];
436
+ if (nominationsOpt.isNone)
437
+ return [2 /*return*/, []];
438
+ targets = nominationsOpt.unwrap().targets;
439
+ return [4 /*yield*/, Promise.all([
440
+ api.query.staking.erasStakers.multi(targets.map(function (target) { return [activeEra, target]; })),
441
+ api.derive.staking.stashes(),
442
+ ])];
443
+ case 2:
444
+ _b = __read.apply(void 0, [_c.sent(), 2]), exposures = _b[0], stashes = _b[1];
445
+ allStashes = stashes.map(function (stash) { return stash.toString(); });
446
+ return [2 /*return*/, targets.map(function (target, index) {
447
+ var exposure = exposures[index];
448
+ var individualExposure = exposure.others.find(function (o) { return o.who.toString() === addr; });
449
+ var value = individualExposure
450
+ ? new bignumber_js_1.BigNumber(individualExposure.value)
451
+ : new bignumber_js_1.BigNumber(0);
452
+ var status = exposure.others.length
453
+ ? individualExposure
454
+ ? "active"
455
+ : "inactive"
456
+ : allStashes.includes(target.toString())
457
+ ? "waiting"
458
+ : null;
459
+ return {
460
+ address: target.toString(),
461
+ value: value,
462
+ status: status
463
+ };
464
+ })];
465
+ }
466
+ });
467
+ }); })];
468
+ });
469
+ }); };
470
+ exports.getNominations = getNominations;
471
+ /**
472
+ * Returns all the params from the chain to build an extrinsic (a transaction on Substrate)
473
+ */
474
+ var getTransactionParams = function () { return __awaiter(void 0, void 0, void 0, function () {
475
+ return __generator(this, function (_a) {
476
+ return [2 /*return*/, withApi(function (api) { return __awaiter(void 0, void 0, void 0, function () {
477
+ var chainName, blockHash, genesisHash, number, _a, specName, specVersion, transactionVersion;
478
+ return __generator(this, function (_b) {
479
+ switch (_b.label) {
480
+ case 0: return [4 /*yield*/, api.rpc.system.chain()];
481
+ case 1:
482
+ chainName = _b.sent();
483
+ return [4 /*yield*/, api.rpc.chain.getFinalizedHead()];
484
+ case 2:
485
+ blockHash = _b.sent();
486
+ return [4 /*yield*/, api.rpc.chain.getBlockHash(0)];
487
+ case 3:
488
+ genesisHash = _b.sent();
489
+ return [4 /*yield*/, api.rpc.chain.getHeader(blockHash)];
490
+ case 4:
491
+ number = (_b.sent()).number;
492
+ return [4 /*yield*/, api.rpc.state.getRuntimeVersion(blockHash)];
493
+ case 5:
494
+ _a = _b.sent(), specName = _a.specName, specVersion = _a.specVersion, transactionVersion = _a.transactionVersion;
495
+ return [2 /*return*/, {
496
+ blockHash: blockHash,
497
+ blockNumber: number,
498
+ genesisHash: genesisHash,
499
+ chainName: chainName.toString(),
500
+ specName: specName.toString(),
501
+ specVersion: specVersion,
502
+ transactionVersion: transactionVersion
503
+ }];
504
+ }
505
+ });
506
+ }); })];
507
+ });
508
+ }); };
509
+ exports.getTransactionParams = getTransactionParams;
510
+ /**
511
+ * Broadcast the transaction to the substrate node
512
+ *
513
+ * @param {string} extrinsic - the encoded extrinsic to send
514
+ */
515
+ var submitExtrinsic = function (extrinsic) { return __awaiter(void 0, void 0, void 0, function () {
516
+ return __generator(this, function (_a) {
517
+ return [2 /*return*/, withApi(function (api) { return __awaiter(void 0, void 0, void 0, function () {
518
+ var tx, hash;
519
+ return __generator(this, function (_a) {
520
+ switch (_a.label) {
521
+ case 0:
522
+ tx = api.tx(extrinsic);
523
+ return [4 /*yield*/, api.rpc.author.submitExtrinsic(tx)];
524
+ case 1:
525
+ hash = _a.sent();
526
+ return [2 /*return*/, hash];
527
+ }
528
+ });
529
+ }); })];
530
+ });
531
+ }); };
532
+ exports.submitExtrinsic = submitExtrinsic;
533
+ /**
534
+ * Retrieve the transaction fees and weights
535
+ * Note: fees on Substrate are not set by the signer, but directly by the blockchain runtime.
536
+ *
537
+ * @param {string} extrinsic - the encoded extrinsic to send with a fake signing
538
+ */
539
+ var paymentInfo = function (extrinsic) { return __awaiter(void 0, void 0, void 0, function () {
540
+ return __generator(this, function (_a) {
541
+ return [2 /*return*/, withApi(function (api) { return __awaiter(void 0, void 0, void 0, function () {
542
+ var info;
543
+ return __generator(this, function (_a) {
544
+ switch (_a.label) {
545
+ case 0: return [4 /*yield*/, api.rpc.payment.queryInfo(extrinsic)];
546
+ case 1:
547
+ info = _a.sent();
548
+ return [2 /*return*/, info];
549
+ }
550
+ });
551
+ }); })];
552
+ });
553
+ }); };
554
+ exports.paymentInfo = paymentInfo;
555
+ /**
556
+ * Fetch all reward points for validators for current era
557
+ *
558
+ * @returns Map<String, BigNumber>
559
+ */
560
+ var fetchRewardPoints = function () { return __awaiter(void 0, void 0, void 0, function () {
561
+ return __generator(this, function (_a) {
562
+ return [2 /*return*/, withApi(function (api) { return __awaiter(void 0, void 0, void 0, function () {
563
+ var activeOpt, activeEra, individual, rewards;
564
+ return __generator(this, function (_a) {
565
+ switch (_a.label) {
566
+ case 0: return [4 /*yield*/, api.query.staking.activeEra()];
567
+ case 1:
568
+ activeOpt = _a.sent();
569
+ activeEra = activeOpt.unwrapOrDefault().index;
570
+ return [4 /*yield*/, api.query.staking.erasRewardPoints(activeEra)];
571
+ case 2:
572
+ individual = (_a.sent()).individual;
573
+ rewards = new Map(__spreadArray([], __read(individual.entries()), false).map(function (_a) {
574
+ var _b = __read(_a, 2), k = _b[0], v = _b[1];
575
+ return [
576
+ k.toString(),
577
+ new bignumber_js_1.BigNumber(v.toString()),
578
+ ];
579
+ }));
580
+ return [2 /*return*/, rewards];
581
+ }
582
+ });
583
+ }); })];
584
+ });
585
+ }); };
586
+ exports.fetchRewardPoints = fetchRewardPoints;
587
+ /**
588
+ * @source https://github.com/polkadot-js/api/blob/master/packages/api-derive/src/accounts/info.ts
589
+ */
590
+ function dataAsString(data) {
591
+ return data.isRaw
592
+ ? (0, util_1.u8aToString)(data.asRaw.toU8a(true)).trim()
593
+ : data.isNone
594
+ ? ""
595
+ : data.toHex();
596
+ }
597
+ /**
598
+ * Fetch identity name of multiple addresses.
599
+ * Get parent identity if any, and concatenate parent name with child name.
600
+ *
601
+ * @param {string[]} addresses
602
+ */
603
+ var fetchIdentities = function (addresses) { return __awaiter(void 0, void 0, void 0, function () {
604
+ return __generator(this, function (_a) {
605
+ return [2 /*return*/, withApi(function (api) { return __awaiter(void 0, void 0, void 0, function () {
606
+ var superOfOpts, withParent, parentAddresses, _a, identities, parentIdentities, map;
607
+ return __generator(this, function (_b) {
608
+ switch (_b.label) {
609
+ case 0: return [4 /*yield*/, api.query.identity.superOf.multi(addresses)];
610
+ case 1:
611
+ superOfOpts = _b.sent();
612
+ withParent = superOfOpts.map(function (superOfOpt) {
613
+ return (superOfOpt === null || superOfOpt === void 0 ? void 0 : superOfOpt.isSome) ? superOfOpt === null || superOfOpt === void 0 ? void 0 : superOfOpt.unwrap() : undefined;
614
+ });
615
+ parentAddresses = (0, uniq_1["default"])((0, compact_1["default"])(withParent.map(function (superOf) { return superOf && superOf[0].toString(); })));
616
+ return [4 /*yield*/, Promise.all([
617
+ api.query.identity.identityOf.multi(addresses),
618
+ api.query.identity.identityOf.multi(parentAddresses),
619
+ ])];
620
+ case 2:
621
+ _a = __read.apply(void 0, [_b.sent(), 2]), identities = _a[0], parentIdentities = _a[1];
622
+ map = new Map(addresses.map(function (addr, index) {
623
+ var indexOfParent = withParent[index]
624
+ ? parentAddresses.indexOf(withParent[index][0].toString())
625
+ : -1;
626
+ var identityOpt = indexOfParent > -1
627
+ ? parentIdentities[indexOfParent]
628
+ : identities[index];
629
+ if (identityOpt.isNone) {
630
+ return [addr, ""];
631
+ }
632
+ var display = identityOpt.unwrap().info.display;
633
+ var name = withParent[index]
634
+ ? "".concat(dataAsString(display), " / ").concat(dataAsString(withParent[index][1]))
635
+ : dataAsString(display);
636
+ return [addr, name];
637
+ }));
638
+ return [2 /*return*/, map];
639
+ }
640
+ });
641
+ }); })];
642
+ });
643
+ }); };
644
+ exports.fetchIdentities = fetchIdentities;
645
+ /**
646
+ * Transforms each validator into an internal Validator type.
647
+ * @param {*} rewards - map of addres sand corresponding reward
648
+ * @param {*} identities - map of address and corresponding identity
649
+ * @param {*} elected - list of elected validator addresses
650
+ * @param {*} maxNominators - constant for oversubscribed validators
651
+ * @param {*} validator - the validator details to transform.
652
+ */
653
+ var mapValidator = function (rewards, identities, elected, maxNominators, validator) {
654
+ var address = validator.accountId.toString();
655
+ return {
656
+ address: address,
657
+ identity: identities.get(address) || "",
658
+ nominatorsCount: validator.exposure.others.length,
659
+ rewardPoints: rewards.get(address) || null,
660
+ commission: new bignumber_js_1.BigNumber(validator.validatorPrefs.commission).dividedBy(VALIDATOR_COMISSION_RATIO),
661
+ totalBonded: new bignumber_js_1.BigNumber(validator.exposure.total),
662
+ selfBonded: new bignumber_js_1.BigNumber(validator.exposure.own),
663
+ isElected: elected.includes(address),
664
+ isOversubscribed: validator.exposure.others.length >= maxNominators
665
+ };
666
+ };
667
+ /**
668
+ * List all validators for the current era, and their exposure, and identity.
669
+ */
670
+ var getValidators = function (stashes) {
671
+ if (stashes === void 0) { stashes = "elected"; }
672
+ return __awaiter(void 0, void 0, void 0, function () {
673
+ return __generator(this, function (_a) {
674
+ return [2 /*return*/, withApi(function (api) { return __awaiter(void 0, void 0, void 0, function () {
675
+ var _a, allStashes, elected, stashIds, allIds, electedIds, waitingIds, _b, validators, rewards, identities;
676
+ return __generator(this, function (_c) {
677
+ switch (_c.label) {
678
+ case 0: return [4 /*yield*/, Promise.all([
679
+ api.derive.staking.stashes(),
680
+ api.query.session.validators(),
681
+ ])];
682
+ case 1:
683
+ _a = __read.apply(void 0, [_c.sent(), 2]), allStashes = _a[0], elected = _a[1];
684
+ allIds = allStashes.map(function (s) { return s.toString(); });
685
+ electedIds = elected.map(function (s) { return s.toString(); });
686
+ if (Array.isArray(stashes)) {
687
+ stashIds = allIds.filter(function (s) { return stashes.includes(s); });
688
+ }
689
+ else if (stashes === "elected") {
690
+ stashIds = electedIds;
691
+ }
692
+ else {
693
+ waitingIds = allIds.filter(function (v) { return !electedIds.includes(v); });
694
+ if (stashes === "waiting") {
695
+ stashIds = waitingIds;
696
+ }
697
+ else {
698
+ // Keep elected in first positions
699
+ stashIds = __spreadArray(__spreadArray([], __read(electedIds), false), __read(waitingIds), false);
700
+ }
701
+ }
702
+ return [4 /*yield*/, Promise.all([
703
+ api.derive.staking.accounts(stashIds),
704
+ (0, exports.fetchRewardPoints)(),
705
+ (0, exports.fetchIdentities)(stashIds),
706
+ ])];
707
+ case 2:
708
+ _b = __read.apply(void 0, [_c.sent(), 3]), validators = _b[0], rewards = _b[1], identities = _b[2];
709
+ return [2 /*return*/, validators.map(mapValidator.bind(null, rewards, identities, electedIds, api.consts.staking.maxNominatorRewardedPerValidator))];
710
+ }
711
+ });
712
+ }); })];
713
+ });
714
+ });
715
+ };
716
+ exports.getValidators = getValidators;
717
+ /**
718
+ * Get Active Era progress
719
+ */
720
+ var getStakingProgress = function () { return __awaiter(void 0, void 0, void 0, function () {
721
+ return __generator(this, function (_a) {
722
+ return [2 /*return*/, withApi(function (api) { return __awaiter(void 0, void 0, void 0, function () {
723
+ var _a, activeEraOpt, status, activeEra;
724
+ return __generator(this, function (_b) {
725
+ switch (_b.label) {
726
+ case 0: return [4 /*yield*/, Promise.all([
727
+ api.query.staking.activeEra(),
728
+ api.query.staking.eraElectionStatus(),
729
+ ])];
730
+ case 1:
731
+ _a = __read.apply(void 0, [_b.sent(), 2]), activeEraOpt = _a[0], status = _a[1];
732
+ activeEra = activeEraOpt.unwrapOrDefault().index;
733
+ return [2 /*return*/, {
734
+ activeEra: activeEra.toNumber(),
735
+ electionClosed: !!status.isClose
736
+ }];
737
+ }
738
+ });
739
+ }); })];
740
+ });
741
+ }); };
742
+ exports.getStakingProgress = getStakingProgress;
743
+ /**
744
+ * Return TypeRegistry and decorated extrinsics from client
745
+ */
746
+ var getRegistry = function () { return __awaiter(void 0, void 0, void 0, function () {
747
+ return __generator(this, function (_a) {
748
+ return [2 /*return*/, withApi(function (api) { return __awaiter(void 0, void 0, void 0, function () {
749
+ return __generator(this, function (_a) {
750
+ return [2 /*return*/, {
751
+ registry: api.registry,
752
+ extrinsics: api.tx
753
+ }];
754
+ });
755
+ }); })];
756
+ });
757
+ }); };
758
+ exports.getRegistry = getRegistry;
759
+ //# sourceMappingURL=websocket.js.map