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