@talismn/sapi 0.0.0-pr1876-20250414012202
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.
- package/LICENSE +674 -0
- package/README.md +1 -0
- package/dist/declarations/src/helpers/errors.d.ts +2 -0
- package/dist/declarations/src/helpers/getCallDocs.d.ts +2 -0
- package/dist/declarations/src/helpers/getChainInfo.d.ts +7 -0
- package/dist/declarations/src/helpers/getConstantValue.d.ts +2 -0
- package/dist/declarations/src/helpers/getDecodedCall.d.ts +11 -0
- package/dist/declarations/src/helpers/getDryRunCall.d.ts +11 -0
- package/dist/declarations/src/helpers/getExtrinsicDispatchInfo.d.ts +7 -0
- package/dist/declarations/src/helpers/getFeeEstimate.d.ts +3 -0
- package/dist/declarations/src/helpers/getPayloadWithMetadataHash.d.ts +6 -0
- package/dist/declarations/src/helpers/getRuntimeCallResult.d.ts +2 -0
- package/dist/declarations/src/helpers/getSapiConnector.d.ts +3 -0
- package/dist/declarations/src/helpers/getSendRequestResult.d.ts +2 -0
- package/dist/declarations/src/helpers/getSignerPayloadJSON.d.ts +7 -0
- package/dist/declarations/src/helpers/getStorageValue.d.ts +2 -0
- package/dist/declarations/src/helpers/getTypeRegistry.d.ts +4 -0
- package/dist/declarations/src/helpers/isApiAvailable.d.ts +2 -0
- package/dist/declarations/src/helpers/papi.d.ts +5 -0
- package/dist/declarations/src/helpers/types.d.ts +26 -0
- package/dist/declarations/src/index.d.ts +2 -0
- package/dist/declarations/src/log.d.ts +2 -0
- package/dist/declarations/src/sapi.d.ts +50 -0
- package/dist/declarations/src/types.d.ts +18 -0
- package/dist/talismn-sapi.cjs.d.ts +1 -0
- package/dist/talismn-sapi.cjs.dev.js +535 -0
- package/dist/talismn-sapi.cjs.js +7 -0
- package/dist/talismn-sapi.cjs.prod.js +535 -0
- package/dist/talismn-sapi.esm.js +529 -0
- package/package.json +55 -0
|
@@ -0,0 +1,535 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
var util = require('@polkadot/util');
|
|
4
|
+
var scale = require('@talismn/scale');
|
|
5
|
+
var anylogger = require('anylogger');
|
|
6
|
+
var polkadotApi = require('polkadot-api');
|
|
7
|
+
var metadataBuilders = require('@polkadot-api/metadata-builders');
|
|
8
|
+
var utils = require('@polkadot-api/utils');
|
|
9
|
+
var types = require('@polkadot/types');
|
|
10
|
+
var merkleizeMetadata = require('@polkadot-api/merkleize-metadata');
|
|
11
|
+
var substrateBindings = require('@polkadot-api/substrate-bindings');
|
|
12
|
+
|
|
13
|
+
function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
|
|
14
|
+
|
|
15
|
+
var anylogger__default = /*#__PURE__*/_interopDefault(anylogger);
|
|
16
|
+
|
|
17
|
+
var packageJson = {
|
|
18
|
+
name: "@talismn/sapi"};
|
|
19
|
+
|
|
20
|
+
var log = anylogger__default.default(packageJson.name);
|
|
21
|
+
|
|
22
|
+
const getCallDocs = (chain, pallet, method) => {
|
|
23
|
+
try {
|
|
24
|
+
const typeIdCalls = chain.metadata.pallets.find(({
|
|
25
|
+
name
|
|
26
|
+
}) => name === pallet)?.calls;
|
|
27
|
+
if (!typeIdCalls) return null;
|
|
28
|
+
|
|
29
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
30
|
+
let palletCalls = chain.metadata.lookup[typeIdCalls];
|
|
31
|
+
if (!palletCalls || palletCalls.id !== typeIdCalls) palletCalls = chain.metadata.lookup.find(v => v.id === typeIdCalls);
|
|
32
|
+
if (!palletCalls) return null;
|
|
33
|
+
const call = palletCalls.def.value.find(c => c.name === method);
|
|
34
|
+
return call?.docs?.join("\n") ?? null;
|
|
35
|
+
} catch (err) {
|
|
36
|
+
log.error("Failed to find call docs", {
|
|
37
|
+
pallet,
|
|
38
|
+
method,
|
|
39
|
+
chain
|
|
40
|
+
});
|
|
41
|
+
return null;
|
|
42
|
+
}
|
|
43
|
+
};
|
|
44
|
+
|
|
45
|
+
const getConstantValue = (chain, pallet, constant) => {
|
|
46
|
+
try {
|
|
47
|
+
const storageCodec = chain.builder.buildConstant(pallet, constant);
|
|
48
|
+
const encodedValue = chain.metadata.pallets.find(({
|
|
49
|
+
name
|
|
50
|
+
}) => name === pallet)?.constants.find(({
|
|
51
|
+
name
|
|
52
|
+
}) => name === constant)?.value;
|
|
53
|
+
if (!encodedValue) throw new Error(`Constant ${pallet}.${constant} not found`);
|
|
54
|
+
return storageCodec.dec(encodedValue);
|
|
55
|
+
} catch (err) {
|
|
56
|
+
log.error("Failed to get constant value", {
|
|
57
|
+
err,
|
|
58
|
+
chainId: chain.connector.chainId,
|
|
59
|
+
pallet,
|
|
60
|
+
constant
|
|
61
|
+
});
|
|
62
|
+
throw err;
|
|
63
|
+
}
|
|
64
|
+
};
|
|
65
|
+
|
|
66
|
+
const getChainInfo = chain => {
|
|
67
|
+
const {
|
|
68
|
+
spec_name: specName,
|
|
69
|
+
spec_version: specVersion,
|
|
70
|
+
transaction_version: transactionVersion
|
|
71
|
+
} = getConstantValue(chain, "System", "Version");
|
|
72
|
+
const base58Prefix = getConstantValue(chain, "System", "SS58Prefix");
|
|
73
|
+
return {
|
|
74
|
+
specName,
|
|
75
|
+
specVersion,
|
|
76
|
+
transactionVersion,
|
|
77
|
+
base58Prefix
|
|
78
|
+
};
|
|
79
|
+
};
|
|
80
|
+
|
|
81
|
+
const getDecodedCall = (palletName, methodName, args) => ({
|
|
82
|
+
type: palletName,
|
|
83
|
+
value: {
|
|
84
|
+
type: methodName,
|
|
85
|
+
value: args
|
|
86
|
+
}
|
|
87
|
+
});
|
|
88
|
+
const getDecodedCallFromPayload = (chain, payload) => {
|
|
89
|
+
const def = chain.builder.buildDefinition(chain.lookup.call);
|
|
90
|
+
const decoded = def.dec(payload.method);
|
|
91
|
+
return {
|
|
92
|
+
pallet: decoded.type,
|
|
93
|
+
method: decoded.value.type,
|
|
94
|
+
args: decoded.value.value
|
|
95
|
+
};
|
|
96
|
+
};
|
|
97
|
+
|
|
98
|
+
const getDispatchErrorMessage = (chain, err) => {
|
|
99
|
+
try {
|
|
100
|
+
if (!err) return null;
|
|
101
|
+
const error = err;
|
|
102
|
+
if (!error.type) throw new Error("Unknown dispatch error");
|
|
103
|
+
const lv1 = DISPATCH_ERROR[error.type];
|
|
104
|
+
if (!lv1) throw new Error("Unknown dispatch error");
|
|
105
|
+
if (lv1 === ERROR_METADATA_LOOKUP) return getModuleErrorMessage(chain, error.value);
|
|
106
|
+
if (typeof lv1 === "string") return lv1;
|
|
107
|
+
const lv2 = lv1[error.value?.type];
|
|
108
|
+
if (!lv2) throw new Error("Unknown dispatch error");
|
|
109
|
+
if (typeof lv2 === "string") return lv2;
|
|
110
|
+
throw new Error("Unknown dispatch error");
|
|
111
|
+
} catch (cause) {
|
|
112
|
+
log.error("Failed to parse runtime error", {
|
|
113
|
+
chainId: chain.connector.chainId,
|
|
114
|
+
cause,
|
|
115
|
+
err
|
|
116
|
+
});
|
|
117
|
+
return tryFormatError(err);
|
|
118
|
+
}
|
|
119
|
+
};
|
|
120
|
+
const ERROR_METADATA_LOOKUP = "METADATA_LOOKUP";
|
|
121
|
+
|
|
122
|
+
// only `Module` errors are part of the metadata
|
|
123
|
+
// errors below are defined as part of the runtime but their docs aren't included in the metadata
|
|
124
|
+
// so those are copy/pasted from the polkadot-sdk repo
|
|
125
|
+
|
|
126
|
+
// https://github.com/paritytech/polkadot-sdk/blob/56d97c3ad8c86e602bc7ac368751210517c4309f/substrate/primitives/runtime/src/lib.rs#L543
|
|
127
|
+
const ERRORS_TRANSACTIONAL = {
|
|
128
|
+
LimitReached: "Too many transactional layers have been spawned",
|
|
129
|
+
NoLayer: "A transactional layer was expected, but does not exist"
|
|
130
|
+
};
|
|
131
|
+
|
|
132
|
+
// https://github.com/paritytech/polkadot-sdk/blob/56d97c3ad8c86e602bc7ac368751210517c4309f/substrate/primitives/runtime/src/lib.rs#L672
|
|
133
|
+
const ERRORS_TOKEN = {
|
|
134
|
+
FundsUnavailable: "Funds are unavailable",
|
|
135
|
+
OnlyProvider: "Account that must exist would die",
|
|
136
|
+
BelowMinimum: "Account cannot exist with the funds that would be given",
|
|
137
|
+
CannotCreate: "Account cannot be created",
|
|
138
|
+
UnknownAsset: "The asset in question is unknown",
|
|
139
|
+
Frozen: "Funds exist but are frozen",
|
|
140
|
+
Unsupported: "Operation is not supported by the asset",
|
|
141
|
+
CannotCreateHold: "Account cannot be created for recording amount on hold",
|
|
142
|
+
NotExpendable: "Account that is desired to remain would die",
|
|
143
|
+
Blocked: "Account cannot receive the assets"
|
|
144
|
+
};
|
|
145
|
+
|
|
146
|
+
// https://github.com/paritytech/polkadot-sdk/blob/56d97c3ad8c86e602bc7ac368751210517c4309f/substrate/primitives/arithmetic/src/lib.rs#L76
|
|
147
|
+
const ERRORS_ARITHMETIC = {
|
|
148
|
+
Overflow: "An underflow would occur",
|
|
149
|
+
Underflow: "An overflow would occur",
|
|
150
|
+
DivisionByZero: "Division by zero"
|
|
151
|
+
};
|
|
152
|
+
|
|
153
|
+
// https://github.com/paritytech/polkadot-sdk/blob/56d97c3ad8c86e602bc7ac368751210517c4309f/substrate/primitives/runtime/src/lib.rs#L714
|
|
154
|
+
const DISPATCH_ERROR = {
|
|
155
|
+
CannotLookup: "Cannot lookup",
|
|
156
|
+
BadOrigin: "Bad origin",
|
|
157
|
+
Module: ERROR_METADATA_LOOKUP,
|
|
158
|
+
ConsumerRemaining: "Consumer remaining",
|
|
159
|
+
NoProviders: "No providers",
|
|
160
|
+
TooManyConsumers: "Too many consumers",
|
|
161
|
+
Token: ERRORS_TOKEN,
|
|
162
|
+
Arithmetic: ERRORS_ARITHMETIC,
|
|
163
|
+
Transactional: ERRORS_TRANSACTIONAL,
|
|
164
|
+
Exhausted: "Resources exhausted",
|
|
165
|
+
Corruption: "State corrupt",
|
|
166
|
+
Unavailable: "Resource unavailable",
|
|
167
|
+
RootNotAllowed: "Root not allowed",
|
|
168
|
+
Trie: "Unknown error",
|
|
169
|
+
// unsupported,
|
|
170
|
+
Other: "Unknown error" // unsupported,
|
|
171
|
+
};
|
|
172
|
+
const getModuleErrorMessage = (chain, error) => {
|
|
173
|
+
try {
|
|
174
|
+
if (!chain.metadata) throw new Error("Could not fetch metadata");
|
|
175
|
+
const pallet = chain.metadata.pallets.find(p => p.name === error.type);
|
|
176
|
+
if (typeof pallet?.errors !== "number") throw new Error("Unknown pallet");
|
|
177
|
+
const lookup = metadataBuilders.getLookupFn(chain.metadata);
|
|
178
|
+
const palletErrors = lookup(pallet.errors);
|
|
179
|
+
if (palletErrors.type !== "enum" || !palletErrors.innerDocs[error.value.type]?.length) throw new Error("Unknown error type");
|
|
180
|
+
|
|
181
|
+
// biome-ignore lint/style/noNonNullAssertion: <explanation>
|
|
182
|
+
return palletErrors.innerDocs[error.value.type].join(" ");
|
|
183
|
+
} catch (err) {
|
|
184
|
+
log.error("Failed to parse module error", {
|
|
185
|
+
chainId: chain.connector.chainId,
|
|
186
|
+
error,
|
|
187
|
+
err
|
|
188
|
+
});
|
|
189
|
+
return [error.type, error.value.type].join(": ");
|
|
190
|
+
}
|
|
191
|
+
};
|
|
192
|
+
const tryFormatError = err => {
|
|
193
|
+
try {
|
|
194
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
195
|
+
const unsafeErr = err;
|
|
196
|
+
if (unsafeErr.type && unsafeErr.value?.type) return [unsafeErr.type, unsafeErr.value.type].join(": ");
|
|
197
|
+
} catch (err) {
|
|
198
|
+
// ignore
|
|
199
|
+
}
|
|
200
|
+
return "Unknown error";
|
|
201
|
+
};
|
|
202
|
+
|
|
203
|
+
const getSendRequestResult = (chain, method, params, isCacheable) => {
|
|
204
|
+
return chain.connector.send(method, params, isCacheable);
|
|
205
|
+
};
|
|
206
|
+
|
|
207
|
+
const getRuntimeCallResult = async (chain, apiName, method, args) => {
|
|
208
|
+
const call = chain.builder.buildRuntimeCall(apiName, method);
|
|
209
|
+
const hex = await getSendRequestResult(chain, "state_call", [`${apiName}_${method}`, utils.toHex(call.args.enc(args))]);
|
|
210
|
+
return call.value.dec(hex);
|
|
211
|
+
};
|
|
212
|
+
|
|
213
|
+
const isApiAvailable = (chain, name, method) => {
|
|
214
|
+
return chain.metadata.apis.some(a => a.name === name && a.methods.some(m => m.name === method));
|
|
215
|
+
};
|
|
216
|
+
|
|
217
|
+
const getDryRunCall = async (chain, from, decodedCall) => {
|
|
218
|
+
log.log(`[sapi] getDryRun begin: ${Date.now()}`);
|
|
219
|
+
try {
|
|
220
|
+
if (!isApiAvailable(chain, "DryRunApi", "dry_run_call")) return {
|
|
221
|
+
available: false,
|
|
222
|
+
data: null
|
|
223
|
+
};
|
|
224
|
+
const origin = polkadotApi.Enum("system", polkadotApi.Enum("Signed", from));
|
|
225
|
+
const {
|
|
226
|
+
pallet,
|
|
227
|
+
method,
|
|
228
|
+
args
|
|
229
|
+
} = decodedCall;
|
|
230
|
+
const call = {
|
|
231
|
+
type: pallet,
|
|
232
|
+
value: {
|
|
233
|
+
type: method,
|
|
234
|
+
value: args
|
|
235
|
+
}
|
|
236
|
+
};
|
|
237
|
+
|
|
238
|
+
// This will throw an error if the api is not available on that chain
|
|
239
|
+
const data = await getRuntimeCallResult(chain, "DryRunApi", "dry_run_call", [origin, call]);
|
|
240
|
+
const ok = data.success && data.value.execution_result.success;
|
|
241
|
+
const errorMessage = data.success && !data.value.execution_result.success ? getDispatchErrorMessage(chain, data.value.execution_result.value.error) : null;
|
|
242
|
+
return {
|
|
243
|
+
available: true,
|
|
244
|
+
// NOTE: we can't re-export `@polkadot-api/descriptors` from this package.
|
|
245
|
+
// So, the caller of this function must pass in their own instance of `type DryRunResult` as the generic argument `T`.
|
|
246
|
+
data: data,
|
|
247
|
+
ok,
|
|
248
|
+
errorMessage
|
|
249
|
+
};
|
|
250
|
+
} catch (err) {
|
|
251
|
+
// Note : err is null if chain doesnt have the api
|
|
252
|
+
log.error("Failed to dry run", {
|
|
253
|
+
chainId: chain.connector.chainId,
|
|
254
|
+
err
|
|
255
|
+
});
|
|
256
|
+
return {
|
|
257
|
+
available: false,
|
|
258
|
+
data: null
|
|
259
|
+
};
|
|
260
|
+
} finally {
|
|
261
|
+
log.log(`[sapi] getDryRun end: ${Date.now()}`);
|
|
262
|
+
}
|
|
263
|
+
};
|
|
264
|
+
|
|
265
|
+
// used for chains that dont have metadata v15 yet
|
|
266
|
+
const getExtrinsicDispatchInfo = async (chain, signedExtrinsic) => {
|
|
267
|
+
util.assert(signedExtrinsic.isSigned, "Extrinsic must be signed (or fakeSigned) in order to query fee");
|
|
268
|
+
const len = signedExtrinsic.registry.createType("u32", signedExtrinsic.encodedLength);
|
|
269
|
+
const dispatchInfo = await stateCall(chain.connector.send, "TransactionPaymentApi_query_info", "RuntimeDispatchInfo", [signedExtrinsic, len], undefined, true);
|
|
270
|
+
return {
|
|
271
|
+
partialFee: dispatchInfo.partialFee.toString()
|
|
272
|
+
};
|
|
273
|
+
};
|
|
274
|
+
const stateCall = async (request, method, resultType, args, blockHash, isCacheable) => {
|
|
275
|
+
// on a state call there are always arguments
|
|
276
|
+
const registry = args[0].registry;
|
|
277
|
+
const bytes = registry.createType("Raw", util.u8aConcatStrict(args.map(arg => arg.toU8a())));
|
|
278
|
+
const result = await request("state_call", [method, bytes.toHex(), blockHash], isCacheable);
|
|
279
|
+
return registry.createType(resultType, result);
|
|
280
|
+
};
|
|
281
|
+
|
|
282
|
+
const getTypeRegistry = (chain, payload) => {
|
|
283
|
+
log.log(`[sapi] getTypeRegistry begin: ${Date.now()}`);
|
|
284
|
+
const registry = new types.TypeRegistry();
|
|
285
|
+
if (chain.registryTypes) registry.register(chain.registryTypes);
|
|
286
|
+
const meta = new types.Metadata(registry, chain.hexMetadata);
|
|
287
|
+
registry.setMetadata(meta, payload.signedExtensions, chain.signedExtensions); // ~30ms
|
|
288
|
+
|
|
289
|
+
log.log(`[sapi] getTypeRegistry end: ${Date.now()}`);
|
|
290
|
+
return registry;
|
|
291
|
+
};
|
|
292
|
+
|
|
293
|
+
const getFeeEstimate = async (chain, payload, chainInfo) => {
|
|
294
|
+
// TODO do this without PJS / registry => waiting for @polkadot-api/tx-utils
|
|
295
|
+
const registry = getTypeRegistry(chain, payload);
|
|
296
|
+
const extrinsic = registry.createType("Extrinsic", payload);
|
|
297
|
+
extrinsic.signFake(payload.address, {
|
|
298
|
+
appId: 0,
|
|
299
|
+
nonce: payload.nonce,
|
|
300
|
+
blockHash: payload.blockHash,
|
|
301
|
+
genesisHash: payload.genesisHash,
|
|
302
|
+
runtimeVersion: {
|
|
303
|
+
specVersion: chainInfo.specVersion,
|
|
304
|
+
transactionVersion: chainInfo.transactionVersion
|
|
305
|
+
// other fields aren't necessary for signing
|
|
306
|
+
}
|
|
307
|
+
});
|
|
308
|
+
const bytes = extrinsic.toU8a(true);
|
|
309
|
+
const binary = polkadotApi.Binary.fromBytes(bytes);
|
|
310
|
+
try {
|
|
311
|
+
const result = await getRuntimeCallResult(chain, "TransactionPaymentApi", "query_info", [binary, bytes.length]);
|
|
312
|
+
// Do not throw if partialFee is 0n. This is a valid response, eg: Bittensor remove_stake fee estimation is 0n.
|
|
313
|
+
if (!result?.partial_fee && result.partial_fee !== 0n) {
|
|
314
|
+
throw new Error("partialFee is not found");
|
|
315
|
+
}
|
|
316
|
+
return result.partial_fee;
|
|
317
|
+
} catch (err) {
|
|
318
|
+
log.error("Failed to get fee estimate using getRuntimeCallValue", {
|
|
319
|
+
err
|
|
320
|
+
});
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
// fallback to pjs encoded state call, in case the above fails (extracting runtime calls codecs might require metadata V15)
|
|
324
|
+
// Note: PAPI will consider TransactionPaymentApi as first class api so it should work even without V15, but this is not the case yet.
|
|
325
|
+
const {
|
|
326
|
+
partialFee
|
|
327
|
+
} = await getExtrinsicDispatchInfo(chain, extrinsic);
|
|
328
|
+
return BigInt(partialFee);
|
|
329
|
+
};
|
|
330
|
+
|
|
331
|
+
const getSapiConnector = ({
|
|
332
|
+
chainId,
|
|
333
|
+
send,
|
|
334
|
+
submit
|
|
335
|
+
}) => ({
|
|
336
|
+
chainId,
|
|
337
|
+
send,
|
|
338
|
+
submit: (...args) => {
|
|
339
|
+
if (submit) return submit(...args);
|
|
340
|
+
throw new Error("submit handler not provided");
|
|
341
|
+
}
|
|
342
|
+
});
|
|
343
|
+
|
|
344
|
+
const getPayloadWithMetadataHash = (chain, chainInfo, payload) => {
|
|
345
|
+
if (!chain.hasCheckMetadataHash || !payload.signedExtensions.includes("CheckMetadataHash")) return {
|
|
346
|
+
payload,
|
|
347
|
+
txMetadata: undefined
|
|
348
|
+
};
|
|
349
|
+
try {
|
|
350
|
+
const {
|
|
351
|
+
decimals,
|
|
352
|
+
symbol: tokenSymbol
|
|
353
|
+
} = chain.token;
|
|
354
|
+
const {
|
|
355
|
+
base58Prefix,
|
|
356
|
+
specName,
|
|
357
|
+
specVersion
|
|
358
|
+
} = chainInfo;
|
|
359
|
+
|
|
360
|
+
// since ultimately this needs a V15 object, would be nice if this accepted one directly as input
|
|
361
|
+
const merkleizedMetadata = merkleizeMetadata.merkleizeMetadata(chain.hexMetadata, {
|
|
362
|
+
tokenSymbol,
|
|
363
|
+
decimals,
|
|
364
|
+
base58Prefix,
|
|
365
|
+
specName,
|
|
366
|
+
specVersion
|
|
367
|
+
});
|
|
368
|
+
const metadataHash = utils.toHex(merkleizedMetadata.digest());
|
|
369
|
+
const payloadWithMetadataHash = {
|
|
370
|
+
...payload,
|
|
371
|
+
mode: 1,
|
|
372
|
+
metadataHash,
|
|
373
|
+
withSignedTransaction: true
|
|
374
|
+
};
|
|
375
|
+
|
|
376
|
+
// TODO do this without PJS / registry => waiting for @polkadot-api/tx-utils
|
|
377
|
+
// const { extra, additionalSigned } = getSignedExtensionValues(payload, metadata)
|
|
378
|
+
// const badExtPayload = mergeUint8(fromHex(payload.method), ...extra, ...additionalSigned)
|
|
379
|
+
|
|
380
|
+
const registry = getTypeRegistry(chain, payload);
|
|
381
|
+
const extPayload = registry.createType("ExtrinsicPayload", payloadWithMetadataHash);
|
|
382
|
+
const barePayload = extPayload.toU8a(true);
|
|
383
|
+
const txMetadata = merkleizedMetadata.getProofForExtrinsicPayload(barePayload);
|
|
384
|
+
return {
|
|
385
|
+
payload: payloadWithMetadataHash,
|
|
386
|
+
txMetadata
|
|
387
|
+
};
|
|
388
|
+
} catch (err) {
|
|
389
|
+
log.error("Failed to get shortened metadata", {
|
|
390
|
+
error: err
|
|
391
|
+
});
|
|
392
|
+
return {
|
|
393
|
+
payload,
|
|
394
|
+
txMetadata: undefined
|
|
395
|
+
};
|
|
396
|
+
}
|
|
397
|
+
};
|
|
398
|
+
|
|
399
|
+
const getStorageValue = async (chain, pallet, entry, keys, at) => {
|
|
400
|
+
const storageCodec = chain.builder.buildStorage(pallet, entry);
|
|
401
|
+
const stateKey = storageCodec.keys.enc(...keys);
|
|
402
|
+
const hexValue = await getSendRequestResult(chain, "state_getStorage", [stateKey, at]);
|
|
403
|
+
if (!hexValue) return null; // caller will need to expect null when applicable
|
|
404
|
+
|
|
405
|
+
return storageCodec.value.dec(hexValue);
|
|
406
|
+
};
|
|
407
|
+
|
|
408
|
+
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
|
|
409
|
+
//////////////////////////// Utilities from PAPI /////////////////////////////
|
|
410
|
+
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
|
|
411
|
+
|
|
412
|
+
const toPjsHex = (value, minByteLen) => {
|
|
413
|
+
let inner = value.toString(16);
|
|
414
|
+
inner = (inner.length % 2 ? "0" : "") + inner;
|
|
415
|
+
const nPaddedBytes = Math.max(0, (minByteLen || 0) - inner.length / 2);
|
|
416
|
+
return "0x" + "00".repeat(nPaddedBytes) + inner;
|
|
417
|
+
};
|
|
418
|
+
const mortal = substrateBindings.enhanceEncoder(substrateBindings.Bytes(2).enc, value => {
|
|
419
|
+
const factor = Math.max(value.period >> 12, 1);
|
|
420
|
+
const left = Math.min(Math.max(trailingZeroes(value.period) - 1, 1), 15);
|
|
421
|
+
const right = value.phase / factor << 4;
|
|
422
|
+
return substrateBindings.u16.enc(left | right);
|
|
423
|
+
});
|
|
424
|
+
function trailingZeroes(n) {
|
|
425
|
+
let i = 0;
|
|
426
|
+
while (!(n & 1)) {
|
|
427
|
+
i++;
|
|
428
|
+
n >>= 1;
|
|
429
|
+
}
|
|
430
|
+
return i;
|
|
431
|
+
}
|
|
432
|
+
|
|
433
|
+
const getSignerPayloadJSON = async (chain, palletName, methodName, args, signerConfig, chainInfo) => {
|
|
434
|
+
const {
|
|
435
|
+
codec,
|
|
436
|
+
location
|
|
437
|
+
} = chain.builder.buildCall(palletName, methodName);
|
|
438
|
+
const method = polkadotApi.Binary.fromBytes(utils.mergeUint8(new Uint8Array(location), codec.enc(args)));
|
|
439
|
+
const blockNumber = await getStorageValue(chain, "System", "Number", []);
|
|
440
|
+
if (blockNumber === null) throw new Error("Block number not found");
|
|
441
|
+
const [account, genesisHash, blockHash] = await Promise.all([
|
|
442
|
+
// TODO if V15 available, use a runtime call instead : AccountNonceApi/account_nonce
|
|
443
|
+
// about nonce https://github.com/paritytech/json-rpc-interface-spec/issues/156
|
|
444
|
+
getStorageValue(chain, "System", "Account", [signerConfig.address]), getStorageValue(chain, "System", "BlockHash", [0]), getSendRequestResult(chain, "chain_getBlockHash", [blockNumber], false) // TODO find the right way to fetch this with new RPC api, this is not available in storage yet
|
|
445
|
+
]);
|
|
446
|
+
if (!genesisHash) throw new Error("Genesis hash not found");
|
|
447
|
+
if (!blockHash) throw new Error("Block hash not found");
|
|
448
|
+
const nonce = account ? account.nonce : 0;
|
|
449
|
+
const era = mortal({
|
|
450
|
+
period: 16,
|
|
451
|
+
phase: blockNumber % 16
|
|
452
|
+
});
|
|
453
|
+
const signedExtensions = chain.metadata.extrinsic.signedExtensions.map(ext => ext.identifier.toString());
|
|
454
|
+
const basePayload = {
|
|
455
|
+
address: signerConfig.address,
|
|
456
|
+
genesisHash: genesisHash.asHex(),
|
|
457
|
+
blockHash,
|
|
458
|
+
method: method.asHex(),
|
|
459
|
+
signedExtensions,
|
|
460
|
+
nonce: toPjsHex(nonce, 4),
|
|
461
|
+
specVersion: toPjsHex(chainInfo.specVersion, 4),
|
|
462
|
+
transactionVersion: toPjsHex(chainInfo.transactionVersion, 4),
|
|
463
|
+
blockNumber: toPjsHex(blockNumber, 4),
|
|
464
|
+
era: utils.toHex(era),
|
|
465
|
+
tip: toPjsHex(0, 16),
|
|
466
|
+
// TODO gas station (required for Astar)
|
|
467
|
+
assetId: undefined,
|
|
468
|
+
version: 4
|
|
469
|
+
};
|
|
470
|
+
const {
|
|
471
|
+
payload,
|
|
472
|
+
txMetadata
|
|
473
|
+
} = getPayloadWithMetadataHash(chain, chainInfo, basePayload);
|
|
474
|
+
|
|
475
|
+
// Avail support
|
|
476
|
+
if (payload.signedExtensions.includes("CheckAppId")) payload.appId = 0;
|
|
477
|
+
log.log("[sapi] payload", {
|
|
478
|
+
newPayload: payload,
|
|
479
|
+
txMetadata
|
|
480
|
+
});
|
|
481
|
+
return {
|
|
482
|
+
payload,
|
|
483
|
+
txMetadata
|
|
484
|
+
};
|
|
485
|
+
};
|
|
486
|
+
|
|
487
|
+
const getScaleApi = (connector, hexMetadata, token, hasCheckMetadataHash, signedExtensions, registryTypes) => {
|
|
488
|
+
const decoded = scale.decodeMetadata(hexMetadata);
|
|
489
|
+
util.assert(decoded.metadata, `Missing Metadata V14+ for chain ${connector.chainId}`);
|
|
490
|
+
const {
|
|
491
|
+
metadata
|
|
492
|
+
} = decoded;
|
|
493
|
+
const lookup = scale.getLookupFn(metadata);
|
|
494
|
+
const builder = scale.getDynamicBuilder(lookup);
|
|
495
|
+
const chain = {
|
|
496
|
+
connector: getSapiConnector(connector),
|
|
497
|
+
hexMetadata,
|
|
498
|
+
token,
|
|
499
|
+
hasCheckMetadataHash,
|
|
500
|
+
signedExtensions,
|
|
501
|
+
registryTypes,
|
|
502
|
+
metadata,
|
|
503
|
+
lookup,
|
|
504
|
+
builder
|
|
505
|
+
};
|
|
506
|
+
const chainInfo = getChainInfo(chain);
|
|
507
|
+
const {
|
|
508
|
+
specName,
|
|
509
|
+
specVersion,
|
|
510
|
+
base58Prefix
|
|
511
|
+
} = chainInfo;
|
|
512
|
+
return {
|
|
513
|
+
id: `${connector.chainId}::${specName}::${specVersion}`,
|
|
514
|
+
chainId: connector.chainId,
|
|
515
|
+
specName,
|
|
516
|
+
specVersion,
|
|
517
|
+
hasCheckMetadataHash,
|
|
518
|
+
base58Prefix,
|
|
519
|
+
token: chain.token,
|
|
520
|
+
getConstant: (pallet, constant) => getConstantValue(chain, pallet, constant),
|
|
521
|
+
getStorage: (pallet, entry, keys, at) => getStorageValue(chain, pallet, entry, keys, at),
|
|
522
|
+
getDecodedCall: (pallet, method, args) => getDecodedCall(pallet, method, args),
|
|
523
|
+
getDecodedCallFromPayload: payload => getDecodedCallFromPayload(chain, payload),
|
|
524
|
+
getExtrinsicPayload: (pallet, method, args, config) => getSignerPayloadJSON(chain, pallet, method, args, config, chainInfo),
|
|
525
|
+
getFeeEstimate: payload => getFeeEstimate(chain, payload, chainInfo),
|
|
526
|
+
getRuntimeCallValue: (apiName, method, args) => getRuntimeCallResult(chain, apiName, method, args),
|
|
527
|
+
getTypeRegistry: payload => getTypeRegistry(chain, payload),
|
|
528
|
+
submit: (payload, signature) => chain.connector.submit(payload, signature),
|
|
529
|
+
getCallDocs: (pallet, method) => getCallDocs(chain, pallet, method),
|
|
530
|
+
getDryRunCall: (from, decodedCall) => getDryRunCall(chain, from, decodedCall),
|
|
531
|
+
isApiAvailable: (name, method) => isApiAvailable(chain, name, method)
|
|
532
|
+
};
|
|
533
|
+
};
|
|
534
|
+
|
|
535
|
+
exports.getScaleApi = getScaleApi;
|