dedot 0.0.1-next.fecbe32d.13 → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (152) hide show
  1. package/README.md +80 -86
  2. package/bin/dedot +3 -0
  3. package/chaintypes/index.d.ts +1 -1
  4. package/chaintypes/index.js +1 -1
  5. package/cjs/chaintypes/index.js +1 -1
  6. package/cjs/{json-rpc → codecs}/index.js +1 -1
  7. package/cjs/{storage → contracts}/index.js +1 -1
  8. package/cjs/index.js +6 -15
  9. package/cjs/runtime-specs/index.js +17 -0
  10. package/cjs/{chaintypes/substrate → shape}/index.js +1 -1
  11. package/cjs/{client → types}/index.js +1 -1
  12. package/cjs/types/json-rpc/index.js +17 -0
  13. package/cjs/utils/index.js +17 -0
  14. package/codecs/index.d.ts +1 -0
  15. package/codecs/index.js +1 -0
  16. package/contracts/index.d.ts +1 -0
  17. package/contracts/index.js +1 -0
  18. package/index.d.ts +2 -9
  19. package/index.js +2 -9
  20. package/package.json +76 -36
  21. package/runtime-specs/index.d.ts +1 -0
  22. package/runtime-specs/index.js +1 -0
  23. package/shape/index.d.ts +1 -0
  24. package/shape/index.js +1 -0
  25. package/types/index.d.ts +1 -0
  26. package/types/index.js +1 -0
  27. package/types/json-rpc/index.d.ts +1 -0
  28. package/types/json-rpc/index.js +1 -0
  29. package/utils/index.d.ts +1 -0
  30. package/utils/index.js +1 -0
  31. package/chaintypes/substrate/consts.d.ts +0 -1971
  32. package/chaintypes/substrate/consts.js +0 -1
  33. package/chaintypes/substrate/errors.d.ts +0 -3337
  34. package/chaintypes/substrate/errors.js +0 -1
  35. package/chaintypes/substrate/events.d.ts +0 -4777
  36. package/chaintypes/substrate/events.js +0 -1
  37. package/chaintypes/substrate/index.d.ts +0 -18
  38. package/chaintypes/substrate/index.js +0 -1
  39. package/chaintypes/substrate/json-rpc.d.ts +0 -3
  40. package/chaintypes/substrate/json-rpc.js +0 -1
  41. package/chaintypes/substrate/query.d.ts +0 -3447
  42. package/chaintypes/substrate/query.js +0 -1
  43. package/chaintypes/substrate/runtime.d.ts +0 -708
  44. package/chaintypes/substrate/runtime.js +0 -1
  45. package/chaintypes/substrate/tx.d.ts +0 -8800
  46. package/chaintypes/substrate/tx.js +0 -1
  47. package/chaintypes/substrate/types.d.ts +0 -20332
  48. package/chaintypes/substrate/types.js +0 -1
  49. package/cjs/chaintypes/substrate/consts.js +0 -2
  50. package/cjs/chaintypes/substrate/errors.js +0 -2
  51. package/cjs/chaintypes/substrate/events.js +0 -2
  52. package/cjs/chaintypes/substrate/json-rpc.js +0 -2
  53. package/cjs/chaintypes/substrate/query.js +0 -2
  54. package/cjs/chaintypes/substrate/runtime.js +0 -2
  55. package/cjs/chaintypes/substrate/tx.js +0 -2
  56. package/cjs/chaintypes/substrate/types.js +0 -2
  57. package/cjs/client/BaseSubstrateClient.js +0 -247
  58. package/cjs/client/Dedot.js +0 -257
  59. package/cjs/executor/ConstantExecutor.js +0 -20
  60. package/cjs/executor/ErrorExecutor.js +0 -46
  61. package/cjs/executor/EventExecutor.js +0 -52
  62. package/cjs/executor/Executor.js +0 -45
  63. package/cjs/executor/RuntimeApiExecutor.js +0 -113
  64. package/cjs/executor/StorageQueryExecutor.js +0 -109
  65. package/cjs/executor/TxExecutor.js +0 -158
  66. package/cjs/executor/index.js +0 -23
  67. package/cjs/extrinsic/SubmittableResult.js +0 -33
  68. package/cjs/extrinsic/extensions/ExtraSignedExtension.js +0 -87
  69. package/cjs/extrinsic/extensions/SignedExtension.js +0 -41
  70. package/cjs/extrinsic/extensions/index.js +0 -19
  71. package/cjs/extrinsic/extensions/known/ChargeAssetTxPayment.js +0 -43
  72. package/cjs/extrinsic/extensions/known/ChargeTransactionPayment.js +0 -16
  73. package/cjs/extrinsic/extensions/known/CheckGenesis.js +0 -19
  74. package/cjs/extrinsic/extensions/known/CheckMortality.js +0 -70
  75. package/cjs/extrinsic/extensions/known/CheckNonZeroSender.js +0 -10
  76. package/cjs/extrinsic/extensions/known/CheckNonce.js +0 -33
  77. package/cjs/extrinsic/extensions/known/CheckSpecVersion.js +0 -19
  78. package/cjs/extrinsic/extensions/known/CheckTxVersion.js +0 -19
  79. package/cjs/extrinsic/extensions/known/CheckWeight.js +0 -10
  80. package/cjs/extrinsic/extensions/known/PrevalidateAttests.js +0 -11
  81. package/cjs/extrinsic/extensions/known/index.js +0 -25
  82. package/cjs/extrinsic/index.js +0 -18
  83. package/cjs/json-rpc/JsonRpcClient.js +0 -157
  84. package/cjs/proxychain.js +0 -27
  85. package/cjs/storage/QueryableStorage.js +0 -161
  86. package/cjs/types.js +0 -2
  87. package/client/BaseSubstrateClient.d.ts +0 -65
  88. package/client/BaseSubstrateClient.js +0 -242
  89. package/client/Dedot.d.ts +0 -130
  90. package/client/Dedot.js +0 -253
  91. package/client/index.d.ts +0 -1
  92. package/client/index.js +0 -1
  93. package/executor/ConstantExecutor.d.ts +0 -11
  94. package/executor/ConstantExecutor.js +0 -16
  95. package/executor/ErrorExecutor.d.ts +0 -11
  96. package/executor/ErrorExecutor.js +0 -42
  97. package/executor/EventExecutor.d.ts +0 -11
  98. package/executor/EventExecutor.js +0 -48
  99. package/executor/Executor.d.ts +0 -150
  100. package/executor/Executor.js +0 -41
  101. package/executor/RuntimeApiExecutor.d.ts +0 -19
  102. package/executor/RuntimeApiExecutor.js +0 -109
  103. package/executor/StorageQueryExecutor.d.ts +0 -13
  104. package/executor/StorageQueryExecutor.js +0 -105
  105. package/executor/TxExecutor.d.ts +0 -48
  106. package/executor/TxExecutor.js +0 -152
  107. package/executor/index.d.ts +0 -7
  108. package/executor/index.js +0 -7
  109. package/extrinsic/SubmittableResult.d.ts +0 -19
  110. package/extrinsic/SubmittableResult.js +0 -29
  111. package/extrinsic/extensions/ExtraSignedExtension.d.ts +0 -14
  112. package/extrinsic/extensions/ExtraSignedExtension.js +0 -60
  113. package/extrinsic/extensions/SignedExtension.d.ts +0 -40
  114. package/extrinsic/extensions/SignedExtension.js +0 -37
  115. package/extrinsic/extensions/index.d.ts +0 -3
  116. package/extrinsic/extensions/index.js +0 -3
  117. package/extrinsic/extensions/known/ChargeAssetTxPayment.d.ts +0 -14
  118. package/extrinsic/extensions/known/ChargeAssetTxPayment.js +0 -39
  119. package/extrinsic/extensions/known/ChargeTransactionPayment.d.ts +0 -6
  120. package/extrinsic/extensions/known/ChargeTransactionPayment.js +0 -12
  121. package/extrinsic/extensions/known/CheckGenesis.d.ts +0 -10
  122. package/extrinsic/extensions/known/CheckGenesis.js +0 -15
  123. package/extrinsic/extensions/known/CheckMortality.d.ts +0 -15
  124. package/extrinsic/extensions/known/CheckMortality.js +0 -66
  125. package/extrinsic/extensions/known/CheckNonZeroSender.d.ts +0 -6
  126. package/extrinsic/extensions/known/CheckNonZeroSender.js +0 -6
  127. package/extrinsic/extensions/known/CheckNonce.d.ts +0 -10
  128. package/extrinsic/extensions/known/CheckNonce.js +0 -29
  129. package/extrinsic/extensions/known/CheckSpecVersion.d.ts +0 -9
  130. package/extrinsic/extensions/known/CheckSpecVersion.js +0 -15
  131. package/extrinsic/extensions/known/CheckTxVersion.d.ts +0 -9
  132. package/extrinsic/extensions/known/CheckTxVersion.js +0 -15
  133. package/extrinsic/extensions/known/CheckWeight.d.ts +0 -6
  134. package/extrinsic/extensions/known/CheckWeight.js +0 -6
  135. package/extrinsic/extensions/known/PrevalidateAttests.d.ts +0 -7
  136. package/extrinsic/extensions/known/PrevalidateAttests.js +0 -7
  137. package/extrinsic/extensions/known/index.d.ts +0 -3
  138. package/extrinsic/extensions/known/index.js +0 -22
  139. package/extrinsic/index.d.ts +0 -2
  140. package/extrinsic/index.js +0 -2
  141. package/json-rpc/JsonRpcClient.d.ts +0 -49
  142. package/json-rpc/JsonRpcClient.js +0 -153
  143. package/json-rpc/index.d.ts +0 -1
  144. package/json-rpc/index.js +0 -1
  145. package/proxychain.d.ts +0 -14
  146. package/proxychain.js +0 -23
  147. package/storage/QueryableStorage.d.ts +0 -35
  148. package/storage/QueryableStorage.js +0 -157
  149. package/storage/index.d.ts +0 -1
  150. package/storage/index.js +0 -1
  151. package/types.d.ts +0 -103
  152. package/types.js +0 -1
@@ -1,9 +0,0 @@
1
- import { SignerPayloadJSON } from '@polkadot/types/types';
2
- import { SignedExtension } from '../SignedExtension.js';
3
- /**
4
- * @description Ensure the transaction version registered in the transaction is the same as at present.
5
- */
6
- export declare class CheckTxVersion extends SignedExtension<{}, number> {
7
- init(): Promise<void>;
8
- toPayload(): Partial<SignerPayloadJSON>;
9
- }
@@ -1,15 +0,0 @@
1
- import { numberToHex } from '@dedot/utils';
2
- import { SignedExtension } from '../SignedExtension.js';
3
- /**
4
- * @description Ensure the transaction version registered in the transaction is the same as at present.
5
- */
6
- export class CheckTxVersion extends SignedExtension {
7
- async init() {
8
- this.additionalSigned = this.api.runtimeVersion.transactionVersion;
9
- }
10
- toPayload() {
11
- return {
12
- transactionVersion: numberToHex(this.additionalSigned),
13
- };
14
- }
15
- }
@@ -1,6 +0,0 @@
1
- import { SignedExtension } from '../SignedExtension.js';
2
- /**
3
- * @description Block resource (weight) limit check.
4
- */
5
- export declare class CheckWeight extends SignedExtension {
6
- }
@@ -1,6 +0,0 @@
1
- import { SignedExtension } from '../SignedExtension.js';
2
- /**
3
- * @description Block resource (weight) limit check.
4
- */
5
- export class CheckWeight extends SignedExtension {
6
- }
@@ -1,7 +0,0 @@
1
- import { SignedExtension } from '../SignedExtension.js';
2
- /**
3
- * @description Validate `attest` calls prior to execution.
4
- * Needed to avoid a DoS attack since they are otherwise free to place on chain.
5
- */
6
- export declare class PrevalidateAttests extends SignedExtension {
7
- }
@@ -1,7 +0,0 @@
1
- import { SignedExtension } from '../SignedExtension.js';
2
- /**
3
- * @description Validate `attest` calls prior to execution.
4
- * Needed to avoid a DoS attack since they are otherwise free to place on chain.
5
- */
6
- export class PrevalidateAttests extends SignedExtension {
7
- }
@@ -1,3 +0,0 @@
1
- import { ISignedExtension } from '../SignedExtension.js';
2
- export type AnySignedExtension = new (...args: any[]) => ISignedExtension;
3
- export declare const knownSignedExtensions: Record<string, AnySignedExtension>;
@@ -1,22 +0,0 @@
1
- import { ChargeAssetTxPayment } from './ChargeAssetTxPayment.js';
2
- import { ChargeTransactionPayment } from './ChargeTransactionPayment.js';
3
- import { CheckGenesis } from './CheckGenesis.js';
4
- import { CheckMortality } from './CheckMortality.js';
5
- import { CheckNonZeroSender } from './CheckNonZeroSender.js';
6
- import { CheckNonce } from './CheckNonce.js';
7
- import { CheckSpecVersion } from './CheckSpecVersion.js';
8
- import { CheckTxVersion } from './CheckTxVersion.js';
9
- import { CheckWeight } from './CheckWeight.js';
10
- import { PrevalidateAttests } from './PrevalidateAttests.js';
11
- export const knownSignedExtensions = {
12
- CheckNonZeroSender,
13
- CheckSpecVersion,
14
- CheckTxVersion,
15
- CheckGenesis,
16
- CheckMortality,
17
- CheckNonce,
18
- CheckWeight,
19
- ChargeTransactionPayment,
20
- PrevalidateAttests,
21
- ChargeAssetTxPayment,
22
- };
@@ -1,2 +0,0 @@
1
- export * from './extensions/index.js';
2
- export * from './SubmittableResult.js';
@@ -1,2 +0,0 @@
1
- export * from './extensions/index.js';
2
- export * from './SubmittableResult.js';
@@ -1,49 +0,0 @@
1
- import { ConnectionStatus, JsonRpcProvider, ProviderEvent } from '@dedot/providers';
2
- import { GenericSubstrateApi } from '@dedot/types';
3
- import { EventEmitter } from '@dedot/utils';
4
- import { SubstrateApi } from '../chaintypes/index.js';
5
- import { IJsonRpcClient, JsonRpcClientOptions, NetworkEndpoint } from '../types.js';
6
- export declare class JsonRpcClient<ChainApi extends GenericSubstrateApi = SubstrateApi, Events extends string = ProviderEvent> extends EventEmitter<Events> implements IJsonRpcClient<ChainApi, Events> {
7
- #private;
8
- constructor(options: JsonRpcClientOptions | NetworkEndpoint);
9
- /**
10
- * Factory method to create a new JsonRpcClient instance
11
- *
12
- * @param options
13
- */
14
- static create<ChainApi extends GenericSubstrateApi = SubstrateApi>(options: JsonRpcClientOptions | NetworkEndpoint): Promise<JsonRpcClient<ChainApi>>;
15
- /**
16
- * Alias for __JsonRpcClient.create__
17
- *
18
- * @param options
19
- */
20
- static new<ChainApi extends GenericSubstrateApi = SubstrateApi>(options: JsonRpcClientOptions | NetworkEndpoint): Promise<JsonRpcClient<ChainApi>>;
21
- get options(): JsonRpcClientOptions;
22
- /**
23
- * @description Check connection status of the api instance
24
- */
25
- get status(): ConnectionStatus;
26
- /**
27
- * @description Get the JSON-RPC provider instance
28
- */
29
- get provider(): JsonRpcProvider;
30
- connect(): Promise<this>;
31
- disconnect(): Promise<void>;
32
- /**
33
- * @description Entry-point for executing JSON-RPCs to blockchain node.
34
- *
35
- * ```typescript
36
- * const client = new JsonRpcClient('wss://rpc.polkadot.io');
37
- * await client.connect();
38
- *
39
- * // Subscribe to new heads
40
- * client.rpc.chain_subscribeNewHeads((header) => {
41
- * console.log(header);
42
- * });
43
- *
44
- * // Execute arbitrary rpc method: `module_rpc_name`
45
- * const result = await client.rpc.module_rpc_name();
46
- * ```
47
- */
48
- get rpc(): ChainApi['rpc'];
49
- }
@@ -1,153 +0,0 @@
1
- import { WsProvider } from '@dedot/providers';
2
- import { scaledResponses, subscriptionsInfo } from '@dedot/specs';
3
- import { assert, EventEmitter, isFunction } from '@dedot/utils';
4
- export class JsonRpcClient extends EventEmitter {
5
- #options;
6
- #provider;
7
- constructor(options) {
8
- super();
9
- this.#options = typeof options === 'string' ? { endpoint: options } : options;
10
- this.#provider = this.#getProvider();
11
- }
12
- /**
13
- * Factory method to create a new JsonRpcClient instance
14
- *
15
- * @param options
16
- */
17
- static async create(options) {
18
- return new JsonRpcClient(options).connect();
19
- }
20
- /**
21
- * Alias for __JsonRpcClient.create__
22
- *
23
- * @param options
24
- */
25
- static async new(options) {
26
- return JsonRpcClient.create(options);
27
- }
28
- get options() {
29
- return this.#options;
30
- }
31
- /**
32
- * @description Check connection status of the api instance
33
- */
34
- get status() {
35
- return this.provider.status;
36
- }
37
- /**
38
- * @description Get the JSON-RPC provider instance
39
- */
40
- get provider() {
41
- return this.#provider;
42
- }
43
- connect() {
44
- return this.#doConnect();
45
- }
46
- async #doConnect() {
47
- this.provider.on('connected', this.#onConnected);
48
- this.provider.on('disconnected', this.#onDisconnected);
49
- this.provider.on('reconnecting', this.#onReconnecting);
50
- this.provider.on('error', this.#onError);
51
- return new Promise((resolve, reject) => {
52
- // @ts-ignore
53
- this.once('connected', () => {
54
- resolve(this);
55
- });
56
- if (this.status === 'connected') {
57
- this.#onConnected().catch(reject);
58
- }
59
- else {
60
- this.provider.connect().catch(reject);
61
- }
62
- });
63
- }
64
- #onConnected = async () => {
65
- // @ts-ignore
66
- this.emit('connected');
67
- };
68
- #onDisconnected = async () => {
69
- // @ts-ignore
70
- this.emit('disconnected');
71
- };
72
- #onReconnecting = async () => {
73
- // @ts-ignore
74
- this.emit('reconnecting');
75
- };
76
- #onError = async (e) => {
77
- // @ts-ignore
78
- this.emit('error', e);
79
- };
80
- async disconnect() {
81
- await this.#provider.disconnect();
82
- }
83
- #getProvider() {
84
- const { provider, endpoint } = this.#options;
85
- if (provider)
86
- return provider;
87
- if (endpoint)
88
- return new WsProvider(endpoint);
89
- // TODO support light-client
90
- return new WsProvider('ws://127.0.0.1:9944');
91
- }
92
- /**
93
- * @description Entry-point for executing JSON-RPCs to blockchain node.
94
- *
95
- * ```typescript
96
- * const client = new JsonRpcClient('wss://rpc.polkadot.io');
97
- * await client.connect();
98
- *
99
- * // Subscribe to new heads
100
- * client.rpc.chain_subscribeNewHeads((header) => {
101
- * console.log(header);
102
- * });
103
- *
104
- * // Execute arbitrary rpc method: `module_rpc_name`
105
- * const result = await client.rpc.module_rpc_name();
106
- * ```
107
- */
108
- get rpc() {
109
- return new Proxy(this, {
110
- get(target, property, receiver) {
111
- const rpcMethod = property.toString();
112
- return target.#doExecute(rpcMethod);
113
- },
114
- });
115
- }
116
- #doExecute(rpcName) {
117
- const subscriptionInfo = this.options.subscriptions?.[rpcName] || subscriptionsInfo[rpcName];
118
- const isSubscription = !!subscriptionInfo;
119
- const fnRpc = async (...args) => {
120
- const result = await this.provider.send(rpcName, args);
121
- return this.#tryDecode(rpcName, result);
122
- };
123
- const fnSubRpc = async (...args) => {
124
- const inArgs = args.slice();
125
- const callback = inArgs.pop();
126
- assert(isFunction(callback), 'A callback is required for subscription');
127
- const onNewMessage = (error, result, subscription) => {
128
- if (error) {
129
- console.error(error);
130
- return;
131
- }
132
- callback(this.#tryDecode(rpcName, result), subscription);
133
- };
134
- const [subname, unsubscribe] = subscriptionInfo;
135
- const subscription = await this.provider.subscribe({ subname, subscribe: rpcName, params: inArgs, unsubscribe }, onNewMessage);
136
- return async () => {
137
- await subscription.unsubscribe();
138
- };
139
- };
140
- return isSubscription ? fnSubRpc : fnRpc;
141
- }
142
- #tryDecode(rpcName, raw) {
143
- if (raw === null) {
144
- // We use `undefined` to represent Option::None in the client
145
- return undefined;
146
- }
147
- const $maybeCodec = this.options.scaledResponses?.[rpcName] || scaledResponses[rpcName];
148
- if ($maybeCodec) {
149
- return $maybeCodec.tryDecode(raw);
150
- }
151
- return raw;
152
- }
153
- }
@@ -1 +0,0 @@
1
- export * from './JsonRpcClient.js';
package/json-rpc/index.js DELETED
@@ -1 +0,0 @@
1
- export * from './JsonRpcClient.js';
package/proxychain.d.ts DELETED
@@ -1,14 +0,0 @@
1
- import { GenericSubstrateApi } from '@dedot/types';
2
- import { Executor } from './executor/index.js';
3
- export interface Carrier<ChainApi extends GenericSubstrateApi> {
4
- executor: Executor<ChainApi>;
5
- chain?: string[];
6
- }
7
- /**
8
- * Create a chain of proxy objects
9
- *
10
- * @param carrier
11
- * @param currentLevel
12
- * @param maxLevel
13
- */
14
- export declare const newProxyChain: <ChainApi extends GenericSubstrateApi>(carrier: Carrier<ChainApi>, currentLevel?: number, maxLevel?: number) => unknown;
package/proxychain.js DELETED
@@ -1,23 +0,0 @@
1
- /**
2
- * Create a chain of proxy objects
3
- *
4
- * @param carrier
5
- * @param currentLevel
6
- * @param maxLevel
7
- */
8
- export const newProxyChain = (carrier, currentLevel = 1, maxLevel = 3) => {
9
- const { executor, chain = [] } = carrier;
10
- if (currentLevel === maxLevel) {
11
- return executor.execute(...chain);
12
- }
13
- return new Proxy(carrier, {
14
- get(target, property, receiver) {
15
- if (!target.chain) {
16
- target.chain = [];
17
- }
18
- const { chain } = target;
19
- chain.push(property.toString());
20
- return newProxyChain(target, currentLevel + 1, maxLevel);
21
- },
22
- });
23
- };
@@ -1,35 +0,0 @@
1
- import { PortableRegistry, PalletDefLatest, StorageDataLike, StorageEntryLatest, StorageKey, PrefixedStorageKey } from '@dedot/codecs';
2
- /**
3
- * @name QueryableStorage
4
- * @description A helper to encode key & decode value for a storage entry
5
- */
6
- export declare class QueryableStorage {
7
- #private;
8
- readonly registry: PortableRegistry;
9
- readonly palletName: string;
10
- readonly storageItem: string;
11
- readonly pallet: PalletDefLatest;
12
- readonly storageEntry: StorageEntryLatest;
13
- constructor(registry: PortableRegistry, palletName: string, storageItem: string);
14
- get prefixKey(): PrefixedStorageKey;
15
- get prefixKeyAsU8a(): Uint8Array;
16
- /**
17
- * Encode plain key input to raw/bytes storage key
18
- *
19
- * @param keyInput
20
- */
21
- encodeKey(keyInput?: any): StorageKey;
22
- /**
23
- * Decode storage key to plain key input
24
- * Only storage keys that hashed by `twox64Concat`, `blake2_128Concat`, or `identity` can be decoded
25
- *
26
- * @param key
27
- */
28
- decodeKey(key: StorageKey): any;
29
- /**
30
- * Decode raw/bytes storage data to plain value
31
- *
32
- * @param raw
33
- */
34
- decodeValue(raw?: StorageDataLike | null): any;
35
- }
@@ -1,157 +0,0 @@
1
- import { $StorageData, } from '@dedot/codecs';
2
- import { assert, HASHERS, hexAddPrefix, UnknownApiError } from '@dedot/utils';
3
- import { xxhashAsU8a, hexToU8a, stringCamelCase, concatU8a, u8aToHex } from '@dedot/utils';
4
- // https://github.com/polkadot-js/api/blob/0982f68507942c5bf6f751f662804344e211b289/packages/types/src/primitive/StorageKey.ts#L29-L38
5
- const HASHER_INFO = {
6
- blake2_128: [16, false],
7
- blake2_256: [32, false],
8
- blake2_128Concat: [16, true],
9
- twox128: [16, false],
10
- twox256: [32, false],
11
- twox64Concat: [8, true],
12
- identity: [0, true],
13
- };
14
- /**
15
- * @name QueryableStorage
16
- * @description A helper to encode key & decode value for a storage entry
17
- */
18
- export class QueryableStorage {
19
- registry;
20
- palletName;
21
- storageItem;
22
- pallet;
23
- storageEntry;
24
- constructor(registry, palletName, storageItem) {
25
- this.registry = registry;
26
- this.palletName = palletName;
27
- this.storageItem = storageItem;
28
- this.pallet = this.#getPallet();
29
- this.storageEntry = this.#getStorageEntry();
30
- }
31
- get prefixKey() {
32
- return u8aToHex(this.prefixKeyAsU8a);
33
- }
34
- get prefixKeyAsU8a() {
35
- const palletNameHash = xxhashAsU8a(this.pallet.name, 128);
36
- const storageItemHash = xxhashAsU8a(this.storageEntry.name, 128);
37
- return concatU8a(palletNameHash, storageItemHash);
38
- }
39
- #getStorageMapInfo(type) {
40
- assert(type.tag === 'Map');
41
- const { hashers, keyTypeId } = type.value;
42
- let keyTypeIds = [keyTypeId];
43
- if (hashers.length > 1) {
44
- const { type } = this.registry.findType(keyTypeId);
45
- assert(type.tag === 'Tuple', 'Key type should be a tuple!');
46
- keyTypeIds = type.value.fields;
47
- }
48
- return { hashers, keyTypeIds };
49
- }
50
- /**
51
- * Encode plain key input to raw/bytes storage key
52
- *
53
- * @param keyInput
54
- */
55
- encodeKey(keyInput) {
56
- const { type } = this.storageEntry;
57
- if (type.tag === 'Plain') {
58
- return this.prefixKey;
59
- }
60
- else if (type.tag === 'Map') {
61
- const { hashers, keyTypeIds } = this.#getStorageMapInfo(type);
62
- const extractedInputs = this.#extractRequiredKeyInputs(keyInput, hashers.length);
63
- const keyParts = keyTypeIds.map((keyId, index) => {
64
- const input = extractedInputs[index];
65
- const hasher = HASHERS[hashers[index]];
66
- const $keyCodec = this.registry.findCodec(keyId);
67
- return hasher($keyCodec.tryEncode(input));
68
- });
69
- return u8aToHex(concatU8a(this.prefixKeyAsU8a, ...keyParts));
70
- }
71
- throw Error(`Invalid storage entry type: ${type}`);
72
- }
73
- /**
74
- * Decode storage key to plain key input
75
- * Only storage keys that hashed by `twox64Concat`, `blake2_128Concat`, or `identity` can be decoded
76
- *
77
- * @param key
78
- */
79
- decodeKey(key) {
80
- const { type } = this.storageEntry;
81
- if (type.tag === 'Plain') {
82
- return;
83
- }
84
- else if (type.tag === 'Map') {
85
- const prefix = this.prefixKey;
86
- if (!key.startsWith(prefix)) {
87
- throw new Error(`Storage key does not match this storage entry (${this.palletName}.${this.storageItem})`);
88
- }
89
- const { hashers, keyTypeIds } = this.#getStorageMapInfo(type);
90
- let keyData = hexToU8a(hexAddPrefix(key.slice(prefix.length)));
91
- const results = keyTypeIds.map((keyId, index) => {
92
- const [hashLen, canDecode] = HASHER_INFO[hashers[index]];
93
- if (!canDecode)
94
- throw new Error('Cannot decode storage key');
95
- const $keyCodec = this.registry.findCodec(keyId);
96
- keyData = keyData.slice(hashLen);
97
- const result = $keyCodec.tryDecode(keyData);
98
- const encoded = $keyCodec.tryEncode(result);
99
- keyData = keyData.slice(encoded.length);
100
- return result;
101
- });
102
- return hashers.length > 1 ? results : results[0];
103
- }
104
- throw Error(`Invalid storage entry type: ${type}`);
105
- }
106
- /**
107
- * Decode raw/bytes storage data to plain value
108
- *
109
- * @param raw
110
- */
111
- decodeValue(raw) {
112
- const { modifier, type: { value: { valueTypeId }, }, default: defaultValue, } = this.storageEntry;
113
- if (raw === null || raw === undefined) {
114
- if (modifier === 'Optional') {
115
- return undefined;
116
- }
117
- else if (modifier === 'Default') {
118
- return this.registry.findCodec(valueTypeId).tryDecode(hexToU8a(defaultValue));
119
- }
120
- }
121
- else {
122
- return this.registry.findCodec(valueTypeId).tryDecode($StorageData.tryEncode(raw));
123
- }
124
- }
125
- #extractRequiredKeyInputs(keyInput, numberOfValue) {
126
- if (numberOfValue === 0) {
127
- return [];
128
- }
129
- else {
130
- if (keyInput === undefined) {
131
- throw new Error(`Invalid key inputs, required ${numberOfValue} input(s)`);
132
- }
133
- if (numberOfValue === 1) {
134
- return [keyInput];
135
- }
136
- else {
137
- if (!Array.isArray(keyInput)) {
138
- throw new Error(`Input should be an array with ${numberOfValue} value(s)`);
139
- }
140
- if (keyInput.length !== numberOfValue) {
141
- throw new Error(`Mismatch key inputs length, required an array of ${numberOfValue} value(s)`);
142
- }
143
- return keyInput.slice(0, numberOfValue);
144
- }
145
- }
146
- }
147
- #getPallet() {
148
- const targetPallet = this.registry.metadata.pallets.find((p) => stringCamelCase(p.name) === stringCamelCase(this.palletName));
149
- assert(targetPallet, new UnknownApiError(`Pallet not found: ${this.palletName}`));
150
- return targetPallet;
151
- }
152
- #getStorageEntry() {
153
- const targetEntry = this.pallet.storage?.entries?.find((entry) => stringCamelCase(entry.name) === stringCamelCase(this.storageItem));
154
- assert(targetEntry, new UnknownApiError(`Storage item not found: ${this.storageItem}`));
155
- return targetEntry;
156
- }
157
- }
@@ -1 +0,0 @@
1
- export * from './QueryableStorage.js';
package/storage/index.js DELETED
@@ -1 +0,0 @@
1
- export * from './QueryableStorage.js';
package/types.d.ts DELETED
@@ -1,103 +0,0 @@
1
- import { BlockHash, Hash, Metadata, PortableRegistry } from '@dedot/codecs';
2
- import type { ConnectionStatus, JsonRpcProvider, ProviderEvent } from '@dedot/providers';
3
- import type { AnyShape } from '@dedot/shape';
4
- import { SubscriptionsInfo } from '@dedot/specs';
5
- import type { IStorage } from '@dedot/storage';
6
- import type { GenericSubstrateApi, RuntimeApiName, RuntimeApiSpec } from '@dedot/types';
7
- import type { HashFn, HexString, IEventEmitter } from '@dedot/utils';
8
- import type { AnySignedExtension } from './extrinsic/index.js';
9
- export type NetworkEndpoint = string;
10
- export type MetadataKey = `RAW_META/${string}`;
11
- export interface JsonRpcClientOptions {
12
- provider?: JsonRpcProvider;
13
- /**
14
- * @description A `ProviderInterface` will be created based on the supplied endpoint.
15
- * If both `provider` and `endpoint` is provided, the `provider` will be used for connection.
16
- *
17
- * A valid endpoint should start with `wss://`, `ws://`, `https://` or `http://`
18
- */
19
- endpoint?: NetworkEndpoint;
20
- subscriptions?: SubscriptionsInfo;
21
- scaledResponses?: Record<string, AnyShape>;
22
- }
23
- export interface ApiOptions extends JsonRpcClientOptions {
24
- cacheMetadata?: boolean;
25
- cacheStorage?: IStorage;
26
- /**
27
- * @description Metadata is usually downloaded from chain via RPC upon API initialization,
28
- * We can supply the metadata directly via this option to skip the download metadata step.
29
- *
30
- * Metadata Key format: `RAW_META/{genesisHash}/{runtimeSpecVersion}`
31
- *
32
- * If the `genesisHash` & `runtimeSpecVersion` of the supplied metadata key match with connected chain,
33
- * then use the provided metadata, else we fetch it anew from chain.
34
- */
35
- metadata?: Record<MetadataKey, HexString>;
36
- /**
37
- * @description User-defined chain-specific signed extensions
38
- */
39
- signedExtensions?: Record<string, AnySignedExtension>;
40
- /**
41
- * @description Custom runtime api definitions/specs
42
- *
43
- * You probably don't need to use this with the latest Metadata V15,
44
- * unless you're connecting to a chain supports only Metadata V14
45
- */
46
- runtimeApis?: Record<RuntimeApiName, RuntimeApiSpec[]>;
47
- /**
48
- * By default, an `UnknownApiError` error will be thrown out if an api is known (e.g: `api.query.pallet.unknown`) upon evaluation.
49
- * When set this to `false`, the api evaluation will simply return `undefined`
50
- *
51
- * @default true
52
- */
53
- throwOnUnknownApi?: boolean;
54
- /**
55
- * Customize hashing algorithm used
56
- *
57
- * @default blake2_256
58
- */
59
- hasher?: HashFn;
60
- }
61
- export type ApiEvent = ProviderEvent | 'ready';
62
- export interface SubstrateRuntimeVersion {
63
- specName: string;
64
- implName: string;
65
- specVersion: number;
66
- implVersion: number;
67
- apis: Record<string, number>;
68
- transactionVersion: number;
69
- }
70
- export interface SubstrateChainProperties {
71
- isEthereum?: boolean;
72
- ss58Format?: number;
73
- tokenDecimals?: number | Array<number>;
74
- tokenSymbol?: string | Array<string>;
75
- [prop: string]: any;
76
- }
77
- export interface IJsonRpcClient<ChainApi extends GenericSubstrateApi, Events extends string = ProviderEvent> extends IEventEmitter<Events> {
78
- options: JsonRpcClientOptions;
79
- status: ConnectionStatus;
80
- provider: JsonRpcProvider;
81
- connect(): Promise<this>;
82
- disconnect(): Promise<void>;
83
- rpc: ChainApi['rpc'];
84
- }
85
- export interface ISubstrateClientAt<ChainApi extends GenericSubstrateApi> {
86
- atBlockHash?: BlockHash;
87
- options: ApiOptions;
88
- genesisHash: Hash;
89
- runtimeVersion: SubstrateRuntimeVersion;
90
- metadata: Metadata;
91
- registry: PortableRegistry;
92
- rpc: ChainApi['rpc'];
93
- consts: ChainApi['consts'];
94
- query: ChainApi['query'];
95
- call: ChainApi['call'];
96
- events: ChainApi['events'];
97
- errors: ChainApi['errors'];
98
- }
99
- export interface ISubstrateClient<ChainApi extends GenericSubstrateApi, Events extends string = ApiEvent> extends IJsonRpcClient<ChainApi, Events>, ISubstrateClientAt<ChainApi> {
100
- options: ApiOptions;
101
- tx: ChainApi['tx'];
102
- at<ChainApiAt extends GenericSubstrateApi = ChainApi>(hash: BlockHash): Promise<ISubstrateClientAt<ChainApiAt>>;
103
- }
package/types.js DELETED
@@ -1 +0,0 @@
1
- export {};