dedot 0.0.1-next.f5bf4fc2.1 → 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 (119) hide show
  1. package/README.md +211 -64
  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 -7
  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 +77 -33
  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 -436
  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 -110
  37. package/cjs/executor/RuntimeApiExecutor.js +0 -108
  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 -432
  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 -106
  72. package/executor/RuntimeApiExecutor.d.ts +0 -12
  73. package/executor/RuntimeApiExecutor.js +0 -104
  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 -54
  119. package/types.js +0 -1
@@ -1,47 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.ErrorExecutor = void 0;
4
- const Executor_1 = require("./Executor");
5
- const utils_1 = require("@dedot/utils");
6
- const util_1 = require("@polkadot/util");
7
- /**
8
- * @name ErrorExecutor
9
- * @description Find pallet error information from metadata
10
- */
11
- class ErrorExecutor extends Executor_1.Executor {
12
- execute(pallet, errorName) {
13
- const targetPallet = this.getPallet(pallet);
14
- const errorTypeId = targetPallet.error;
15
- (0, utils_1.assert)(errorTypeId, `Not found error with id ${errorTypeId} in pallet ${pallet}`);
16
- const errorDef = this.#getErrorDef(errorTypeId, errorName);
17
- return {
18
- meta: {
19
- ...errorDef,
20
- pallet: targetPallet.name,
21
- palletIndex: targetPallet.index,
22
- },
23
- is: (errorInfo) => {
24
- if ((0, util_1.isObject)(errorInfo) && errorInfo.tag === 'Module') {
25
- errorInfo = errorInfo.value;
26
- }
27
- if ((0, util_1.isObject)(errorInfo) && (0, util_1.isNumber)(errorInfo.index) && (0, util_1.isHex)(errorInfo.error)) {
28
- return errorInfo.index === targetPallet.index && (0, util_1.hexToU8a)(errorInfo.error)[0] === errorDef.index;
29
- }
30
- return false;
31
- },
32
- };
33
- }
34
- #getErrorDef(errorTypeId, errorName) {
35
- const def = this.metadata.types[errorTypeId];
36
- (0, utils_1.assert)(def, `Error def not found for id ${errorTypeId}`);
37
- const { tag, value } = def.type;
38
- (0, utils_1.assert)(tag === 'Enum', `Error type should be an enum, found: ${tag}`);
39
- const errorDef = value.members.find(({ name }) => (0, util_1.stringPascalCase)(name) === errorName);
40
- (0, utils_1.assert)(errorDef, `Error def not found for ${errorName}`);
41
- return {
42
- ...errorDef,
43
- fieldCodecs: errorDef.fields.map(({ typeId }) => this.registry.findCodec(typeId)),
44
- };
45
- }
46
- }
47
- exports.ErrorExecutor = ErrorExecutor;
@@ -1,53 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.EventExecutor = void 0;
4
- const Executor_1 = require("./Executor");
5
- const util_1 = require("@polkadot/util");
6
- const utils_1 = require("@dedot/utils");
7
- /**
8
- * @name EventExecutor
9
- * @description Find pallet event information from metadata
10
- */
11
- class EventExecutor extends Executor_1.Executor {
12
- execute(pallet, errorName) {
13
- const targetPallet = this.getPallet(pallet);
14
- const eventTypeId = targetPallet.event;
15
- (0, utils_1.assert)(eventTypeId, `Not found event with id ${eventTypeId} in pallet ${pallet}`);
16
- const eventDef = this.#getEventDef(eventTypeId, errorName);
17
- const is = (event) => {
18
- const palletCheck = (0, util_1.stringCamelCase)(event.pallet) === pallet;
19
- if (typeof event.palletEvent === 'string') {
20
- return palletCheck && (0, util_1.stringPascalCase)(event.palletEvent) === errorName;
21
- }
22
- else if (typeof event.palletEvent === 'object') {
23
- return palletCheck && (0, util_1.stringPascalCase)(event.palletEvent.name) === errorName;
24
- }
25
- return false;
26
- };
27
- const as = (event) => {
28
- return is(event) ? event : undefined;
29
- };
30
- return {
31
- is,
32
- as,
33
- meta: {
34
- ...eventDef,
35
- pallet: targetPallet.name,
36
- palletIndex: targetPallet.index,
37
- },
38
- };
39
- }
40
- #getEventDef(eventTypeId, errorName) {
41
- const def = this.metadata.types[eventTypeId];
42
- (0, utils_1.assert)(def, `Event def not found for id ${eventTypeId}`);
43
- const { tag, value } = def.type;
44
- (0, utils_1.assert)(tag === 'Enum', `Event type should be an enum, found: ${tag}`);
45
- const eventDef = value.members.find(({ name }) => (0, util_1.stringPascalCase)(name) === errorName);
46
- (0, utils_1.assert)(eventDef, `Event def not found for ${errorName}`);
47
- return {
48
- ...eventDef,
49
- fieldCodecs: eventDef.fields.map(({ typeId }) => this.registry.findCodec(typeId)),
50
- };
51
- }
52
- }
53
- exports.EventExecutor = EventExecutor;
@@ -1,39 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.Executor = void 0;
4
- const util_1 = require("@polkadot/util");
5
- /**
6
- * @name Executor
7
- * @description Execution abstraction for a specific action
8
- */
9
- class Executor {
10
- #api;
11
- #atBlockHash;
12
- constructor(api, atBlockHash) {
13
- this.#api = api;
14
- this.#atBlockHash = atBlockHash;
15
- }
16
- get api() {
17
- return this.#api;
18
- }
19
- get atBlockHash() {
20
- return this.#atBlockHash;
21
- }
22
- get provider() {
23
- return this.api.provider;
24
- }
25
- get registry() {
26
- return this.api.registry;
27
- }
28
- get metadata() {
29
- return this.api.metadataLatest;
30
- }
31
- getPallet(name, throwErr = true) {
32
- const targetPallet = this.metadata.pallets.find((p) => (0, util_1.stringCamelCase)(p.name) === name);
33
- if (!targetPallet && throwErr) {
34
- throw new Error(`Pallet not found: ${name}`);
35
- }
36
- return targetPallet;
37
- }
38
- }
39
- exports.Executor = Executor;
@@ -1,110 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.RpcExecutor = void 0;
4
- const util_1 = require("@polkadot/util");
5
- const specs_1 = require("@dedot/specs");
6
- const utils_1 = require("@dedot/utils");
7
- const Executor_1 = require("./Executor");
8
- const isOptionalParam = (param) => {
9
- return param.isOptional || param.name.startsWith('Option<');
10
- };
11
- /**
12
- * @name RpcExecutor
13
- * @description Execute a rpc based from an RPC spec,
14
- * if a spec is not found we execute an arbitrary rpc method
15
- */
16
- class RpcExecutor extends Executor_1.Executor {
17
- execute(section, method) {
18
- const maybeRpcName = `${section}_${method}`;
19
- const callSpec = (0, specs_1.findRpcSpec)(maybeRpcName) || (0, specs_1.findAliasRpcSpec)(maybeRpcName);
20
- const rpcName = callSpec?.name || `${section}_${method}`;
21
- const isSubscription = !!callSpec?.pubsub;
22
- const fnRpc = async (...args) => {
23
- (0, utils_1.assert)(callSpec, 'Rpc spec not found');
24
- this.checkRpcInputs(callSpec, args);
25
- const { params } = callSpec;
26
- const formattedInputs = args.map((input, index) => this.tryEncode(params[index], input));
27
- const result = await this.provider.send(rpcName, formattedInputs);
28
- return this.tryDecode(callSpec, result);
29
- };
30
- const fnSubRpc = async (...args) => {
31
- (0, utils_1.assert)(callSpec, 'Rpc spec not found');
32
- const inArgs = args.slice();
33
- const callback = inArgs.pop();
34
- (0, utils_1.assert)((0, util_1.isFunction)(callback), 'A callback is required for subscription');
35
- this.checkRpcInputs(callSpec, inArgs);
36
- const onNewMessage = (error, result) => {
37
- if (error) {
38
- console.error(error);
39
- return;
40
- }
41
- callback(this.tryDecode(callSpec, result));
42
- };
43
- const { params, pubsub } = callSpec;
44
- const formattedInputs = inArgs.map((input, index) => this.tryEncode(params[index], input));
45
- const [subname, subscribe, unsubcribe] = pubsub;
46
- const subscription = this.provider.subscribe(subname, subscribe, formattedInputs, onNewMessage);
47
- return async () => {
48
- return subscription
49
- .then((subscriptionId) => this.provider.unsubscribe(subname, unsubcribe, subscriptionId))
50
- .catch((err) => {
51
- console.error(err);
52
- return false;
53
- });
54
- };
55
- };
56
- if (!callSpec) {
57
- // Call arbitrary rpc method
58
- return async (...args) => {
59
- return await this.provider.send(rpcName, args);
60
- };
61
- }
62
- const oneFnRpc = isSubscription ? fnSubRpc : fnRpc;
63
- oneFnRpc.meta = callSpec;
64
- return oneFnRpc;
65
- }
66
- tryDecode(callSpec, raw) {
67
- if (raw === null) {
68
- // We use `undefined` to represent Option::None in the client
69
- return undefined;
70
- }
71
- const { type, isScale, codec } = callSpec;
72
- if (isScale) {
73
- (0, utils_1.assert)(codec, 'Codec not found to decode response');
74
- return codec.tryDecode(raw);
75
- }
76
- if ((0, utils_1.isNativeType)(type)) {
77
- return raw;
78
- }
79
- return raw;
80
- }
81
- tryEncode(paramSpec, value) {
82
- const { isScale, codec, isOptional } = paramSpec;
83
- if (isScale) {
84
- if (isOptional && (value === undefined || value === null)) {
85
- return null;
86
- }
87
- (0, utils_1.assert)(codec, 'Codec not found to encode params');
88
- return (0, util_1.u8aToHex)(codec.tryEncode(value));
89
- }
90
- // TODO generalize this!
91
- if (value && value['toJSON']) {
92
- return value.toJSON();
93
- }
94
- return value;
95
- }
96
- checkRpcInputs(callSpec, actualArgs) {
97
- const params = callSpec.params;
98
- if (params.length === actualArgs.length) {
99
- return;
100
- }
101
- params.forEach((param, idx) => {
102
- const isRequiredParam = !isOptionalParam(param);
103
- if (isRequiredParam && actualArgs[idx] === undefined) {
104
- const requiredParamCount = params.filter((p) => !isOptionalParam(p)).length;
105
- throw new Error(`Miss match RPC params, required ${requiredParamCount} params, current inputs length: ${actualArgs.length}`);
106
- }
107
- });
108
- }
109
- }
110
- exports.RpcExecutor = RpcExecutor;
@@ -1,108 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.RuntimeApiExecutor = exports.FallbackRuntimeApiSpecs = exports.FallbackRuntimeApis = void 0;
4
- const Executor_1 = require("./Executor");
5
- const utils_1 = require("@dedot/utils");
6
- const util_1 = require("@polkadot/util");
7
- const specs_1 = require("@dedot/specs");
8
- exports.FallbackRuntimeApis = [
9
- ['0x37e397fc7c91f5e4', 2], // Metadata Api v2
10
- ];
11
- exports.FallbackRuntimeApiSpecs = { Metadata: specs_1.Metadata };
12
- class RuntimeApiExecutor extends Executor_1.Executor {
13
- execute(runtimeApi, method) {
14
- const runtimeApiName = (0, util_1.stringPascalCase)(runtimeApi);
15
- const methodName = (0, utils_1.stringSnakeCase)(method);
16
- const callName = this.#callName({ runtimeApiName, methodName });
17
- const callSpec = this.#findRuntimeApiMethodSpec(runtimeApiName, methodName);
18
- (0, utils_1.assert)(callSpec, `Runtime api spec not found for ${callName}`);
19
- const callFn = async (...args) => {
20
- const { params } = callSpec;
21
- const formattedInputs = params.map((param, index) => this.tryEncode(param, args[index]));
22
- const bytes = (0, util_1.u8aToHex)((0, util_1.u8aConcat)(...formattedInputs));
23
- const callArgs = [callName, bytes];
24
- if (this.atBlockHash) {
25
- callArgs.push(this.atBlockHash);
26
- }
27
- const result = await this.api.rpc.state.call(...callArgs);
28
- return this.tryDecode(callSpec, result);
29
- };
30
- callFn.meta = callSpec;
31
- return callFn;
32
- }
33
- tryDecode(callSpec, raw) {
34
- const $codec = this.#findCodec(callSpec, `Codec not found to decode respond data for ${this.#callName(callSpec)}`);
35
- return $codec.tryDecode(raw);
36
- }
37
- tryEncode(paramSpec, value) {
38
- const $codec = this.#findCodec(paramSpec, `Codec not found to encode input for param ${paramSpec.name}`);
39
- return $codec.tryEncode(value);
40
- }
41
- #findCodec(spec, error) {
42
- const { codec, typeId, type } = spec;
43
- if (codec)
44
- return codec;
45
- if ((0, util_1.isNumber)(typeId)) {
46
- return this.registry.findCodec(typeId);
47
- }
48
- throw new Error(error || 'Codec not found');
49
- }
50
- #callName({ runtimeApiName, methodName }) {
51
- return `${runtimeApiName}_${methodName}`;
52
- }
53
- #findRuntimeApiMethodSpec(runtimeApi, method) {
54
- const targetVersion = this.#findTargetRuntimeApiVersion(runtimeApi);
55
- if (!(0, util_1.isNumber)(targetVersion))
56
- return undefined;
57
- const userDefinedSpec = this.#findDefinedSpec(this.api.options.runtimeApis, runtimeApi, method, targetVersion);
58
- if (userDefinedSpec)
59
- return userDefinedSpec;
60
- const methodDef = this.#findRuntimeApiMethodDef(runtimeApi, method);
61
- if (methodDef) {
62
- return this.#toMethodSpec(runtimeApi, methodDef);
63
- }
64
- return this.#findDefinedSpec(exports.FallbackRuntimeApiSpecs, runtimeApi, method, targetVersion);
65
- }
66
- #findRuntimeApiMethodDef(runtimeApi, method) {
67
- try {
68
- for (const api of this.metadata.apis) {
69
- if (api.name !== runtimeApi)
70
- continue;
71
- for (const apiMethod of api.methods) {
72
- if (apiMethod.name === method)
73
- return apiMethod;
74
- }
75
- }
76
- }
77
- catch { }
78
- }
79
- #toMethodSpec(runtimeApi, methodDef) {
80
- const { name, inputs, output, docs } = methodDef;
81
- return {
82
- docs,
83
- runtimeApiName: runtimeApi,
84
- methodName: name,
85
- typeId: output,
86
- params: inputs.map(({ name, typeId }) => ({
87
- name,
88
- typeId,
89
- })),
90
- };
91
- }
92
- #findTargetRuntimeApiVersion(runtimeApi) {
93
- const runtimeApiHash = (0, utils_1.calculateRuntimeApiHash)(runtimeApi);
94
- const runtimeApiVersions = this.api.runtimeVersion?.apis || exports.FallbackRuntimeApis;
95
- const foundVersion = runtimeApiVersions
96
- .find(([supportedRuntimeApiHash]) => runtimeApiHash === supportedRuntimeApiHash)
97
- ?.at(1);
98
- return foundVersion;
99
- }
100
- #findDefinedSpec(specs, runtimeApi, method, runtimeApiVersion) {
101
- if (!specs)
102
- return undefined;
103
- const methodSpecs = (0, specs_1.toRuntimeApiSpecs)(specs).map(specs_1.toRuntimeApiMethods).flat();
104
- return methodSpecs.find(({ runtimeApiName, methodName, version }) => `${(0, util_1.stringPascalCase)(runtimeApiName)}_${(0, utils_1.stringSnakeCase)(methodName)}` === `${runtimeApi}_${method}` &&
105
- runtimeApiVersion === version);
106
- }
107
- }
108
- exports.RuntimeApiExecutor = RuntimeApiExecutor;
@@ -1,33 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.StorageQueryExecutor = void 0;
4
- const Executor_1 = require("./Executor");
5
- const QueryableStorage_1 = require("../storage/QueryableStorage");
6
- const util_1 = require("@polkadot/util");
7
- /**
8
- * @name StorageQueryExecutor
9
- * @description Execute a query to on-chain storage
10
- */
11
- class StorageQueryExecutor extends Executor_1.Executor {
12
- execute(pallet, storage) {
13
- return async (...args) => {
14
- const entry = new QueryableStorage_1.QueryableStorage(this.registry, pallet, storage);
15
- const inArgs = args.slice();
16
- const lastArg = args.at(-1);
17
- const callback = (0, util_1.isFunction)(lastArg) ? inArgs.pop() : undefined;
18
- const encodedKey = entry.encodeKey(inArgs.at(0));
19
- // if a callback is passed, make a storage subscription and return an unsub function
20
- if (callback) {
21
- return await this.api.rpc.state.subscribeStorage([encodedKey], (changeSet) => {
22
- const targetChange = changeSet.changes.find((change) => change[0] === encodedKey);
23
- targetChange && callback(entry.decodeValue(targetChange[1]));
24
- });
25
- }
26
- else {
27
- const result = await this.api.rpc.state.getStorage(encodedKey, this.atBlockHash);
28
- return entry.decodeValue(result);
29
- }
30
- };
31
- }
32
- }
33
- exports.StorageQueryExecutor = StorageQueryExecutor;
@@ -1,153 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.TxExecutor = exports.signRaw = exports.isKeyringPair = void 0;
4
- const Executor_1 = require("./Executor");
5
- const utils_1 = require("@dedot/utils");
6
- const util_1 = require("@polkadot/util");
7
- const codecs_1 = require("@dedot/codecs");
8
- const extrinsic_1 = require("../extrinsic");
9
- const utils_2 = require("@dedot/utils");
10
- function isKeyringPair(account) {
11
- return (0, util_1.isFunction)(account.sign);
12
- }
13
- exports.isKeyringPair = isKeyringPair;
14
- /**
15
- * Sign a raw message
16
- * @param signerPair
17
- * @param raw
18
- * @param options
19
- */
20
- function signRaw(signerPair, raw, options) {
21
- const u8a = (0, util_1.hexToU8a)(raw);
22
- // Ref: https://github.com/paritytech/polkadot-sdk/blob/943697fa693a4da6ef481ef93df522accb7d0583/substrate/primitives/runtime/src/generic/unchecked_extrinsic.rs#L234-L238
23
- const toSignRaw = u8a.length > 256 ? (0, utils_2.blake2AsU8a)(u8a, 256) : u8a;
24
- return signerPair.sign(toSignRaw, options);
25
- }
26
- exports.signRaw = signRaw;
27
- /**
28
- * @name TxExecutor
29
- * @description Execute a transaction instruction, returns a submittable extrinsic
30
- */
31
- class TxExecutor extends Executor_1.Executor {
32
- execute(pallet, functionName) {
33
- const targetPallet = this.getPallet(pallet);
34
- (0, utils_1.assert)(targetPallet.calls, `Tx calls are not available for pallet ${targetPallet.name}`);
35
- const txType = this.metadata.types[targetPallet.calls];
36
- (0, utils_1.assert)(txType.type.tag === 'Enum', 'Tx type defs should be enum');
37
- const isFlatEnum = txType.type.value.members.every((m) => m.fields.length === 0);
38
- const txCallDef = txType.type.value.members.find((m) => (0, util_1.stringCamelCase)(m.name) === functionName);
39
- (0, utils_1.assert)(txCallDef, `Tx call spec not found for ${pallet}.${functionName}`);
40
- const txCallFn = (...args) => {
41
- let call;
42
- if (isFlatEnum) {
43
- call = {
44
- pallet: (0, util_1.stringPascalCase)(targetPallet.name),
45
- palletCall: (0, util_1.stringPascalCase)(txCallDef.name),
46
- };
47
- }
48
- else {
49
- const callParams = txCallDef.fields.reduce((o, { name }, idx) => {
50
- o[(0, util_1.stringCamelCase)(name)] = args[idx];
51
- return o;
52
- }, {});
53
- call = {
54
- pallet: (0, util_1.stringPascalCase)(targetPallet.name),
55
- palletCall: {
56
- name: (0, util_1.stringPascalCase)(txCallDef.name),
57
- params: callParams,
58
- },
59
- };
60
- }
61
- return this.createExtrinsic(call);
62
- };
63
- txCallFn.meta = {
64
- ...txCallDef,
65
- fieldCodecs: txCallDef.fields.map(({ typeId }) => this.registry.findCodec(typeId)),
66
- pallet: targetPallet.name,
67
- palletIndex: targetPallet.index,
68
- };
69
- return txCallFn;
70
- }
71
- createExtrinsic(call) {
72
- const api = this.api;
73
- class SubmittableExtrinsic extends codecs_1.Extrinsic {
74
- async sign(fromAccount, options) {
75
- const address = isKeyringPair(fromAccount) ? fromAccount.address : fromAccount.toString();
76
- const extra = new extrinsic_1.ExtraSignedExtension(api, {
77
- signerAddress: address,
78
- payloadOptions: options,
79
- });
80
- await extra.init();
81
- const { signer } = options || {};
82
- let signature;
83
- if (isKeyringPair(fromAccount)) {
84
- signature = (0, util_1.u8aToHex)(signRaw(fromAccount, extra.toRawPayload(this.callHex).data, { withType: true }));
85
- }
86
- else if (signer?.signPayload) {
87
- const result = await signer.signPayload(extra.toPayload(this.callHex));
88
- signature = result.signature;
89
- }
90
- else {
91
- throw new Error('Signer not found. Cannot sign the extrinsic!');
92
- }
93
- const { signatureTypeId } = this.registry.metadata.extrinsic;
94
- const $Signature = this.registry.findCodec(signatureTypeId);
95
- this.attachSignature({
96
- address: address,
97
- signature: $Signature.tryDecode(signature),
98
- extra: extra.data,
99
- });
100
- return this;
101
- }
102
- async signAndSend(fromAccount, partialOptions, maybeCallback) {
103
- const [options, callback] = this.#normalizeOptions(partialOptions, maybeCallback);
104
- await this.sign(fromAccount, options);
105
- return this.send(callback);
106
- }
107
- #normalizeOptions(partialOptions, callback) {
108
- if ((0, util_1.isFunction)(partialOptions)) {
109
- return [{}, partialOptions];
110
- }
111
- else {
112
- return [(0, util_1.objectSpread)({}, partialOptions), callback];
113
- }
114
- }
115
- async dryRun(account, optionsOrHash) {
116
- const dryRunFn = api.rpc.system.dryRun;
117
- (0, utils_1.assert)(dryRunFn.meta, 'system_dryRun RPC does not supported!');
118
- if ((0, util_1.isHex)(optionsOrHash)) {
119
- return dryRunFn(this.toHex(), optionsOrHash);
120
- }
121
- await this.sign(account, optionsOrHash);
122
- return dryRunFn(this.toHex());
123
- }
124
- async send(callback) {
125
- const isSubscription = !!callback;
126
- const txHash = this.hash;
127
- if (isSubscription) {
128
- return api.rpc.author.submitAndWatchExtrinsic(this.toHex(), async (status) => {
129
- if (status.tag === 'InBlock' || status.tag === 'Finalized') {
130
- const blockHash = status.value;
131
- const [signedBlock, blockEvents] = await Promise.all([
132
- api.rpc.chain.getBlock(blockHash),
133
- api.queryAt(blockHash).system.events(),
134
- ]);
135
- const txIndex = signedBlock.block.extrinsics.findIndex((tx) => (0, utils_2.blake2AsHex)((0, util_1.hexToU8a)(tx)) === txHash);
136
- (0, utils_1.assert)(txIndex >= 0, 'Extrinsic not found!');
137
- const events = blockEvents.filter(({ phase }) => phase.tag === 'ApplyExtrinsic' && phase.value === txIndex);
138
- return callback(new extrinsic_1.SubmittableResult({ status, txHash, events, txIndex }));
139
- }
140
- else {
141
- return callback(new extrinsic_1.SubmittableResult({ status, txHash }));
142
- }
143
- });
144
- }
145
- else {
146
- return api.rpc.author.submitExtrinsic(this.toHex());
147
- }
148
- }
149
- }
150
- return new SubmittableExtrinsic(api.registry, call);
151
- }
152
- }
153
- exports.TxExecutor = TxExecutor;
@@ -1,33 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.SubmittableResult = void 0;
4
- class SubmittableResult {
5
- dispatchInfo;
6
- dispatchError;
7
- events;
8
- status;
9
- txHash;
10
- txIndex;
11
- constructor({ events, status, txHash, txIndex }) {
12
- this.events = events || [];
13
- this.status = status;
14
- this.txHash = txHash;
15
- this.txIndex = txIndex;
16
- [this.dispatchInfo, this.dispatchError] = this.#extractInfo();
17
- }
18
- #extractInfo() {
19
- for (const { event } of this.events) {
20
- const { pallet, palletEvent } = event;
21
- if (pallet === 'System' && palletEvent.name === 'ExtrinsicFailed') {
22
- const { dispatchInfo, dispatchError } = palletEvent.data;
23
- return [dispatchInfo, dispatchError];
24
- }
25
- else if (pallet === 'System' && palletEvent.name === 'ExtrinsicSuccess') {
26
- const { dispatchInfo } = palletEvent.data;
27
- return [dispatchInfo, undefined];
28
- }
29
- }
30
- return [undefined, undefined];
31
- }
32
- }
33
- exports.SubmittableResult = SubmittableResult;
@@ -1,88 +0,0 @@
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 __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
- };
25
- Object.defineProperty(exports, "__esModule", { value: true });
26
- exports.ExtraSignedExtension = void 0;
27
- const SignedExtension_1 = require("./SignedExtension");
28
- const utils_1 = require("@dedot/utils");
29
- const $ = __importStar(require("@dedot/shape"));
30
- const known_1 = require("./known");
31
- const util_1 = require("@polkadot/util");
32
- class ExtraSignedExtension extends SignedExtension_1.SignedExtension {
33
- #signedExtensions;
34
- async init() {
35
- this.#signedExtensions = this.#getSignedExtensions();
36
- await Promise.all(this.#signedExtensions.map((se) => se.init()));
37
- this.data = this.#signedExtensions.map((se) => se.data);
38
- this.additionalSigned = this.#signedExtensions.map((se) => se.additionalSigned);
39
- }
40
- get identifier() {
41
- return 'ExtraSignedExtension';
42
- }
43
- get dataCodec() {
44
- const { extraTypeId } = this.registry.metadata.extrinsic;
45
- return (0, utils_1.ensurePresence)(this.registry.findCodec(extraTypeId));
46
- }
47
- get additionalSignedCodec() {
48
- const $AdditionalSignedCodecs = this.#signedExtensionDefs.map((se) => this.registry.findCodec(se.additionalSigned));
49
- return $.Tuple(...$AdditionalSignedCodecs);
50
- }
51
- get payloadCodec() {
52
- const { callTypeId } = this.registry.metadata.extrinsic;
53
- const $Call = this.registry.findCodec(callTypeId);
54
- return $.Tuple($Call, this.dataCodec, this.additionalSignedCodec);
55
- }
56
- get #signedExtensionDefs() {
57
- return this.registry.metadata.extrinsic.signedExtensions;
58
- }
59
- #getSignedExtensions() {
60
- return this.#signedExtensionDefs.map((extDef) => {
61
- const { signedExtensions: userSignedExtensions = {} } = this.api.options;
62
- const Extension = userSignedExtensions[extDef.ident] ||
63
- known_1.knownSignedExtensions[extDef.ident];
64
- (0, utils_1.assert)(Extension, `SignedExtension for ${extDef.ident} not found`);
65
- return new Extension(this.api, {
66
- ...(0, utils_1.ensurePresence)(this.options),
67
- def: extDef,
68
- });
69
- });
70
- }
71
- toPayload(call = '0x') {
72
- const signedExtensions = this.#signedExtensions.map((se) => se.identifier);
73
- const { version } = this.registry.metadata.extrinsic;
74
- return (0, util_1.objectSpread)({ address: this.options.signerAddress, signedExtensions, version, method: call }, ...this.#signedExtensions.map((se) => se.toPayload()));
75
- }
76
- toRawPayload(call = '0x') {
77
- const payload = this.toPayload(call);
78
- const $ToSignPayload = $.Tuple($.RawHex, this.dataCodec, this.additionalSignedCodec);
79
- const toSignPayload = [call, this.data, this.additionalSigned];
80
- const rawPayload = $ToSignPayload.tryEncode(toSignPayload);
81
- return {
82
- address: payload.address,
83
- data: (0, util_1.u8aToHex)(rawPayload),
84
- type: 'payload',
85
- };
86
- }
87
- }
88
- exports.ExtraSignedExtension = ExtraSignedExtension;