dedot 0.0.1-alpha.4 → 0.0.1-alpha.41

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 (119) hide show
  1. package/README.md +312 -53
  2. package/bin/dedot +3 -0
  3. package/chaintypes/index.d.ts +1 -0
  4. package/chaintypes/index.js +1 -0
  5. package/cjs/{extrinsic → chaintypes}/index.js +1 -2
  6. package/cjs/{extrinsic/extensions → codecs}/index.js +1 -3
  7. package/cjs/{executor → contracts}/index.js +1 -8
  8. package/cjs/index.js +16 -9
  9. package/cjs/runtime-specs/index.js +17 -0
  10. package/cjs/{client → shape}/index.js +1 -1
  11. package/cjs/types/index.js +17 -0
  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 +3 -6
  19. package/index.js +3 -5
  20. package/package.json +78 -34
  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/cjs/client/Dedot.js +0 -447
  32. package/cjs/executor/ConstantExecutor.js +0 -22
  33. package/cjs/executor/ErrorExecutor.js +0 -47
  34. package/cjs/executor/EventExecutor.js +0 -53
  35. package/cjs/executor/Executor.js +0 -39
  36. package/cjs/executor/RpcExecutor.js +0 -109
  37. package/cjs/executor/RuntimeApiExecutor.js +0 -93
  38. package/cjs/executor/StorageQueryExecutor.js +0 -33
  39. package/cjs/executor/TxExecutor.js +0 -153
  40. package/cjs/extrinsic/SubmittableResult.js +0 -33
  41. package/cjs/extrinsic/extensions/ExtraSignedExtension.js +0 -88
  42. package/cjs/extrinsic/extensions/SignedExtension.js +0 -41
  43. package/cjs/extrinsic/extensions/known/ChargeAssetTxPayment.js +0 -44
  44. package/cjs/extrinsic/extensions/known/ChargeTransactionPayment.js +0 -16
  45. package/cjs/extrinsic/extensions/known/CheckGenesis.js +0 -19
  46. package/cjs/extrinsic/extensions/known/CheckMortality.js +0 -71
  47. package/cjs/extrinsic/extensions/known/CheckNonZeroSender.js +0 -10
  48. package/cjs/extrinsic/extensions/known/CheckNonce.js +0 -34
  49. package/cjs/extrinsic/extensions/known/CheckSpecVersion.js +0 -19
  50. package/cjs/extrinsic/extensions/known/CheckTxVersion.js +0 -19
  51. package/cjs/extrinsic/extensions/known/CheckWeight.js +0 -10
  52. package/cjs/extrinsic/extensions/known/PrevalidateAttests.js +0 -11
  53. package/cjs/extrinsic/extensions/known/index.js +0 -25
  54. package/cjs/packageInfo.js +0 -5
  55. package/cjs/proxychain.js +0 -20
  56. package/cjs/storage/QueryableStorage.js +0 -99
  57. package/cjs/types.js +0 -2
  58. package/client/Dedot.d.ts +0 -181
  59. package/client/Dedot.js +0 -440
  60. package/client/index.d.ts +0 -1
  61. package/client/index.js +0 -1
  62. package/executor/ConstantExecutor.d.ts +0 -11
  63. package/executor/ConstantExecutor.js +0 -18
  64. package/executor/ErrorExecutor.d.ts +0 -11
  65. package/executor/ErrorExecutor.js +0 -43
  66. package/executor/EventExecutor.d.ts +0 -11
  67. package/executor/EventExecutor.js +0 -49
  68. package/executor/Executor.d.ts +0 -150
  69. package/executor/Executor.js +0 -35
  70. package/executor/RpcExecutor.d.ts +0 -14
  71. package/executor/RpcExecutor.js +0 -105
  72. package/executor/RuntimeApiExecutor.d.ts +0 -9
  73. package/executor/RuntimeApiExecutor.js +0 -89
  74. package/executor/StorageQueryExecutor.d.ts +0 -10
  75. package/executor/StorageQueryExecutor.js +0 -29
  76. package/executor/TxExecutor.d.ts +0 -47
  77. package/executor/TxExecutor.js +0 -147
  78. package/executor/index.d.ts +0 -8
  79. package/executor/index.js +0 -8
  80. package/extrinsic/SubmittableResult.d.ts +0 -19
  81. package/extrinsic/SubmittableResult.js +0 -29
  82. package/extrinsic/extensions/ExtraSignedExtension.d.ts +0 -14
  83. package/extrinsic/extensions/ExtraSignedExtension.js +0 -61
  84. package/extrinsic/extensions/SignedExtension.d.ts +0 -40
  85. package/extrinsic/extensions/SignedExtension.js +0 -37
  86. package/extrinsic/extensions/index.d.ts +0 -3
  87. package/extrinsic/extensions/index.js +0 -3
  88. package/extrinsic/extensions/known/ChargeAssetTxPayment.d.ts +0 -14
  89. package/extrinsic/extensions/known/ChargeAssetTxPayment.js +0 -40
  90. package/extrinsic/extensions/known/ChargeTransactionPayment.d.ts +0 -6
  91. package/extrinsic/extensions/known/ChargeTransactionPayment.js +0 -12
  92. package/extrinsic/extensions/known/CheckGenesis.d.ts +0 -10
  93. package/extrinsic/extensions/known/CheckGenesis.js +0 -15
  94. package/extrinsic/extensions/known/CheckMortality.d.ts +0 -15
  95. package/extrinsic/extensions/known/CheckMortality.js +0 -67
  96. package/extrinsic/extensions/known/CheckNonZeroSender.d.ts +0 -6
  97. package/extrinsic/extensions/known/CheckNonZeroSender.js +0 -6
  98. package/extrinsic/extensions/known/CheckNonce.d.ts +0 -10
  99. package/extrinsic/extensions/known/CheckNonce.js +0 -30
  100. package/extrinsic/extensions/known/CheckSpecVersion.d.ts +0 -9
  101. package/extrinsic/extensions/known/CheckSpecVersion.js +0 -15
  102. package/extrinsic/extensions/known/CheckTxVersion.d.ts +0 -9
  103. package/extrinsic/extensions/known/CheckTxVersion.js +0 -15
  104. package/extrinsic/extensions/known/CheckWeight.d.ts +0 -6
  105. package/extrinsic/extensions/known/CheckWeight.js +0 -6
  106. package/extrinsic/extensions/known/PrevalidateAttests.d.ts +0 -7
  107. package/extrinsic/extensions/known/PrevalidateAttests.js +0 -7
  108. package/extrinsic/extensions/known/index.d.ts +0 -3
  109. package/extrinsic/extensions/known/index.js +0 -22
  110. package/extrinsic/index.d.ts +0 -2
  111. package/extrinsic/index.js +0 -2
  112. package/packageInfo.d.ts +0 -4
  113. package/packageInfo.js +0 -2
  114. package/proxychain.d.ts +0 -7
  115. package/proxychain.js +0 -16
  116. package/storage/QueryableStorage.d.ts +0 -16
  117. package/storage/QueryableStorage.js +0 -95
  118. package/types.d.ts +0 -44
  119. package/types.js +0 -1
package/README.md CHANGED
@@ -1,53 +1,68 @@
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"/>
7
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/actions/workflow/status/dedotdev/dedot/zombienet-tests.yml?label=e2e%20tests&style=flat-square"/>
8
9
  <img src="https://img.shields.io/github/package-json/v/dedotdev/dedot?filename=packages%2Fapi%2Fpackage.json&style=flat-square"/>
9
10
  </p>
10
11
 
11
12
  _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
 
13
14
  ---
15
+ ### Features
16
+ - ✅ Small bundle size, tree-shakable (no more bn.js or wasm-blob tight dependencies)
17
+ - ✅ Built-in metadata caching mechanism
18
+ - ✅ Types & APIs suggestions for each individual Substrate-based blockchain network ([@dedot/chaintypes](https://github.com/dedotdev/chaintypes))
19
+ - ✅ Familiar api style with `@polkadot/api`, easy & fast migration!
20
+ - ✅ Native TypeScript type system for scale-codec
21
+ - ✅ Compatible with `@polkadot/extension`-based wallets
22
+ - ✅ Support Metadata V14, V15 (latest)
23
+ - ✅ Build on top of both the [new](https://paritytech.github.io/json-rpc-interface-spec/introduction.html) & legacy (deprecated soon) JSON-RPC APIs
24
+ - ✅ Support light clients (e.g: [smoldot](https://www.npmjs.com/package/smoldot)) (_docs coming soon_)
25
+ - ✅ Typed Contract APIs (_docs coming soon_)
26
+ - ✅ Fully-typed low-level JSON-RPC client (_docs coming soon_)
27
+ - ⏳ [Compact Metadata](https://github.com/dedotdev/dedot/issues/45)
28
+
14
29
  ### Have a quick taste
15
30
 
16
31
  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.
17
32
  - Install `dedot` package
18
33
  ```shell
19
34
  # via yarn
20
- yarn add dedot
35
+ yarn add dedot@latest
21
36
 
22
37
  # via npm
23
- npm i dedot
38
+ npm i dedot@latest
24
39
  ```
25
40
 
26
41
  - Install `@dedot/chaintypes` package for chain types & APIs suggestion. Skip this step if you don't use TypeScript.
27
42
  ```shell
28
43
  # via yarn
29
- yarn add -D @dedot/chaintypes
44
+ yarn add -D @dedot/chaintypes@latest
30
45
 
31
46
  # via npm
32
- npm i -D @dedot/chaintypes
47
+ npm i -D @dedot/chaintypes@latest
33
48
  ```
34
49
 
35
50
  - Initialize the API client and start interacting with Polkadot network
36
51
  ```typescript
37
52
  // main.ts
38
- import { Dedot } from 'dedot';
53
+ import { DedotClient, WsProvider } from 'dedot';
39
54
  import type { PolkadotApi } from '@dedot/chaintypes';
40
55
 
41
56
  const run = async () => {
42
- const api = await Dedot.new<PolkadotApi>('wss://rpc.polkadot.io');
57
+ const provider = new WsProvider('wss://rpc.polkadot.io');
58
+ const api = await DedotClient.new<PolkadotApi>(provider);
43
59
 
44
60
  // Call rpc `state_getMetadata` to fetch raw scale-encoded metadata and decode it.
45
- const metadata = await api.rpc.state.getMetadata();
61
+ const metadata = await api.rpc.state_getMetadata();
46
62
  console.log('Metadata:', metadata);
47
63
 
48
64
  // Query on-chain storage
49
- const address = '14...';
50
- const balance = await api.query.system.account(address);
65
+ const balance = await api.query.system.account(<address>);
51
66
  console.log('Balance:', balance);
52
67
 
53
68
 
@@ -58,7 +73,11 @@ const run = async () => {
58
73
 
59
74
  // Get pallet constants
60
75
  const ss58Prefix = api.consts.system.ss58Prefix;
61
- console.log('Polkadot ss58Prefix:', ss58Prefix)
76
+ console.log('Polkadot ss58Prefix:', ss58Prefix);
77
+
78
+ // Call runtime api
79
+ const pendingRewards = await api.call.nominationPoolsApi.pendingRewards(<address>)
80
+ console.log('Pending rewards:', pendingRewards);
62
81
 
63
82
  // await unsub();
64
83
  // await api.disconnect();
@@ -70,93 +89,94 @@ run().catch(console.error);
70
89
 
71
90
  ```js
72
91
  // main.js
73
- const { Dedot } = require('dedot');
92
+ const { DedotClient, WsProvider } = require('dedot');
74
93
  // ...
75
- const api = await Dedot.new('wss://rpc.polkadot.io');
94
+ const provider = new WsProvider('wss://rpc.polkadot.io');
95
+ const api = await DedotClient.new(provider);
96
+ ```
97
+
98
+ - If the JSON-RPC server doesn't support [new](https://paritytech.github.io/json-rpc-interface-spec/introduction.html) JSON-RPC APIs yet, you can connect using the `LegacyClient` which build on top of the legacy JSON-RPC APIs.
99
+ ```typescript
100
+ import { LegacyClient, WsProvider } from 'dedot';
101
+
102
+ const provider = new WsProvider('wss://rpc.polkadot.io');
103
+ const api = await LegacyClient.new(provider);
76
104
  ```
105
+
77
106
  ### Table of contents
78
107
  - [Status](#status)
79
108
  - [Chain Types & APIs](#chain-types--apis)
80
109
  - [Execute RPC Methods](#execute-rpc-methods)
81
110
  - [Query On-chain Storage](#query-on-chain-storage)
82
111
  - [Constants](#constants)
83
- - [Runtime APIs](#runtime-apis)
84
- - [Submit Transactions](#submit-transactions)
112
+ - [Runtime APIs](#runtime-apis)
113
+ - [Submit Transactions](#transaction-apis)
85
114
  - [Events](#events)
86
115
  - [Errors](#errors)
116
+ - [`@polkadot/api` -> `dedot`](#migration-from-polkadotapi-to-dedot)
87
117
  - [Credit](#credit)
88
118
 
89
- ### Status
90
-
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) | ⏳ |
104
-
105
119
  ### Chain Types & APIs
106
120
 
107
121
  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.
108
122
 
109
- Types & APIs for each Substrate-based blockchains are defined in package [`@dedot/chaintypes`](https://github.com/dedotdev/dedot/tree/main/packages/chaintypes):
123
+ Types & APIs for each Substrate-based blockchains are defined in package [`@dedot/chaintypes`](https://github.com/dedotdev/chaintypes):
110
124
  ```shell
111
125
  # via yarn
112
- yarn add -D @dedot/chaintypes
126
+ yarn add -D @dedot/chaintypes@latest
113
127
 
114
128
  # via npm
115
- npm i -D @dedot/chaintypes
129
+ npm i -D @dedot/chaintypes@latest
116
130
  ```
117
131
 
118
- Initialize a `Dedot` instance using the `ChainApi` interface for a target chain to enable types & APIs suggestion/autocompletion for that particular chain:
132
+ Initialize a `DedotClient` instance using the `ChainApi` interface for a target chain to enable types & APIs suggestion/autocompletion for that particular chain:
133
+
119
134
  ```typescript
120
- import { Dedot } from 'dedot';
135
+ import { DedotClient, WsProvider } from 'dedot';
121
136
  import type { PolkadotApi, KusamaApi, MoonbeamApi, AstarApi } from '@dedot/chaintypes';
122
137
 
123
138
  // ...
124
139
 
125
- const polkadotApi = await Dedot.new<PolkadotApi>('wss://rpc.polkadot.io');
140
+ const polkadotApi = await DedotClient.new<PolkadotApi>(new WsProvider('wss://rpc.polkadot.io'));
126
141
  console.log(await polkadotApi.query.babe.authorities());
127
142
 
128
- const kusamaApi = await Dedot.new<KusamaApi>('wss://kusama-rpc.polkadot.io');
143
+ const kusamaApi = await DedotClient.new<KusamaApi>(new WsProvider('wss://kusama-rpc.polkadot.io'));
129
144
  console.log(await kusamaApi.query.society.memberCount());
130
145
 
131
- const moonbeamApi = await Dedot.new<MoonbeamApi>('wss://wss.api.moonbeam.network');
146
+ const moonbeamApi = await DedotClient.new<MoonbeamApi>(new WsProvider('wss://wss.api.moonbeam.network'));
132
147
  console.log(await moonbeamApi.query.ethereumChainId.chainId());
133
148
 
134
- const astarApi = await Dedot.new<AstarApi>('wss://rpc.astar.network');
149
+ const astarApi = await DedotClient.new<AstarApi>(new WsProvider('wss://rpc.astar.network'));
135
150
  console.log(await astarApi.query.dappsStaking.blockRewardAccumulator());
136
151
 
137
- const genericApi = await Dedot.new('ws://localhost:9944');
152
+ const genericApi = await DedotClient.new(new WsProvider('ws://localhost:9944'));
138
153
 
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/chaintypes/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
+ # Generate ChainApi interface for Polkadot network via rpc endpoint: wss://rpc.polkadot.io
161
+ npx dedot chaintypes -w wss://rpc.polkadot.io
162
+ ```
143
163
 
144
164
  ### Execute RPC Methods
145
165
 
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.
166
+ 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.method_name(param1, param2, ...)`. E.g: you can find all supported RPC methods for Polkadot network [here](https://github.com/dedotdev/chaintypes/blob/main/packages/chaintypes/src/polkadot/json-rpc.d.ts), similarly for other networks as well.
147
167
 
148
168
  Examples:
149
169
  ```typescript
150
170
  // Call rpc: `state_getMetadata`
151
- const metadata = await api.rpc.state.getMetadata();
171
+ const metadata = await api.rpc.state_getMetadata();
152
172
 
153
173
  // Call an arbitrary rpc: `module_rpc_name` with arguments ['param1', 'param2']
154
- const result = await api.rpc.module.rpc_name('param1', 'param2');
174
+ const result = await api.rpc.module_rpc_name('param1', 'param2');
155
175
  ```
156
176
 
157
177
  ### Query On-chain Storage
158
178
 
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.
179
+ 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/chaintypes/blob/main/packages/chaintypes/src/polkadot/query.d.ts), similarly for other networks as well.
160
180
 
161
181
  Examples:
162
182
  ```typescript
@@ -168,7 +188,7 @@ const events = await api.query.system.events();
168
188
  ```
169
189
  ### Constants
170
190
 
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.
191
+ 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/chaintypes/blob/main/packages/chaintypes/src/polkadot/consts.d.ts), similarly for other networks.
172
192
 
173
193
  Examples:
174
194
  ```typescript
@@ -181,15 +201,174 @@ const existentialDeposit = api.consts.balances.existentialDeposit;
181
201
 
182
202
  ### Runtime APIs
183
203
 
184
- _coming soon_
204
+ 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/chaintypes/blob/main/packages/chaintypes/src/polkadot/runtime.d.ts), similarly for other networks as well.
205
+
206
+ Examples:
207
+ ```typescript
208
+ // Get account nonce
209
+ const nonce = await api.call.accountNonceApi.accountNonce(<address>);
210
+
211
+ // Query transaction payment info
212
+ const tx = api.tx.balances.transferKeepAlive(<address>, 2_000_000_000_000n);
213
+ const queryInfo = await api.call.transactionPaymentApi.queryInfo(tx.toU8a(), tx.length);
214
+
215
+ // Get runtime version
216
+ const runtimeVersion = await api.call.core.version();
217
+ ```
218
+
219
+ For chains that only support Metadata V14, we need to bring in the Runtime Api definitions when initializing the DedotClient instance to encode & decode the calls. You can find all supported Runtime Api definitions in [`dedot/runtime-specs`](https://github.com/dedotdev/dedot/blob/fefe71cf4a04d1433841f5cfc8400a1e2a8db112/packages/runtime-specs/src/all.ts#L21-L39) package.
185
220
 
186
- ### Submit Transactions
221
+ Examples:
222
+ ```typescript
223
+ import { RuntimeApis } from 'dedot/runtime-specs';
224
+ const api = await DedotClient.new({ provider: new WsProvider('wss://rpc.mynetwork.com'), runtimeApis: RuntimeApis });
225
+
226
+ // Or bring in only the Runtime Api definition that you want to interact with
227
+ import { AccountNonceApi } from 'dedot/runtime-specs';
228
+ const api = await DedotClient.new({ provider: new WsProvider('wss://rpc.mynetwork.com'), runtimeApis: { AccountNonceApi } });
229
+
230
+ // Get account nonce
231
+ const nonce = await api.call.accountNonceApi.accountNonce(<address>);
232
+ ```
233
+
234
+ 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/fefe71cf4a04d1433841f5cfc8400a1e2a8db112/packages/runtime-specs/src/all.ts#L21-L39).
235
+
236
+ ### Transaction APIs
237
+
238
+ 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.
239
+
240
+ 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/chaintypes/blob/main/packages/chaintypes/src/polkadot/tx.d.ts), similarly for other networks as well.
241
+
242
+ Example 1: Sign transaction with a Keying account
243
+ ```typescript
244
+ import { cryptoWaitReady } from '@polkadot/util-crypto';
245
+ import { Keyring } from '@polkadot/keyring';
246
+ ...
247
+ await cryptoWaitReady();
248
+ const keyring = new Keyring({ type: 'sr25519' });
249
+ const alice = keyring.addFromUri('//Alice');
250
+
251
+ const unsub = await api.tx.balances
252
+ .transferKeepAlive(<destAddress>, 2_000_000_000_000n)
253
+ .signAndSend(alice, async ({ status }) => {
254
+ console.log('Transaction status', status.type);
255
+ if (status.type === 'BestChainBlockIncluded') { // or status.type === 'Finalized'
256
+ console.log(`Transaction completed at block hash ${status.value}`);
257
+ await unsub();
258
+ }
259
+ });
260
+ ```
261
+
262
+ Example 2: Sign transaction using `Signer` from Polkadot{.js} wallet extension
263
+ ```typescript
264
+ const injected = await window.injectedWeb3['polkadot-js'].enable('A cool dapp');
265
+ const account = (await injected.accounts.get())[0];
266
+ const signer = injected.signer;
267
+
268
+ const unsub = await api.tx.balances
269
+ .transferKeepAlive(<destAddress>, 2_000_000_000_000n)
270
+ .signAndSend(account.address, { signer }, async ({ status }) => {
271
+ console.log('Transaction status', status.type);
272
+ if (status.type === 'BestChainBlockIncluded') { // or status.type === 'Finalized'
273
+ console.log(`Transaction completed at block hash ${status.value}`);
274
+ await unsub();
275
+ }
276
+ });
277
+ ```
278
+
279
+ Example 3: Submit a batch transaction
280
+ ```typescript
281
+ import type { PolkadotRuntimeRuntimeCallLike } from '@dedot/chaintypes/polkadot';
282
+
283
+ // Omit the detail for simplicity
284
+ const account = ...;
285
+ const signer = ...;
286
+
287
+ const transferTx = api.tx.balances.transferKeepAlive(<destAddress>, 2_000_000_000_000n);
288
+ const remarkCall: PolkadotRuntimeRuntimeCallLike = {
289
+ pallet: 'System',
290
+ palletCall: {
291
+ name: 'RemarkWithEvent',
292
+ params: {
293
+ remark: 'Hello Dedot!',
294
+ },
295
+ },
296
+ };
297
+
298
+ const unsub = api.tx.utility.batch([transferTx.call, remarkCall])
299
+ .signAndSend(account.address, { signer }, async ({ status }) => {
300
+ console.log('Transaction status', status.type);
301
+ if (status.type === 'BestChainBlockIncluded') { // or status.type === 'Finalized'
302
+ console.log(`Transaction completed at block hash ${status.value}`);
303
+ await unsub();
304
+ }
305
+ });
306
+ ```
307
+
308
+ <details>
309
+ <summary>Example 4: Teleport WND from Westend Asset Hub to Westend via XCM</summary>
310
+
311
+ ```typescript
312
+ import { WestendAssetHubApi, XcmVersionedLocation, XcmVersionedAssets, XcmV3WeightLimit } from '@dedot/chaintypes/westendAssetHub';
313
+ import { AccountId32 } from 'dedot/codecs';
314
+
315
+ const TWO_TOKENS = 2_000_000_000_000n;
316
+ const destAddress = <bobAddress>;
317
+
318
+ const api = await DedotClient.new<WestendAssetHubApi>('...westend-assethub-rpc...');
319
+
320
+ const dest: XcmVersionedLocation = {
321
+ type: 'V3',
322
+ value: { parents: 1, interior: { type: 'Here' } },
323
+ };
324
+
325
+ const beneficiary: XcmVersionedLocation = {
326
+ type: 'V3',
327
+ value: {
328
+ parents: 0,
329
+ interior: {
330
+ type: 'X1',
331
+ value: {
332
+ type: 'AccountId32',
333
+ value: { id: new AccountId32(destAddress).raw },
334
+ },
335
+ },
336
+ },
337
+ };
338
+
339
+ const assets: XcmVersionedAssets = {
340
+ type: 'V3',
341
+ value: [
342
+ {
343
+ id: {
344
+ type: 'Concrete',
345
+ value: {
346
+ parents: 1,
347
+ interior: { type: 'Here' },
348
+ },
349
+ },
350
+ fun: {
351
+ type: 'Fungible',
352
+ value: TWO_TOKENS,
353
+ },
354
+ },
355
+ ],
356
+ };
357
+
358
+ const weight: XcmV3WeightLimit = { type: 'Unlimited' };
359
+
360
+ api.tx.polkadotXcm
361
+ .limitedTeleportAssets(dest, beneficiary, assets, 0, weight)
362
+ .signAndSend(alice, { signer, tip: 1_000_000n }, (result) => {
363
+ console.dir(result, { depth: null });
364
+ });
365
+ ```
366
+ </details>
187
367
 
188
- ⏳ _coming soon_
189
368
 
190
369
  ### Events
191
370
 
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.
371
+ 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/chaintypes/blob/main/packages/chaintypes/src/polkadot/events.d.ts), similarly for other network as well.
193
372
 
194
373
  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
374
 
@@ -213,7 +392,7 @@ await api.query.system.events(async (eventRecords) => {
213
392
 
214
393
  ### Errors
215
394
 
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).
395
+ 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/chaintypes/blob/main/packages/chaintypes/src/polkadot/errors.d.ts).
217
396
 
218
397
  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
398
 
@@ -224,7 +403,7 @@ await api.query.system.events(async (eventRecords) => {
224
403
  for (const tx of eventRecords) {
225
404
  if (api.events.system.ExtrinsicFailed.is(tx.event)) {
226
405
  const { dispatchError } = tx.event.palletEvent.data;
227
- if (dispatchError.tag === 'Module' && api.errors.assets.AlreadyExists.is(dispatchError.value)) {
406
+ if (api.errors.assets.AlreadyExists.is(dispatchError)) {
228
407
  console.log('Assets.AlreadyExists error occurred!');
229
408
  } else {
230
409
  console.log('Other error occurred', dispatchError);
@@ -235,6 +414,86 @@ await api.query.system.events(async (eventRecords) => {
235
414
  // ...
236
415
  ```
237
416
 
417
+ ### Migration from `@polkadot/api` to `dedot`
418
+ `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.
419
+
420
+ While the api style are similar, but there're also some differences you might need to be aware of when switching to use `dedot`.
421
+
422
+ **Initialize api client**
423
+ - `@polkadot/api`
424
+ ```typescript
425
+ import { ApiPromise, WsProvider } from '@polkadot/api';
426
+
427
+ const api = await ApiPromise.create({ provider: new WsProvider('wss://rpc.polkadot.io') });
428
+ ```
429
+ - `dedot`
430
+
431
+ ```typescript
432
+ import { DedotClient, WsProvider } from 'dedot';
433
+ import type { PolkadotApi } from '@dedot/chaintypes';
434
+
435
+ const api = await DedotClient.new<PolkadotApi>(new WsProvider('wss://rpc.polkadot.io')); // or DedotClient.create(...) if you prefer
436
+
437
+ // OR
438
+ const api = await DedotClient.new<PolkadotApi>({ provider: new WsProvider('wss://rpc.polkadot.io') });
439
+ ```
440
+
441
+ - Notes:
442
+ - `dedot` only supports provider can make subscription request (e.g: via Websocket).
443
+ - We recommend specifying the `ChainApi` interface (e.g: [`PolkadotApi`](https://github.com/dedotdev/chaintypes/blob/main/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.
444
+ - `WsProvider` from `dedot` and `@polkadot/api` are different, they cannot be used interchangeable.
445
+
446
+ **Type system**
447
+
448
+ 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`:
449
+
450
+
451
+ | Scale Codec | TypeScript (`dedot`) |
452
+ |---------------------------------------------------------|--------------------------------------------------------------------------------------------------------------------------------|
453
+ | `u8`, `u16`, `u32`, `i8`, `i16`, `i32` | `number` |
454
+ | `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) |
455
+ | `bool` | `boolean` (true, false) |
456
+ | `Option<T>` | `T \| undefined` |
457
+ | `Result<Ok, Err>` | `{ isOk: true; isErr?: false; value: Ok } \| { isOk?: false; isErr: true; err: Err }` |
458
+ | `Vec<T>` | `Array<T>` |
459
+ | `str` | `string` |
460
+ | Tuple: `(A, B)`, `()` | `[A, B]`, `[]` |
461
+ | Struct: `struct { field_1: u8, field_2: str }` | `{ field_1: number, field_2: string}` |
462
+ | Enum: `enum { Variant1(u8), Variant2(bool), Variant3 }` | `{ type: 'Variant1', value: number } \| { type: 'Variant2', value: boolean } \| { type: 'Variant2' }` |
463
+ | FlatEnum: `enum { Variant1, Variant2 }` | `'Variant1' \| 'Variant2'` |
464
+
465
+ E.g 1:
466
+ ```typescript
467
+ const runtimeVersion = api.consts.system.version;
468
+
469
+ // @polkadot/api
470
+ const specName: string = runtimeVersion.toJSON().specName; // OR runtimeVersion.specName.toString()
471
+
472
+ // dedot
473
+ const specName: string = runtimeVersion.specName;
474
+ ```
475
+
476
+ E.g 2:
477
+ ```typescript
478
+ const balance = await api.query.system.account(<address>);
479
+
480
+ // @polkadot/api
481
+ const freeBalance: bigint = balance.data.free.toBigInt();
482
+
483
+ // dedot
484
+ const freeBalance: bigint = balance.data.free;
485
+ ```
486
+
487
+ E.g 3:
488
+ ```typescript
489
+ // @polkadot/api
490
+ const proposalBondMaximum: bigint | undefined = api.consts.treasury.proposalBondMaximum.unwrapOr(undefined)?.toBigInt();
491
+
492
+ // dedot
493
+ const proposalBondMaximum: bigint | undefined = api.consts.treasury.proposalBondMaximum;
494
+ ```
495
+
496
+
238
497
  ### Credit
239
498
 
240
499
  `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.
package/bin/dedot ADDED
@@ -0,0 +1,3 @@
1
+ #!/usr/bin/env node
2
+
3
+ require('@dedot/cli').dedot();
@@ -0,0 +1 @@
1
+ export * from '@dedot/api/chaintypes';
@@ -0,0 +1 @@
1
+ export * from '@dedot/api/chaintypes';
@@ -14,5 +14,4 @@ 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("./extensions"), exports);
18
- __exportStar(require("./SubmittableResult"), exports);
17
+ __exportStar(require("@dedot/api/chaintypes"), exports);
@@ -14,6 +14,4 @@ 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("./SignedExtension"), exports);
18
- __exportStar(require("./known"), exports);
19
- __exportStar(require("./ExtraSignedExtension"), exports);
17
+ __exportStar(require("@dedot/codecs"), exports);
@@ -14,11 +14,4 @@ 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("./Executor"), exports);
18
- __exportStar(require("./RpcExecutor"), exports);
19
- __exportStar(require("./ConstantExecutor"), exports);
20
- __exportStar(require("./StorageQueryExecutor"), exports);
21
- __exportStar(require("./ErrorExecutor"), exports);
22
- __exportStar(require("./EventExecutor"), exports);
23
- __exportStar(require("./RuntimeApiExecutor"), exports);
24
- __exportStar(require("./TxExecutor"), exports);
17
+ __exportStar(require("@dedot/contracts"), exports);
package/cjs/index.js CHANGED
@@ -10,16 +10,23 @@ var __createBinding = (this && this.__createBinding) || (Object.create ? (functi
10
10
  if (k2 === undefined) k2 = k;
11
11
  o[k2] = m[k];
12
12
  }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || function (mod) {
19
+ if (mod && mod.__esModule) return mod;
20
+ var result = {};
21
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
+ __setModuleDefault(result, mod);
23
+ return result;
24
+ };
13
25
  var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
26
  for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
27
  };
16
28
  Object.defineProperty(exports, "__esModule", { value: true });
17
- exports.WsProvider = exports.ScProvider = exports.HttpProvider = exports.Dedot = void 0;
18
- const client_1 = require("./client");
19
- Object.defineProperty(exports, "Dedot", { enumerable: true, get: function () { return client_1.Dedot; } });
20
- __exportStar(require("./executor"), exports);
21
- __exportStar(require("./extrinsic"), exports);
22
- var rpc_provider_1 = require("@polkadot/rpc-provider");
23
- Object.defineProperty(exports, "HttpProvider", { enumerable: true, get: function () { return rpc_provider_1.HttpProvider; } });
24
- Object.defineProperty(exports, "ScProvider", { enumerable: true, get: function () { return rpc_provider_1.ScProvider; } });
25
- Object.defineProperty(exports, "WsProvider", { enumerable: true, get: function () { return rpc_provider_1.WsProvider; } });
29
+ exports.$ = void 0;
30
+ exports.$ = __importStar(require("@dedot/shape"));
31
+ __exportStar(require("@dedot/api"), exports);
32
+ __exportStar(require("@dedot/providers"), exports);
@@ -0,0 +1,17 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("@dedot/runtime-specs"), exports);
@@ -14,4 +14,4 @@ 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"), exports);
17
+ __exportStar(require("@dedot/shape"), exports);
@@ -0,0 +1,17 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("@dedot/types"), exports);