@dedot/api 0.0.1-next.8d3b3cd0.51 → 0.0.1-next.a5b1d2fb.22

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/README.md +1 -517
  2. package/chaintypes/substrate/consts.js +1 -1
  3. package/chaintypes/substrate/errors.js +1 -1
  4. package/chaintypes/substrate/events.js +1 -1
  5. package/chaintypes/substrate/index.d.ts +1 -1
  6. package/chaintypes/substrate/index.js +1 -1
  7. package/chaintypes/substrate/json-rpc.d.ts +1 -1
  8. package/chaintypes/substrate/json-rpc.js +1 -1
  9. package/chaintypes/substrate/query.js +1 -1
  10. package/chaintypes/substrate/runtime.js +1 -1
  11. package/chaintypes/substrate/tx.js +1 -1
  12. package/chaintypes/substrate/types.js +1 -1
  13. package/cjs/chaintypes/substrate/consts.js +1 -1
  14. package/cjs/chaintypes/substrate/errors.js +1 -1
  15. package/cjs/chaintypes/substrate/events.js +1 -1
  16. package/cjs/chaintypes/substrate/index.js +1 -1
  17. package/cjs/chaintypes/substrate/json-rpc.js +1 -1
  18. package/cjs/chaintypes/substrate/query.js +1 -1
  19. package/cjs/chaintypes/substrate/runtime.js +1 -1
  20. package/cjs/chaintypes/substrate/tx.js +1 -1
  21. package/cjs/chaintypes/substrate/types.js +1 -1
  22. package/cjs/client/BaseSubstrateClient.js +2 -2
  23. package/cjs/client/{Dedot.js → LegacyClient.js} +8 -8
  24. package/cjs/client/index.js +1 -1
  25. package/cjs/executor/v2/StorageQueryExecutorV2.js +3 -3
  26. package/cjs/extrinsic/extensions/known/CheckMetadataHash.js +31 -0
  27. package/cjs/extrinsic/extensions/known/StorageWeightReclaim.js +10 -0
  28. package/cjs/extrinsic/extensions/known/index.js +4 -0
  29. package/cjs/extrinsic/submittable/utils.js +2 -3
  30. package/client/{Dedot.d.ts → LegacyClient.d.ts} +6 -6
  31. package/client/{Dedot.js → LegacyClient.js} +6 -6
  32. package/client/index.d.ts +1 -1
  33. package/client/index.js +1 -1
  34. package/executor/v2/StorageQueryExecutorV2.js +3 -3
  35. package/extrinsic/extensions/known/CheckMetadataHash.d.ts +13 -0
  36. package/extrinsic/extensions/known/CheckMetadataHash.js +27 -0
  37. package/extrinsic/extensions/known/StorageWeightReclaim.d.ts +6 -0
  38. package/extrinsic/extensions/known/StorageWeightReclaim.js +6 -0
  39. package/extrinsic/extensions/known/index.js +4 -0
  40. package/package.json +10 -10
  41. package/proxychain.d.ts +1 -1
package/README.md CHANGED
@@ -1,517 +1 @@
1
- # dedot
2
-
3
- A delightful JavaScript/TypeScript client for [Polkadot](https://polkadot.network/) & [Substrate](https://substrate.io/)
4
-
5
- <p align="left">
6
- <img src="https://img.shields.io/github/license/dedotdev/dedot?style=flat-square"/>
7
- <img src="https://img.shields.io/github/actions/workflow/status/dedotdev/dedot/run-tests.yml?label=unit%20tests&style=flat-square"/>
8
- <img src="https://img.shields.io/github/package-json/v/dedotdev/dedot?filename=packages%2Fapi%2Fpackage.json&style=flat-square"/>
9
- </p>
10
-
11
- _Note: The project is still in active development phase, the information on this page might be outdated. Feel free to raise an [issue](https://github.com/dedotdev/dedot/issues/new) if you run into any problems or want to share any ideas._
12
-
13
- ---
14
- ### Features
15
- - ✅ Small bundle size, tree-shakable (no more bn.js or wasm-blob tight dependencies)
16
- - ✅ Built-in metadata caching mechanism
17
- - ✅ Types & APIs suggestions for each individual Substrate-based blockchain network ([@dedot/chaintypes](https://github.com/dedotdev/chaintypes))
18
- - ✅ Familiar api style with `@polkadot/api`, easy & fast migration!
19
- - ✅ Native TypeScript type system for scale-codec
20
- - ✅ Compatible with `@polkadot/extension`-based wallets
21
- - ✅ Support Metadata V14, V15 (latest)
22
- - ⏳ Support both the legacy (✅) & [new](https://paritytech.github.io/json-rpc-interface-spec/introduction.html) (⏳) JSON-RPC APIs
23
- - ⏳ Support light clients ([smoldot](https://www.npmjs.com/package/smoldot))
24
-
25
- ### Have a quick taste
26
-
27
- Try `dedot` now on [CodeSandbox Playground](https://codesandbox.io/p/devbox/trydedot-th96cm?file=%2Fmain.ts%3A24%2C26) or follow the below steps to run it on your local environment.
28
- - Install `dedot` package
29
- ```shell
30
- # via yarn
31
- yarn add dedot
32
-
33
- # via npm
34
- npm i dedot
35
- ```
36
-
37
- - Install `@dedot/chaintypes` package for chain types & APIs suggestion. Skip this step if you don't use TypeScript.
38
- ```shell
39
- # via yarn
40
- yarn add -D @dedot/chaintypes
41
-
42
- # via npm
43
- npm i -D @dedot/chaintypes
44
- ```
45
-
46
- - Initialize the API client and start interacting with Polkadot network
47
- ```typescript
48
- // main.ts
49
- import { Dedot } from 'dedot';
50
- import type { PolkadotApi } from '@dedot/chaintypes';
51
-
52
- const run = async () => {
53
- const api = await Dedot.new<PolkadotApi>('wss://rpc.polkadot.io');
54
-
55
- // Call rpc `state_getMetadata` to fetch raw scale-encoded metadata and decode it.
56
- const metadata = await api.rpc.state.getMetadata();
57
- console.log('Metadata:', metadata);
58
-
59
- // Query on-chain storage
60
- const balance = await api.query.system.account(<address>);
61
- console.log('Balance:', balance);
62
-
63
-
64
- // Subscribe to on-chain storage changes
65
- const unsub = await api.query.system.number((blockNumber) => {
66
- console.log(`Current block number: ${blockNumber}`);
67
- });
68
-
69
- // Get pallet constants
70
- const ss58Prefix = api.consts.system.ss58Prefix;
71
- console.log('Polkadot ss58Prefix:', ss58Prefix);
72
-
73
- // Call runtime api
74
- const pendingRewards = await api.call.nominationPoolsApi.pendingRewards(<address>)
75
- console.log('Pending rewards:', pendingRewards);
76
-
77
- // await unsub();
78
- // await api.disconnect();
79
- }
80
-
81
- run().catch(console.error);
82
- ```
83
- - You can also import `dedot` using `require`.
84
-
85
- ```js
86
- // main.js
87
- const { Dedot } = require('dedot');
88
- // ...
89
- const api = await Dedot.new('wss://rpc.polkadot.io');
90
- ```
91
- ### Table of contents
92
- - [Status](#status)
93
- - [Chain Types & APIs](#chain-types--apis)
94
- - [Execute RPC Methods](#execute-rpc-methods)
95
- - [Query On-chain Storage](#query-on-chain-storage)
96
- - [Constants](#constants)
97
- - [Runtime APIs](#runtime-apis)
98
- - [Submit Transactions](#transaction-apis)
99
- - [Events](#events)
100
- - [Errors](#errors)
101
- - [`@polkadot/api` -> `dedot`](#migration-from-polkadotapi-to-dedot)
102
- - [Credit](#credit)
103
-
104
- ### Status
105
-
106
- | Feature | Status |
107
- |-------------------------------------------------------------|--------|
108
- | Execute RPC (`api.rpc`) | ✅ |
109
- | Query On-chain Storage (`api.query`) | ✅ |
110
- | Get runtime constants (`api.consts`) | ✅ |
111
- | Runtime APIs (`api.call`) | ✅ |
112
- | Transaction APIs (`api.tx`) | ✅ |
113
- | Events (`api.events`) | ✅ |
114
- | Errors (`api.errors`) | ✅ |
115
- | Contract APIs | ⏳ |
116
- | Metadata v14 | ✅ |
117
- | Metadata v15 | ✅ |
118
- | [RPC v2](https://github.com/dedotdev/dedot/issues/20) | ⏳ |
119
- | [Extrinsic V5](https://github.com/dedotdev/dedot/issues/55) | ⏳ |
120
-
121
- ### Chain Types & APIs
122
-
123
- Each Substrate-based blockchain has their own set of data types & APIs to interact with, so being aware of those types & APIs when working with a blockchain will greatly improve the overall development experience. `dedot` exposes TypeScript's types & APIs for each individual Substrate-based blockchain, we recommend using TypeScript for your project to have the best experience.
124
-
125
- Types & APIs for each Substrate-based blockchains are defined in package [`@dedot/chaintypes`](https://github.com/dedotdev/dedot/tree/main/packages/chaintypes):
126
- ```shell
127
- # via yarn
128
- yarn add -D @dedot/chaintypes
129
-
130
- # via npm
131
- npm i -D @dedot/chaintypes
132
- ```
133
-
134
- Initialize a `Dedot` instance using the `ChainApi` interface for a target chain to enable types & APIs suggestion/autocompletion for that particular chain:
135
- ```typescript
136
- import { Dedot } from 'dedot';
137
- import type { PolkadotApi, KusamaApi, MoonbeamApi, AstarApi } from '@dedot/chaintypes';
138
-
139
- // ...
140
-
141
- const polkadotApi = await Dedot.new<PolkadotApi>('wss://rpc.polkadot.io');
142
- console.log(await polkadotApi.query.babe.authorities());
143
-
144
- const kusamaApi = await Dedot.new<KusamaApi>('wss://kusama-rpc.polkadot.io');
145
- console.log(await kusamaApi.query.society.memberCount());
146
-
147
- const moonbeamApi = await Dedot.new<MoonbeamApi>('wss://wss.api.moonbeam.network');
148
- console.log(await moonbeamApi.query.ethereumChainId.chainId());
149
-
150
- const astarApi = await Dedot.new<AstarApi>('wss://rpc.astar.network');
151
- console.log(await astarApi.query.dappsStaking.blockRewardAccumulator());
152
-
153
- const genericApi = await Dedot.new('ws://localhost:9944');
154
-
155
- // ...
156
- ```
157
-
158
- Supported `ChainApi` interfaces are defined [here](https://github.com/dedotdev/dedot/blob/main/packages/chaintypes/src/index.ts), you can also generate the `ChainApi` interface for the chain you want to connect with using `@dedot/cli`.
159
-
160
- ```shell
161
- # Install @dedot/cli via yarn
162
- yarn add -D @dedot/cli
163
-
164
- # Or via npm
165
- npm i -D @dedot/cli
166
-
167
- # Generate ChainApi interface for Polkadot network via rpc endpoint: wss://rpc.polkadot.io
168
- npx dedot chaintypes -w wss://rpc.polkadot.io
169
- ```
170
-
171
- ### Execute RPC Methods
172
-
173
- RPCs can be executed via `api.rpc` entry point. After creating a `Dedot` instance with a `ChainApi` interface of the network you want to interact with, all RPC methods of the network will be exposed in the autocompletion/suggestion with format: `api.rpc.<module>.<methodName>`. E.g: you can find all supported RPC methods for Polkadot network [here](https://github.com/dedotdev/dedot/blob/main/packages/chaintypes/src/polkadot/rpc.d.ts), similarly for other networks as well.
174
-
175
- Examples:
176
- ```typescript
177
- // Call rpc: `state_getMetadata`
178
- const metadata = await api.rpc.state.getMetadata();
179
-
180
- // Call an arbitrary rpc: `module_rpc_name` with arguments ['param1', 'param2']
181
- const result = await api.rpc.module.rpc_name('param1', 'param2');
182
- ```
183
-
184
- ### Query On-chain Storage
185
-
186
- On-chain storage can be queried via `api.query` entry point. All the available storage entries for a chain are exposed in the `ChainApi` interface for that chain and can be executed with format: `api.query.<pallet>.<storgeEntry>`. E.g: You can find all the available storage queries of Polkadot network [here](https://github.com/dedotdev/dedot/blob/main/packages/chaintypes/src/polkadot/query.d.ts), similarly for other networks as well.
187
-
188
- Examples:
189
- ```typescript
190
- // Query account balance
191
- const balance = await api.query.system.account(<address>);
192
-
193
- // Get all events of current block
194
- const events = await api.query.system.events();
195
- ```
196
- ### Constants
197
-
198
- Runtime constants (parameter types) are defined in metadata, and can be inspected via `api.consts` entry point with format: `api.consts.<pallet>.<constantName>`. All available constants are also exposed in the `ChainApi` interface. E.g: Available constants for Polkadot network is defined [here](https://github.com/dedotdev/dedot/blob/main/packages/chaintypes/src/polkadot/consts.d.ts), similarly for other networks.
199
-
200
- Examples:
201
- ```typescript
202
- // Get runtime version
203
- const runtimeVersion = api.consts.system.version;
204
-
205
- // Get existential deposit in pallet balances
206
- const existentialDeposit = api.consts.balances.existentialDeposit;
207
- ```
208
-
209
- ### Runtime APIs
210
-
211
- The latest stable Metadata V15 now includes all the runtime apis type information. So for chains that are supported Metadata V15, we can now execute all available runtime apis with syntax `api.call.<runtimeApi>.<methodName>`, those apis are exposed in `ChainApi` interface. E.g: Runtime Apis for Polkadot network is defined [here](https://github.com/dedotdev/dedot/blob/main/packages/chaintypes/src/polkadot/runtime.d.ts), similarly for other networks as well.
212
-
213
- Examples:
214
- ```typescript
215
- // Get account nonce
216
- const nonce = await api.call.accountNonceApi.accountNonce(<address>);
217
-
218
- // Query transaction payment info
219
- const tx = api.tx.balances.transferKeepAlive(<address>, 2_000_000_000_000n);
220
- const queryInfo = await api.call.transactionPaymentApi.queryInfo(tx.toU8a(), tx.length);
221
-
222
- // Get runtime version
223
- const runtimeVersion = await api.call.core.version();
224
- ```
225
-
226
- For chains that only support Metadata V14, we need to bring in the Runtime Api definitions when initializing the Dedot client instance to encode & decode the calls. You can find all supported Runtime Api definitions in [`@dedot/runtime-specs`](https://github.com/dedotdev/dedot/blob/60de0fed8ba19c67a7e174c6168a127fdbf6caef/packages/runtime-specs/src/runtime/all.ts#L21-L39) package.
227
-
228
- Examples:
229
- ```typescript
230
- import { RuntimeApis } from '@dedot/runtime-specs';
231
- const api = await Dedot.new({ endpoint: 'wss://rpc.mynetwork.com', runtimeApis: RuntimeApis });
232
-
233
- // Or bring in only the Runtime Api definition that you want to interact with
234
- import { AccountNonceApi } from '@dedot/runtime-specs';
235
- const api = await Dedot.new({ endpoint: 'wss://rpc.mynetwork.com', runtimeApis: { AccountNonceApi } });
236
-
237
- // Get account nonce
238
- const nonce = await api.call.accountNonceApi.accountNonce(<address>);
239
- ```
240
-
241
- You absolutely can define your own Runtime Api definition if you don't find it in the [supported list](https://github.com/dedotdev/dedot/blob/60de0fed8ba19c67a7e174c6168a127fdbf6caef/packages/runtime-specs/src/runtime/all.ts#L21-L39).
242
-
243
- ### Transaction APIs
244
-
245
- Transaction apis are designed to be compatible with [`IKeyringPair`](https://github.com/polkadot-js/api/blob/3bdf49b0428a62f16b3222b9a31bfefa43c1ca55/packages/types/src/types/interfaces.ts#L15-L21) and [`Signer`](https://github.com/polkadot-js/api/blob/3bdf49b0428a62f16b3222b9a31bfefa43c1ca55/packages/types/src/types/extrinsic.ts#L135-L150) interfaces, so you can sign the transactions with accounts created by a [`Keyring`](https://github.com/polkadot-js/common/blob/22aab4a4e62944a2cf8c885f50be2c1b842813ec/packages/keyring/src/keyring.ts#L41-L40) or from any [Polkadot{.js}-based](https://github.com/polkadot-js/extension?tab=readme-ov-file#api-interface) wallet extensions.
246
-
247
- All transaction apis are exposed in `ChainApi` interface and can be access with syntax: `api.tx.<pallet>.<transactionName>`. E.g: Available transaction apis for Polkadot network are defined [here](https://github.com/dedotdev/dedot/blob/516c5dd948ac89ef53644b7fb1f62df1727adadb/packages/chaintypes/src/polkadot/tx.d.ts), similarly for other networks as well.
248
-
249
- Example 1: Sign transaction with a Keying account
250
- ```typescript
251
- import { cryptoWaitReady } from '@polkadot/util-crypto';
252
- import { Keyring } from '@polkadot/keyring';
253
- ...
254
- await cryptoWaitReady();
255
- const keyring = new Keyring({ type: 'sr25519' });
256
- const alice = keyring.addFromUri('//Alice');
257
-
258
- const unsub = await api.tx.balances
259
- .transferKeepAlive(<destAddress>, 2_000_000_000_000n)
260
- .signAndSend(alice, async ({ status }) => {
261
- console.log('Transaction status', status.tag);
262
- if (status.tag === 'InBlock') {
263
- console.log(`Transaction completed at block hash ${status.value}`);
264
- await unsub();
265
- }
266
- });
267
- ```
268
-
269
- Example 2: Sign transaction using `Signer` from Polkadot{.js} wallet extension
270
- ```typescript
271
- const injected = await window.injectedWeb3['polkadot-js'].enable('A cool dapp');
272
- const account = (await injected.accounts.get())[0];
273
- const signer = injected.signer;
274
-
275
- const unsub = await api.tx.balances
276
- .transferKeepAlive(<destAddress>, 2_000_000_000_000n)
277
- .signAndSend(account.address, { signer }, async ({ status }) => {
278
- console.log('Transaction status', status.tag);
279
- if (status.tag === 'InBlock') {
280
- console.log(`Transaction completed at block hash ${status.value}`);
281
- await unsub();
282
- }
283
- });
284
- ```
285
-
286
- Example 3: Submit a batch transaction
287
- ```typescript
288
- import type { PolkadotRuntimeRuntimeCallLike } from '@dedot/chaintypes/polkadot';
289
-
290
- // Omit the detail for simplicity
291
- const account = ...;
292
- const signer = ...;
293
-
294
- const transferTx = api.tx.balances.transferKeepAlive(<destAddress>, 2_000_000_000_000n);
295
- const remarkCall: PolkadotRuntimeRuntimeCallLike = {
296
- pallet: 'System',
297
- palletCall: {
298
- name: 'RemarkWithEvent',
299
- params: {
300
- remark: 'Hello Dedot!',
301
- },
302
- },
303
- };
304
-
305
- const unsub = api.tx.utility.batch([transferTx.call, remarkCall])
306
- .signAndSend(account.address, { signer }, async ({ status }) => {
307
- console.log('Transaction status', status.tag);
308
- if (status.tag === 'InBlock') {
309
- console.log(`Transaction completed at block hash ${status.value}`);
310
- await unsub();
311
- }
312
- });
313
- ```
314
-
315
- <details>
316
- <summary>Example 4: Teleport WND from Westend Asset Hub to Westend via XCM</summary>
317
-
318
- ```typescript
319
- import { WestendAssetHubApi, XcmVersionedLocation, XcmVersionedAssets, XcmV3WeightLimit } from '@dedot/chaintypes/westendAssetHub';
320
- import { AccountId32 } from '@dedot/codecs';
321
-
322
- const TWO_TOKENS = 2_000_000_000_000n;
323
- const destAddress = <bobAddress>;
324
-
325
- const api = await Dedot.new<WestendAssetHubApi>('...westend-assethub-rpc...');
326
-
327
- const dest: XcmVersionedLocation = {
328
- tag: 'V3',
329
- value: { parents: 1, interior: { tag: 'Here' } },
330
- };
331
-
332
- const beneficiary: XcmVersionedLocation = {
333
- tag: 'V3',
334
- value: {
335
- parents: 0,
336
- interior: {
337
- tag: 'X1',
338
- value: {
339
- tag: 'AccountId32',
340
- value: { id: new AccountId32(destAddress).raw },
341
- },
342
- },
343
- },
344
- };
345
-
346
- const assets: XcmVersionedAssets = {
347
- tag: 'V3',
348
- value: [
349
- {
350
- id: {
351
- tag: 'Concrete',
352
- value: {
353
- parents: 1,
354
- interior: { tag: 'Here' },
355
- },
356
- },
357
- fun: {
358
- tag: 'Fungible',
359
- value: TWO_TOKENS,
360
- },
361
- },
362
- ],
363
- };
364
-
365
- const weight: XcmV3WeightLimit = { tag: 'Unlimited' };
366
-
367
- api.tx.polkadotXcm
368
- .limitedTeleportAssets(dest, beneficiary, assets, 0, weight)
369
- .signAndSend(alice, { signer, tip: 1_000_000n }, (result) => {
370
- console.dir(result, { depth: null });
371
- });
372
- ```
373
- </details>
374
-
375
-
376
- ### Events
377
-
378
- Events for each pallet emit during runtime operations and are defined in the medata. Available events are also exposed in `ChainApi` interface so we can get information of an event through syntax `api.events.<pallet>.<eventName>`. E.g: Events for Polkadot network can be found [here](https://github.com/dedotdev/dedot/blob/main/packages/chaintypes/src/polkadot/events.d.ts), similarly for other network as well.
379
-
380
- This `api.events` is helpful when we want quickly check if an event matches with an event that we're expecting in a list of events, the API also comes with type narrowing for the matched event, so event name & related data of the event are fully typed.
381
-
382
- Example to list new accounts created in each block:
383
- ```typescript
384
- // ...
385
- const ss58Prefix = api.consts.system.ss58Prefix;
386
- await api.query.system.events(async (eventRecords) => {
387
- const newAccountEvents = eventRecords
388
- .map(({ event }) => api.events.system.NewAccount.as(event))
389
- .filter((one) => one);
390
-
391
- console.log(newAccountEvents.length, 'account(s) was created in block', await api.query.system.number());
392
-
393
- newAccountEvents.forEach((event, index) => {
394
- console.log(`New Account ${index + 1}:`, event.palletEvent.data.account.address(ss58Prefix));
395
- });
396
- });
397
- // ...
398
- ```
399
-
400
- ### Errors
401
-
402
- Pallet errors are thrown out when things go wrong in the runtime, those are defined in the metadata. Available errors for each pallet are also exposed in `ChainApi` interface, so we can get information an error through this syntax: `api.errors.<pallet>.<errorName>`. E.g: Available errors for Polkadot network can be found [here](https://github.com/dedotdev/dedot/blob/main/packages/chaintypes/src/polkadot/errors.d.ts).
403
-
404
- Similar to events API, this API is helpful when we want to check if an error maches with an error that we're expecting.
405
-
406
- Example if an error is `AlreadyExists` from `Assets` pallet:
407
- ```typescript
408
- // ...
409
- await api.query.system.events(async (eventRecords) => {
410
- for (const tx of eventRecords) {
411
- if (api.events.system.ExtrinsicFailed.is(tx.event)) {
412
- const { dispatchError } = tx.event.palletEvent.data;
413
- if (dispatchError.tag === 'Module' && api.errors.assets.AlreadyExists.is(dispatchError.value)) {
414
- console.log('Assets.AlreadyExists error occurred!');
415
- } else {
416
- console.log('Other error occurred', dispatchError);
417
- }
418
- }
419
- }
420
- });
421
- // ...
422
- ```
423
-
424
- ### Migration from `@polkadot/api` to `dedot`
425
- `dedot` is inspired by `@polkadot/api`, so both are sharing some common patterns and api styling (eg: api syntax `api.<type>.<module>.<section>`). Although we have experimented some other different api stylings but to our findings and development experience, we find that the api style of `@polkadot/api` is very intuiative and easy to use. We decide the use a similar api styling with `@polkadot/api`, this also helps the migration from `@polkadot/api` to `dedot` easier & faster.
426
-
427
- While the api style are similar, but there're also some differences you might need to be aware of when switching to use `dedot`.
428
-
429
- **Initialize api client**
430
- - `@polkadot/api`
431
- ```typescript
432
- import { ApiPromise, WsProvider } from '@polkadot/api';
433
-
434
- const api = await ApiPromise.create({ provider: new WsProvider('wss://rpc.polkadot.io') });
435
- ```
436
- - `dedot`
437
- ```typescript
438
- import { Dedot } from 'dedot';
439
- import type { PolkadotApi } from '@dedot/chaintypes';
440
-
441
- const api = await Dedot.new<PolkadotApi>('wss://rpc.polkadot.io'); // or Dedot.create(...) if you prefer
442
-
443
- // OR you want to have a custom provider
444
- import { WsProvider } from 'dedot'
445
- const api = await Dedot.new<PolkadotApi>({ provider: new WsProvider('wss://rpc.polkadot.io') });
446
- ```
447
-
448
- - Notes:
449
- - Under the hood, a `WsProvider` will be created if you initialize `Dedot` directly with an rpc endpoint.
450
- - `dedot` only supports provider can make subscription request (e.g: via Websocket).
451
- - We recommend specifying the `ChainApi` interface (e.g: [`PolkadotApi`](https://github.com/dedotdev/dedot/blob/02d7bca4c3c3d12c9591ea43b3410daf8e5aacbb/packages/chaintypes/src/polkadot/index.d.ts) in the example above) of the chain that you want to interact with. This enable apis & types suggestion/autocompletion for that particular chain (via IntelliSense). If you don't specify a `ChainApi` interface, the default [`SubstrateApi`](https://github.com/dedotdev/dedot/blob/a762faf8f6af40d3e4ef163bd538b270a5ca31e8/packages/chaintypes/src/substrate/index.d.ts) interface will be used.
452
-
453
- **Type system**
454
-
455
- Unlike `@polkadot/api` where data are wrapped inside a [codec types](https://polkadot.js.org/docs/api/start/types.basics), so we always need to unwrap the data before using it (e.g: via `.unwrap()`, `.toNumber()`, `.toString()`, `.toJSON()` ...). `dedot` leverages the native TypeScript type system to represent scale-codec types, so you can use the data directly without extra handling/unwrapping. The table below is a mapping between scale-codec types and TypeScript types that we're using for `dedot`:
456
-
457
-
458
- | Scale Codec | TypeScript (`dedot`) |
459
- |---------------------------------------------------------|--------------------------------------------------------------------------------------------------------------------------------|
460
- | `u8`, `u16`, `u32`, `i8`, `i16`, `i32` | `number` |
461
- | `u64`, `u128`, `u256`, `i64`, `i128`, `i256` | `bigint` (native [BigInt](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt), not bn.js) |
462
- | `bool` | `boolean` (true, false) |
463
- | `Option<T>` | `T \| undefined` |
464
- | `Result<Ok, Err>` | `{ isOk: true; isErr?: false; value: Ok } \| { isOk?: false; isErr: true; err: Err }` |
465
- | `Vec<T>` | `Array<T>` |
466
- | `str` | `string` |
467
- | Tuple: `(A, B)`, `()` | `[A, B]`, `[]` |
468
- | Struct: `struct { field_1: u8, field_2: str }` | `{ field_1: number, field_2: string}` |
469
- | Enum: `enum { Variant1(u8), Variant2(bool), Variant3 }` | `{ tag: 'Variant1', value: number } \| { tag: 'Variant2', value: boolean } \| { tag: 'Variant2' }` |
470
- | FlatEnum: `enum { Variant1, Variant2 }` | `'Variant1' \| 'Variant2'` |
471
-
472
- E.g 1:
473
- ```typescript
474
- const runtimeVersion = api.consts.system.version;
475
-
476
- // @polkadot/api
477
- const specName: string = runtimeVersion.toJSON().specName; // OR runtimeVersion.specName.toString()
478
-
479
- // dedot
480
- const specName: string = runtimeVersion.specName;
481
- ```
482
-
483
- E.g 2:
484
- ```typescript
485
- const balance = await api.query.system.account(<address>);
486
-
487
- // @polkadot/api
488
- const freeBalance: bigint = balance.data.free.toBigInt();
489
-
490
- // dedot
491
- const freeBalance: bigint = balance.data.free;
492
- ```
493
-
494
- E.g 3:
495
- ```typescript
496
- // @polkadot/api
497
- const proposalBondMaximum: bigint | undefined = api.consts.treasury.proposalBondMaximum.unwrapOr(undefined)?.toBigInt();
498
-
499
- // dedot
500
- const proposalBondMaximum: bigint | undefined = api.consts.treasury.proposalBondMaximum;
501
- ```
502
-
503
-
504
- ### Credit
505
-
506
- `dedot` take a lot of inspirations from project [@polkadot/api](https://github.com/polkadot-js/api). A big thank to all the maintainers/contributors of this awesome library.
507
-
508
- Proudly supported by Web3 Foundation Grants Program.
509
- <p align="left">
510
- <img width="479" src="https://user-images.githubusercontent.com/6867026/227230786-0796214a-3e3f-42af-94e9-d4122c730b62.png">
511
- </p>
512
-
513
-
514
- ### License
515
-
516
- [Apache-2.0](https://github.com/dedotdev/dedot/blob/main/LICENSE)
517
-
1
+ # @dedot/api
@@ -1,2 +1,2 @@
1
- // Generated by @dedot/codegen
1
+ // Generated by dedot cli
2
2
  export {};
@@ -1,2 +1,2 @@
1
- // Generated by @dedot/codegen
1
+ // Generated by dedot cli
2
2
  export {};
@@ -1,2 +1,2 @@
1
- // Generated by @dedot/codegen
1
+ // Generated by dedot cli
2
2
  export {};
@@ -1,4 +1,4 @@
1
- import { GenericSubstrateApi, RpcLegacy, RpcV2, RpcVersion } from '@dedot/types';
1
+ import type { GenericSubstrateApi, RpcLegacy, RpcV2, RpcVersion } from '@dedot/types';
2
2
  import { ChainConsts } from './consts.js';
3
3
  import { ChainErrors } from './errors.js';
4
4
  import { ChainEvents } from './events.js';
@@ -1,2 +1,2 @@
1
- // Generated by @dedot/codegen
1
+ // Generated by dedot cli
2
2
  export * from './types.js';
@@ -1,3 +1,3 @@
1
1
  import type { GenericJsonRpcApis, RpcVersion } from '@dedot/types';
2
2
  import type { JsonRpcApis } from '@dedot/types/json-rpc';
3
- export type ChainJsonRpcApis<Rv extends RpcVersion> = Pick<JsonRpcApis, 'author_hasKey' | 'author_hasSessionKeys' | 'author_insertKey' | 'author_pendingExtrinsics' | 'author_removeExtrinsic' | 'author_rotateKeys' | 'author_submitAndWatchExtrinsic' | 'author_submitExtrinsic' | 'babe_epochAuthorship' | 'beefy_getFinalizedHead' | 'beefy_subscribeJustifications' | 'chainHead_unstable_body' | 'chainHead_unstable_call' | 'chainHead_unstable_continue' | 'chainHead_unstable_follow' | 'chainHead_unstable_header' | 'chainHead_unstable_stopOperation' | 'chainHead_unstable_storage' | 'chainHead_unstable_unpin' | 'chainSpec_v1_chainName' | 'chainSpec_v1_genesisHash' | 'chainSpec_v1_properties' | 'chain_getBlock' | 'chain_getBlockHash' | 'chain_getFinalizedHead' | 'chain_getHeader' | 'chain_subscribeAllHeads' | 'chain_subscribeFinalizedHeads' | 'chain_subscribeNewHeads' | 'childstate_getKeys' | 'childstate_getKeysPaged' | 'childstate_getStorage' | 'childstate_getStorageEntries' | 'childstate_getStorageHash' | 'childstate_getStorageSize' | 'dev_getBlockStats' | 'grandpa_proveFinality' | 'grandpa_roundState' | 'grandpa_subscribeJustifications' | 'mmr_generateProof' | 'mmr_root' | 'mmr_verifyProof' | 'mmr_verifyProofStateless' | 'offchain_localStorageGet' | 'offchain_localStorageSet' | 'payment_queryFeeDetails' | 'payment_queryInfo' | 'rpc_methods' | 'state_call' | 'state_getChildReadProof' | 'state_getKeys' | 'state_getKeysPaged' | 'state_getMetadata' | 'state_getPairs' | 'state_getReadProof' | 'state_getRuntimeVersion' | 'state_getStorage' | 'state_getStorageHash' | 'state_getStorageSize' | 'state_queryStorage' | 'state_queryStorageAt' | 'state_subscribeRuntimeVersion' | 'state_subscribeStorage' | 'state_traceBlock' | 'state_trieMigrationStatus' | 'statement_broadcasts' | 'statement_dump' | 'statement_posted' | 'statement_postedClear' | 'statement_remove' | 'statement_submit' | 'sync_state_genSyncSpec' | 'system_accountNextIndex' | 'system_addLogFilter' | 'system_addReservedPeer' | 'system_chain' | 'system_chainType' | 'system_dryRun' | 'system_health' | 'system_localListenAddresses' | 'system_localPeerId' | 'system_name' | 'system_nodeRoles' | 'system_peers' | 'system_properties' | 'system_removeReservedPeer' | 'system_reservedPeers' | 'system_resetLogFilter' | 'system_syncState' | 'system_unstable_networkState' | 'system_version' | 'transactionWatch_unstable_submitAndWatch' | 'transaction_unstable_broadcast' | 'transaction_unstable_stop'> & GenericJsonRpcApis<Rv>;
3
+ export type ChainJsonRpcApis<Rv extends RpcVersion> = Pick<JsonRpcApis, 'author_hasKey' | 'author_hasSessionKeys' | 'author_insertKey' | 'author_pendingExtrinsics' | 'author_removeExtrinsic' | 'author_rotateKeys' | 'author_submitAndWatchExtrinsic' | 'author_submitExtrinsic' | 'babe_epochAuthorship' | 'beefy_getFinalizedHead' | 'beefy_subscribeJustifications' | 'chainHead_v1_body' | 'chainHead_v1_call' | 'chainHead_v1_continue' | 'chainHead_v1_follow' | 'chainHead_v1_header' | 'chainHead_v1_stopOperation' | 'chainHead_v1_storage' | 'chainHead_v1_unpin' | 'chainSpec_v1_chainName' | 'chainSpec_v1_genesisHash' | 'chainSpec_v1_properties' | 'chain_getBlock' | 'chain_getBlockHash' | 'chain_getFinalizedHead' | 'chain_getHeader' | 'chain_subscribeAllHeads' | 'chain_subscribeFinalizedHeads' | 'chain_subscribeNewHeads' | 'childstate_getKeys' | 'childstate_getKeysPaged' | 'childstate_getStorage' | 'childstate_getStorageEntries' | 'childstate_getStorageHash' | 'childstate_getStorageSize' | 'dev_getBlockStats' | 'grandpa_proveFinality' | 'grandpa_roundState' | 'grandpa_subscribeJustifications' | 'mmr_generateProof' | 'mmr_root' | 'mmr_verifyProof' | 'mmr_verifyProofStateless' | 'offchain_localStorageGet' | 'offchain_localStorageSet' | 'payment_queryFeeDetails' | 'payment_queryInfo' | 'rpc_methods' | 'state_call' | 'state_getChildReadProof' | 'state_getKeys' | 'state_getKeysPaged' | 'state_getMetadata' | 'state_getPairs' | 'state_getReadProof' | 'state_getRuntimeVersion' | 'state_getStorage' | 'state_getStorageHash' | 'state_getStorageSize' | 'state_queryStorage' | 'state_queryStorageAt' | 'state_subscribeRuntimeVersion' | 'state_subscribeStorage' | 'state_traceBlock' | 'state_trieMigrationStatus' | 'statement_broadcasts' | 'statement_dump' | 'statement_posted' | 'statement_postedClear' | 'statement_remove' | 'statement_submit' | 'sync_state_genSyncSpec' | 'system_accountNextIndex' | 'system_addLogFilter' | 'system_addReservedPeer' | 'system_chain' | 'system_chainType' | 'system_dryRun' | 'system_health' | 'system_localListenAddresses' | 'system_localPeerId' | 'system_name' | 'system_nodeRoles' | 'system_peers' | 'system_properties' | 'system_removeReservedPeer' | 'system_reservedPeers' | 'system_resetLogFilter' | 'system_syncState' | 'system_unstable_networkState' | 'system_version' | 'transactionWatch_v1_submitAndWatch' | 'transaction_v1_broadcast' | 'transaction_v1_stop'> & GenericJsonRpcApis<Rv>;
@@ -1,2 +1,2 @@
1
- // Generated by @dedot/codegen
1
+ // Generated by dedot cli
2
2
  export {};
@@ -1,2 +1,2 @@
1
- // Generated by @dedot/codegen
1
+ // Generated by dedot cli
2
2
  export {};
@@ -1,2 +1,2 @@
1
- // Generated by @dedot/codegen
1
+ // Generated by dedot cli
2
2
  export {};
@@ -1,2 +1,2 @@
1
- // Generated by @dedot/codegen
1
+ // Generated by dedot cli
2
2
  export {};
@@ -1,2 +1,2 @@
1
- // Generated by @dedot/codegen
1
+ // Generated by dedot cli
2
2
  export {};
@@ -1,3 +1,3 @@
1
1
  "use strict";
2
- // Generated by @dedot/codegen
2
+ // Generated by dedot cli
3
3
  Object.defineProperty(exports, "__esModule", { value: true });
@@ -1,3 +1,3 @@
1
1
  "use strict";
2
- // Generated by @dedot/codegen
2
+ // Generated by dedot cli
3
3
  Object.defineProperty(exports, "__esModule", { value: true });
@@ -1,3 +1,3 @@
1
1
  "use strict";
2
- // Generated by @dedot/codegen
2
+ // Generated by dedot cli
3
3
  Object.defineProperty(exports, "__esModule", { value: true });
@@ -1,5 +1,5 @@
1
1
  "use strict";
2
- // Generated by @dedot/codegen
2
+ // Generated by dedot cli
3
3
  var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
4
4
  if (k2 === undefined) k2 = k;
5
5
  var desc = Object.getOwnPropertyDescriptor(m, k);
@@ -1,3 +1,3 @@
1
1
  "use strict";
2
- // Generated by @dedot/codegen
2
+ // Generated by dedot cli
3
3
  Object.defineProperty(exports, "__esModule", { value: true });
@@ -1,3 +1,3 @@
1
1
  "use strict";
2
- // Generated by @dedot/codegen
2
+ // Generated by dedot cli
3
3
  Object.defineProperty(exports, "__esModule", { value: true });
@@ -1,3 +1,3 @@
1
1
  "use strict";
2
- // Generated by @dedot/codegen
2
+ // Generated by dedot cli
3
3
  Object.defineProperty(exports, "__esModule", { value: true });
@@ -1,3 +1,3 @@
1
1
  "use strict";
2
- // Generated by @dedot/codegen
2
+ // Generated by dedot cli
3
3
  Object.defineProperty(exports, "__esModule", { value: true });
@@ -1,3 +1,3 @@
1
1
  "use strict";
2
- // Generated by @dedot/codegen
2
+ // Generated by dedot cli
3
3
  Object.defineProperty(exports, "__esModule", { value: true });
@@ -1,6 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.BaseSubstrateClient = exports.ensurePresence = void 0;
3
+ exports.BaseSubstrateClient = void 0;
4
+ exports.ensurePresence = ensurePresence;
4
5
  const codecs_1 = require("@dedot/codecs");
5
6
  const storage_1 = require("@dedot/storage");
6
7
  const utils_1 = require("@dedot/utils");
@@ -13,7 +14,6 @@ const MESSAGE = 'Make sure to call `.connect()` method first before using the AP
13
14
  function ensurePresence(value) {
14
15
  return (0, utils_1.ensurePresence)(value, MESSAGE);
15
16
  }
16
- exports.ensurePresence = ensurePresence;
17
17
  /**
18
18
  * @name BaseSubstrateClient
19
19
  * @description Base & shared abstraction for Substrate API Clients
@@ -1,13 +1,13 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.Dedot = void 0;
3
+ exports.LegacyClient = void 0;
4
4
  const codecs_1 = require("@dedot/codecs");
5
5
  const index_js_1 = require("../executor/index.js");
6
6
  const proxychain_js_1 = require("../proxychain.js");
7
7
  const BaseSubstrateClient_js_1 = require("./BaseSubstrateClient.js");
8
8
  const KEEP_ALIVE_INTERVAL = 10_000; // in ms
9
9
  /**
10
- * @name Dedot
10
+ * @name LegacyClient
11
11
  * @description Promised-based API Client for Polkadot & Substrate
12
12
  *
13
13
  * Initialize API instance and interact with substrate-based network
@@ -16,7 +16,7 @@ const KEEP_ALIVE_INTERVAL = 10_000; // in ms
16
16
  * import type { PolkadotApi } from '@dedot/chaintypes/polkadot';
17
17
  *
18
18
  * const run = async () => {
19
- * const api = await Dedot.new<PolkadotApi>('wss://rpc.polkadot.io');
19
+ * const api = await LegacyClient.new<PolkadotApi>('wss://rpc.polkadot.io');
20
20
  *
21
21
  * // Call rpc `state_getMetadata` to fetch raw scale-encoded metadata and decode it.
22
22
  * const metadata = await api.rpc.state.getMetadata();
@@ -44,7 +44,7 @@ const KEEP_ALIVE_INTERVAL = 10_000; // in ms
44
44
  * run().catch(console.error);
45
45
  * ```
46
46
  */
47
- class Dedot extends BaseSubstrateClient_js_1.BaseSubstrateClient {
47
+ class LegacyClient extends BaseSubstrateClient_js_1.BaseSubstrateClient {
48
48
  #runtimeSubscriptionUnsub;
49
49
  #healthTimer;
50
50
  #apiAtCache = {};
@@ -62,15 +62,15 @@ class Dedot extends BaseSubstrateClient_js_1.BaseSubstrateClient {
62
62
  * @param options
63
63
  */
64
64
  static async create(options) {
65
- return new Dedot(options).connect();
65
+ return new LegacyClient(options).connect();
66
66
  }
67
67
  /**
68
- * Alias for __Dedot.create__
68
+ * Alias for __LegacyClient.create__
69
69
  *
70
70
  * @param options
71
71
  */
72
72
  static async new(options) {
73
- return Dedot.create(options);
73
+ return LegacyClient.create(options);
74
74
  }
75
75
  onDisconnected = async () => {
76
76
  await this.#unsubscribeUpdates();
@@ -247,4 +247,4 @@ class Dedot extends BaseSubstrateClient_js_1.BaseSubstrateClient {
247
247
  return api;
248
248
  }
249
249
  }
250
- exports.Dedot = Dedot;
250
+ exports.LegacyClient = LegacyClient;
@@ -14,5 +14,5 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
14
  for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
15
  };
16
16
  Object.defineProperty(exports, "__esModule", { value: true });
17
- __exportStar(require("./Dedot.js"), exports);
17
+ __exportStar(require("./LegacyClient.js"), exports);
18
18
  __exportStar(require("./DedotClient.js"), exports);
@@ -35,13 +35,13 @@ class StorageQueryExecutorV2 extends StorageQueryExecutor_js_1.StorageQueryExecu
35
35
  }, {});
36
36
  }
37
37
  async subscribeStorage(keys, callback) {
38
- let initialHash = await this.chainHead.bestHash();
38
+ let best = await this.chainHead.bestBlock();
39
39
  let eventToListen = 'bestBlock';
40
40
  // TODO subscribe to finalized data source
41
41
  // initialHash = this.chainHead.finalizedHash;
42
42
  // eventToListen = 'finalizedBlock';
43
43
  const latestChanges = {};
44
- const pull = async (hash) => {
44
+ const pull = async ({ hash }) => {
45
45
  const results = await this.queryStorage(keys, hash);
46
46
  let changed = false;
47
47
  keys.forEach((key) => {
@@ -55,7 +55,7 @@ class StorageQueryExecutorV2 extends StorageQueryExecutor_js_1.StorageQueryExecu
55
55
  return;
56
56
  callback(keys.map((key) => latestChanges[key]));
57
57
  };
58
- await pull(initialHash);
58
+ await pull(best);
59
59
  const unsub = this.chainHead.on(eventToListen, pull);
60
60
  return async () => {
61
61
  unsub();
@@ -0,0 +1,31 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.CheckMetadataHash = void 0;
4
+ const utils_1 = require("@dedot/utils");
5
+ const SignedExtension_js_1 = require("../SignedExtension.js");
6
+ /**
7
+ * @description Genesis hash check to provide replay protection between different networks.
8
+ */
9
+ class CheckMetadataHash extends SignedExtension_js_1.SignedExtension {
10
+ async init() {
11
+ let metadataHash = this.payloadOptions.metadataHash;
12
+ if (metadataHash) {
13
+ (0, utils_1.assert)((0, utils_1.isHex)(metadataHash), 'Metadata hash is not a valid hex string');
14
+ this.data = { mode: 'Enabled' };
15
+ this.additionalSigned = metadataHash;
16
+ }
17
+ else {
18
+ this.data = { mode: 'Disabled' };
19
+ this.additionalSigned = undefined;
20
+ }
21
+ }
22
+ toPayload() {
23
+ // Ref: https://github.com/paritytech/polkadot-sdk/blob/8dbe4ee80734bba6644c7e5f879a363ce7c0a19f/substrate/frame/metadata-hash-extension/src/lib.rs#L55-L58
24
+ let enabled = this.data.mode === 'Enabled';
25
+ return {
26
+ mode: enabled ? 1 : 0, // 0 -> disabled, 1 -> enabled
27
+ metadataHash: this.additionalSigned,
28
+ };
29
+ }
30
+ }
31
+ exports.CheckMetadataHash = CheckMetadataHash;
@@ -0,0 +1,10 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.StorageWeightReclaim = void 0;
4
+ const SignedExtension_js_1 = require("../SignedExtension.js");
5
+ /**
6
+ * @description Storage weight reclaim mechanism.
7
+ */
8
+ class StorageWeightReclaim extends SignedExtension_js_1.SignedExtension {
9
+ }
10
+ exports.StorageWeightReclaim = StorageWeightReclaim;
@@ -4,6 +4,7 @@ exports.knownSignedExtensions = void 0;
4
4
  const ChargeAssetTxPayment_js_1 = require("./ChargeAssetTxPayment.js");
5
5
  const ChargeTransactionPayment_js_1 = require("./ChargeTransactionPayment.js");
6
6
  const CheckGenesis_js_1 = require("./CheckGenesis.js");
7
+ const CheckMetadataHash_js_1 = require("./CheckMetadataHash.js");
7
8
  const CheckMortality_js_1 = require("./CheckMortality.js");
8
9
  const CheckNonZeroSender_js_1 = require("./CheckNonZeroSender.js");
9
10
  const CheckNonce_js_1 = require("./CheckNonce.js");
@@ -11,6 +12,7 @@ const CheckSpecVersion_js_1 = require("./CheckSpecVersion.js");
11
12
  const CheckTxVersion_js_1 = require("./CheckTxVersion.js");
12
13
  const CheckWeight_js_1 = require("./CheckWeight.js");
13
14
  const PrevalidateAttests_js_1 = require("./PrevalidateAttests.js");
15
+ const StorageWeightReclaim_js_1 = require("./StorageWeightReclaim.js");
14
16
  exports.knownSignedExtensions = {
15
17
  CheckNonZeroSender: CheckNonZeroSender_js_1.CheckNonZeroSender,
16
18
  CheckSpecVersion: CheckSpecVersion_js_1.CheckSpecVersion,
@@ -22,4 +24,6 @@ exports.knownSignedExtensions = {
22
24
  ChargeTransactionPayment: ChargeTransactionPayment_js_1.ChargeTransactionPayment,
23
25
  PrevalidateAttests: PrevalidateAttests_js_1.PrevalidateAttests,
24
26
  ChargeAssetTxPayment: ChargeAssetTxPayment_js_1.ChargeAssetTxPayment,
27
+ CheckMetadataHash: CheckMetadataHash_js_1.CheckMetadataHash,
28
+ StorageWeightReclaim: StorageWeightReclaim_js_1.StorageWeightReclaim,
25
29
  };
@@ -1,11 +1,11 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.signRaw = exports.isKeyringPair = void 0;
3
+ exports.isKeyringPair = isKeyringPair;
4
+ exports.signRaw = signRaw;
4
5
  const utils_1 = require("@dedot/utils");
5
6
  function isKeyringPair(account) {
6
7
  return (0, utils_1.isFunction)(account.sign);
7
8
  }
8
- exports.isKeyringPair = isKeyringPair;
9
9
  /**
10
10
  * Sign a raw message
11
11
  * @param signerPair
@@ -17,4 +17,3 @@ function signRaw(signerPair, raw) {
17
17
  const toSignRaw = u8a.length > 256 ? (0, utils_1.blake2AsU8a)(u8a, 256) : u8a;
18
18
  return signerPair.sign(toSignRaw, { withType: true });
19
19
  }
20
- exports.signRaw = signRaw;
@@ -5,7 +5,7 @@ import type { SubstrateApi } from '../chaintypes/index.js';
5
5
  import type { ApiOptions, ISubstrateClientAt } from '../types.js';
6
6
  import { BaseSubstrateClient } from './BaseSubstrateClient.js';
7
7
  /**
8
- * @name Dedot
8
+ * @name LegacyClient
9
9
  * @description Promised-based API Client for Polkadot & Substrate
10
10
  *
11
11
  * Initialize API instance and interact with substrate-based network
@@ -14,7 +14,7 @@ import { BaseSubstrateClient } from './BaseSubstrateClient.js';
14
14
  * import type { PolkadotApi } from '@dedot/chaintypes/polkadot';
15
15
  *
16
16
  * const run = async () => {
17
- * const api = await Dedot.new<PolkadotApi>('wss://rpc.polkadot.io');
17
+ * const api = await LegacyClient.new<PolkadotApi>('wss://rpc.polkadot.io');
18
18
  *
19
19
  * // Call rpc `state_getMetadata` to fetch raw scale-encoded metadata and decode it.
20
20
  * const metadata = await api.rpc.state.getMetadata();
@@ -42,7 +42,7 @@ import { BaseSubstrateClient } from './BaseSubstrateClient.js';
42
42
  * run().catch(console.error);
43
43
  * ```
44
44
  */
45
- export declare class Dedot<ChainApi extends VersionedGenericSubstrateApi = SubstrateApi> extends BaseSubstrateClient<ChainApi> {
45
+ export declare class LegacyClient<ChainApi extends VersionedGenericSubstrateApi = SubstrateApi> extends BaseSubstrateClient<ChainApi> {
46
46
  #private;
47
47
  /**
48
48
  * Use factory methods (`create`, `new`) to create `Dedot` instances.
@@ -55,13 +55,13 @@ export declare class Dedot<ChainApi extends VersionedGenericSubstrateApi = Subst
55
55
  *
56
56
  * @param options
57
57
  */
58
- static create<ChainApi extends VersionedGenericSubstrateApi = SubstrateApi>(options: ApiOptions | JsonRpcProvider): Promise<Dedot<ChainApi>>;
58
+ static create<ChainApi extends VersionedGenericSubstrateApi = SubstrateApi>(options: ApiOptions | JsonRpcProvider): Promise<LegacyClient<ChainApi>>;
59
59
  /**
60
- * Alias for __Dedot.create__
60
+ * Alias for __LegacyClient.create__
61
61
  *
62
62
  * @param options
63
63
  */
64
- static new<ChainApi extends VersionedGenericSubstrateApi = SubstrateApi>(options: ApiOptions | JsonRpcProvider): Promise<Dedot<ChainApi>>;
64
+ static new<ChainApi extends VersionedGenericSubstrateApi = SubstrateApi>(options: ApiOptions | JsonRpcProvider): Promise<LegacyClient<ChainApi>>;
65
65
  protected onDisconnected: () => Promise<void>;
66
66
  protected beforeDisconnect(): Promise<void>;
67
67
  /**
@@ -4,7 +4,7 @@ import { newProxyChain } from '../proxychain.js';
4
4
  import { BaseSubstrateClient } from './BaseSubstrateClient.js';
5
5
  const KEEP_ALIVE_INTERVAL = 10_000; // in ms
6
6
  /**
7
- * @name Dedot
7
+ * @name LegacyClient
8
8
  * @description Promised-based API Client for Polkadot & Substrate
9
9
  *
10
10
  * Initialize API instance and interact with substrate-based network
@@ -13,7 +13,7 @@ const KEEP_ALIVE_INTERVAL = 10_000; // in ms
13
13
  * import type { PolkadotApi } from '@dedot/chaintypes/polkadot';
14
14
  *
15
15
  * const run = async () => {
16
- * const api = await Dedot.new<PolkadotApi>('wss://rpc.polkadot.io');
16
+ * const api = await LegacyClient.new<PolkadotApi>('wss://rpc.polkadot.io');
17
17
  *
18
18
  * // Call rpc `state_getMetadata` to fetch raw scale-encoded metadata and decode it.
19
19
  * const metadata = await api.rpc.state.getMetadata();
@@ -41,7 +41,7 @@ const KEEP_ALIVE_INTERVAL = 10_000; // in ms
41
41
  * run().catch(console.error);
42
42
  * ```
43
43
  */
44
- export class Dedot extends BaseSubstrateClient {
44
+ export class LegacyClient extends BaseSubstrateClient {
45
45
  #runtimeSubscriptionUnsub;
46
46
  #healthTimer;
47
47
  #apiAtCache = {};
@@ -59,15 +59,15 @@ export class Dedot extends BaseSubstrateClient {
59
59
  * @param options
60
60
  */
61
61
  static async create(options) {
62
- return new Dedot(options).connect();
62
+ return new LegacyClient(options).connect();
63
63
  }
64
64
  /**
65
- * Alias for __Dedot.create__
65
+ * Alias for __LegacyClient.create__
66
66
  *
67
67
  * @param options
68
68
  */
69
69
  static async new(options) {
70
- return Dedot.create(options);
70
+ return LegacyClient.create(options);
71
71
  }
72
72
  onDisconnected = async () => {
73
73
  await this.#unsubscribeUpdates();
package/client/index.d.ts CHANGED
@@ -1,2 +1,2 @@
1
- export * from './Dedot.js';
1
+ export * from './LegacyClient.js';
2
2
  export * from './DedotClient.js';
package/client/index.js CHANGED
@@ -1,2 +1,2 @@
1
- export * from './Dedot.js';
1
+ export * from './LegacyClient.js';
2
2
  export * from './DedotClient.js';
@@ -32,13 +32,13 @@ export class StorageQueryExecutorV2 extends StorageQueryExecutor {
32
32
  }, {});
33
33
  }
34
34
  async subscribeStorage(keys, callback) {
35
- let initialHash = await this.chainHead.bestHash();
35
+ let best = await this.chainHead.bestBlock();
36
36
  let eventToListen = 'bestBlock';
37
37
  // TODO subscribe to finalized data source
38
38
  // initialHash = this.chainHead.finalizedHash;
39
39
  // eventToListen = 'finalizedBlock';
40
40
  const latestChanges = {};
41
- const pull = async (hash) => {
41
+ const pull = async ({ hash }) => {
42
42
  const results = await this.queryStorage(keys, hash);
43
43
  let changed = false;
44
44
  keys.forEach((key) => {
@@ -52,7 +52,7 @@ export class StorageQueryExecutorV2 extends StorageQueryExecutor {
52
52
  return;
53
53
  callback(keys.map((key) => latestChanges[key]));
54
54
  };
55
- await pull(initialHash);
55
+ await pull(best);
56
56
  const unsub = this.chainHead.on(eventToListen, pull);
57
57
  return async () => {
58
58
  unsub();
@@ -0,0 +1,13 @@
1
+ import { SignerPayloadJSON } from '@polkadot/types/types';
2
+ import { Hash } from '@dedot/codecs';
3
+ import { SignedExtension } from '../SignedExtension.js';
4
+ export type CheckMetadataHashMode = 'Disabled' | 'Enabled';
5
+ /**
6
+ * @description Genesis hash check to provide replay protection between different networks.
7
+ */
8
+ export declare class CheckMetadataHash extends SignedExtension<{
9
+ mode: CheckMetadataHashMode;
10
+ }, Hash | undefined> {
11
+ init(): Promise<void>;
12
+ toPayload(): Partial<SignerPayloadJSON>;
13
+ }
@@ -0,0 +1,27 @@
1
+ import { assert, isHex } from '@dedot/utils';
2
+ import { SignedExtension } from '../SignedExtension.js';
3
+ /**
4
+ * @description Genesis hash check to provide replay protection between different networks.
5
+ */
6
+ export class CheckMetadataHash extends SignedExtension {
7
+ async init() {
8
+ let metadataHash = this.payloadOptions.metadataHash;
9
+ if (metadataHash) {
10
+ assert(isHex(metadataHash), 'Metadata hash is not a valid hex string');
11
+ this.data = { mode: 'Enabled' };
12
+ this.additionalSigned = metadataHash;
13
+ }
14
+ else {
15
+ this.data = { mode: 'Disabled' };
16
+ this.additionalSigned = undefined;
17
+ }
18
+ }
19
+ toPayload() {
20
+ // Ref: https://github.com/paritytech/polkadot-sdk/blob/8dbe4ee80734bba6644c7e5f879a363ce7c0a19f/substrate/frame/metadata-hash-extension/src/lib.rs#L55-L58
21
+ let enabled = this.data.mode === 'Enabled';
22
+ return {
23
+ mode: enabled ? 1 : 0, // 0 -> disabled, 1 -> enabled
24
+ metadataHash: this.additionalSigned,
25
+ };
26
+ }
27
+ }
@@ -0,0 +1,6 @@
1
+ import { SignedExtension } from '../SignedExtension.js';
2
+ /**
3
+ * @description Storage weight reclaim mechanism.
4
+ */
5
+ export declare class StorageWeightReclaim extends SignedExtension {
6
+ }
@@ -0,0 +1,6 @@
1
+ import { SignedExtension } from '../SignedExtension.js';
2
+ /**
3
+ * @description Storage weight reclaim mechanism.
4
+ */
5
+ export class StorageWeightReclaim extends SignedExtension {
6
+ }
@@ -1,6 +1,7 @@
1
1
  import { ChargeAssetTxPayment } from './ChargeAssetTxPayment.js';
2
2
  import { ChargeTransactionPayment } from './ChargeTransactionPayment.js';
3
3
  import { CheckGenesis } from './CheckGenesis.js';
4
+ import { CheckMetadataHash } from './CheckMetadataHash.js';
4
5
  import { CheckMortality } from './CheckMortality.js';
5
6
  import { CheckNonZeroSender } from './CheckNonZeroSender.js';
6
7
  import { CheckNonce } from './CheckNonce.js';
@@ -8,6 +9,7 @@ import { CheckSpecVersion } from './CheckSpecVersion.js';
8
9
  import { CheckTxVersion } from './CheckTxVersion.js';
9
10
  import { CheckWeight } from './CheckWeight.js';
10
11
  import { PrevalidateAttests } from './PrevalidateAttests.js';
12
+ import { StorageWeightReclaim } from './StorageWeightReclaim.js';
11
13
  export const knownSignedExtensions = {
12
14
  CheckNonZeroSender,
13
15
  CheckSpecVersion,
@@ -19,4 +21,6 @@ export const knownSignedExtensions = {
19
21
  ChargeTransactionPayment,
20
22
  PrevalidateAttests,
21
23
  ChargeAssetTxPayment,
24
+ CheckMetadataHash,
25
+ StorageWeightReclaim,
22
26
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dedot/api",
3
- "version": "0.0.1-next.8d3b3cd0.51+8d3b3cd",
3
+ "version": "0.0.1-next.a5b1d2fb.22+a5b1d2f",
4
4
  "description": "A delightful JavaScript/TypeScript client for Polkadot & Substrate",
5
5
  "author": "Thang X. Vu <thang@coongcrafts.io>",
6
6
  "homepage": "https://github.com/dedotdev/dedot",
@@ -13,13 +13,13 @@
13
13
  "type": "module",
14
14
  "sideEffects": false,
15
15
  "dependencies": {
16
- "@dedot/codecs": "0.0.1-next.8d3b3cd0.51+8d3b3cd",
17
- "@dedot/providers": "0.0.1-next.8d3b3cd0.51+8d3b3cd",
18
- "@dedot/runtime-specs": "0.0.1-next.8d3b3cd0.51+8d3b3cd",
19
- "@dedot/shape": "0.0.1-next.8d3b3cd0.51+8d3b3cd",
20
- "@dedot/storage": "0.0.1-next.8d3b3cd0.51+8d3b3cd",
21
- "@dedot/types": "0.0.1-next.8d3b3cd0.51+8d3b3cd",
22
- "@dedot/utils": "0.0.1-next.8d3b3cd0.51+8d3b3cd"
16
+ "@dedot/codecs": "0.0.1-next.a5b1d2fb.22+a5b1d2f",
17
+ "@dedot/providers": "0.0.1-next.a5b1d2fb.22+a5b1d2f",
18
+ "@dedot/runtime-specs": "0.0.1-next.a5b1d2fb.22+a5b1d2f",
19
+ "@dedot/shape": "0.0.1-next.a5b1d2fb.22+a5b1d2f",
20
+ "@dedot/storage": "0.0.1-next.a5b1d2fb.22+a5b1d2f",
21
+ "@dedot/types": "0.0.1-next.a5b1d2fb.22+a5b1d2f",
22
+ "@dedot/utils": "0.0.1-next.a5b1d2fb.22+a5b1d2f"
23
23
  },
24
24
  "scripts": {
25
25
  "build": "tsc --project tsconfig.build.json && tsc --project tsconfig.build.cjs.json",
@@ -46,9 +46,9 @@
46
46
  },
47
47
  "license": "Apache-2.0",
48
48
  "devDependencies": {
49
- "@polkadot/types": "^11.0.2"
49
+ "@polkadot/types": "^11.3.1"
50
50
  },
51
- "gitHead": "8d3b3cd091a10b2d2c362b346cf29437610cd8cc",
51
+ "gitHead": "a5b1d2fbb14107e2e5bb9de229b2707d814a02e5",
52
52
  "module": "./index.js",
53
53
  "types": "./index.d.ts"
54
54
  }
package/proxychain.d.ts CHANGED
@@ -11,4 +11,4 @@ export interface Carrier<ChainApi extends GenericSubstrateApi> {
11
11
  * @param currentLevel
12
12
  * @param maxLevel
13
13
  */
14
- export declare const newProxyChain: <ChainApi extends GenericSubstrateApi<import("@dedot/types").RpcVersion>>(carrier: Carrier<ChainApi>, currentLevel?: number, maxLevel?: number) => unknown;
14
+ export declare const newProxyChain: <ChainApi extends GenericSubstrateApi>(carrier: Carrier<ChainApi>, currentLevel?: number, maxLevel?: number) => unknown;