dedot 0.0.1-next.fecbe32d.13 → 0.1.0

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 (152) hide show
  1. package/README.md +80 -86
  2. package/bin/dedot +3 -0
  3. package/chaintypes/index.d.ts +1 -1
  4. package/chaintypes/index.js +1 -1
  5. package/cjs/chaintypes/index.js +1 -1
  6. package/cjs/{json-rpc → codecs}/index.js +1 -1
  7. package/cjs/{storage → contracts}/index.js +1 -1
  8. package/cjs/index.js +6 -15
  9. package/cjs/runtime-specs/index.js +17 -0
  10. package/cjs/{chaintypes/substrate → shape}/index.js +1 -1
  11. package/cjs/{client → types}/index.js +1 -1
  12. package/cjs/types/json-rpc/index.js +17 -0
  13. package/cjs/utils/index.js +17 -0
  14. package/codecs/index.d.ts +1 -0
  15. package/codecs/index.js +1 -0
  16. package/contracts/index.d.ts +1 -0
  17. package/contracts/index.js +1 -0
  18. package/index.d.ts +2 -9
  19. package/index.js +2 -9
  20. package/package.json +76 -36
  21. package/runtime-specs/index.d.ts +1 -0
  22. package/runtime-specs/index.js +1 -0
  23. package/shape/index.d.ts +1 -0
  24. package/shape/index.js +1 -0
  25. package/types/index.d.ts +1 -0
  26. package/types/index.js +1 -0
  27. package/types/json-rpc/index.d.ts +1 -0
  28. package/types/json-rpc/index.js +1 -0
  29. package/utils/index.d.ts +1 -0
  30. package/utils/index.js +1 -0
  31. package/chaintypes/substrate/consts.d.ts +0 -1971
  32. package/chaintypes/substrate/consts.js +0 -1
  33. package/chaintypes/substrate/errors.d.ts +0 -3337
  34. package/chaintypes/substrate/errors.js +0 -1
  35. package/chaintypes/substrate/events.d.ts +0 -4777
  36. package/chaintypes/substrate/events.js +0 -1
  37. package/chaintypes/substrate/index.d.ts +0 -18
  38. package/chaintypes/substrate/index.js +0 -1
  39. package/chaintypes/substrate/json-rpc.d.ts +0 -3
  40. package/chaintypes/substrate/json-rpc.js +0 -1
  41. package/chaintypes/substrate/query.d.ts +0 -3447
  42. package/chaintypes/substrate/query.js +0 -1
  43. package/chaintypes/substrate/runtime.d.ts +0 -708
  44. package/chaintypes/substrate/runtime.js +0 -1
  45. package/chaintypes/substrate/tx.d.ts +0 -8800
  46. package/chaintypes/substrate/tx.js +0 -1
  47. package/chaintypes/substrate/types.d.ts +0 -20332
  48. package/chaintypes/substrate/types.js +0 -1
  49. package/cjs/chaintypes/substrate/consts.js +0 -2
  50. package/cjs/chaintypes/substrate/errors.js +0 -2
  51. package/cjs/chaintypes/substrate/events.js +0 -2
  52. package/cjs/chaintypes/substrate/json-rpc.js +0 -2
  53. package/cjs/chaintypes/substrate/query.js +0 -2
  54. package/cjs/chaintypes/substrate/runtime.js +0 -2
  55. package/cjs/chaintypes/substrate/tx.js +0 -2
  56. package/cjs/chaintypes/substrate/types.js +0 -2
  57. package/cjs/client/BaseSubstrateClient.js +0 -247
  58. package/cjs/client/Dedot.js +0 -257
  59. package/cjs/executor/ConstantExecutor.js +0 -20
  60. package/cjs/executor/ErrorExecutor.js +0 -46
  61. package/cjs/executor/EventExecutor.js +0 -52
  62. package/cjs/executor/Executor.js +0 -45
  63. package/cjs/executor/RuntimeApiExecutor.js +0 -113
  64. package/cjs/executor/StorageQueryExecutor.js +0 -109
  65. package/cjs/executor/TxExecutor.js +0 -158
  66. package/cjs/executor/index.js +0 -23
  67. package/cjs/extrinsic/SubmittableResult.js +0 -33
  68. package/cjs/extrinsic/extensions/ExtraSignedExtension.js +0 -87
  69. package/cjs/extrinsic/extensions/SignedExtension.js +0 -41
  70. package/cjs/extrinsic/extensions/index.js +0 -19
  71. package/cjs/extrinsic/extensions/known/ChargeAssetTxPayment.js +0 -43
  72. package/cjs/extrinsic/extensions/known/ChargeTransactionPayment.js +0 -16
  73. package/cjs/extrinsic/extensions/known/CheckGenesis.js +0 -19
  74. package/cjs/extrinsic/extensions/known/CheckMortality.js +0 -70
  75. package/cjs/extrinsic/extensions/known/CheckNonZeroSender.js +0 -10
  76. package/cjs/extrinsic/extensions/known/CheckNonce.js +0 -33
  77. package/cjs/extrinsic/extensions/known/CheckSpecVersion.js +0 -19
  78. package/cjs/extrinsic/extensions/known/CheckTxVersion.js +0 -19
  79. package/cjs/extrinsic/extensions/known/CheckWeight.js +0 -10
  80. package/cjs/extrinsic/extensions/known/PrevalidateAttests.js +0 -11
  81. package/cjs/extrinsic/extensions/known/index.js +0 -25
  82. package/cjs/extrinsic/index.js +0 -18
  83. package/cjs/json-rpc/JsonRpcClient.js +0 -157
  84. package/cjs/proxychain.js +0 -27
  85. package/cjs/storage/QueryableStorage.js +0 -161
  86. package/cjs/types.js +0 -2
  87. package/client/BaseSubstrateClient.d.ts +0 -65
  88. package/client/BaseSubstrateClient.js +0 -242
  89. package/client/Dedot.d.ts +0 -130
  90. package/client/Dedot.js +0 -253
  91. package/client/index.d.ts +0 -1
  92. package/client/index.js +0 -1
  93. package/executor/ConstantExecutor.d.ts +0 -11
  94. package/executor/ConstantExecutor.js +0 -16
  95. package/executor/ErrorExecutor.d.ts +0 -11
  96. package/executor/ErrorExecutor.js +0 -42
  97. package/executor/EventExecutor.d.ts +0 -11
  98. package/executor/EventExecutor.js +0 -48
  99. package/executor/Executor.d.ts +0 -150
  100. package/executor/Executor.js +0 -41
  101. package/executor/RuntimeApiExecutor.d.ts +0 -19
  102. package/executor/RuntimeApiExecutor.js +0 -109
  103. package/executor/StorageQueryExecutor.d.ts +0 -13
  104. package/executor/StorageQueryExecutor.js +0 -105
  105. package/executor/TxExecutor.d.ts +0 -48
  106. package/executor/TxExecutor.js +0 -152
  107. package/executor/index.d.ts +0 -7
  108. package/executor/index.js +0 -7
  109. package/extrinsic/SubmittableResult.d.ts +0 -19
  110. package/extrinsic/SubmittableResult.js +0 -29
  111. package/extrinsic/extensions/ExtraSignedExtension.d.ts +0 -14
  112. package/extrinsic/extensions/ExtraSignedExtension.js +0 -60
  113. package/extrinsic/extensions/SignedExtension.d.ts +0 -40
  114. package/extrinsic/extensions/SignedExtension.js +0 -37
  115. package/extrinsic/extensions/index.d.ts +0 -3
  116. package/extrinsic/extensions/index.js +0 -3
  117. package/extrinsic/extensions/known/ChargeAssetTxPayment.d.ts +0 -14
  118. package/extrinsic/extensions/known/ChargeAssetTxPayment.js +0 -39
  119. package/extrinsic/extensions/known/ChargeTransactionPayment.d.ts +0 -6
  120. package/extrinsic/extensions/known/ChargeTransactionPayment.js +0 -12
  121. package/extrinsic/extensions/known/CheckGenesis.d.ts +0 -10
  122. package/extrinsic/extensions/known/CheckGenesis.js +0 -15
  123. package/extrinsic/extensions/known/CheckMortality.d.ts +0 -15
  124. package/extrinsic/extensions/known/CheckMortality.js +0 -66
  125. package/extrinsic/extensions/known/CheckNonZeroSender.d.ts +0 -6
  126. package/extrinsic/extensions/known/CheckNonZeroSender.js +0 -6
  127. package/extrinsic/extensions/known/CheckNonce.d.ts +0 -10
  128. package/extrinsic/extensions/known/CheckNonce.js +0 -29
  129. package/extrinsic/extensions/known/CheckSpecVersion.d.ts +0 -9
  130. package/extrinsic/extensions/known/CheckSpecVersion.js +0 -15
  131. package/extrinsic/extensions/known/CheckTxVersion.d.ts +0 -9
  132. package/extrinsic/extensions/known/CheckTxVersion.js +0 -15
  133. package/extrinsic/extensions/known/CheckWeight.d.ts +0 -6
  134. package/extrinsic/extensions/known/CheckWeight.js +0 -6
  135. package/extrinsic/extensions/known/PrevalidateAttests.d.ts +0 -7
  136. package/extrinsic/extensions/known/PrevalidateAttests.js +0 -7
  137. package/extrinsic/extensions/known/index.d.ts +0 -3
  138. package/extrinsic/extensions/known/index.js +0 -22
  139. package/extrinsic/index.d.ts +0 -2
  140. package/extrinsic/index.js +0 -2
  141. package/json-rpc/JsonRpcClient.d.ts +0 -49
  142. package/json-rpc/JsonRpcClient.js +0 -153
  143. package/json-rpc/index.d.ts +0 -1
  144. package/json-rpc/index.js +0 -1
  145. package/proxychain.d.ts +0 -14
  146. package/proxychain.js +0 -23
  147. package/storage/QueryableStorage.d.ts +0 -35
  148. package/storage/QueryableStorage.js +0 -157
  149. package/storage/index.d.ts +0 -1
  150. package/storage/index.js +0 -1
  151. package/types.d.ts +0 -103
  152. package/types.js +0 -1
@@ -1 +0,0 @@
1
- export {};
@@ -1,2 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
@@ -1,2 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
@@ -1,2 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
@@ -1,2 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
@@ -1,2 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
@@ -1,2 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
@@ -1,2 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
@@ -1,2 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
@@ -1,247 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.BaseSubstrateClient = exports.ensurePresence = exports.MetadataApiHash = exports.SUPPORTED_METADATA_VERSIONS = exports.KEEP_ALIVE_INTERVAL = void 0;
4
- const codecs_1 = require("@dedot/codecs");
5
- const storage_1 = require("@dedot/storage");
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
- exports.KEEP_ALIVE_INTERVAL = 10_000; // in ms
11
- exports.SUPPORTED_METADATA_VERSIONS = [15, 14];
12
- exports.MetadataApiHash = (0, utils_1.calcRuntimeApiHash)('Metadata'); // 0x37e397fc7c91f5e4
13
- const MESSAGE = 'Make sure to call `.connect()` method first before using the API interfaces.';
14
- function ensurePresence(value) {
15
- return (0, utils_1.ensurePresence)(value, MESSAGE);
16
- }
17
- exports.ensurePresence = ensurePresence;
18
- /**
19
- * @name BaseSubstrateClient
20
- * @description Base & shared abstraction for Substrate API Clients
21
- */
22
- class BaseSubstrateClient extends index_js_2.JsonRpcClient {
23
- _options;
24
- _registry;
25
- _metadata;
26
- _genesisHash;
27
- _runtimeVersion;
28
- _localCache;
29
- constructor(options) {
30
- super(options);
31
- this._options = this.normalizeOptions(options);
32
- }
33
- /// --- Internal logics
34
- normalizeOptions(options) {
35
- const defaultOptions = { throwOnUnknownApi: true };
36
- if (typeof options === 'string') {
37
- return { ...defaultOptions, endpoint: options };
38
- }
39
- else {
40
- return { ...defaultOptions, ...options };
41
- }
42
- }
43
- async initializeLocalCache() {
44
- if (!this._options.cacheMetadata)
45
- return;
46
- // Initialize local cache
47
- if (this._options.cacheStorage) {
48
- this._localCache = this._options.cacheStorage;
49
- return;
50
- }
51
- try {
52
- this._localCache = new storage_1.LocalStorage();
53
- }
54
- catch {
55
- throw new Error('localStorage is not available for caching, please provide a cacheStorage option');
56
- }
57
- }
58
- async setupMetadata(preloadMetadata) {
59
- let metadata = preloadMetadata;
60
- let shouldUpdateCache = !!metadata;
61
- if (!metadata) {
62
- metadata = this.getMetadataFromOptions(this._runtimeVersion);
63
- }
64
- const metadataKey = this.currentMetadataKey;
65
- try {
66
- if (this._localCache && this._options.cacheMetadata) {
67
- if (!metadata) {
68
- try {
69
- const cachedRawMetadata = await this._localCache.get(metadataKey);
70
- if (cachedRawMetadata) {
71
- metadata = codecs_1.$Metadata.tryDecode(cachedRawMetadata);
72
- }
73
- }
74
- catch (e) {
75
- console.error('Cannot decode raw metadata, try fetching fresh metadata from chain.', e);
76
- }
77
- }
78
- }
79
- }
80
- finally {
81
- if (!metadata) {
82
- metadata = await this.fetchMetadata();
83
- if (this._options.cacheMetadata)
84
- shouldUpdateCache = true;
85
- }
86
- }
87
- if (shouldUpdateCache && this._localCache) {
88
- await this._localCache.set(metadataKey, (0, utils_1.u8aToHex)(codecs_1.$Metadata.tryEncode(metadata)));
89
- }
90
- if (!metadata) {
91
- throw new Error('Cannot load metadata');
92
- }
93
- this.setMetadata(metadata);
94
- }
95
- setMetadata(metadata) {
96
- this._metadata = metadata;
97
- this._registry = new codecs_1.PortableRegistry(metadata.latest, this.options.hasher);
98
- }
99
- getMetadataKey(runtime) {
100
- return `RAW_META/${this._genesisHash || '0x'}/${runtime?.specVersion || '---'}`;
101
- }
102
- get currentMetadataKey() {
103
- return this.getMetadataKey(this._runtimeVersion);
104
- }
105
- async shouldLoadPreloadMetadata() {
106
- if (this._options.metadata && Object.keys(this._options.metadata).length) {
107
- return false;
108
- }
109
- if (!this._options.cacheMetadata || !this._localCache) {
110
- return true;
111
- }
112
- // TODO improve this
113
- const keys = await this._localCache.keys();
114
- return !keys.some((k) => k.startsWith('RAW_META/'));
115
- }
116
- getMetadataFromOptions(runtime) {
117
- if (!runtime || !this.options.metadata)
118
- return;
119
- const key = this.getMetadataKey(runtime);
120
- if (this.options.metadata[key]) {
121
- return codecs_1.$Metadata.tryDecode(this.options.metadata[key]);
122
- }
123
- }
124
- async fetchMetadata(hash, runtime) {
125
- // First try finding metadata from the provided option
126
- const optionMetadata = this.getMetadataFromOptions(runtime);
127
- if (optionMetadata)
128
- return optionMetadata;
129
- // If there is no runtime, we assume that the node supports Metadata Api V2
130
- const supportedV2 = runtime ? runtime.apis[exports.MetadataApiHash] === 2 : true;
131
- if (supportedV2) {
132
- // It makes sense to call metadata.metadataVersions to fetch the list of supported metadata versions first
133
- // But for now, this approach could potentially help save/reduce one rpc call to the server in case the node support v15
134
- // Question: Why not having a `metadata.metadataLatest` to fetch the latest version?
135
- for (const version of exports.SUPPORTED_METADATA_VERSIONS) {
136
- try {
137
- const rawMetadata = await this.callAt(hash).metadata.metadataAtVersion(version);
138
- if (!rawMetadata)
139
- continue;
140
- return codecs_1.$Metadata.tryDecode(rawMetadata);
141
- }
142
- catch { }
143
- }
144
- }
145
- try {
146
- return codecs_1.$Metadata.tryDecode(await this.callAt(hash).metadata.metadata());
147
- }
148
- catch {
149
- return await this.rpc.state_getMetadata();
150
- }
151
- }
152
- cleanUp() {
153
- this._registry = undefined;
154
- this._metadata = undefined;
155
- this._genesisHash = undefined;
156
- this._runtimeVersion = undefined;
157
- this._localCache = undefined;
158
- }
159
- /**
160
- * @description Clear local cache
161
- */
162
- async clearCache() {
163
- await this._localCache?.clear();
164
- }
165
- async doConnect() {
166
- this.on('connected', this.onConnected);
167
- this.on('disconnected', this.onDisconnected);
168
- return new Promise((resolve) => {
169
- this.once('ready', () => {
170
- resolve(this);
171
- });
172
- });
173
- }
174
- onConnected = async () => {
175
- await this.initialize();
176
- };
177
- onDisconnected = async () => { };
178
- async initialize() {
179
- await this.initializeLocalCache();
180
- await this.doInitialize();
181
- this.emit('ready');
182
- }
183
- async doInitialize() {
184
- throw new Error('Unimplemented!');
185
- }
186
- async beforeDisconnect() { }
187
- async afterDisconnect() {
188
- this.cleanUp();
189
- }
190
- /// --- Public APIs ---
191
- /**
192
- * @description Connect to blockchain node
193
- */
194
- async connect() {
195
- const [api, _] = await Promise.all([this.doConnect(), super.connect()]);
196
- return api;
197
- }
198
- /**
199
- * @description Disconnect to blockchain node
200
- */
201
- async disconnect() {
202
- await this.beforeDisconnect();
203
- await super.disconnect();
204
- await this.afterDisconnect();
205
- }
206
- get options() {
207
- return this._options;
208
- }
209
- get metadata() {
210
- return ensurePresence(this._metadata);
211
- }
212
- get registry() {
213
- return ensurePresence(this._registry);
214
- }
215
- get genesisHash() {
216
- return ensurePresence(this._genesisHash);
217
- }
218
- get runtimeVersion() {
219
- return ensurePresence(this._runtimeVersion);
220
- }
221
- get consts() {
222
- return (0, proxychain_js_1.newProxyChain)({ executor: new index_js_1.ConstantExecutor(this) });
223
- }
224
- get errors() {
225
- return (0, proxychain_js_1.newProxyChain)({ executor: new index_js_1.ErrorExecutor(this) });
226
- }
227
- get events() {
228
- return (0, proxychain_js_1.newProxyChain)({ executor: new index_js_1.EventExecutor(this) });
229
- }
230
- get query() {
231
- throw new Error('Unimplemented!');
232
- }
233
- get call() {
234
- return this.callAt();
235
- }
236
- // For internal use with caution
237
- callAt(hash) {
238
- throw new Error('Unimplemented!');
239
- }
240
- get tx() {
241
- throw new Error('Unimplemented!');
242
- }
243
- at(hash) {
244
- throw new Error('Unimplemented!');
245
- }
246
- }
247
- exports.BaseSubstrateClient = BaseSubstrateClient;
@@ -1,257 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.Dedot = void 0;
4
- const codecs_1 = require("@dedot/codecs");
5
- const index_js_1 = require("../executor/index.js");
6
- const proxychain_js_1 = require("../proxychain.js");
7
- const BaseSubstrateClient_js_1 = require("./BaseSubstrateClient.js");
8
- /**
9
- * @name Dedot
10
- * @description Promised-based API Client for Polkadot & Substrate
11
- *
12
- * Initialize API instance and interact with substrate-based network
13
- * ```typescript
14
- * import { Dedot } from 'dedot';
15
- * import type { PolkadotApi } from '@dedot/chaintypes/polkadot';
16
- *
17
- * const run = async () => {
18
- * const api = await Dedot.new<PolkadotApi>('wss://rpc.polkadot.io');
19
- *
20
- * // Call rpc `state_getMetadata` to fetch raw scale-encoded metadata and decode it.
21
- * const metadata = await api.rpc.state.getMetadata();
22
- * console.log('Metadata:', metadata);
23
- *
24
- * // Query on-chain storage
25
- * const address = '14...';
26
- * const balance = await api.query.system.account(address);
27
- * console.log('Balance:', balance);
28
- *
29
- *
30
- * // Subscribe to on-chain storage changes
31
- * const unsub = await api.query.system.number((blockNumber) => {
32
- * console.log(`Current block number: ${blockNumber}`);
33
- * });
34
- *
35
- * // Get pallet constants
36
- * const ss58Prefix = api.consts.system.ss58Prefix;
37
- * console.log('Polkadot ss58Prefix:', ss58Prefix)
38
- *
39
- * // await unsub();
40
- * // await api.disconnect();
41
- * }
42
- *
43
- * run().catch(console.error);
44
- * ```
45
- */
46
- class Dedot extends BaseSubstrateClient_js_1.BaseSubstrateClient {
47
- #runtimeSubscriptionUnsub;
48
- #healthTimer;
49
- #apiAtCache = {};
50
- /**
51
- * Use factory methods (`create`, `new`) to create `Dedot` instances.
52
- *
53
- * @param options
54
- */
55
- constructor(options) {
56
- super(options);
57
- }
58
- /**
59
- * Factory method to create a new Dedot instance
60
- *
61
- * @param options
62
- */
63
- static async create(options) {
64
- return new Dedot(options).connect();
65
- }
66
- /**
67
- * Alias for __Dedot.create__
68
- *
69
- * @param options
70
- */
71
- static async new(options) {
72
- return Dedot.create(options);
73
- }
74
- onDisconnected = async () => {
75
- await this.#unsubscribeUpdates();
76
- };
77
- async beforeDisconnect() {
78
- await this.#unsubscribeUpdates();
79
- }
80
- /**
81
- * Initialize APIs before usage
82
- */
83
- async doInitialize() {
84
- let [genesisHash, runtimeVersion, metadata] = await Promise.all([
85
- this.rpc.chain_getBlockHash(0),
86
- this.#getRuntimeVersion(),
87
- (await this.shouldLoadPreloadMetadata()) ? this.fetchMetadata() : Promise.resolve(undefined),
88
- ]);
89
- this._genesisHash = genesisHash;
90
- this._runtimeVersion = runtimeVersion;
91
- await this.setupMetadata(metadata);
92
- this.#subscribeUpdates();
93
- }
94
- cleanUp() {
95
- super.cleanUp();
96
- this.#apiAtCache = {};
97
- this.#healthTimer = undefined;
98
- this.#runtimeSubscriptionUnsub = undefined;
99
- }
100
- #subscribeRuntimeUpgrades() {
101
- if (this.#runtimeSubscriptionUnsub)
102
- return;
103
- this.rpc
104
- .state_subscribeRuntimeVersion(async (runtimeVersion) => {
105
- if (runtimeVersion.specVersion !== this.runtimeVersion?.specVersion) {
106
- this._runtimeVersion = this.#toSubstrateRuntimeVersion(runtimeVersion);
107
- const newMetadata = await this.fetchMetadata(undefined, this._runtimeVersion);
108
- await this.setupMetadata(newMetadata);
109
- }
110
- })
111
- .then((unsub) => {
112
- this.#runtimeSubscriptionUnsub = unsub;
113
- });
114
- }
115
- async #getRuntimeVersion(at) {
116
- return this.#toSubstrateRuntimeVersion(await this.rpc.state_getRuntimeVersion(at));
117
- }
118
- #toSubstrateRuntimeVersion(runtimeVersion) {
119
- return {
120
- ...runtimeVersion,
121
- apis: runtimeVersion.apis.reduce((o, [name, version]) => {
122
- o[name] = version;
123
- return o;
124
- }, {}),
125
- };
126
- }
127
- #subscribeHealth() {
128
- this.#unsubscribeHealth();
129
- this.#healthTimer = setInterval(() => {
130
- this.rpc.system_health().catch(console.error);
131
- }, BaseSubstrateClient_js_1.KEEP_ALIVE_INTERVAL);
132
- }
133
- #unsubscribeHealth() {
134
- if (!this.#healthTimer) {
135
- return;
136
- }
137
- clearInterval(this.#healthTimer);
138
- this.#healthTimer = undefined;
139
- }
140
- async #unsubscribeRuntimeUpdates() {
141
- if (!this.#runtimeSubscriptionUnsub) {
142
- return;
143
- }
144
- await this.#runtimeSubscriptionUnsub();
145
- this.#runtimeSubscriptionUnsub = undefined;
146
- }
147
- #subscribeUpdates() {
148
- this.#subscribeRuntimeUpgrades();
149
- this.#subscribeHealth();
150
- }
151
- async #unsubscribeUpdates() {
152
- await this.#unsubscribeRuntimeUpdates();
153
- this.#unsubscribeHealth();
154
- }
155
- /// --- Public APIs ---
156
- /**
157
- * @description Entry-point for inspecting constants (parameter types) for all pallets (modules).
158
- *
159
- * ```typescript
160
- * const ss58Prefix = api.consts.system.ss58Prefix;
161
- * console.log('ss58Prefix:', ss58Prefix)
162
- * ```
163
- */
164
- get consts() {
165
- return (0, proxychain_js_1.newProxyChain)({ executor: new index_js_1.ConstantExecutor(this) });
166
- }
167
- /**
168
- * @description Entry-point for executing query to on-chain storage.
169
- *
170
- * ```typescript
171
- * const balance = await api.query.system.account(<address>);
172
- * console.log('Balance:', balance);
173
- * ```
174
- */
175
- get query() {
176
- return (0, proxychain_js_1.newProxyChain)({ executor: new index_js_1.StorageQueryExecutor(this) });
177
- }
178
- /**
179
- * @description Entry-point for inspecting errors from metadata
180
- */
181
- get errors() {
182
- return (0, proxychain_js_1.newProxyChain)({ executor: new index_js_1.ErrorExecutor(this) });
183
- }
184
- /**
185
- * @description Entry-point for inspecting events from metadata
186
- */
187
- get events() {
188
- return (0, proxychain_js_1.newProxyChain)({ executor: new index_js_1.EventExecutor(this) });
189
- }
190
- /**
191
- * @description Entry-point for executing runtime api
192
- *
193
- * ```typescript
194
- * // Get account nonce
195
- * const nonce = await api.call.accountNonceApi.accountNonce(<address>);
196
- *
197
- * // Query transaction payment info
198
- * const tx = api.tx.balances.transferKeepAlive(<address>, 2_000_000_000_000n);
199
- * const queryInfo = await api.call.transactionPaymentApi.queryInfo(tx.toU8a(), tx.length);
200
- * ```
201
- */
202
- get call() {
203
- return this.callAt();
204
- }
205
- // For internal use with caution
206
- callAt(hash) {
207
- return (0, proxychain_js_1.newProxyChain)({ executor: new index_js_1.RuntimeApiExecutor(this, hash) });
208
- }
209
- /**
210
- * @description Entry-point for executing on-chain transactions
211
- *
212
- * ```typescript
213
- * // Make a transfer balance transaction
214
- * api.tx.balances.transferKeepAlive(<address>, <amount>)
215
- * .signAndSend(<keyPair|address>, { signer }, ({ status }) => {
216
- * console.log('Transaction status', status.tag);
217
- * });
218
- * ```
219
- */
220
- get tx() {
221
- return (0, proxychain_js_1.newProxyChain)({ executor: new index_js_1.TxExecutor(this) });
222
- }
223
- /**
224
- * Create a new API instance at a specific block hash
225
- * This is useful when we want to inspect the state of the chain at a specific block hash
226
- *
227
- * @param hash
228
- */
229
- async at(hash) {
230
- if (this.#apiAtCache[hash])
231
- return this.#apiAtCache[hash];
232
- const targetVersion = await this.#getRuntimeVersion(hash);
233
- let metadata = this.metadata;
234
- let registry = this.registry;
235
- if (targetVersion.specVersion !== this.runtimeVersion.specVersion) {
236
- metadata = await this.fetchMetadata(hash, targetVersion);
237
- registry = new codecs_1.PortableRegistry(metadata.latest, this.options.hasher);
238
- }
239
- const api = {
240
- atBlockHash: hash,
241
- options: this.options,
242
- genesisHash: this.genesisHash,
243
- runtimeVersion: targetVersion,
244
- metadata,
245
- registry,
246
- rpc: this.rpc,
247
- };
248
- api.consts = (0, proxychain_js_1.newProxyChain)({ executor: new index_js_1.ConstantExecutor(api) });
249
- api.query = (0, proxychain_js_1.newProxyChain)({ executor: new index_js_1.StorageQueryExecutor(api) });
250
- api.call = (0, proxychain_js_1.newProxyChain)({ executor: new index_js_1.RuntimeApiExecutor(api) });
251
- api.events = (0, proxychain_js_1.newProxyChain)({ executor: new index_js_1.EventExecutor(api) });
252
- api.errors = (0, proxychain_js_1.newProxyChain)({ executor: new index_js_1.ErrorExecutor(api) });
253
- this.#apiAtCache[hash] = api;
254
- return api;
255
- }
256
- }
257
- exports.Dedot = Dedot;
@@ -1,20 +0,0 @@
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;
@@ -1,46 +0,0 @@
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;
@@ -1,52 +0,0 @@
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;