dedot 0.0.1-alpha.3 → 0.0.1-alpha.31

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 (96) hide show
  1. package/README.md +293 -28
  2. package/cjs/client/Dedot.js +116 -76
  3. package/cjs/client/index.js +1 -1
  4. package/cjs/executor/ConstantExecutor.js +7 -9
  5. package/cjs/executor/ErrorExecutor.js +12 -13
  6. package/cjs/executor/EventExecutor.js +12 -13
  7. package/cjs/executor/Executor.js +15 -6
  8. package/cjs/executor/RpcExecutor.js +16 -24
  9. package/cjs/executor/RuntimeApiExecutor.js +51 -30
  10. package/cjs/executor/StorageQueryExecutor.js +34 -8
  11. package/cjs/executor/TxExecutor.js +26 -28
  12. package/cjs/executor/index.js +8 -8
  13. package/cjs/extrinsic/extensions/ExtraSignedExtension.js +13 -14
  14. package/cjs/extrinsic/extensions/SignedExtension.js +2 -2
  15. package/cjs/extrinsic/extensions/index.js +3 -3
  16. package/cjs/extrinsic/extensions/known/ChargeAssetTxPayment.js +6 -7
  17. package/cjs/extrinsic/extensions/known/ChargeTransactionPayment.js +4 -4
  18. package/cjs/extrinsic/extensions/known/CheckGenesis.js +2 -2
  19. package/cjs/extrinsic/extensions/known/CheckMortality.js +6 -7
  20. package/cjs/extrinsic/extensions/known/CheckNonZeroSender.js +2 -2
  21. package/cjs/extrinsic/extensions/known/CheckNonce.js +3 -4
  22. package/cjs/extrinsic/extensions/known/CheckSpecVersion.js +4 -4
  23. package/cjs/extrinsic/extensions/known/CheckTxVersion.js +4 -4
  24. package/cjs/extrinsic/extensions/known/CheckWeight.js +2 -2
  25. package/cjs/extrinsic/extensions/known/PrevalidateAttests.js +2 -2
  26. package/cjs/extrinsic/extensions/known/index.js +20 -20
  27. package/cjs/extrinsic/index.js +2 -2
  28. package/cjs/index.js +7 -9
  29. package/cjs/proxychain.js +7 -0
  30. package/cjs/storage/QueryableStorage.js +14 -15
  31. package/cjs/test.js +69 -0
  32. package/client/Dedot.d.ts +39 -19
  33. package/client/Dedot.js +109 -66
  34. package/client/index.d.ts +1 -1
  35. package/client/index.js +1 -1
  36. package/executor/ConstantExecutor.d.ts +2 -2
  37. package/executor/ConstantExecutor.js +5 -7
  38. package/executor/ErrorExecutor.d.ts +2 -2
  39. package/executor/ErrorExecutor.js +8 -9
  40. package/executor/EventExecutor.d.ts +2 -2
  41. package/executor/EventExecutor.js +8 -9
  42. package/executor/Executor.d.ts +6 -5
  43. package/executor/Executor.js +14 -5
  44. package/executor/RpcExecutor.d.ts +3 -3
  45. package/executor/RpcExecutor.js +15 -23
  46. package/executor/RuntimeApiExecutor.d.ts +13 -3
  47. package/executor/RuntimeApiExecutor.js +51 -30
  48. package/executor/StorageQueryExecutor.d.ts +3 -3
  49. package/executor/StorageQueryExecutor.js +32 -6
  50. package/executor/TxExecutor.d.ts +7 -7
  51. package/executor/TxExecutor.js +10 -12
  52. package/executor/index.d.ts +8 -8
  53. package/executor/index.js +8 -8
  54. package/extrinsic/extensions/ExtraSignedExtension.d.ts +1 -1
  55. package/extrinsic/extensions/ExtraSignedExtension.js +11 -12
  56. package/extrinsic/extensions/SignedExtension.d.ts +4 -4
  57. package/extrinsic/extensions/SignedExtension.js +2 -2
  58. package/extrinsic/extensions/index.d.ts +3 -3
  59. package/extrinsic/extensions/index.js +3 -3
  60. package/extrinsic/extensions/known/ChargeAssetTxPayment.d.ts +1 -1
  61. package/extrinsic/extensions/known/ChargeAssetTxPayment.js +5 -6
  62. package/extrinsic/extensions/known/ChargeTransactionPayment.d.ts +1 -1
  63. package/extrinsic/extensions/known/ChargeTransactionPayment.js +3 -3
  64. package/extrinsic/extensions/known/CheckGenesis.d.ts +1 -1
  65. package/extrinsic/extensions/known/CheckGenesis.js +1 -1
  66. package/extrinsic/extensions/known/CheckMortality.d.ts +1 -1
  67. package/extrinsic/extensions/known/CheckMortality.js +4 -5
  68. package/extrinsic/extensions/known/CheckNonZeroSender.d.ts +1 -1
  69. package/extrinsic/extensions/known/CheckNonZeroSender.js +1 -1
  70. package/extrinsic/extensions/known/CheckNonce.d.ts +1 -1
  71. package/extrinsic/extensions/known/CheckNonce.js +2 -3
  72. package/extrinsic/extensions/known/CheckSpecVersion.d.ts +1 -1
  73. package/extrinsic/extensions/known/CheckSpecVersion.js +2 -2
  74. package/extrinsic/extensions/known/CheckTxVersion.d.ts +1 -1
  75. package/extrinsic/extensions/known/CheckTxVersion.js +2 -2
  76. package/extrinsic/extensions/known/CheckWeight.d.ts +1 -1
  77. package/extrinsic/extensions/known/CheckWeight.js +1 -1
  78. package/extrinsic/extensions/known/PrevalidateAttests.d.ts +1 -1
  79. package/extrinsic/extensions/known/PrevalidateAttests.js +1 -1
  80. package/extrinsic/extensions/known/index.d.ts +1 -1
  81. package/extrinsic/extensions/known/index.js +10 -10
  82. package/extrinsic/index.d.ts +2 -2
  83. package/extrinsic/index.js +2 -2
  84. package/index.d.ts +5 -6
  85. package/index.js +4 -5
  86. package/package.json +11 -12
  87. package/proxychain.d.ts +8 -1
  88. package/proxychain.js +7 -0
  89. package/storage/QueryableStorage.d.ts +3 -3
  90. package/storage/QueryableStorage.js +10 -11
  91. package/test.d.ts +1 -0
  92. package/test.js +67 -0
  93. package/types.d.ts +22 -4
  94. package/cjs/packageInfo.js +0 -5
  95. package/packageInfo.d.ts +0 -4
  96. package/packageInfo.js +0 -2
package/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # dedot
2
2
 
3
- A fast & lightweight JavaScript/TypeScript client for [Polkadot](https://polkadot.network/) & [Substrate](https://substrate.io/)
3
+ A delightful JavaScript/TypeScript client for [Polkadot](https://polkadot.network/) & [Substrate](https://substrate.io/)
4
4
 
5
5
  <p align="left">
6
6
  <img src="https://img.shields.io/github/license/dedotdev/dedot?style=flat-square"/>
@@ -11,6 +11,16 @@ A fast & lightweight JavaScript/TypeScript client for [Polkadot](https://polkado
11
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
12
 
13
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
+ - ⏳ Use the new JSON-RPC APIs ([v2](https://paritytech.github.io/json-rpc-interface-spec/introduction.html))
22
+ - ✅ Support Metadata V14, V15 (latest)
23
+
14
24
  ### Have a quick taste
15
25
 
16
26
  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.
@@ -46,8 +56,7 @@ const run = async () => {
46
56
  console.log('Metadata:', metadata);
47
57
 
48
58
  // Query on-chain storage
49
- const address = '14...';
50
- const balance = await api.query.system.account(address);
59
+ const balance = await api.query.system.account(<address>);
51
60
  console.log('Balance:', balance);
52
61
 
53
62
 
@@ -58,7 +67,11 @@ const run = async () => {
58
67
 
59
68
  // Get pallet constants
60
69
  const ss58Prefix = api.consts.system.ss58Prefix;
61
- console.log('Polkadot ss58Prefix:', ss58Prefix)
70
+ console.log('Polkadot ss58Prefix:', ss58Prefix);
71
+
72
+ // Call runtime api
73
+ const pendingRewards = await api.call.nominationPoolsApi.pendingRewards(<address>)
74
+ console.log('Pending rewards:', pendingRewards);
62
75
 
63
76
  // await unsub();
64
77
  // await api.disconnect();
@@ -80,27 +93,29 @@ const api = await Dedot.new('wss://rpc.polkadot.io');
80
93
  - [Execute RPC Methods](#execute-rpc-methods)
81
94
  - [Query On-chain Storage](#query-on-chain-storage)
82
95
  - [Constants](#constants)
83
- - [Runtime APIs](#runtime-apis)
84
- - [Submit Transactions](#submit-transactions)
96
+ - [Runtime APIs](#runtime-apis)
97
+ - [Submit Transactions](#transaction-apis)
85
98
  - [Events](#events)
86
99
  - [Errors](#errors)
100
+ - [`@polkadot/api` -> `dedot`](#migration-from-polkadotapi-to-dedot)
87
101
  - [Credit](#credit)
88
102
 
89
103
  ### Status
90
104
 
91
- | Feature | Status |
92
- |-------------------------------------------------------| ----------- |
93
- | Execute RPC (`api.rpc`) | ✅ |
94
- | Query on-chain storage (`api.query`) | ✅ |
95
- | Get runtime constants (`api.consts`) | ✅ |
96
- | Runtime APIs (`api.call`) | |
97
- | Transaction APIs (`api.tx`) | |
98
- | Events (`api.events`) | ✅ |
99
- | Errors (`api.errors`) | ✅ |
100
- | Contract APIs | ⏳ |
101
- | Metadata v14 | ✅ |
102
- | Metadata v15 | ✅ |
103
- | [RPC v2](https://github.com/dedotdev/dedot/issues/20) | ⏳ |
105
+ | Feature | Status |
106
+ |-------------------------------------------------------------|--------|
107
+ | Execute RPC (`api.rpc`) | ✅ |
108
+ | Query On-chain Storage (`api.query`) | ✅ |
109
+ | Get runtime constants (`api.consts`) | ✅ |
110
+ | Runtime APIs (`api.call`) | |
111
+ | Transaction APIs (`api.tx`) | |
112
+ | Events (`api.events`) | ✅ |
113
+ | Errors (`api.errors`) | ✅ |
114
+ | Contract APIs | ⏳ |
115
+ | Metadata v14 | ✅ |
116
+ | Metadata v15 | ✅ |
117
+ | [RPC v2](https://github.com/dedotdev/dedot/issues/20) | ⏳ |
118
+ | [Extrinsic V5](https://github.com/dedotdev/dedot/issues/55) | ⏳ |
104
119
 
105
120
  ### Chain Types & APIs
106
121
 
@@ -139,11 +154,22 @@ const genericApi = await Dedot.new('ws://localhost:9944');
139
154
  // ...
140
155
  ```
141
156
 
142
- In alpha test version, we only support `ChainApi` interfaces for 4 networks (Polkadot, Kusama, Moonbeam & Astar), we plan to expand this list to support more Substrate-based blockchains in the near future.
157
+ 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`.
158
+
159
+ ```shell
160
+ # Install @dedot/cli via yarn
161
+ yarn add -D @dedot/cli
162
+
163
+ # Or via npm
164
+ npm i -D @dedot/cli
165
+
166
+ # Generate ChainApi interface for Polkadot network via rpc endpoint: wss://rpc.polkadot.io
167
+ npx dedot chaintypes -w wss://rpc.polkadot.io
168
+ ```
143
169
 
144
170
  ### Execute RPC Methods
145
171
 
146
- RPCs can be execute 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.ts), similarly for other networks as well.
172
+ 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.
147
173
 
148
174
  Examples:
149
175
  ```typescript
@@ -156,7 +182,7 @@ const result = await api.rpc.module.rpc_name('param1', 'param2');
156
182
 
157
183
  ### Query On-chain Storage
158
184
 
159
- On-chain storage can be query 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 execute 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.ts), similarly for other networks as well.
185
+ 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.
160
186
 
161
187
  Examples:
162
188
  ```typescript
@@ -168,7 +194,7 @@ const events = await api.query.system.events();
168
194
  ```
169
195
  ### Constants
170
196
 
171
- Runtime constants (parameter types) are defined in metadata, and can be inspect 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.ts), similarly for other networks.
197
+ 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.
172
198
 
173
199
  Examples:
174
200
  ```typescript
@@ -181,15 +207,174 @@ const existentialDeposit = api.consts.balances.existentialDeposit;
181
207
 
182
208
  ### Runtime APIs
183
209
 
184
- _coming soon_
210
+ 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.
211
+
212
+ Examples:
213
+ ```typescript
214
+ // Get account nonce
215
+ const nonce = await api.call.accountNonceApi.accountNonce(<address>);
216
+
217
+ // Query transaction payment info
218
+ const tx = api.tx.balances.transferKeepAlive(<address>, 2_000_000_000_000n);
219
+ const queryInfo = await api.call.transactionPaymentApi.queryInfo(tx.toU8a(), tx.length);
220
+
221
+ // Get runtime version
222
+ const runtimeVersion = await api.call.core.version();
223
+ ```
224
+
225
+ 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/specs`](https://github.com/dedotdev/dedot/blob/60de0fed8ba19c67a7e174c6168a127fdbf6caef/packages/specs/src/runtime/all.ts#L21-L39) package.
226
+
227
+ Examples:
228
+ ```typescript
229
+ import { RuntimeApis } from '@dedot/specs';
230
+ const api = await Dedot.new({ endpoint: 'wss://rpc.mynetwork.com', runtimeApis: RuntimeApis });
231
+
232
+ // Or bring in only the Runtime Api definition that you want to interact with
233
+ import { AccountNonceApi } from '@dedot/specs';
234
+ const api = await Dedot.new({ endpoint: 'wss://rpc.mynetwork.com', runtimeApis: { AccountNonceApi } });
235
+
236
+ // Get account nonce
237
+ const nonce = await api.call.accountNonceApi.accountNonce(<address>);
238
+ ```
239
+
240
+ 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/specs/src/runtime/all.ts#L21-L39).
241
+
242
+ ### Transaction APIs
243
+
244
+ 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.
245
+
246
+ 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.
247
+
248
+ Example 1: Sign transaction with a Keying account
249
+ ```typescript
250
+ import { cryptoWaitReady } from '@polkadot/util-crypto';
251
+ import { Keyring } from '@polkadot/keyring';
252
+ ...
253
+ await cryptoWaitReady();
254
+ const keyring = new Keyring({ type: 'sr25519' });
255
+ const alice = keyring.addFromUri('//Alice');
256
+
257
+ const unsub = await api.tx.balances
258
+ .transferKeepAlive(<destAddress>, 2_000_000_000_000n)
259
+ .signAndSend(alice, async ({ status }) => {
260
+ console.log('Transaction status', status.tag);
261
+ if (status.tag === 'InBlock') {
262
+ console.log(`Transaction completed at block hash ${status.value}`);
263
+ await unsub();
264
+ }
265
+ });
266
+ ```
267
+
268
+ Example 2: Sign transaction using `Signer` from Polkadot{.js} wallet extension
269
+ ```typescript
270
+ const injected = await window.injectedWeb3['polkadot-js'].enable('A cool dapp');
271
+ const account = (await injected.accounts.get())[0];
272
+ const signer = injected.signer;
273
+
274
+ const unsub = await api.tx.balances
275
+ .transferKeepAlive(<destAddress>, 2_000_000_000_000n)
276
+ .signAndSend(account.address, { signer }, async ({ status }) => {
277
+ console.log('Transaction status', status.tag);
278
+ if (status.tag === 'InBlock') {
279
+ console.log(`Transaction completed at block hash ${status.value}`);
280
+ await unsub();
281
+ }
282
+ });
283
+ ```
284
+
285
+ Example 3: Submit a batch transaction
286
+ ```typescript
287
+ import type { PolkadotRuntimeRuntimeCallLike } from '@dedot/chaintypes/polkadot';
288
+
289
+ // Omit the detail for simplicity
290
+ const account = ...;
291
+ const signer = ...;
292
+
293
+ const transferTx = api.tx.balances.transferKeepAlive(<destAddress>, 2_000_000_000_000n);
294
+ const remarkCall: PolkadotRuntimeRuntimeCallLike = {
295
+ pallet: 'System',
296
+ palletCall: {
297
+ name: 'RemarkWithEvent',
298
+ params: {
299
+ remark: 'Hello Dedot!',
300
+ },
301
+ },
302
+ };
303
+
304
+ const unsub = api.tx.utility.batch([transferTx.call, remarkCall])
305
+ .signAndSend(account.address, { signer }, async ({ status }) => {
306
+ console.log('Transaction status', status.tag);
307
+ if (status.tag === 'InBlock') {
308
+ console.log(`Transaction completed at block hash ${status.value}`);
309
+ await unsub();
310
+ }
311
+ });
312
+ ```
185
313
 
186
- ### Submit Transactions
314
+ <details>
315
+ <summary>Example 4: Teleport WND from Westend Asset Hub to Westend via XCM</summary>
316
+
317
+ ```typescript
318
+ import { WestendAssetHubApi, XcmVersionedLocation, XcmVersionedAssets, XcmV3WeightLimit } from '@dedot/chaintypes/westendAssetHub';
319
+ import { AccountId32 } from '@dedot/codecs';
320
+
321
+ const TWO_TOKENS = 2_000_000_000_000n;
322
+ const destAddress = <bobAddress>;
323
+
324
+ const api = await Dedot.new<WestendAssetHubApi>('...westend-assethub-rpc...');
325
+
326
+ const dest: XcmVersionedLocation = {
327
+ tag: 'V3',
328
+ value: { parents: 1, interior: { tag: 'Here' } },
329
+ };
330
+
331
+ const beneficiary: XcmVersionedLocation = {
332
+ tag: 'V3',
333
+ value: {
334
+ parents: 0,
335
+ interior: {
336
+ tag: 'X1',
337
+ value: {
338
+ tag: 'AccountId32',
339
+ value: { id: new AccountId32(destAddress).raw },
340
+ },
341
+ },
342
+ },
343
+ };
344
+
345
+ const assets: XcmVersionedAssets = {
346
+ tag: 'V3',
347
+ value: [
348
+ {
349
+ id: {
350
+ tag: 'Concrete',
351
+ value: {
352
+ parents: 1,
353
+ interior: { tag: 'Here' },
354
+ },
355
+ },
356
+ fun: {
357
+ tag: 'Fungible',
358
+ value: TWO_TOKENS,
359
+ },
360
+ },
361
+ ],
362
+ };
363
+
364
+ const weight: XcmV3WeightLimit = { tag: 'Unlimited' };
365
+
366
+ api.tx.polkadotXcm
367
+ .limitedTeleportAssets(dest, beneficiary, assets, 0, weight)
368
+ .signAndSend(alice, { signer, tip: 1_000_000n }, (result) => {
369
+ console.dir(result, { depth: null });
370
+ });
371
+ ```
372
+ </details>
187
373
 
188
- ⏳ _coming soon_
189
374
 
190
375
  ### Events
191
376
 
192
- 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.ts), similarly for other network as well.
377
+ 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.
193
378
 
194
379
  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.
195
380
 
@@ -213,7 +398,7 @@ await api.query.system.events(async (eventRecords) => {
213
398
 
214
399
  ### Errors
215
400
 
216
- 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.ts).
401
+ 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).
217
402
 
218
403
  Similar to events API, this API is helpful when we want to check if an error maches with an error that we're expecting.
219
404
 
@@ -235,6 +420,86 @@ await api.query.system.events(async (eventRecords) => {
235
420
  // ...
236
421
  ```
237
422
 
423
+ ### Migration from `@polkadot/api` to `dedot`
424
+ `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.
425
+
426
+ While the api style are similar, but there're also some differences you might need to be aware of when switching to use `dedot`.
427
+
428
+ **Initialize api client**
429
+ - `@polkadot/api`
430
+ ```typescript
431
+ import { ApiPromise, WsProvider } from '@polkadot/api';
432
+
433
+ const api = await ApiPromise.create({ provider: new WsProvider('wss://rpc.polkadot.io') });
434
+ ```
435
+ - `dedot`
436
+ ```typescript
437
+ import { Dedot } from 'dedot';
438
+ import type { PolkadotApi } from '@dedot/chaintypes';
439
+
440
+ const api = await Dedot.new<PolkadotApi>('wss://rpc.polkadot.io'); // or Dedot.create(...) if you prefer
441
+
442
+ // OR you want to have a custom provider
443
+ import { WsProvider } from 'dedot'
444
+ const api = await Dedot.new<PolkadotApi>({ provider: new WsProvider('wss://rpc.polkadot.io') });
445
+ ```
446
+
447
+ - Notes:
448
+ - Under the hood, a `WsProvider` will be created if you initialize `Dedot` directly with an rpc endpoint.
449
+ - `dedot` only supports provider can make subscription request (e.g: via Websocket).
450
+ - 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.
451
+
452
+ **Type system**
453
+
454
+ 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`:
455
+
456
+
457
+ | Scale Codec | TypeScript (`dedot`) |
458
+ |---------------------------------------------------------|--------------------------------------------------------------------------------------------------------------------------------|
459
+ | `u8`, `u16`, `u32`, `i8`, `i16`, `i32` | `number` |
460
+ | `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) |
461
+ | `bool` | `boolean` (true, false) |
462
+ | `Option<T>` | `T \| undefined` |
463
+ | `Result<Ok, Err>` | `{ isOk: true; isErr?: false; value: Ok } \| { isOk?: false; isErr: true; err: Err }` |
464
+ | `Vec<T>` | `Array<T>` |
465
+ | `str` | `string` |
466
+ | Tuple: `(A, B)`, `()` | `[A, B]`, `[]` |
467
+ | Struct: `struct { field_1: u8, field_2: str }` | `{ field_1: number, field_2: string}` |
468
+ | Enum: `enum { Variant1(u8), Variant2(bool), Variant3 }` | `{ tag: 'Variant1', value: number } \| { tag: 'Variant2', value: boolean } \| { tag: 'Variant2' }` |
469
+ | FlatEnum: `enum { Variant1, Variant2 }` | `'Variant1' \| 'Variant2'` |
470
+
471
+ E.g 1:
472
+ ```typescript
473
+ const runtimeVersion = api.consts.system.version;
474
+
475
+ // @polkadot/api
476
+ const specName: string = runtimeVersion.toJSON().specName; // OR runtimeVersion.specName.toString()
477
+
478
+ // dedot
479
+ const specName: string = runtimeVersion.specName;
480
+ ```
481
+
482
+ E.g 2:
483
+ ```typescript
484
+ const balance = await api.query.system.account(<address>);
485
+
486
+ // @polkadot/api
487
+ const freeBalance: bigint = balance.data.free.toBigInt();
488
+
489
+ // dedot
490
+ const freeBalance: bigint = balance.data.free;
491
+ ```
492
+
493
+ E.g 3:
494
+ ```typescript
495
+ // @polkadot/api
496
+ const proposalBondMaximum: bigint | undefined = api.consts.treasury.proposalBondMaximum.unwrapOr(undefined)?.toBigInt();
497
+
498
+ // dedot
499
+ const proposalBondMaximum: bigint | undefined = api.consts.treasury.proposalBondMaximum;
500
+ ```
501
+
502
+
238
503
  ### Credit
239
504
 
240
505
  `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.