@dedot/api 0.0.1-alpha.32

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 (202) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +1 -0
  3. package/chaintypes/index.d.ts +1 -0
  4. package/chaintypes/index.js +1 -0
  5. package/chaintypes/substrate/consts.d.ts +2132 -0
  6. package/chaintypes/substrate/consts.js +2 -0
  7. package/chaintypes/substrate/errors.d.ts +3490 -0
  8. package/chaintypes/substrate/errors.js +2 -0
  9. package/chaintypes/substrate/events.d.ts +5187 -0
  10. package/chaintypes/substrate/events.js +2 -0
  11. package/chaintypes/substrate/index.d.ts +22 -0
  12. package/chaintypes/substrate/index.js +2 -0
  13. package/chaintypes/substrate/json-rpc.d.ts +3 -0
  14. package/chaintypes/substrate/json-rpc.js +2 -0
  15. package/chaintypes/substrate/query.d.ts +3829 -0
  16. package/chaintypes/substrate/query.js +2 -0
  17. package/chaintypes/substrate/runtime.d.ts +850 -0
  18. package/chaintypes/substrate/runtime.js +2 -0
  19. package/chaintypes/substrate/tx.d.ts +14269 -0
  20. package/chaintypes/substrate/tx.js +2 -0
  21. package/chaintypes/substrate/types.d.ts +30457 -0
  22. package/chaintypes/substrate/types.js +2 -0
  23. package/cjs/chaintypes/index.js +17 -0
  24. package/cjs/chaintypes/substrate/consts.js +3 -0
  25. package/cjs/chaintypes/substrate/errors.js +3 -0
  26. package/cjs/chaintypes/substrate/events.js +3 -0
  27. package/cjs/chaintypes/substrate/index.js +18 -0
  28. package/cjs/chaintypes/substrate/json-rpc.js +3 -0
  29. package/cjs/chaintypes/substrate/query.js +3 -0
  30. package/cjs/chaintypes/substrate/runtime.js +3 -0
  31. package/cjs/chaintypes/substrate/tx.js +3 -0
  32. package/cjs/chaintypes/substrate/types.js +3 -0
  33. package/cjs/client/BaseSubstrateClient.js +257 -0
  34. package/cjs/client/Dedot.js +250 -0
  35. package/cjs/client/DedotClient.js +186 -0
  36. package/cjs/client/index.js +18 -0
  37. package/cjs/executor/ConstantExecutor.js +20 -0
  38. package/cjs/executor/ErrorExecutor.js +46 -0
  39. package/cjs/executor/EventExecutor.js +52 -0
  40. package/cjs/executor/Executor.js +42 -0
  41. package/cjs/executor/RuntimeApiExecutor.js +121 -0
  42. package/cjs/executor/StorageQueryExecutor.js +115 -0
  43. package/cjs/executor/TxExecutor.js +55 -0
  44. package/cjs/executor/index.js +26 -0
  45. package/cjs/executor/v2/RuntimeApiExecutorV2.js +21 -0
  46. package/cjs/executor/v2/StorageQueryExecutorV2.js +65 -0
  47. package/cjs/executor/v2/TxExecutorV2.js +20 -0
  48. package/cjs/extrinsic/extensions/ExtraSignedExtension.js +87 -0
  49. package/cjs/extrinsic/extensions/SignedExtension.js +41 -0
  50. package/cjs/extrinsic/extensions/index.js +19 -0
  51. package/cjs/extrinsic/extensions/known/ChargeAssetTxPayment.js +43 -0
  52. package/cjs/extrinsic/extensions/known/ChargeTransactionPayment.js +16 -0
  53. package/cjs/extrinsic/extensions/known/CheckGenesis.js +19 -0
  54. package/cjs/extrinsic/extensions/known/CheckMortality.js +90 -0
  55. package/cjs/extrinsic/extensions/known/CheckNonZeroSender.js +10 -0
  56. package/cjs/extrinsic/extensions/known/CheckNonce.js +33 -0
  57. package/cjs/extrinsic/extensions/known/CheckSpecVersion.js +19 -0
  58. package/cjs/extrinsic/extensions/known/CheckTxVersion.js +19 -0
  59. package/cjs/extrinsic/extensions/known/CheckWeight.js +10 -0
  60. package/cjs/extrinsic/extensions/known/PrevalidateAttests.js +11 -0
  61. package/cjs/extrinsic/extensions/known/index.js +25 -0
  62. package/cjs/extrinsic/index.js +18 -0
  63. package/cjs/extrinsic/submittable/BaseSubmittableExtrinsic.js +70 -0
  64. package/cjs/extrinsic/submittable/SubmittableExtrinsic.js +47 -0
  65. package/cjs/extrinsic/submittable/SubmittableExtrinsicV2.js +204 -0
  66. package/cjs/extrinsic/submittable/SubmittableResult.js +33 -0
  67. package/cjs/extrinsic/submittable/errors.js +16 -0
  68. package/cjs/extrinsic/submittable/fakeSigner.js +13 -0
  69. package/cjs/extrinsic/submittable/index.js +20 -0
  70. package/cjs/extrinsic/submittable/utils.js +20 -0
  71. package/cjs/index.js +21 -0
  72. package/cjs/json-rpc/JsonRpcClient.js +165 -0
  73. package/cjs/json-rpc/group/ChainHead/BlockUsage.js +24 -0
  74. package/cjs/json-rpc/group/ChainHead/ChainHead.js +603 -0
  75. package/cjs/json-rpc/group/ChainHead/error.js +59 -0
  76. package/cjs/json-rpc/group/ChainHead/index.js +18 -0
  77. package/cjs/json-rpc/group/ChainSpec.js +19 -0
  78. package/cjs/json-rpc/group/JsonRpcGroup.js +89 -0
  79. package/cjs/json-rpc/group/Transaction.js +25 -0
  80. package/cjs/json-rpc/group/TransactionWatch.js +17 -0
  81. package/cjs/json-rpc/group/index.js +21 -0
  82. package/cjs/json-rpc/index.js +20 -0
  83. package/cjs/json-rpc/scaledResponses.js +15 -0
  84. package/cjs/json-rpc/subscriptionsInfo.js +20 -0
  85. package/cjs/package.json +1 -0
  86. package/cjs/proxychain.js +27 -0
  87. package/cjs/storage/QueryableStorage.js +161 -0
  88. package/cjs/storage/index.js +17 -0
  89. package/cjs/types.js +2 -0
  90. package/client/BaseSubstrateClient.d.ts +65 -0
  91. package/client/BaseSubstrateClient.js +252 -0
  92. package/client/Dedot.d.ts +131 -0
  93. package/client/Dedot.js +246 -0
  94. package/client/DedotClient.d.ts +61 -0
  95. package/client/DedotClient.js +182 -0
  96. package/client/index.d.ts +2 -0
  97. package/client/index.js +2 -0
  98. package/executor/ConstantExecutor.d.ts +10 -0
  99. package/executor/ConstantExecutor.js +16 -0
  100. package/executor/ErrorExecutor.d.ts +10 -0
  101. package/executor/ErrorExecutor.js +42 -0
  102. package/executor/EventExecutor.d.ts +10 -0
  103. package/executor/EventExecutor.js +48 -0
  104. package/executor/Executor.d.ts +149 -0
  105. package/executor/Executor.js +38 -0
  106. package/executor/RuntimeApiExecutor.d.ts +27 -0
  107. package/executor/RuntimeApiExecutor.js +117 -0
  108. package/executor/StorageQueryExecutor.d.ts +14 -0
  109. package/executor/StorageQueryExecutor.js +111 -0
  110. package/executor/TxExecutor.d.ts +10 -0
  111. package/executor/TxExecutor.js +51 -0
  112. package/executor/index.d.ts +10 -0
  113. package/executor/index.js +10 -0
  114. package/executor/v2/RuntimeApiExecutorV2.d.ts +14 -0
  115. package/executor/v2/RuntimeApiExecutorV2.js +17 -0
  116. package/executor/v2/StorageQueryExecutorV2.d.ts +17 -0
  117. package/executor/v2/StorageQueryExecutorV2.js +61 -0
  118. package/executor/v2/TxExecutorV2.d.ts +11 -0
  119. package/executor/v2/TxExecutorV2.js +16 -0
  120. package/extrinsic/extensions/ExtraSignedExtension.d.ts +14 -0
  121. package/extrinsic/extensions/ExtraSignedExtension.js +60 -0
  122. package/extrinsic/extensions/SignedExtension.d.ts +40 -0
  123. package/extrinsic/extensions/SignedExtension.js +37 -0
  124. package/extrinsic/extensions/index.d.ts +3 -0
  125. package/extrinsic/extensions/index.js +3 -0
  126. package/extrinsic/extensions/known/ChargeAssetTxPayment.d.ts +14 -0
  127. package/extrinsic/extensions/known/ChargeAssetTxPayment.js +39 -0
  128. package/extrinsic/extensions/known/ChargeTransactionPayment.d.ts +6 -0
  129. package/extrinsic/extensions/known/ChargeTransactionPayment.js +12 -0
  130. package/extrinsic/extensions/known/CheckGenesis.d.ts +10 -0
  131. package/extrinsic/extensions/known/CheckGenesis.js +15 -0
  132. package/extrinsic/extensions/known/CheckMortality.d.ts +15 -0
  133. package/extrinsic/extensions/known/CheckMortality.js +86 -0
  134. package/extrinsic/extensions/known/CheckNonZeroSender.d.ts +6 -0
  135. package/extrinsic/extensions/known/CheckNonZeroSender.js +6 -0
  136. package/extrinsic/extensions/known/CheckNonce.d.ts +10 -0
  137. package/extrinsic/extensions/known/CheckNonce.js +29 -0
  138. package/extrinsic/extensions/known/CheckSpecVersion.d.ts +9 -0
  139. package/extrinsic/extensions/known/CheckSpecVersion.js +15 -0
  140. package/extrinsic/extensions/known/CheckTxVersion.d.ts +9 -0
  141. package/extrinsic/extensions/known/CheckTxVersion.js +15 -0
  142. package/extrinsic/extensions/known/CheckWeight.d.ts +6 -0
  143. package/extrinsic/extensions/known/CheckWeight.js +6 -0
  144. package/extrinsic/extensions/known/PrevalidateAttests.d.ts +7 -0
  145. package/extrinsic/extensions/known/PrevalidateAttests.js +7 -0
  146. package/extrinsic/extensions/known/index.d.ts +3 -0
  147. package/extrinsic/extensions/known/index.js +22 -0
  148. package/extrinsic/index.d.ts +2 -0
  149. package/extrinsic/index.js +2 -0
  150. package/extrinsic/submittable/BaseSubmittableExtrinsic.d.ts +17 -0
  151. package/extrinsic/submittable/BaseSubmittableExtrinsic.js +66 -0
  152. package/extrinsic/submittable/SubmittableExtrinsic.d.ts +12 -0
  153. package/extrinsic/submittable/SubmittableExtrinsic.js +43 -0
  154. package/extrinsic/submittable/SubmittableExtrinsicV2.d.ts +15 -0
  155. package/extrinsic/submittable/SubmittableExtrinsicV2.js +200 -0
  156. package/extrinsic/submittable/SubmittableResult.d.ts +19 -0
  157. package/extrinsic/submittable/SubmittableResult.js +29 -0
  158. package/extrinsic/submittable/errors.d.ts +11 -0
  159. package/extrinsic/submittable/errors.js +12 -0
  160. package/extrinsic/submittable/fakeSigner.d.ts +2 -0
  161. package/extrinsic/submittable/fakeSigner.js +10 -0
  162. package/extrinsic/submittable/index.d.ts +4 -0
  163. package/extrinsic/submittable/index.js +4 -0
  164. package/extrinsic/submittable/utils.d.ts +10 -0
  165. package/extrinsic/submittable/utils.js +15 -0
  166. package/index.d.ts +6 -0
  167. package/index.js +5 -0
  168. package/json-rpc/JsonRpcClient.d.ts +50 -0
  169. package/json-rpc/JsonRpcClient.js +160 -0
  170. package/json-rpc/group/ChainHead/BlockUsage.d.ts +11 -0
  171. package/json-rpc/group/ChainHead/BlockUsage.js +20 -0
  172. package/json-rpc/group/ChainHead/ChainHead.d.ts +70 -0
  173. package/json-rpc/group/ChainHead/ChainHead.js +599 -0
  174. package/json-rpc/group/ChainHead/error.d.ts +47 -0
  175. package/json-rpc/group/ChainHead/error.js +48 -0
  176. package/json-rpc/group/ChainHead/index.d.ts +2 -0
  177. package/json-rpc/group/ChainHead/index.js +2 -0
  178. package/json-rpc/group/ChainSpec.d.ts +10 -0
  179. package/json-rpc/group/ChainSpec.js +15 -0
  180. package/json-rpc/group/JsonRpcGroup.d.ts +74 -0
  181. package/json-rpc/group/JsonRpcGroup.js +85 -0
  182. package/json-rpc/group/Transaction.d.ts +11 -0
  183. package/json-rpc/group/Transaction.js +21 -0
  184. package/json-rpc/group/TransactionWatch.d.ts +10 -0
  185. package/json-rpc/group/TransactionWatch.js +13 -0
  186. package/json-rpc/group/index.d.ts +5 -0
  187. package/json-rpc/group/index.js +5 -0
  188. package/json-rpc/index.d.ts +4 -0
  189. package/json-rpc/index.js +4 -0
  190. package/json-rpc/scaledResponses.d.ts +2 -0
  191. package/json-rpc/scaledResponses.js +12 -0
  192. package/json-rpc/subscriptionsInfo.d.ts +2 -0
  193. package/json-rpc/subscriptionsInfo.js +17 -0
  194. package/package.json +54 -0
  195. package/proxychain.d.ts +14 -0
  196. package/proxychain.js +23 -0
  197. package/storage/QueryableStorage.d.ts +35 -0
  198. package/storage/QueryableStorage.js +157 -0
  199. package/storage/index.d.ts +1 -0
  200. package/storage/index.js +1 -0
  201. package/types.d.ts +120 -0
  202. package/types.js +1 -0
@@ -0,0 +1,186 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.DedotClient = void 0;
4
+ const codecs_1 = require("@dedot/codecs");
5
+ const shape_1 = require("@dedot/shape");
6
+ const utils_1 = require("@dedot/utils");
7
+ const index_js_1 = require("../executor/index.js");
8
+ const index_js_2 = require("../json-rpc/index.js");
9
+ const proxychain_js_1 = require("../proxychain.js");
10
+ const BaseSubstrateClient_js_1 = require("./BaseSubstrateClient.js");
11
+ /**
12
+ * @name DedotClient
13
+ * @description New promised-based API Client for Polkadot & Substrate based on JSON-RPC V2
14
+ *
15
+ * __Unstable, use with caution.__
16
+ */
17
+ class DedotClient extends BaseSubstrateClient_js_1.BaseSubstrateClient {
18
+ _chainHead;
19
+ _chainSpec;
20
+ _txBroadcaster;
21
+ #apiAtCache = {};
22
+ /**
23
+ * Use factory methods (`create`, `new`) to create `DedotClient` instances.
24
+ *
25
+ * @param options
26
+ */
27
+ constructor(options) {
28
+ super('v2', options);
29
+ }
30
+ /**
31
+ * Factory method to create a new DedotClient instance
32
+ *
33
+ * @param options
34
+ */
35
+ static async create(options) {
36
+ return new DedotClient(options).connect();
37
+ }
38
+ /**
39
+ * Alias for __DedotClient.create__
40
+ *
41
+ * @param options
42
+ */
43
+ static async new(options) {
44
+ return DedotClient.create(options);
45
+ }
46
+ get chainSpec() {
47
+ return (0, BaseSubstrateClient_js_1.ensurePresence)(this._chainSpec);
48
+ }
49
+ get chainHead() {
50
+ return (0, BaseSubstrateClient_js_1.ensurePresence)(this._chainHead);
51
+ }
52
+ get txBroadcaster() {
53
+ this.chainHead; // Ensure chain head is initialized
54
+ (0, utils_1.assert)(this._txBroadcaster, 'JSON-RPC method to broadcast transactions is not supported by the server/node.');
55
+ return this._txBroadcaster;
56
+ }
57
+ async #initializeTxBroadcaster(rpcMethods) {
58
+ const tx = new index_js_2.Transaction(this, { rpcMethods });
59
+ if (await tx.supported())
60
+ return tx;
61
+ const txWatch = new index_js_2.TransactionWatch(this, { rpcMethods });
62
+ if (await txWatch.supported())
63
+ return txWatch;
64
+ }
65
+ /**
66
+ * Initialize APIs before usage
67
+ */
68
+ async doInitialize() {
69
+ const rpcMethods = (await this.rpc.rpc_methods()).methods;
70
+ this._chainHead = new index_js_2.ChainHead(this, { rpcMethods });
71
+ this._chainSpec = new index_js_2.ChainSpec(this, { rpcMethods });
72
+ this._txBroadcaster = await this.#initializeTxBroadcaster(rpcMethods);
73
+ // Fetching node information
74
+ let [_, genesisHash] = await Promise.all([
75
+ this.chainHead.follow(),
76
+ this.chainSpec.genesisHash().catch(() => undefined),
77
+ ]);
78
+ this._genesisHash = genesisHash || (await this.#getGenesisHashFallback());
79
+ this._runtimeVersion = await this.chainHead.bestRuntimeVersion();
80
+ let metadata;
81
+ if (await this.shouldPreloadMetadata()) {
82
+ metadata = await this.fetchMetadata();
83
+ }
84
+ await this.setupMetadata(metadata);
85
+ this.subscribeRuntimeUpgrades();
86
+ }
87
+ /**
88
+ * Ref: https://github.com/paritytech/polkadot-sdk/blob/bbd51ce867967f71657b901f1a956ad4f75d352e/substrate/frame/system/src/lib.rs#L909-L913
89
+ * @private
90
+ */
91
+ async #getGenesisHashFallback() {
92
+ const pallet = (0, utils_1.xxhashAsU8a)('System', 128);
93
+ const item = (0, utils_1.xxhashAsU8a)('BlockHash', 128);
94
+ const blockHeightAt0 = (0, utils_1.twox64Concat)(shape_1.u32.encode(0));
95
+ const key = (0, utils_1.u8aToHex)((0, utils_1.concatU8a)(pallet, item, blockHeightAt0));
96
+ const storageValue = await this.chainHead.storage([{ type: 'value', key }]);
97
+ const rawGenesisHash = storageValue.at(0)?.value;
98
+ (0, utils_1.assert)(rawGenesisHash, 'Genesis hash not found!');
99
+ // Here we assume that in most case the hash is stored as a H256
100
+ return codecs_1.$H256.tryDecode(rawGenesisHash);
101
+ }
102
+ subscribeRuntimeUpgrades() {
103
+ this.chainHead.on('bestBlock', this.onRuntimeUpgrade);
104
+ }
105
+ unsubscribeRuntimeUpgrades() {
106
+ this.chainHead.off('bestBlock', this.onRuntimeUpgrade);
107
+ }
108
+ onRuntimeUpgrade = async (block) => {
109
+ const runtimeUpgraded = block.runtime && block.runtime.specVersion !== this._runtimeVersion?.specVersion;
110
+ if (!runtimeUpgraded)
111
+ return;
112
+ this._runtimeVersion = block.runtime;
113
+ const newMetadata = await this.fetchMetadata(undefined, this._runtimeVersion);
114
+ await this.setupMetadata(newMetadata);
115
+ };
116
+ async beforeDisconnect() {
117
+ await this.chainHead.unfollow();
118
+ }
119
+ onDisconnected = async () => {
120
+ this.chainHead.unfollow().catch(utils_1.noop);
121
+ };
122
+ cleanUp() {
123
+ super.cleanUp();
124
+ this._chainHead = undefined;
125
+ this._chainSpec = undefined;
126
+ this._txBroadcaster = undefined;
127
+ this.#apiAtCache = {};
128
+ }
129
+ get query() {
130
+ return (0, proxychain_js_1.newProxyChain)({
131
+ executor: new index_js_1.StorageQueryExecutorV2(this, this.chainHead),
132
+ });
133
+ }
134
+ get call() {
135
+ return this.callAt();
136
+ }
137
+ callAt(blockHash) {
138
+ return (0, proxychain_js_1.newProxyChain)({
139
+ executor: new index_js_1.RuntimeApiExecutorV2(this, this.chainHead, blockHash),
140
+ });
141
+ }
142
+ get tx() {
143
+ return (0, proxychain_js_1.newProxyChain)({ executor: new index_js_1.TxExecutorV2(this) });
144
+ }
145
+ /**
146
+ * Get a new API instance at a specific block hash
147
+ * For now, this only supports pinned block hashes from the chain head
148
+ *
149
+ * @param hash
150
+ */
151
+ async at(hash) {
152
+ if (this.#apiAtCache[hash])
153
+ return this.#apiAtCache[hash];
154
+ const targetBlock = this.chainHead.findBlock(hash);
155
+ (0, utils_1.assert)(targetBlock, 'Block is not pinned!');
156
+ let targetVersion = targetBlock.runtime;
157
+ if (!targetVersion) {
158
+ // fallback to fetching on-chain runtime if we can't find it in the block
159
+ targetVersion = this.toSubstrateRuntimeVersion(await this.callAt(hash).core.version());
160
+ }
161
+ let metadata = this.metadata;
162
+ let registry = this.registry;
163
+ if (targetVersion && targetVersion.specVersion !== this.runtimeVersion.specVersion) {
164
+ metadata = await this.fetchMetadata(hash, targetVersion);
165
+ registry = new codecs_1.PortableRegistry(metadata.latest, this.options.hasher);
166
+ }
167
+ const api = {
168
+ rpcVersion: 'v2',
169
+ atBlockHash: hash,
170
+ options: this.options,
171
+ genesisHash: this.genesisHash,
172
+ runtimeVersion: targetVersion,
173
+ metadata,
174
+ registry,
175
+ rpc: this.rpc,
176
+ };
177
+ api.consts = (0, proxychain_js_1.newProxyChain)({ executor: new index_js_1.ConstantExecutor(api) });
178
+ api.events = (0, proxychain_js_1.newProxyChain)({ executor: new index_js_1.EventExecutor(api) });
179
+ api.errors = (0, proxychain_js_1.newProxyChain)({ executor: new index_js_1.ErrorExecutor(api) });
180
+ api.query = (0, proxychain_js_1.newProxyChain)({ executor: new index_js_1.StorageQueryExecutorV2(api, this.chainHead) });
181
+ api.call = (0, proxychain_js_1.newProxyChain)({ executor: new index_js_1.RuntimeApiExecutorV2(api, this.chainHead) });
182
+ this.#apiAtCache[hash] = api;
183
+ return api;
184
+ }
185
+ }
186
+ exports.DedotClient = DedotClient;
@@ -0,0 +1,18 @@
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.js"), exports);
18
+ __exportStar(require("./DedotClient.js"), exports);
@@ -0,0 +1,20 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ConstantExecutor = void 0;
4
+ const utils_1 = require("@dedot/utils");
5
+ const Executor_js_1 = require("./Executor.js");
6
+ /**
7
+ * @name ConstantExecutor
8
+ *
9
+ * Find & decode the constant value from metadata
10
+ */
11
+ class ConstantExecutor extends Executor_js_1.Executor {
12
+ doExecute(pallet, constantName) {
13
+ const targetPallet = this.getPallet(pallet);
14
+ const constantDef = targetPallet.constants.find((one) => (0, utils_1.stringCamelCase)(one.name) === constantName);
15
+ (0, utils_1.assert)(constantDef, new utils_1.UnknownApiError(`Constant ${constantName} not found in pallet ${pallet}`));
16
+ const $codec = this.registry.findCodec(constantDef.typeId);
17
+ return $codec.tryDecode(constantDef.value);
18
+ }
19
+ }
20
+ exports.ConstantExecutor = ConstantExecutor;
@@ -0,0 +1,46 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ErrorExecutor = void 0;
4
+ const utils_1 = require("@dedot/utils");
5
+ const Executor_js_1 = require("./Executor.js");
6
+ /**
7
+ * @name ErrorExecutor
8
+ * @description Find pallet error information from metadata
9
+ */
10
+ class ErrorExecutor extends Executor_js_1.Executor {
11
+ doExecute(pallet, errorName) {
12
+ const targetPallet = this.getPallet(pallet);
13
+ const errorTypeId = targetPallet.error;
14
+ (0, utils_1.assert)(errorTypeId, new utils_1.UnknownApiError(`Not found error with id ${errorTypeId} in pallet ${pallet}`));
15
+ const errorDef = this.#getErrorDef(errorTypeId, errorName);
16
+ return {
17
+ meta: {
18
+ ...errorDef,
19
+ pallet: targetPallet.name,
20
+ palletIndex: targetPallet.index,
21
+ },
22
+ is: (errorInfo) => {
23
+ if ((0, utils_1.isObject)(errorInfo) && errorInfo.tag === 'Module') {
24
+ errorInfo = errorInfo.value;
25
+ }
26
+ if ((0, utils_1.isObject)(errorInfo) && (0, utils_1.isNumber)(errorInfo.index) && (0, utils_1.isHex)(errorInfo.error)) {
27
+ return errorInfo.index === targetPallet.index && (0, utils_1.hexToU8a)(errorInfo.error)[0] === errorDef.index;
28
+ }
29
+ return false;
30
+ },
31
+ };
32
+ }
33
+ #getErrorDef(errorTypeId, errorName) {
34
+ const def = this.metadata.types[errorTypeId];
35
+ (0, utils_1.assert)(def, new utils_1.UnknownApiError(`Error def not found for id ${errorTypeId}`));
36
+ const { tag, value } = def.type;
37
+ (0, utils_1.assert)(tag === 'Enum', new utils_1.UnknownApiError(`Error type should be an enum, found: ${tag}`));
38
+ const errorDef = value.members.find(({ name }) => (0, utils_1.stringPascalCase)(name) === errorName);
39
+ (0, utils_1.assert)(errorDef, new utils_1.UnknownApiError(`Error def not found for ${errorName}`));
40
+ return {
41
+ ...errorDef,
42
+ fieldCodecs: errorDef.fields.map(({ typeId }) => this.registry.findCodec(typeId)),
43
+ };
44
+ }
45
+ }
46
+ exports.ErrorExecutor = ErrorExecutor;
@@ -0,0 +1,52 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.EventExecutor = void 0;
4
+ const utils_1 = require("@dedot/utils");
5
+ const Executor_js_1 = require("./Executor.js");
6
+ /**
7
+ * @name EventExecutor
8
+ * @description Find pallet event information from metadata
9
+ */
10
+ class EventExecutor extends Executor_js_1.Executor {
11
+ doExecute(pallet, errorName) {
12
+ const targetPallet = this.getPallet(pallet);
13
+ const eventTypeId = targetPallet.event;
14
+ (0, utils_1.assert)(eventTypeId, new utils_1.UnknownApiError(`Not found event with id ${eventTypeId} in pallet ${pallet}`));
15
+ const eventDef = this.#getEventDef(eventTypeId, errorName);
16
+ const is = (event) => {
17
+ const palletCheck = (0, utils_1.stringCamelCase)(event.pallet) === pallet;
18
+ if (typeof event.palletEvent === 'string') {
19
+ return palletCheck && (0, utils_1.stringPascalCase)(event.palletEvent) === errorName;
20
+ }
21
+ else if (typeof event.palletEvent === 'object') {
22
+ return palletCheck && (0, utils_1.stringPascalCase)(event.palletEvent.name) === errorName;
23
+ }
24
+ return false;
25
+ };
26
+ const as = (event) => {
27
+ return is(event) ? event : undefined;
28
+ };
29
+ return {
30
+ is,
31
+ as,
32
+ meta: {
33
+ ...eventDef,
34
+ pallet: targetPallet.name,
35
+ palletIndex: targetPallet.index,
36
+ },
37
+ };
38
+ }
39
+ #getEventDef(eventTypeId, errorName) {
40
+ const def = this.metadata.types[eventTypeId];
41
+ (0, utils_1.assert)(def, new utils_1.UnknownApiError(`Event def not found for id ${eventTypeId}`));
42
+ const { tag, value } = def.type;
43
+ (0, utils_1.assert)(tag === 'Enum', new utils_1.UnknownApiError(`Event type should be an enum, found: ${tag}`));
44
+ const eventDef = value.members.find(({ name }) => (0, utils_1.stringPascalCase)(name) === errorName);
45
+ (0, utils_1.assert)(eventDef, new utils_1.UnknownApiError(`Event def not found for ${errorName}`));
46
+ return {
47
+ ...eventDef,
48
+ fieldCodecs: eventDef.fields.map(({ typeId }) => this.registry.findCodec(typeId)),
49
+ };
50
+ }
51
+ }
52
+ exports.EventExecutor = EventExecutor;
@@ -0,0 +1,42 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.Executor = void 0;
4
+ const utils_1 = require("@dedot/utils");
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 atBlockHash() {
17
+ return this.#atBlockHash || this.api.atBlockHash;
18
+ }
19
+ get registry() {
20
+ return this.api.registry;
21
+ }
22
+ get metadata() {
23
+ return this.registry.metadata;
24
+ }
25
+ getPallet(name) {
26
+ const targetPallet = this.metadata.pallets.find((p) => (0, utils_1.stringCamelCase)(p.name) === name);
27
+ (0, utils_1.assert)(targetPallet, new utils_1.UnknownApiError(`Pallet not found: ${name}`));
28
+ return targetPallet;
29
+ }
30
+ execute(...paths) {
31
+ try {
32
+ return this.doExecute(...paths);
33
+ }
34
+ catch (e) {
35
+ if (!this.api.options?.throwOnUnknownApi && e instanceof utils_1.UnknownApiError) {
36
+ return undefined;
37
+ }
38
+ throw e;
39
+ }
40
+ }
41
+ }
42
+ exports.Executor = Executor;
@@ -0,0 +1,121 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.RuntimeApiExecutor = exports.FallbackRuntimeApiSpecs = exports.FallbackRuntimeApis = void 0;
4
+ const runtime_specs_1 = require("@dedot/runtime-specs");
5
+ const utils_1 = require("@dedot/utils");
6
+ const Executor_js_1 = require("./Executor.js");
7
+ exports.FallbackRuntimeApis = { '0x37e397fc7c91f5e4': 2 };
8
+ exports.FallbackRuntimeApiSpecs = { Metadata: runtime_specs_1.Metadata };
9
+ /**
10
+ * @name RuntimeApiExecutor
11
+ * @description Execute a runtime api call,
12
+ * runtime api definitions/specs are either from Metadata V15
13
+ * or defined externally when initializing `Dedot` instance
14
+ * via `ApiOptions.runtimeApis` option.
15
+ */
16
+ class RuntimeApiExecutor extends Executor_js_1.Executor {
17
+ doExecute(runtimeApi, method) {
18
+ const runtimeApiName = (0, utils_1.stringPascalCase)(runtimeApi);
19
+ const methodName = (0, utils_1.stringSnakeCase)(method);
20
+ const callName = this.#callName({ runtimeApiName, methodName });
21
+ const callSpec = this.#findRuntimeApiMethodSpec(runtimeApiName, methodName);
22
+ (0, utils_1.assert)(callSpec, new utils_1.UnknownApiError(`Runtime api spec not found for ${callName}`));
23
+ const callFn = async (...args) => {
24
+ const { params } = callSpec;
25
+ const formattedInputs = params.map((param, index) => this.tryEncode(param, args[index]));
26
+ const bytes = (0, utils_1.u8aToHex)((0, utils_1.concatU8a)(...formattedInputs));
27
+ const callParams = {
28
+ func: callName,
29
+ params: bytes,
30
+ at: this.atBlockHash,
31
+ };
32
+ const result = await this.stateCall(callParams);
33
+ return this.tryDecode(callSpec, result);
34
+ };
35
+ callFn.meta = callSpec;
36
+ return callFn;
37
+ }
38
+ stateCall(callParams) {
39
+ const { func, params, at } = callParams;
40
+ const args = [func, params];
41
+ if (at)
42
+ args.push(at);
43
+ return this.api.rpc.state_call(...args);
44
+ }
45
+ tryDecode(callSpec, raw) {
46
+ const $codec = this.#findCodec(callSpec, `Codec not found to decode respond data for ${this.#callName(callSpec)}`);
47
+ return $codec.tryDecode(raw);
48
+ }
49
+ tryEncode(paramSpec, value) {
50
+ const $codec = this.#findCodec(paramSpec, `Codec not found to encode input for param ${paramSpec.name}`);
51
+ return $codec.tryEncode(value);
52
+ }
53
+ #findCodec(spec, error) {
54
+ const { codec, typeId, type } = spec;
55
+ if (codec)
56
+ return codec;
57
+ if ((0, utils_1.isNumber)(typeId)) {
58
+ return this.registry.findCodec(typeId);
59
+ }
60
+ throw new Error(error || 'Codec not found');
61
+ }
62
+ #callName({ runtimeApiName, methodName }) {
63
+ return `${runtimeApiName}_${methodName}`;
64
+ }
65
+ #findRuntimeApiMethodSpec(runtimeApi, method) {
66
+ const targetVersion = this.#findTargetRuntimeApiVersion(runtimeApi);
67
+ if (!(0, utils_1.isNumber)(targetVersion))
68
+ return undefined;
69
+ const userDefinedSpec = this.#findDefinedSpec(this.api.options.runtimeApis, runtimeApi, method, targetVersion);
70
+ if (userDefinedSpec)
71
+ return userDefinedSpec;
72
+ const methodDef = this.#findRuntimeApiMethodDef(runtimeApi, method);
73
+ if (methodDef) {
74
+ return this.#toMethodSpec(runtimeApi, methodDef);
75
+ }
76
+ return this.#findDefinedSpec(exports.FallbackRuntimeApiSpecs, runtimeApi, method, targetVersion);
77
+ }
78
+ #findRuntimeApiMethodDef(runtimeApi, method) {
79
+ try {
80
+ for (const api of this.metadata.apis) {
81
+ if (api.name !== runtimeApi)
82
+ continue;
83
+ for (const apiMethod of api.methods) {
84
+ if (apiMethod.name === method)
85
+ return apiMethod;
86
+ }
87
+ }
88
+ }
89
+ catch { }
90
+ }
91
+ #toMethodSpec(runtimeApi, methodDef) {
92
+ const { name, inputs, output, docs } = methodDef;
93
+ return {
94
+ docs,
95
+ runtimeApiName: runtimeApi,
96
+ methodName: name,
97
+ typeId: output,
98
+ params: inputs.map(({ name, typeId }) => ({
99
+ name,
100
+ typeId,
101
+ })),
102
+ };
103
+ }
104
+ #findTargetRuntimeApiVersion(runtimeApi) {
105
+ const runtimeApiHash = (0, utils_1.calcRuntimeApiHash)(runtimeApi);
106
+ try {
107
+ return this.api.runtimeVersion.apis[runtimeApiHash] || exports.FallbackRuntimeApis[runtimeApiHash];
108
+ }
109
+ catch {
110
+ return exports.FallbackRuntimeApis[runtimeApiHash];
111
+ }
112
+ }
113
+ #findDefinedSpec(specs, runtimeApi, method, runtimeApiVersion) {
114
+ if (!specs)
115
+ return undefined;
116
+ const methodSpecs = (0, runtime_specs_1.toRuntimeApiSpecs)(specs).map(runtime_specs_1.toRuntimeApiMethods).flat();
117
+ return methodSpecs.find(({ runtimeApiName, methodName, version }) => `${(0, utils_1.stringPascalCase)(runtimeApiName)}_${(0, utils_1.stringSnakeCase)(methodName)}` === `${runtimeApi}_${method}` &&
118
+ runtimeApiVersion === version);
119
+ }
120
+ }
121
+ exports.RuntimeApiExecutor = RuntimeApiExecutor;
@@ -0,0 +1,115 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.StorageQueryExecutor = void 0;
4
+ const utils_1 = require("@dedot/utils");
5
+ const QueryableStorage_js_1 = require("../storage/QueryableStorage.js");
6
+ const Executor_js_1 = require("./Executor.js");
7
+ const DEFAULT_KEYS_PAGE_SIZE = 1000;
8
+ const DEFAULT_ENTRIES_PAGE_SIZE = 250;
9
+ /**
10
+ * @name StorageQueryExecutor
11
+ * @description Execute a query to on-chain storage
12
+ */
13
+ class StorageQueryExecutor extends Executor_js_1.Executor {
14
+ doExecute(pallet, storage) {
15
+ const entry = new QueryableStorage_js_1.QueryableStorage(this.registry, pallet, storage);
16
+ const extractArgs = (args) => {
17
+ const inArgs = args.slice();
18
+ const lastArg = args.at(-1);
19
+ const callback = (0, utils_1.isFunction)(lastArg) ? inArgs.pop() : undefined;
20
+ return [inArgs, callback];
21
+ };
22
+ const getStorageKey = (...args) => {
23
+ const [inArgs] = extractArgs(args);
24
+ return entry.encodeKey(inArgs.at(0));
25
+ };
26
+ const getStorage = async (keys) => {
27
+ const results = await this.queryStorage(keys, this.atBlockHash);
28
+ return keys.reduce((o, key) => {
29
+ o[key] = entry.decodeValue(results[key]);
30
+ return o;
31
+ }, {});
32
+ };
33
+ const queryFn = async (...args) => {
34
+ const [inArgs, callback] = extractArgs(args);
35
+ const encodedKey = entry.encodeKey(inArgs.at(0));
36
+ // if a callback is passed, make a storage subscription and return an unsub function
37
+ if (callback) {
38
+ return await this.subscribeStorage([encodedKey], (changes) => {
39
+ if (changes.length === 0)
40
+ return;
41
+ callback(entry.decodeValue(changes[0]));
42
+ });
43
+ }
44
+ else {
45
+ const results = await getStorage([encodedKey]);
46
+ return results[encodedKey];
47
+ }
48
+ };
49
+ queryFn.rawKey = getStorageKey;
50
+ queryFn.meta = {
51
+ pallet: entry.pallet.name,
52
+ palletIndex: entry.pallet.index,
53
+ ...entry.storageEntry,
54
+ };
55
+ const isMap = entry.storageEntry.type.tag === 'Map';
56
+ if (isMap) {
57
+ const queryMultiFn = async (...args) => {
58
+ const [inArgs, callback] = extractArgs(args);
59
+ const multiArgs = inArgs.at(0);
60
+ (0, utils_1.assert)(Array.isArray(multiArgs), 'First param for multi query should be an array');
61
+ const encodedKeys = multiArgs.map((arg) => entry.encodeKey(arg));
62
+ // if a callback is passed, make a storage subscription and return an unsub function
63
+ if (callback) {
64
+ return await this.subscribeStorage(encodedKeys, (changes) => {
65
+ callback(changes.map((change) => entry.decodeValue(change)));
66
+ });
67
+ }
68
+ else {
69
+ const result = await getStorage(encodedKeys);
70
+ return encodedKeys.map((key) => result[key]);
71
+ }
72
+ };
73
+ // @ts-ignore
74
+ queryFn.multi = queryMultiFn;
75
+ Object.assign(queryFn, this.exposeStorageMapMethods(entry));
76
+ }
77
+ return queryFn;
78
+ }
79
+ exposeStorageMapMethods(entry) {
80
+ const rawKeys = async (pagination) => {
81
+ const pageSize = pagination?.pageSize || DEFAULT_KEYS_PAGE_SIZE;
82
+ const startKey = pagination?.startKey || entry.prefixKey;
83
+ return await this.api.rpc.state_getKeysPaged(entry.prefixKey, pageSize, startKey, this.atBlockHash);
84
+ };
85
+ const pagedKeys = async (pagination) => {
86
+ const storageKeys = await rawKeys({ pageSize: DEFAULT_KEYS_PAGE_SIZE, ...pagination });
87
+ return storageKeys.map((key) => entry.decodeKey(key));
88
+ };
89
+ const pagedEntries = async (pagination) => {
90
+ const storageKeys = await rawKeys({ pageSize: DEFAULT_ENTRIES_PAGE_SIZE, ...pagination });
91
+ const storageMap = await this.queryStorage(storageKeys, this.atBlockHash);
92
+ return storageKeys.map((key) => [entry.decodeKey(key), entry.decodeValue(storageMap[key])]);
93
+ };
94
+ return { pagedKeys, pagedEntries };
95
+ }
96
+ async queryStorage(keys, hash) {
97
+ const changeSets = await this.api.rpc.state_queryStorageAt(keys, hash);
98
+ return changeSets[0].changes.reduce((o, [key, value]) => {
99
+ o[key] = value ?? undefined;
100
+ return o;
101
+ }, {});
102
+ }
103
+ subscribeStorage(keys, callback) {
104
+ const lastChanges = {};
105
+ return this.api.rpc.state_subscribeStorage(keys, (changeSet) => {
106
+ changeSet.changes.forEach(([key, value]) => {
107
+ if (lastChanges[key] !== value) {
108
+ lastChanges[key] = value ?? undefined;
109
+ }
110
+ });
111
+ return callback(keys.map((key) => lastChanges[key]));
112
+ });
113
+ }
114
+ }
115
+ exports.StorageQueryExecutor = StorageQueryExecutor;
@@ -0,0 +1,55 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.TxExecutor = void 0;
4
+ const utils_1 = require("@dedot/utils");
5
+ const index_js_1 = require("../extrinsic/index.js");
6
+ const Executor_js_1 = require("./Executor.js");
7
+ /**
8
+ * @name TxExecutor
9
+ * @description Execute a transaction instruction, returns a submittable extrinsic
10
+ */
11
+ class TxExecutor extends Executor_js_1.Executor {
12
+ doExecute(pallet, functionName) {
13
+ const targetPallet = this.getPallet(pallet);
14
+ (0, utils_1.assert)(targetPallet.calls, new utils_1.UnknownApiError(`Tx calls are not available for pallet ${targetPallet.name}`));
15
+ const txType = this.metadata.types[targetPallet.calls];
16
+ (0, utils_1.assert)(txType.type.tag === 'Enum', new utils_1.UnknownApiError('Tx type defs should be enum'));
17
+ const isFlatEnum = txType.type.value.members.every((m) => m.fields.length === 0);
18
+ const txCallDef = txType.type.value.members.find((m) => (0, utils_1.stringCamelCase)(m.name) === functionName);
19
+ (0, utils_1.assert)(txCallDef, new utils_1.UnknownApiError(`Tx call spec not found for ${pallet}.${functionName}`));
20
+ const txCallFn = (...args) => {
21
+ let call;
22
+ if (isFlatEnum) {
23
+ call = {
24
+ pallet: (0, utils_1.stringPascalCase)(targetPallet.name),
25
+ palletCall: (0, utils_1.stringPascalCase)(txCallDef.name),
26
+ };
27
+ }
28
+ else {
29
+ const callParams = txCallDef.fields.reduce((o, { name }, idx) => {
30
+ o[(0, utils_1.stringCamelCase)(name)] = args[idx];
31
+ return o;
32
+ }, {});
33
+ call = {
34
+ pallet: (0, utils_1.stringPascalCase)(targetPallet.name),
35
+ palletCall: {
36
+ name: (0, utils_1.stringPascalCase)(txCallDef.name),
37
+ params: callParams,
38
+ },
39
+ };
40
+ }
41
+ return this.createExtrinsic(call);
42
+ };
43
+ txCallFn.meta = {
44
+ ...txCallDef,
45
+ fieldCodecs: txCallDef.fields.map(({ typeId }) => this.registry.findCodec(typeId)),
46
+ pallet: targetPallet.name,
47
+ palletIndex: targetPallet.index,
48
+ };
49
+ return txCallFn;
50
+ }
51
+ createExtrinsic(call) {
52
+ return new index_js_1.SubmittableExtrinsic(this.api, call);
53
+ }
54
+ }
55
+ exports.TxExecutor = TxExecutor;