dedot 0.0.1-alpha.22

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