dedot 0.0.1-alpha.11

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 (103) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +251 -0
  3. package/cjs/client/Dedot.js +447 -0
  4. package/cjs/client/index.js +17 -0
  5. package/cjs/executor/ConstantExecutor.js +22 -0
  6. package/cjs/executor/ErrorExecutor.js +47 -0
  7. package/cjs/executor/EventExecutor.js +53 -0
  8. package/cjs/executor/Executor.js +39 -0
  9. package/cjs/executor/RpcExecutor.js +109 -0
  10. package/cjs/executor/RuntimeApiExecutor.js +93 -0
  11. package/cjs/executor/StorageQueryExecutor.js +33 -0
  12. package/cjs/executor/TxExecutor.js +153 -0
  13. package/cjs/executor/index.js +24 -0
  14. package/cjs/extrinsic/SubmittableResult.js +33 -0
  15. package/cjs/extrinsic/extensions/ExtraSignedExtension.js +88 -0
  16. package/cjs/extrinsic/extensions/SignedExtension.js +41 -0
  17. package/cjs/extrinsic/extensions/index.js +19 -0
  18. package/cjs/extrinsic/extensions/known/ChargeAssetTxPayment.js +44 -0
  19. package/cjs/extrinsic/extensions/known/ChargeTransactionPayment.js +16 -0
  20. package/cjs/extrinsic/extensions/known/CheckGenesis.js +19 -0
  21. package/cjs/extrinsic/extensions/known/CheckMortality.js +71 -0
  22. package/cjs/extrinsic/extensions/known/CheckNonZeroSender.js +10 -0
  23. package/cjs/extrinsic/extensions/known/CheckNonce.js +34 -0
  24. package/cjs/extrinsic/extensions/known/CheckSpecVersion.js +19 -0
  25. package/cjs/extrinsic/extensions/known/CheckTxVersion.js +19 -0
  26. package/cjs/extrinsic/extensions/known/CheckWeight.js +10 -0
  27. package/cjs/extrinsic/extensions/known/PrevalidateAttests.js +11 -0
  28. package/cjs/extrinsic/extensions/known/index.js +25 -0
  29. package/cjs/extrinsic/index.js +18 -0
  30. package/cjs/index.js +25 -0
  31. package/cjs/package.json +1 -0
  32. package/cjs/packageInfo.js +5 -0
  33. package/cjs/proxychain.js +20 -0
  34. package/cjs/storage/QueryableStorage.js +99 -0
  35. package/cjs/test.js +5 -0
  36. package/cjs/types.js +2 -0
  37. package/client/Dedot.d.ts +181 -0
  38. package/client/Dedot.js +440 -0
  39. package/client/index.d.ts +1 -0
  40. package/client/index.js +1 -0
  41. package/executor/ConstantExecutor.d.ts +11 -0
  42. package/executor/ConstantExecutor.js +18 -0
  43. package/executor/ErrorExecutor.d.ts +11 -0
  44. package/executor/ErrorExecutor.js +43 -0
  45. package/executor/EventExecutor.d.ts +11 -0
  46. package/executor/EventExecutor.js +49 -0
  47. package/executor/Executor.d.ts +150 -0
  48. package/executor/Executor.js +35 -0
  49. package/executor/RpcExecutor.d.ts +14 -0
  50. package/executor/RpcExecutor.js +105 -0
  51. package/executor/RuntimeApiExecutor.d.ts +9 -0
  52. package/executor/RuntimeApiExecutor.js +89 -0
  53. package/executor/StorageQueryExecutor.d.ts +10 -0
  54. package/executor/StorageQueryExecutor.js +29 -0
  55. package/executor/TxExecutor.d.ts +47 -0
  56. package/executor/TxExecutor.js +147 -0
  57. package/executor/index.d.ts +8 -0
  58. package/executor/index.js +8 -0
  59. package/extrinsic/SubmittableResult.d.ts +19 -0
  60. package/extrinsic/SubmittableResult.js +29 -0
  61. package/extrinsic/extensions/ExtraSignedExtension.d.ts +14 -0
  62. package/extrinsic/extensions/ExtraSignedExtension.js +61 -0
  63. package/extrinsic/extensions/SignedExtension.d.ts +40 -0
  64. package/extrinsic/extensions/SignedExtension.js +37 -0
  65. package/extrinsic/extensions/index.d.ts +3 -0
  66. package/extrinsic/extensions/index.js +3 -0
  67. package/extrinsic/extensions/known/ChargeAssetTxPayment.d.ts +14 -0
  68. package/extrinsic/extensions/known/ChargeAssetTxPayment.js +40 -0
  69. package/extrinsic/extensions/known/ChargeTransactionPayment.d.ts +6 -0
  70. package/extrinsic/extensions/known/ChargeTransactionPayment.js +12 -0
  71. package/extrinsic/extensions/known/CheckGenesis.d.ts +10 -0
  72. package/extrinsic/extensions/known/CheckGenesis.js +15 -0
  73. package/extrinsic/extensions/known/CheckMortality.d.ts +15 -0
  74. package/extrinsic/extensions/known/CheckMortality.js +67 -0
  75. package/extrinsic/extensions/known/CheckNonZeroSender.d.ts +6 -0
  76. package/extrinsic/extensions/known/CheckNonZeroSender.js +6 -0
  77. package/extrinsic/extensions/known/CheckNonce.d.ts +10 -0
  78. package/extrinsic/extensions/known/CheckNonce.js +30 -0
  79. package/extrinsic/extensions/known/CheckSpecVersion.d.ts +9 -0
  80. package/extrinsic/extensions/known/CheckSpecVersion.js +15 -0
  81. package/extrinsic/extensions/known/CheckTxVersion.d.ts +9 -0
  82. package/extrinsic/extensions/known/CheckTxVersion.js +15 -0
  83. package/extrinsic/extensions/known/CheckWeight.d.ts +6 -0
  84. package/extrinsic/extensions/known/CheckWeight.js +6 -0
  85. package/extrinsic/extensions/known/PrevalidateAttests.d.ts +7 -0
  86. package/extrinsic/extensions/known/PrevalidateAttests.js +7 -0
  87. package/extrinsic/extensions/known/index.d.ts +3 -0
  88. package/extrinsic/extensions/known/index.js +22 -0
  89. package/extrinsic/index.d.ts +2 -0
  90. package/extrinsic/index.js +2 -0
  91. package/index.d.ts +6 -0
  92. package/index.js +5 -0
  93. package/package.json +54 -0
  94. package/packageInfo.d.ts +4 -0
  95. package/packageInfo.js +2 -0
  96. package/proxychain.d.ts +7 -0
  97. package/proxychain.js +16 -0
  98. package/storage/QueryableStorage.d.ts +16 -0
  99. package/storage/QueryableStorage.js +95 -0
  100. package/test.d.ts +1 -0
  101. package/test.js +5 -0
  102. package/types.d.ts +44 -0
  103. package/types.js +1 -0
@@ -0,0 +1,447 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.Dedot = exports.SUPPORTED_METADATA_VERSIONS = exports.CATCH_ALL_METADATA_KEY = exports.KEEP_ALIVE_INTERVAL = void 0;
7
+ const rpc_provider_1 = require("@polkadot/rpc-provider");
8
+ const codecs_1 = require("@dedot/codecs");
9
+ const executor_1 = require("../executor");
10
+ const proxychain_1 = require("../proxychain");
11
+ const utils_1 = require("@dedot/utils");
12
+ const localforage_1 = __importDefault(require("localforage"));
13
+ const util_1 = require("@polkadot/util");
14
+ exports.KEEP_ALIVE_INTERVAL = 10_000; // in ms
15
+ exports.CATCH_ALL_METADATA_KEY = `RAW_META/ALL`;
16
+ exports.SUPPORTED_METADATA_VERSIONS = [15, 14];
17
+ /**
18
+ * @name Dedot
19
+ * @description Promised-based API Client for Polkadot & Substrate
20
+ *
21
+ * ### Initialize API instance and interact with substrate-based network
22
+ * ```typescript
23
+ * import { Dedot } from 'dedot';
24
+ * import { PolkadotApi } from '@dedot/chaintypes/polkadot';
25
+ *
26
+ * const run = async () => {
27
+ * const api = await Dedot.new<PolkadotApi>('wss://rpc.polkadot.io');
28
+ *
29
+ * // Call rpc `state_getMetadata` to fetch raw scale-encoded metadata and decode it.
30
+ * const metadata = await api.rpc.state.getMetadata();
31
+ * console.log('Metadata:', metadata);
32
+ *
33
+ * // Query on-chain storage
34
+ * const address = '14...';
35
+ * const balance = await api.query.system.account(address);
36
+ * console.log('Balance:', balance);
37
+ *
38
+ *
39
+ * // Subscribe to on-chain storage changes
40
+ * const unsub = await api.query.system.number((blockNumber) => {
41
+ * console.log(`Current block number: ${blockNumber}`);
42
+ * });
43
+ *
44
+ * // Get pallet constants
45
+ * const ss58Prefix = api.consts.system.ss58Prefix;
46
+ * console.log('Polkadot ss58Prefix:', ss58Prefix)
47
+ *
48
+ * // await unsub();
49
+ * // await api.disconnect();
50
+ * }
51
+ *
52
+ * run().catch(console.error);
53
+ * ```
54
+ */
55
+ class Dedot {
56
+ #provider;
57
+ #registry;
58
+ #options;
59
+ #metadata;
60
+ #metadataLatest;
61
+ #genesisHash;
62
+ #runtimeVersion;
63
+ #chainProperties;
64
+ #runtimeChain;
65
+ #localCache;
66
+ #runtimeSubscriptionUnsub;
67
+ #healthTimer;
68
+ /**
69
+ * Use factory methods (`create`, `new`) to create `Dedot` instances.
70
+ *
71
+ * @param options
72
+ * @protected
73
+ */
74
+ constructor(options) {
75
+ this.#options = this.#normalizeOptions(options);
76
+ this.#provider = this.#getProvider();
77
+ this.#registry = new codecs_1.CodecRegistry();
78
+ }
79
+ /**
80
+ * Factory method to create a new Dedot instance
81
+ *
82
+ * @param options
83
+ */
84
+ static async create(options) {
85
+ const api = new Dedot(options);
86
+ if (api.provider instanceof rpc_provider_1.WsProvider) {
87
+ await api.provider.isReady;
88
+ }
89
+ await api.init();
90
+ return api;
91
+ }
92
+ /**
93
+ * Alias for __Dedot.create__
94
+ * @param options
95
+ */
96
+ static async new(options) {
97
+ return Dedot.create(options);
98
+ }
99
+ /**
100
+ * Initialize APIs before usage
101
+ */
102
+ async init() {
103
+ await this.#initializeLocalCache();
104
+ // Fetching node information
105
+ let [genesisHash, runtimeVersion, chainName, chainProps, metadata] = await Promise.all([
106
+ this.rpc.chain.getBlockHash(0),
107
+ this.rpc.state.getRuntimeVersion(),
108
+ this.rpc.system.chain(),
109
+ this.rpc.system.properties(),
110
+ (await this.#shouldLoadPreloadMetadata()) ? this.#fetchMetadata() : Promise.resolve(undefined),
111
+ ]);
112
+ this.#genesisHash = genesisHash;
113
+ this.#runtimeVersion = runtimeVersion;
114
+ this.#chainProperties = chainProps;
115
+ this.#runtimeChain = chainName;
116
+ await this.#setupMetadata(metadata);
117
+ this.#subscribeUpdates();
118
+ }
119
+ async #initializeLocalCache() {
120
+ // Initialize local cache
121
+ if (this.#options.cacheMetadata) {
122
+ try {
123
+ // TODO add a custom driver to support nodejs
124
+ this.#localCache = localforage_1.default.createInstance({
125
+ driver: [localforage_1.default.INDEXEDDB, localforage_1.default.LOCALSTORAGE],
126
+ name: 'DedotCache',
127
+ storeName: 'LocalCache',
128
+ });
129
+ // Verify the storage is working
130
+ await this.#localCache.setItem('testKey', 'testValue');
131
+ await this.#localCache.removeItem('testKey');
132
+ }
133
+ catch (e) {
134
+ this.#localCache = undefined;
135
+ this.#options.cacheMetadata = false;
136
+ console.error('Cannot initialize local cache in this environment, disable metadata caching');
137
+ }
138
+ }
139
+ }
140
+ async #setupMetadata(preloadMetadata) {
141
+ let metadata = preloadMetadata;
142
+ const metadataKey = this.currentMetadataKey;
143
+ const optMetadataBundles = this.#options.metadata;
144
+ let shouldUpdateCache = !!metadata;
145
+ if (optMetadataBundles && !metadata) {
146
+ const optRawMetadata = optMetadataBundles[exports.CATCH_ALL_METADATA_KEY] || optMetadataBundles[metadataKey];
147
+ if (optRawMetadata) {
148
+ metadata = codecs_1.$Metadata.tryDecode(optRawMetadata);
149
+ }
150
+ }
151
+ try {
152
+ if (this.#localCache && this.#options.cacheMetadata) {
153
+ if (!metadata) {
154
+ try {
155
+ const cachedRawMetadata = await this.#localCache.getItem(metadataKey);
156
+ if (cachedRawMetadata) {
157
+ metadata = codecs_1.$Metadata.tryDecode(cachedRawMetadata);
158
+ }
159
+ }
160
+ catch (e) {
161
+ console.error('Cannot decode raw metadata, try fetching fresh metadata from chain.', e);
162
+ }
163
+ }
164
+ }
165
+ }
166
+ finally {
167
+ if (!metadata) {
168
+ metadata = await this.#fetchMetadata();
169
+ if (this.#options.cacheMetadata)
170
+ shouldUpdateCache = true;
171
+ }
172
+ }
173
+ if (shouldUpdateCache && this.#localCache) {
174
+ await this.#localCache.setItem(metadataKey, (0, util_1.u8aToHex)(codecs_1.$Metadata.tryEncode(metadata)));
175
+ }
176
+ if (!metadata) {
177
+ throw new Error('Cannot load metadata');
178
+ }
179
+ this.setMetadata(metadata);
180
+ }
181
+ async #fetchMetadata() {
182
+ // It makes sense to call metadata.metadataVersions to fetch the list of supported metadata versions first
183
+ // But for now, this approach could potentially help save/reduce one rpc call to the server in case the node support v15
184
+ // Question: Why not having a `metadata.metadataLatest` to fetch the latest version?
185
+ for (const version of exports.SUPPORTED_METADATA_VERSIONS) {
186
+ try {
187
+ const rawMetadata = await this.call.metadata.metadataAtVersion(version);
188
+ if (!rawMetadata)
189
+ continue;
190
+ return codecs_1.$Metadata.tryDecode(rawMetadata);
191
+ }
192
+ catch { }
193
+ }
194
+ try {
195
+ return codecs_1.$Metadata.tryDecode(await this.call.metadata.metadata());
196
+ }
197
+ catch {
198
+ return await this.rpc.state.getMetadata();
199
+ }
200
+ }
201
+ #subscribeRuntimeUpgrades() {
202
+ // Disable runtime upgrades subscriptions if using a catch all metadata
203
+ if (this.#runtimeSubscriptionUnsub || !this.hasSubscriptions || this.hasCatchAllMetadata) {
204
+ return;
205
+ }
206
+ this.rpc.state
207
+ .subscribeRuntimeVersion(async (runtimeVersion) => {
208
+ if (runtimeVersion.specVersion !== this.#runtimeVersion?.specVersion) {
209
+ this.#runtimeVersion = runtimeVersion;
210
+ const newMetadata = await this.#fetchMetadata();
211
+ await this.#setupMetadata(newMetadata);
212
+ }
213
+ })
214
+ .then((unsub) => {
215
+ this.#runtimeSubscriptionUnsub = unsub;
216
+ });
217
+ }
218
+ #subscribeHealth() {
219
+ this.#unsubscribeHealth();
220
+ this.#healthTimer = setInterval(() => {
221
+ this.rpc.system.health().catch(console.error);
222
+ }, exports.KEEP_ALIVE_INTERVAL);
223
+ }
224
+ #unsubscribeHealth() {
225
+ if (!this.#healthTimer) {
226
+ return;
227
+ }
228
+ clearInterval(this.#healthTimer);
229
+ this.#healthTimer = undefined;
230
+ }
231
+ async #unsubscribeRuntimeUpdates() {
232
+ if (!this.#runtimeSubscriptionUnsub) {
233
+ return;
234
+ }
235
+ await this.#runtimeSubscriptionUnsub();
236
+ this.#runtimeSubscriptionUnsub = undefined;
237
+ }
238
+ #subscribeUpdates() {
239
+ this.#subscribeRuntimeUpgrades();
240
+ this.#subscribeHealth();
241
+ }
242
+ async #unsubscribeUpdates() {
243
+ await this.#unsubscribeRuntimeUpdates();
244
+ this.#unsubscribeHealth();
245
+ }
246
+ async #shouldLoadPreloadMetadata() {
247
+ if (this.#options.metadata && Object.keys(this.#options.metadata).length) {
248
+ return false;
249
+ }
250
+ if (!this.#options.cacheMetadata || !this.#localCache) {
251
+ return true;
252
+ }
253
+ // TODO improve this
254
+ const keys = await this.#localCache.keys();
255
+ return !keys.some((k) => k.startsWith('RAW_META/'));
256
+ }
257
+ #normalizeOptions(options) {
258
+ if (typeof options === 'string') {
259
+ return { endpoint: options };
260
+ }
261
+ else {
262
+ let { metadata } = options || {};
263
+ if (metadata && typeof metadata === 'string') {
264
+ metadata = {
265
+ [exports.CATCH_ALL_METADATA_KEY]: (0, util_1.hexAddPrefix)(metadata),
266
+ };
267
+ }
268
+ return { ...options, metadata };
269
+ }
270
+ }
271
+ #getProvider() {
272
+ const { provider, endpoint } = this.#options;
273
+ if (provider)
274
+ return provider;
275
+ if (endpoint) {
276
+ if (endpoint.startsWith('ws://') || endpoint.startsWith('wss://')) {
277
+ return new rpc_provider_1.WsProvider(endpoint);
278
+ }
279
+ else if (endpoint.startsWith('http://') || endpoint.startsWith('https://')) {
280
+ return new rpc_provider_1.HttpProvider(endpoint);
281
+ }
282
+ else {
283
+ throw new Error('Invalid network endpoint, a valid endpoint should start with `wss://`, `ws://`, `https://` or `http://`');
284
+ }
285
+ }
286
+ // TODO support light-client
287
+ return new rpc_provider_1.WsProvider();
288
+ }
289
+ /**
290
+ * @description Entry-point for executing RPCs to blockchain node.
291
+ *
292
+ * ```typescript
293
+ * // Subscribe to new heads
294
+ * api.rpc.chain.subscribeNewHeads((header) => {
295
+ * console.log(header);
296
+ * });
297
+ *
298
+ * // Execute arbitrary rpc method: `module_rpc_name`
299
+ * const result = await api.rpc.module.rpc_name();
300
+ * ```
301
+ */
302
+ get rpc() {
303
+ // TODO add executable carrier to support calling arbitrary rpc methods via api.rpc(<method>)
304
+ return (0, proxychain_1.newProxyChain)({ executor: new executor_1.RpcExecutor(this) });
305
+ }
306
+ /**
307
+ * @description Entry-point for inspecting constants (parameter types) for all pallets (modules).
308
+ *
309
+ * ```typescript
310
+ * const ss58Prefix = api.consts.system.ss58Prefix;
311
+ * console.log('ss58Prefix:', ss58Prefix)
312
+ * ```
313
+ */
314
+ get consts() {
315
+ return (0, proxychain_1.newProxyChain)({ executor: new executor_1.ConstantExecutor(this) });
316
+ }
317
+ /**
318
+ * @description Entry-point for executing query to on-chain storage.
319
+ *
320
+ * ```typescript
321
+ * const balance = await api.query.system.account(<address>);
322
+ * console.log('Balance:', balance);
323
+ * ```
324
+ */
325
+ get query() {
326
+ return (0, proxychain_1.newProxyChain)({ executor: new executor_1.StorageQueryExecutor(this) });
327
+ }
328
+ queryAt(blockHash) {
329
+ return (0, proxychain_1.newProxyChain)({ executor: new executor_1.StorageQueryExecutor(this, blockHash) });
330
+ }
331
+ /**
332
+ * @description Entry-point for inspecting errors from metadata
333
+ */
334
+ get errors() {
335
+ return (0, proxychain_1.newProxyChain)({ executor: new executor_1.ErrorExecutor(this) });
336
+ }
337
+ /**
338
+ * @description Entry-point for inspecting events from metadata
339
+ */
340
+ get events() {
341
+ return (0, proxychain_1.newProxyChain)({ executor: new executor_1.EventExecutor(this) });
342
+ }
343
+ get call() {
344
+ return (0, proxychain_1.newProxyChain)({ executor: new executor_1.RuntimeApiExecutor(this) });
345
+ }
346
+ callAt(blockHash) {
347
+ return (0, proxychain_1.newProxyChain)({ executor: new executor_1.RuntimeApiExecutor(this, blockHash) });
348
+ }
349
+ get tx() {
350
+ return (0, proxychain_1.newProxyChain)({ executor: new executor_1.TxExecutor(this) });
351
+ }
352
+ /**
353
+ * @description Current provider for api connection
354
+ */
355
+ get provider() {
356
+ return this.#provider;
357
+ }
358
+ /**
359
+ * @description Codec registry
360
+ */
361
+ get registry() {
362
+ return this.#registry;
363
+ }
364
+ /**
365
+ * @description Check if metadata is present
366
+ */
367
+ get hasMetadata() {
368
+ return !!this.#metadata && !!this.#metadataLatest;
369
+ }
370
+ get metadata() {
371
+ return (0, utils_1.ensurePresence)(this.#metadata);
372
+ }
373
+ get metadataLatest() {
374
+ return (0, utils_1.ensurePresence)(this.#metadataLatest);
375
+ }
376
+ /**
377
+ * Setup metadata for
378
+ * @param metadata
379
+ */
380
+ setMetadata(metadata) {
381
+ this.#metadata = metadata;
382
+ this.#metadataLatest = metadata.latest;
383
+ this.registry.setMetadata(this.#metadataLatest);
384
+ }
385
+ /**
386
+ * @description Disconnect to blockchain node
387
+ */
388
+ async disconnect() {
389
+ await this.#unsubscribeUpdates();
390
+ await this.#provider.disconnect();
391
+ }
392
+ /**
393
+ * @description Clear local cache
394
+ */
395
+ async clearCache() {
396
+ await this.#localCache?.clear();
397
+ }
398
+ /**
399
+ * @description Check if current provider can make subscription request (e.: via WebSocket)
400
+ */
401
+ get hasSubscriptions() {
402
+ return this.provider.hasSubscriptions;
403
+ }
404
+ /**
405
+ * @description Check if it's connected to the blockchain node
406
+ */
407
+ get isConnected() {
408
+ return this.provider.isConnected;
409
+ }
410
+ /**
411
+ * @description Check if the api instance is using a catch-all metadata
412
+ */
413
+ get hasCatchAllMetadata() {
414
+ return !!this.#options.metadata && !!this.#options.metadata[exports.CATCH_ALL_METADATA_KEY];
415
+ }
416
+ get currentMetadataKey() {
417
+ return `RAW_META/${this.#genesisHash || '0x'}/${this.#runtimeVersion?.specVersion || '---'}`;
418
+ }
419
+ /**
420
+ * @description Genesis hash of connected blockchain node
421
+ */
422
+ get genesisHash() {
423
+ return this.#genesisHash;
424
+ }
425
+ /**
426
+ * @description Runtime version of connected blockchain node
427
+ */
428
+ get runtimeVersion() {
429
+ return this.#runtimeVersion;
430
+ }
431
+ /**
432
+ * @description Chain properties of connected blockchain node
433
+ */
434
+ get chainProperties() {
435
+ return this.#chainProperties;
436
+ }
437
+ /**
438
+ * @description Runtime chain name of connected blockchain node
439
+ */
440
+ get runtimeChain() {
441
+ return this.#runtimeChain;
442
+ }
443
+ get options() {
444
+ return this.#options;
445
+ }
446
+ }
447
+ exports.Dedot = Dedot;
@@ -0,0 +1,17 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./Dedot"), exports);
@@ -0,0 +1,22 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ConstantExecutor = void 0;
4
+ const util_1 = require("@polkadot/util");
5
+ const Executor_1 = require("./Executor");
6
+ /**
7
+ * @name ConstantExecutor
8
+ *
9
+ * Find & decode the constant value from metadata
10
+ */
11
+ class ConstantExecutor extends Executor_1.Executor {
12
+ execute(pallet, constantName) {
13
+ const targetPallet = this.getPallet(pallet);
14
+ const constantDef = targetPallet.constants.find((one) => (0, util_1.stringCamelCase)(one.name) === constantName);
15
+ if (!constantDef) {
16
+ throw new Error(`Constant ${constantName} not found in pallet ${pallet}`);
17
+ }
18
+ const $codec = this.registry.findPortableCodec(constantDef.typeId);
19
+ return $codec.tryDecode(constantDef.value);
20
+ }
21
+ }
22
+ exports.ConstantExecutor = ConstantExecutor;
@@ -0,0 +1,47 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ErrorExecutor = void 0;
4
+ const Executor_1 = require("./Executor");
5
+ const utils_1 = require("@dedot/utils");
6
+ const util_1 = require("@polkadot/util");
7
+ /**
8
+ * @name ErrorExecutor
9
+ * @description Find pallet error information from metadata
10
+ */
11
+ class ErrorExecutor extends Executor_1.Executor {
12
+ execute(pallet, errorName) {
13
+ const targetPallet = this.getPallet(pallet);
14
+ const errorTypeId = targetPallet.error;
15
+ (0, utils_1.assert)(errorTypeId, `Not found error with id ${errorTypeId} in pallet ${pallet}`);
16
+ const errorDef = this.#getErrorDef(errorTypeId, errorName);
17
+ return {
18
+ meta: {
19
+ ...errorDef,
20
+ pallet: targetPallet.name,
21
+ palletIndex: targetPallet.index,
22
+ },
23
+ is: (errorInfo) => {
24
+ if ((0, util_1.isObject)(errorInfo) && errorInfo.tag === 'Module') {
25
+ errorInfo = errorInfo.value;
26
+ }
27
+ if ((0, util_1.isObject)(errorInfo) && (0, util_1.isNumber)(errorInfo.index) && (0, util_1.isHex)(errorInfo.error)) {
28
+ return errorInfo.index === targetPallet.index && (0, util_1.hexToU8a)(errorInfo.error)[0] === errorDef.index;
29
+ }
30
+ return false;
31
+ },
32
+ };
33
+ }
34
+ #getErrorDef(errorTypeId, errorName) {
35
+ const def = this.metadata.types[errorTypeId];
36
+ (0, utils_1.assert)(def, `Error def not found for id ${errorTypeId}`);
37
+ const { tag, value } = def.type;
38
+ (0, utils_1.assert)(tag === 'Enum', `Error type should be an enum, found: ${tag}`);
39
+ const errorDef = value.members.find(({ name }) => (0, util_1.stringPascalCase)(name) === errorName);
40
+ (0, utils_1.assert)(errorDef, `Error def not found for ${errorName}`);
41
+ return {
42
+ ...errorDef,
43
+ fieldCodecs: errorDef.fields.map(({ typeId }) => this.registry.findPortableCodec(typeId)),
44
+ };
45
+ }
46
+ }
47
+ exports.ErrorExecutor = ErrorExecutor;
@@ -0,0 +1,53 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.EventExecutor = void 0;
4
+ const Executor_1 = require("./Executor");
5
+ const util_1 = require("@polkadot/util");
6
+ const utils_1 = require("@dedot/utils");
7
+ /**
8
+ * @name EventExecutor
9
+ * @description Find pallet event information from metadata
10
+ */
11
+ class EventExecutor extends Executor_1.Executor {
12
+ execute(pallet, errorName) {
13
+ const targetPallet = this.getPallet(pallet);
14
+ const eventTypeId = targetPallet.event;
15
+ (0, utils_1.assert)(eventTypeId, `Not found event with id ${eventTypeId} in pallet ${pallet}`);
16
+ const eventDef = this.#getEventDef(eventTypeId, errorName);
17
+ const is = (event) => {
18
+ const palletCheck = (0, util_1.stringCamelCase)(event.pallet) === pallet;
19
+ if (typeof event.palletEvent === 'string') {
20
+ return palletCheck && (0, util_1.stringPascalCase)(event.palletEvent) === errorName;
21
+ }
22
+ else if (typeof event.palletEvent === 'object') {
23
+ return palletCheck && (0, util_1.stringPascalCase)(event.palletEvent.name) === errorName;
24
+ }
25
+ return false;
26
+ };
27
+ const as = (event) => {
28
+ return is(event) ? event : undefined;
29
+ };
30
+ return {
31
+ is,
32
+ as,
33
+ meta: {
34
+ ...eventDef,
35
+ pallet: targetPallet.name,
36
+ palletIndex: targetPallet.index,
37
+ },
38
+ };
39
+ }
40
+ #getEventDef(eventTypeId, errorName) {
41
+ const def = this.metadata.types[eventTypeId];
42
+ (0, utils_1.assert)(def, `Event def not found for id ${eventTypeId}`);
43
+ const { tag, value } = def.type;
44
+ (0, utils_1.assert)(tag === 'Enum', `Event type should be an enum, found: ${tag}`);
45
+ const eventDef = value.members.find(({ name }) => (0, util_1.stringPascalCase)(name) === errorName);
46
+ (0, utils_1.assert)(eventDef, `Event def not found for ${errorName}`);
47
+ return {
48
+ ...eventDef,
49
+ fieldCodecs: eventDef.fields.map(({ typeId }) => this.registry.findPortableCodec(typeId)),
50
+ };
51
+ }
52
+ }
53
+ exports.EventExecutor = EventExecutor;
@@ -0,0 +1,39 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.Executor = void 0;
4
+ const util_1 = require("@polkadot/util");
5
+ /**
6
+ * @name Executor
7
+ * @description Execution abstraction for a specific action
8
+ */
9
+ class Executor {
10
+ #api;
11
+ #atBlockHash;
12
+ constructor(api, atBlockHash) {
13
+ this.#api = api;
14
+ this.#atBlockHash = atBlockHash;
15
+ }
16
+ get api() {
17
+ return this.#api;
18
+ }
19
+ get atBlockHash() {
20
+ return this.#atBlockHash;
21
+ }
22
+ get provider() {
23
+ return this.api.provider;
24
+ }
25
+ get registry() {
26
+ return this.api.registry;
27
+ }
28
+ get metadata() {
29
+ return this.api.metadataLatest;
30
+ }
31
+ getPallet(name, throwErr = true) {
32
+ const targetPallet = this.metadata.pallets.find((p) => (0, util_1.stringCamelCase)(p.name) === name);
33
+ if (!targetPallet && throwErr) {
34
+ throw new Error(`Pallet not found: ${name}`);
35
+ }
36
+ return targetPallet;
37
+ }
38
+ }
39
+ exports.Executor = Executor;