@talismn/sapi 0.0.0-pr2277-20251211071316 → 0.0.0-pr2295-20260110044132
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/dist/index.d.mts +111 -0
- package/dist/index.d.ts +111 -0
- package/dist/index.js +655 -0
- package/dist/index.js.map +1 -0
- package/dist/index.mjs +616 -0
- package/dist/index.mjs.map +1 -0
- package/package.json +23 -12
- package/dist/declarations/src/fetchBestMetadata.d.ts +0 -10
- package/dist/declarations/src/helpers/errors.d.ts +0 -2
- package/dist/declarations/src/helpers/getCallDocs.d.ts +0 -2
- package/dist/declarations/src/helpers/getChainInfo.d.ts +0 -7
- package/dist/declarations/src/helpers/getConstantValue.d.ts +0 -2
- package/dist/declarations/src/helpers/getDecodedCall.d.ts +0 -13
- package/dist/declarations/src/helpers/getDryRunCall.d.ts +0 -13
- package/dist/declarations/src/helpers/getExtrinsicDispatchInfo.d.ts +0 -7
- package/dist/declarations/src/helpers/getFeeEstimate.d.ts +0 -3
- package/dist/declarations/src/helpers/getPayloadWithMetadataHash.d.ts +0 -6
- package/dist/declarations/src/helpers/getRuntimeCallResult.d.ts +0 -2
- package/dist/declarations/src/helpers/getSapiConnector.d.ts +0 -3
- package/dist/declarations/src/helpers/getSendRequestResult.d.ts +0 -2
- package/dist/declarations/src/helpers/getSignerPayloadJSON.d.ts +0 -8
- package/dist/declarations/src/helpers/getStorageValue.d.ts +0 -2
- package/dist/declarations/src/helpers/getTypeRegistry.d.ts +0 -4
- package/dist/declarations/src/helpers/isApiAvailable.d.ts +0 -2
- package/dist/declarations/src/helpers/papi.d.ts +0 -5
- package/dist/declarations/src/helpers/submit.d.ts +0 -6
- package/dist/declarations/src/helpers/types.d.ts +0 -24
- package/dist/declarations/src/index.d.ts +0 -3
- package/dist/declarations/src/log.d.ts +0 -2
- package/dist/declarations/src/sapi.d.ts +0 -58
- package/dist/declarations/src/types.d.ts +0 -21
- package/dist/talismn-sapi.cjs.d.ts +0 -1
- package/dist/talismn-sapi.cjs.dev.js +0 -601
- package/dist/talismn-sapi.cjs.js +0 -7
- package/dist/talismn-sapi.cjs.prod.js +0 -601
- package/dist/talismn-sapi.esm.js +0 -593
package/dist/index.mjs
ADDED
|
@@ -0,0 +1,616 @@
|
|
|
1
|
+
// src/sapi.ts
|
|
2
|
+
import { parseMetadataRpc } from "@talismn/scale";
|
|
3
|
+
|
|
4
|
+
// src/log.ts
|
|
5
|
+
import anylogger from "anylogger";
|
|
6
|
+
|
|
7
|
+
// package.json
|
|
8
|
+
var package_default = {
|
|
9
|
+
name: "@talismn/sapi",
|
|
10
|
+
version: "0.0.0-pr2295-20260110044132",
|
|
11
|
+
author: "Talisman",
|
|
12
|
+
homepage: "https://talisman.xyz",
|
|
13
|
+
license: "GPL-3.0-or-later",
|
|
14
|
+
publishConfig: {
|
|
15
|
+
access: "public"
|
|
16
|
+
},
|
|
17
|
+
repository: {
|
|
18
|
+
directory: "packages/sapi",
|
|
19
|
+
type: "git",
|
|
20
|
+
url: "https://github.com/talismansociety/talisman.git"
|
|
21
|
+
},
|
|
22
|
+
main: "./dist/index.js",
|
|
23
|
+
module: "./dist/index.mjs",
|
|
24
|
+
files: [
|
|
25
|
+
"dist"
|
|
26
|
+
],
|
|
27
|
+
engines: {
|
|
28
|
+
node: ">=20"
|
|
29
|
+
},
|
|
30
|
+
scripts: {
|
|
31
|
+
test: "vitest run",
|
|
32
|
+
lint: "eslint src --max-warnings 0",
|
|
33
|
+
clean: "rm -rf dist .turbo node_modules",
|
|
34
|
+
build: "tsup"
|
|
35
|
+
},
|
|
36
|
+
dependencies: {
|
|
37
|
+
"@polkadot-api/merkleize-metadata": "1.1.18",
|
|
38
|
+
"@polkadot-api/metadata-builders": "0.12.2",
|
|
39
|
+
"@polkadot-api/substrate-bindings": "0.14.0",
|
|
40
|
+
"@polkadot-api/utils": "0.2.0",
|
|
41
|
+
"@polkadot/types": "16.1.2",
|
|
42
|
+
"@polkadot/types-codec": "16.1.2",
|
|
43
|
+
"@polkadot/util": "13.5.3",
|
|
44
|
+
"@talismn/scale": "workspace:*",
|
|
45
|
+
anylogger: "^1.0.11",
|
|
46
|
+
"polkadot-api": "1.13.1",
|
|
47
|
+
"scale-ts": "^1.6.1"
|
|
48
|
+
},
|
|
49
|
+
devDependencies: {
|
|
50
|
+
"@talismn/eslint-config": "workspace:*",
|
|
51
|
+
"@talismn/tsconfig": "workspace:*",
|
|
52
|
+
eslint: "^8.57.1",
|
|
53
|
+
typescript: "^5.6.3"
|
|
54
|
+
},
|
|
55
|
+
eslintConfig: {
|
|
56
|
+
root: true,
|
|
57
|
+
extends: [
|
|
58
|
+
"@talismn/eslint-config/base"
|
|
59
|
+
]
|
|
60
|
+
},
|
|
61
|
+
types: "./dist/index.d.ts",
|
|
62
|
+
exports: {
|
|
63
|
+
".": {
|
|
64
|
+
import: {
|
|
65
|
+
types: "./dist/index.d.mts",
|
|
66
|
+
default: "./dist/index.mjs"
|
|
67
|
+
},
|
|
68
|
+
require: {
|
|
69
|
+
types: "./dist/index.d.ts",
|
|
70
|
+
default: "./dist/index.js"
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
};
|
|
75
|
+
|
|
76
|
+
// src/log.ts
|
|
77
|
+
var log_default = anylogger(package_default.name);
|
|
78
|
+
|
|
79
|
+
// src/helpers/getCallDocs.ts
|
|
80
|
+
var getCallDocs = (chain, pallet, method) => {
|
|
81
|
+
try {
|
|
82
|
+
const typeIdCalls = chain.metadata.pallets.find(({ name }) => name === pallet)?.calls?.type;
|
|
83
|
+
if (!typeIdCalls) return null;
|
|
84
|
+
let palletCalls = chain.metadata.lookup[typeIdCalls];
|
|
85
|
+
if (!palletCalls || palletCalls.id !== typeIdCalls)
|
|
86
|
+
palletCalls = chain.metadata.lookup.find((v) => v.id === typeIdCalls);
|
|
87
|
+
if (!palletCalls) return null;
|
|
88
|
+
const call = palletCalls.def.value.find(
|
|
89
|
+
(c) => c.name === method
|
|
90
|
+
);
|
|
91
|
+
return call?.docs?.join("\n") ?? null;
|
|
92
|
+
} catch (err) {
|
|
93
|
+
log_default.error("Failed to find call docs", { pallet, method, chain });
|
|
94
|
+
return null;
|
|
95
|
+
}
|
|
96
|
+
};
|
|
97
|
+
|
|
98
|
+
// src/helpers/getConstantValue.ts
|
|
99
|
+
import { getConstantValueFromMetadata } from "@talismn/scale";
|
|
100
|
+
var getConstantValue = (chain, pallet, constant) => {
|
|
101
|
+
return getConstantValueFromMetadata(
|
|
102
|
+
{
|
|
103
|
+
builder: chain.builder,
|
|
104
|
+
unifiedMetadata: chain.metadata
|
|
105
|
+
},
|
|
106
|
+
pallet,
|
|
107
|
+
constant
|
|
108
|
+
);
|
|
109
|
+
};
|
|
110
|
+
|
|
111
|
+
// src/helpers/getChainInfo.ts
|
|
112
|
+
var getChainInfo = (chain) => {
|
|
113
|
+
const {
|
|
114
|
+
spec_name: specName,
|
|
115
|
+
spec_version: specVersion,
|
|
116
|
+
transaction_version: transactionVersion
|
|
117
|
+
} = getConstantValue(chain, "System", "Version");
|
|
118
|
+
const base58Prefix = getConstantValue(chain, "System", "SS58Prefix");
|
|
119
|
+
return {
|
|
120
|
+
specName,
|
|
121
|
+
specVersion,
|
|
122
|
+
transactionVersion,
|
|
123
|
+
base58Prefix
|
|
124
|
+
};
|
|
125
|
+
};
|
|
126
|
+
|
|
127
|
+
// src/helpers/getDecodedCall.ts
|
|
128
|
+
var getDecodedCall = (palletName, methodName, args) => ({
|
|
129
|
+
type: palletName,
|
|
130
|
+
value: { type: methodName, value: args }
|
|
131
|
+
});
|
|
132
|
+
var getDecodedCallFromPayload = (chain, payload) => {
|
|
133
|
+
const def = chain.builder.buildDefinition(chain.lookup.call);
|
|
134
|
+
const decoded = def.dec(payload.method);
|
|
135
|
+
return {
|
|
136
|
+
pallet: decoded.type,
|
|
137
|
+
method: decoded.value.type,
|
|
138
|
+
args: decoded.value.value
|
|
139
|
+
};
|
|
140
|
+
};
|
|
141
|
+
|
|
142
|
+
// src/helpers/getDryRunCall.ts
|
|
143
|
+
import { Enum } from "polkadot-api";
|
|
144
|
+
|
|
145
|
+
// src/helpers/errors.ts
|
|
146
|
+
import { getLookupFn } from "@polkadot-api/metadata-builders";
|
|
147
|
+
var getDispatchErrorMessage = (chain, err) => {
|
|
148
|
+
try {
|
|
149
|
+
if (!err) return null;
|
|
150
|
+
const error = err;
|
|
151
|
+
if (!error.type) throw new Error("Unknown dispatch error");
|
|
152
|
+
const lv1 = DISPATCH_ERROR[error.type];
|
|
153
|
+
if (!lv1) throw new Error("Unknown dispatch error");
|
|
154
|
+
if (lv1 === ERROR_METADATA_LOOKUP)
|
|
155
|
+
return getModuleErrorMessage(chain, error.value);
|
|
156
|
+
if (typeof lv1 === "string") return lv1;
|
|
157
|
+
const lv2 = lv1[error.value?.type];
|
|
158
|
+
if (!lv2) throw new Error("Unknown dispatch error");
|
|
159
|
+
if (typeof lv2 === "string") return lv2;
|
|
160
|
+
throw new Error("Unknown dispatch error");
|
|
161
|
+
} catch (cause) {
|
|
162
|
+
log_default.error("Failed to parse runtime error", { chainId: chain.connector.chainId, cause, err });
|
|
163
|
+
return tryFormatError(err);
|
|
164
|
+
}
|
|
165
|
+
};
|
|
166
|
+
var ERROR_METADATA_LOOKUP = "METADATA_LOOKUP";
|
|
167
|
+
var ERRORS_TRANSACTIONAL = {
|
|
168
|
+
LimitReached: "Too many transactional layers have been spawned",
|
|
169
|
+
NoLayer: "A transactional layer was expected, but does not exist"
|
|
170
|
+
};
|
|
171
|
+
var ERRORS_TOKEN = {
|
|
172
|
+
FundsUnavailable: "Funds are unavailable",
|
|
173
|
+
OnlyProvider: "Account that must exist would die",
|
|
174
|
+
BelowMinimum: "Account cannot exist with the funds that would be given",
|
|
175
|
+
CannotCreate: "Account cannot be created",
|
|
176
|
+
UnknownAsset: "The asset in question is unknown",
|
|
177
|
+
Frozen: "Funds exist but are frozen",
|
|
178
|
+
Unsupported: "Operation is not supported by the asset",
|
|
179
|
+
CannotCreateHold: "Account cannot be created for recording amount on hold",
|
|
180
|
+
NotExpendable: "Account that is desired to remain would die",
|
|
181
|
+
Blocked: "Account cannot receive the assets"
|
|
182
|
+
};
|
|
183
|
+
var ERRORS_ARITHMETIC = {
|
|
184
|
+
Overflow: "An underflow would occur",
|
|
185
|
+
Underflow: "An overflow would occur",
|
|
186
|
+
DivisionByZero: "Division by zero"
|
|
187
|
+
};
|
|
188
|
+
var DISPATCH_ERROR = {
|
|
189
|
+
CannotLookup: "Cannot lookup",
|
|
190
|
+
BadOrigin: "Bad origin",
|
|
191
|
+
Module: ERROR_METADATA_LOOKUP,
|
|
192
|
+
ConsumerRemaining: "Consumer remaining",
|
|
193
|
+
NoProviders: "No providers",
|
|
194
|
+
TooManyConsumers: "Too many consumers",
|
|
195
|
+
Token: ERRORS_TOKEN,
|
|
196
|
+
Arithmetic: ERRORS_ARITHMETIC,
|
|
197
|
+
Transactional: ERRORS_TRANSACTIONAL,
|
|
198
|
+
Exhausted: "Resources exhausted",
|
|
199
|
+
Corruption: "State corrupt",
|
|
200
|
+
Unavailable: "Resource unavailable",
|
|
201
|
+
RootNotAllowed: "Root not allowed",
|
|
202
|
+
Trie: "Unknown error",
|
|
203
|
+
// unsupported,
|
|
204
|
+
Other: "Unknown error"
|
|
205
|
+
// unsupported,
|
|
206
|
+
};
|
|
207
|
+
var getModuleErrorMessage = (chain, error) => {
|
|
208
|
+
try {
|
|
209
|
+
if (!chain.metadata) throw new Error("Could not fetch metadata");
|
|
210
|
+
const pallet = chain.metadata.pallets.find((p) => p.name === error.type);
|
|
211
|
+
if (typeof pallet?.errors !== "number") throw new Error("Unknown pallet");
|
|
212
|
+
const lookup = getLookupFn(chain.metadata);
|
|
213
|
+
const palletErrors = lookup(pallet.errors);
|
|
214
|
+
if (palletErrors.type !== "enum" || !palletErrors.innerDocs[error.value.type]?.length)
|
|
215
|
+
throw new Error("Unknown error type");
|
|
216
|
+
return palletErrors.innerDocs[error.value.type].join(" ");
|
|
217
|
+
} catch (err) {
|
|
218
|
+
log_default.error("Failed to parse module error", { chainId: chain.connector.chainId, error, err });
|
|
219
|
+
return [error.type, error.value.type].join(": ");
|
|
220
|
+
}
|
|
221
|
+
};
|
|
222
|
+
var tryFormatError = (err) => {
|
|
223
|
+
try {
|
|
224
|
+
const unsafeErr = err;
|
|
225
|
+
if (unsafeErr.type && unsafeErr.value?.type)
|
|
226
|
+
return [unsafeErr.type, unsafeErr.value.type].join(": ");
|
|
227
|
+
} catch (err2) {
|
|
228
|
+
}
|
|
229
|
+
return "Unknown error";
|
|
230
|
+
};
|
|
231
|
+
|
|
232
|
+
// src/helpers/getRuntimeCallResult.ts
|
|
233
|
+
import { toHex } from "@polkadot-api/utils";
|
|
234
|
+
|
|
235
|
+
// src/helpers/getSendRequestResult.ts
|
|
236
|
+
var getSendRequestResult = (chain, method, params, isCacheable) => {
|
|
237
|
+
return chain.connector.send(method, params, isCacheable);
|
|
238
|
+
};
|
|
239
|
+
|
|
240
|
+
// src/helpers/getRuntimeCallResult.ts
|
|
241
|
+
var getRuntimeCallResult = async (chain, apiName, method, args) => {
|
|
242
|
+
const call = chain.builder.buildRuntimeCall(apiName, method);
|
|
243
|
+
const hex = await getSendRequestResult(chain, "state_call", [
|
|
244
|
+
`${apiName}_${method}`,
|
|
245
|
+
toHex(call.args.enc(args))
|
|
246
|
+
]);
|
|
247
|
+
return call.value.dec(hex);
|
|
248
|
+
};
|
|
249
|
+
|
|
250
|
+
// src/helpers/isApiAvailable.ts
|
|
251
|
+
var isApiAvailable = (chain, name, method) => {
|
|
252
|
+
return chain.metadata.apis.some(
|
|
253
|
+
(a) => a.name === name && a.methods.some((m) => m.name === method)
|
|
254
|
+
);
|
|
255
|
+
};
|
|
256
|
+
|
|
257
|
+
// src/helpers/getDryRunCall.ts
|
|
258
|
+
var getDryRunCall = async (chain, from, decodedCall) => {
|
|
259
|
+
try {
|
|
260
|
+
if (!isApiAvailable(chain, "DryRunApi", "dry_run_call"))
|
|
261
|
+
return {
|
|
262
|
+
available: false,
|
|
263
|
+
data: null
|
|
264
|
+
};
|
|
265
|
+
const origin = Enum("system", Enum("Signed", from));
|
|
266
|
+
const { pallet, method, args } = decodedCall;
|
|
267
|
+
const call = { type: pallet, value: { type: method, value: args } };
|
|
268
|
+
const data = await getRuntimeCallResult(chain, "DryRunApi", "dry_run_call", [
|
|
269
|
+
origin,
|
|
270
|
+
call
|
|
271
|
+
]);
|
|
272
|
+
const ok = data.success && data.value.execution_result.success;
|
|
273
|
+
const errorMessage = data.success && !data.value.execution_result.success ? getDispatchErrorMessage(chain, data.value.execution_result.value.error) : null;
|
|
274
|
+
return {
|
|
275
|
+
available: true,
|
|
276
|
+
// NOTE: we can't re-export `@polkadot-api/descriptors` from this package.
|
|
277
|
+
// So, the caller of this function must pass in their own instance of `type DryRunResult` as the generic argument `T`.
|
|
278
|
+
data,
|
|
279
|
+
ok,
|
|
280
|
+
errorMessage
|
|
281
|
+
};
|
|
282
|
+
} catch (err) {
|
|
283
|
+
log_default.error("Failed to dry run", { chainId: chain.connector.chainId, err });
|
|
284
|
+
return {
|
|
285
|
+
available: false,
|
|
286
|
+
data: null
|
|
287
|
+
};
|
|
288
|
+
}
|
|
289
|
+
};
|
|
290
|
+
|
|
291
|
+
// src/helpers/getFeeEstimate.ts
|
|
292
|
+
import { Binary } from "polkadot-api";
|
|
293
|
+
|
|
294
|
+
// src/helpers/getExtrinsicDispatchInfo.ts
|
|
295
|
+
import { assert, u8aConcatStrict } from "@polkadot/util";
|
|
296
|
+
var getExtrinsicDispatchInfo = async (chain, signedExtrinsic) => {
|
|
297
|
+
assert(signedExtrinsic.isSigned, "Extrinsic must be signed (or fakeSigned) in order to query fee");
|
|
298
|
+
const len = signedExtrinsic.registry.createType("u32", signedExtrinsic.encodedLength);
|
|
299
|
+
const dispatchInfo = await stateCall(
|
|
300
|
+
chain.connector.send,
|
|
301
|
+
"TransactionPaymentApi_query_info",
|
|
302
|
+
"RuntimeDispatchInfo",
|
|
303
|
+
[signedExtrinsic, len],
|
|
304
|
+
void 0,
|
|
305
|
+
true
|
|
306
|
+
);
|
|
307
|
+
return {
|
|
308
|
+
partialFee: dispatchInfo.partialFee.toString()
|
|
309
|
+
};
|
|
310
|
+
};
|
|
311
|
+
var stateCall = async (request, method, resultType, args, blockHash, isCacheable) => {
|
|
312
|
+
const registry = args[0].registry;
|
|
313
|
+
const bytes = registry.createType("Raw", u8aConcatStrict(args.map((arg) => arg.toU8a())));
|
|
314
|
+
const result = await request("state_call", [method, bytes.toHex(), blockHash], isCacheable);
|
|
315
|
+
return registry.createType(resultType, result);
|
|
316
|
+
};
|
|
317
|
+
|
|
318
|
+
// src/helpers/getTypeRegistry.ts
|
|
319
|
+
import { Metadata, TypeRegistry } from "@polkadot/types";
|
|
320
|
+
var getTypeRegistry = (chain, payload) => {
|
|
321
|
+
log_default.log(`[sapi] getTypeRegistry begin: ${Date.now()}`);
|
|
322
|
+
const registry = new TypeRegistry();
|
|
323
|
+
if (chain.registryTypes) registry.register(chain.registryTypes);
|
|
324
|
+
const meta = new Metadata(registry, chain.hexMetadata);
|
|
325
|
+
registry.setMetadata(meta, payload.signedExtensions, chain.signedExtensions);
|
|
326
|
+
log_default.log(`[sapi] getTypeRegistry end: ${Date.now()}`);
|
|
327
|
+
return registry;
|
|
328
|
+
};
|
|
329
|
+
|
|
330
|
+
// src/helpers/getFeeEstimate.ts
|
|
331
|
+
var getFeeEstimate = async (chain, payload, chainInfo) => {
|
|
332
|
+
const registry = getTypeRegistry(chain, payload);
|
|
333
|
+
const extrinsic = registry.createType("Extrinsic", payload);
|
|
334
|
+
extrinsic.signFake(payload.address, {
|
|
335
|
+
appId: 0,
|
|
336
|
+
nonce: payload.nonce,
|
|
337
|
+
blockHash: payload.blockHash,
|
|
338
|
+
genesisHash: payload.genesisHash,
|
|
339
|
+
runtimeVersion: {
|
|
340
|
+
specVersion: chainInfo.specVersion,
|
|
341
|
+
transactionVersion: chainInfo.transactionVersion
|
|
342
|
+
// other fields aren't necessary for signing
|
|
343
|
+
}
|
|
344
|
+
});
|
|
345
|
+
const bytes = extrinsic.toU8a(true);
|
|
346
|
+
const binary = Binary.fromBytes(bytes);
|
|
347
|
+
try {
|
|
348
|
+
const result = await getRuntimeCallResult(
|
|
349
|
+
chain,
|
|
350
|
+
"TransactionPaymentApi",
|
|
351
|
+
"query_info",
|
|
352
|
+
[binary, bytes.length]
|
|
353
|
+
);
|
|
354
|
+
if (!result?.partial_fee && result.partial_fee !== 0n) {
|
|
355
|
+
throw new Error("partialFee is not found");
|
|
356
|
+
}
|
|
357
|
+
return result.partial_fee;
|
|
358
|
+
} catch (err) {
|
|
359
|
+
log_default.error("Failed to get fee estimate using getRuntimeCallValue", { err });
|
|
360
|
+
}
|
|
361
|
+
const { partialFee } = await getExtrinsicDispatchInfo(chain, extrinsic);
|
|
362
|
+
return BigInt(partialFee);
|
|
363
|
+
};
|
|
364
|
+
|
|
365
|
+
// src/helpers/getSapiConnector.ts
|
|
366
|
+
var getSapiConnector = ({
|
|
367
|
+
chainId,
|
|
368
|
+
send,
|
|
369
|
+
submit: submit2,
|
|
370
|
+
submitWithBittensorMevShield
|
|
371
|
+
}) => ({
|
|
372
|
+
chainId,
|
|
373
|
+
send,
|
|
374
|
+
submit: (...args) => {
|
|
375
|
+
if (submit2) return submit2(...args);
|
|
376
|
+
throw new Error("submit handler not provided");
|
|
377
|
+
},
|
|
378
|
+
submitWithBittensorMevShield: (...args) => {
|
|
379
|
+
if (submitWithBittensorMevShield) return submitWithBittensorMevShield(...args);
|
|
380
|
+
throw new Error("submitWithBittensorMevShield handler not provided");
|
|
381
|
+
}
|
|
382
|
+
});
|
|
383
|
+
|
|
384
|
+
// src/helpers/getSignerPayloadJSON.ts
|
|
385
|
+
import { mergeUint8, toHex as toHex3 } from "@polkadot-api/utils";
|
|
386
|
+
import { u8aToHex } from "@polkadot/util";
|
|
387
|
+
import { Binary as Binary2 } from "polkadot-api";
|
|
388
|
+
|
|
389
|
+
// src/helpers/getPayloadWithMetadataHash.ts
|
|
390
|
+
import { merkleizeMetadata } from "@polkadot-api/merkleize-metadata";
|
|
391
|
+
import { toHex as toHex2 } from "@polkadot-api/utils";
|
|
392
|
+
var getPayloadWithMetadataHash = (chain, chainInfo, payload) => {
|
|
393
|
+
if (!chain.hasCheckMetadataHash || !payload.signedExtensions.includes("CheckMetadataHash"))
|
|
394
|
+
return {
|
|
395
|
+
payload,
|
|
396
|
+
txMetadata: void 0
|
|
397
|
+
};
|
|
398
|
+
try {
|
|
399
|
+
const { decimals, symbol: tokenSymbol } = chain.token;
|
|
400
|
+
const { base58Prefix, specName, specVersion } = chainInfo;
|
|
401
|
+
const metadataHashInputs = { tokenSymbol, decimals, base58Prefix, specName, specVersion };
|
|
402
|
+
const merkleizedMetadata = merkleizeMetadata(chain.hexMetadata, metadataHashInputs);
|
|
403
|
+
const metadataHash = toHex2(merkleizedMetadata.digest());
|
|
404
|
+
log_default.log("metadataHash", metadataHash, metadataHashInputs);
|
|
405
|
+
const payloadWithMetadataHash = {
|
|
406
|
+
...payload,
|
|
407
|
+
mode: 1,
|
|
408
|
+
metadataHash,
|
|
409
|
+
withSignedTransaction: true
|
|
410
|
+
};
|
|
411
|
+
const registry = getTypeRegistry(chain, payload);
|
|
412
|
+
const extPayload = registry.createType("ExtrinsicPayload", payloadWithMetadataHash);
|
|
413
|
+
const barePayload = extPayload.toU8a(true);
|
|
414
|
+
const txMetadata = merkleizedMetadata.getProofForExtrinsicPayload(barePayload);
|
|
415
|
+
return {
|
|
416
|
+
payload: payloadWithMetadataHash,
|
|
417
|
+
txMetadata
|
|
418
|
+
};
|
|
419
|
+
} catch (err) {
|
|
420
|
+
log_default.error("Failed to get shortened metadata", { error: err });
|
|
421
|
+
return {
|
|
422
|
+
payload,
|
|
423
|
+
txMetadata: void 0
|
|
424
|
+
};
|
|
425
|
+
}
|
|
426
|
+
};
|
|
427
|
+
|
|
428
|
+
// src/helpers/getStorageValue.ts
|
|
429
|
+
var getStorageValue = async (chain, pallet, entry, keys, at) => {
|
|
430
|
+
const storageCodec = chain.builder.buildStorage(pallet, entry);
|
|
431
|
+
const stateKey = storageCodec.keys.enc(...keys);
|
|
432
|
+
const hexValue = await getSendRequestResult(chain, "state_getStorage", [
|
|
433
|
+
stateKey,
|
|
434
|
+
at
|
|
435
|
+
]);
|
|
436
|
+
if (!hexValue) return null;
|
|
437
|
+
return storageCodec.value.dec(hexValue);
|
|
438
|
+
};
|
|
439
|
+
|
|
440
|
+
// src/helpers/papi.ts
|
|
441
|
+
import { Bytes, enhanceEncoder, u16 } from "@polkadot-api/substrate-bindings";
|
|
442
|
+
var toPjsHex = (value, minByteLen) => {
|
|
443
|
+
let inner = value.toString(16);
|
|
444
|
+
inner = (inner.length % 2 ? "0" : "") + inner;
|
|
445
|
+
const nPaddedBytes = Math.max(0, (minByteLen || 0) - inner.length / 2);
|
|
446
|
+
return "0x" + "00".repeat(nPaddedBytes) + inner;
|
|
447
|
+
};
|
|
448
|
+
var mortal = enhanceEncoder(Bytes(2).enc, (value) => {
|
|
449
|
+
const factor = Math.max(value.period >> 12, 1);
|
|
450
|
+
const left = Math.min(Math.max(trailingZeroes(value.period) - 1, 1), 15);
|
|
451
|
+
const right = value.phase / factor << 4;
|
|
452
|
+
return u16.enc(left | right);
|
|
453
|
+
});
|
|
454
|
+
function trailingZeroes(n) {
|
|
455
|
+
let i = 0;
|
|
456
|
+
while (!(n & 1)) {
|
|
457
|
+
i++;
|
|
458
|
+
n >>= 1;
|
|
459
|
+
}
|
|
460
|
+
return i;
|
|
461
|
+
}
|
|
462
|
+
|
|
463
|
+
// src/helpers/getSignerPayloadJSON.ts
|
|
464
|
+
var ERA_PERIOD = 64;
|
|
465
|
+
var getSignerPayloadJSON = async (chain, palletName, methodName, args, signerConfig, chainInfo) => {
|
|
466
|
+
const { codec, location } = chain.builder.buildCall(palletName, methodName);
|
|
467
|
+
const method = Binary2.fromBytes(mergeUint8([new Uint8Array(location), codec.enc(args)]));
|
|
468
|
+
let blockHash = await getSendRequestResult(
|
|
469
|
+
chain,
|
|
470
|
+
"chain_getFinalizedHead",
|
|
471
|
+
[],
|
|
472
|
+
false
|
|
473
|
+
);
|
|
474
|
+
const [nonce, genesisHash, blockNumberFinalized, blockNumberCurrent] = await Promise.all([
|
|
475
|
+
getSendRequestResult(chain, "system_accountNextIndex", [signerConfig.address], false),
|
|
476
|
+
getStorageValue(chain, "System", "BlockHash", [0]),
|
|
477
|
+
getStorageValue(chain, "System", "Number", [], blockHash),
|
|
478
|
+
getStorageValue(chain, "System", "Number", [])
|
|
479
|
+
]);
|
|
480
|
+
if (!genesisHash) throw new Error("Genesis hash not found");
|
|
481
|
+
if (!blockHash) throw new Error("Block hash not found");
|
|
482
|
+
let blockNumber = blockNumberFinalized;
|
|
483
|
+
if (blockNumberCurrent - blockNumberFinalized > 32) {
|
|
484
|
+
blockNumber = blockNumberCurrent - 16;
|
|
485
|
+
const binBlockHash = await getStorageValue(chain, "System", "BlockHash", [blockNumber]);
|
|
486
|
+
blockHash = binBlockHash.asHex();
|
|
487
|
+
}
|
|
488
|
+
const era = mortal({ period: ERA_PERIOD, phase: blockNumber % ERA_PERIOD });
|
|
489
|
+
const signedExtensions = chain.metadata.extrinsic.signedExtensions.map((ext) => ext.identifier);
|
|
490
|
+
const basePayload = {
|
|
491
|
+
address: signerConfig.address,
|
|
492
|
+
genesisHash: genesisHash.asHex(),
|
|
493
|
+
blockHash,
|
|
494
|
+
method: method.asHex(),
|
|
495
|
+
signedExtensions,
|
|
496
|
+
nonce: toPjsHex(nonce, 4),
|
|
497
|
+
specVersion: toPjsHex(chainInfo.specVersion, 4),
|
|
498
|
+
transactionVersion: toPjsHex(chainInfo.transactionVersion, 4),
|
|
499
|
+
blockNumber: toPjsHex(blockNumber, 4),
|
|
500
|
+
era: toHex3(era),
|
|
501
|
+
tip: toPjsHex(0, 16),
|
|
502
|
+
// TODO gas station (required for Astar)
|
|
503
|
+
assetId: void 0,
|
|
504
|
+
version: 4
|
|
505
|
+
};
|
|
506
|
+
const { payload, txMetadata } = getPayloadWithMetadataHash(chain, chainInfo, basePayload);
|
|
507
|
+
const shortMetadata = txMetadata ? u8aToHex(txMetadata) : void 0;
|
|
508
|
+
if (payload.signedExtensions.includes("CheckAppId"))
|
|
509
|
+
payload.appId = 0;
|
|
510
|
+
log_default.log("[sapi] payload", { newPayload: payload, txMetadata });
|
|
511
|
+
return {
|
|
512
|
+
payload,
|
|
513
|
+
txMetadata,
|
|
514
|
+
// TODO remove
|
|
515
|
+
shortMetadata
|
|
516
|
+
};
|
|
517
|
+
};
|
|
518
|
+
|
|
519
|
+
// src/helpers/submit.ts
|
|
520
|
+
var submit = async (chain, payload, signature, txInfo, mode) => {
|
|
521
|
+
switch (mode) {
|
|
522
|
+
case "bittensor-mev-shield":
|
|
523
|
+
if (signature)
|
|
524
|
+
throw new Error("Signature should not be provided when using bittensor-mev-shield mode");
|
|
525
|
+
return chain.connector.submitWithBittensorMevShield(payload, txInfo);
|
|
526
|
+
default:
|
|
527
|
+
return chain.connector.submit(payload, signature, txInfo);
|
|
528
|
+
}
|
|
529
|
+
};
|
|
530
|
+
|
|
531
|
+
// src/sapi.ts
|
|
532
|
+
var getScaleApi = (connector, hexMetadata, token, hasCheckMetadataHash, signedExtensions, registryTypes) => {
|
|
533
|
+
const { unifiedMetadata: metadata, lookupFn: lookup, builder } = parseMetadataRpc(hexMetadata);
|
|
534
|
+
const chain = {
|
|
535
|
+
connector: getSapiConnector(connector),
|
|
536
|
+
hexMetadata,
|
|
537
|
+
token,
|
|
538
|
+
hasCheckMetadataHash,
|
|
539
|
+
signedExtensions,
|
|
540
|
+
registryTypes,
|
|
541
|
+
metadata,
|
|
542
|
+
lookup,
|
|
543
|
+
builder,
|
|
544
|
+
metadataRpc: hexMetadata
|
|
545
|
+
};
|
|
546
|
+
const chainInfo = getChainInfo(chain);
|
|
547
|
+
const { specName, specVersion, base58Prefix } = chainInfo;
|
|
548
|
+
return {
|
|
549
|
+
id: `${connector.chainId}::${specName}::${specVersion}`,
|
|
550
|
+
chainId: connector.chainId,
|
|
551
|
+
specName,
|
|
552
|
+
specVersion,
|
|
553
|
+
hasCheckMetadataHash,
|
|
554
|
+
base58Prefix,
|
|
555
|
+
token: chain.token,
|
|
556
|
+
chain,
|
|
557
|
+
getConstant: (pallet, constant) => getConstantValue(chain, pallet, constant),
|
|
558
|
+
getStorage: (pallet, entry, keys, at) => getStorageValue(chain, pallet, entry, keys, at),
|
|
559
|
+
getDecodedCall: (pallet, method, args) => getDecodedCall(pallet, method, args),
|
|
560
|
+
getDecodedCallFromPayload: (payload) => getDecodedCallFromPayload(chain, payload),
|
|
561
|
+
getExtrinsicPayload: (pallet, method, args, config) => getSignerPayloadJSON(chain, pallet, method, args, config, chainInfo),
|
|
562
|
+
getFeeEstimate: (payload) => getFeeEstimate(chain, payload, chainInfo),
|
|
563
|
+
getRuntimeCallValue: (apiName, method, args) => getRuntimeCallResult(chain, apiName, method, args),
|
|
564
|
+
getTypeRegistry: (payload) => getTypeRegistry(chain, payload),
|
|
565
|
+
submit: (payload, signature, txInfo, mode) => submit(chain, payload, signature, txInfo, mode),
|
|
566
|
+
getCallDocs: (pallet, method) => getCallDocs(chain, pallet, method),
|
|
567
|
+
getDryRunCall: (from, decodedCall) => getDryRunCall(chain, from, decodedCall),
|
|
568
|
+
isApiAvailable: (name, method) => isApiAvailable(chain, name, method)
|
|
569
|
+
};
|
|
570
|
+
};
|
|
571
|
+
|
|
572
|
+
// src/fetchBestMetadata.ts
|
|
573
|
+
import { toHex as toHex4 } from "@polkadot-api/utils";
|
|
574
|
+
import { u32, Vector } from "scale-ts";
|
|
575
|
+
var MAGIC_NUMBER = 1635018093;
|
|
576
|
+
var MAX_SUPPORTED_METADATA_VERSION = 15;
|
|
577
|
+
var fetchBestMetadata = async (rpcSend, allowLegacyFallback) => {
|
|
578
|
+
try {
|
|
579
|
+
const metadataVersions = await rpcSend(
|
|
580
|
+
"state_call",
|
|
581
|
+
["Metadata_metadata_versions", "0x"],
|
|
582
|
+
true
|
|
583
|
+
);
|
|
584
|
+
const availableVersions = Vector(u32).dec(metadataVersions);
|
|
585
|
+
const bestVersion = Math.max(
|
|
586
|
+
...availableVersions.filter((v) => v <= MAX_SUPPORTED_METADATA_VERSION)
|
|
587
|
+
);
|
|
588
|
+
const metadata = await rpcSend(
|
|
589
|
+
"state_call",
|
|
590
|
+
["Metadata_metadata_at_version", toHex4(u32.enc(bestVersion))],
|
|
591
|
+
true
|
|
592
|
+
);
|
|
593
|
+
return normalizeMetadata(metadata);
|
|
594
|
+
} catch (cause) {
|
|
595
|
+
const message = cause?.message;
|
|
596
|
+
if (allowLegacyFallback || message?.includes("is not found") || // ex: crust standalone
|
|
597
|
+
message?.includes("Module doesn't have export Metadata_metadata_versions") || // ex: 3DPass
|
|
598
|
+
message?.includes("Exported method Metadata_metadata_versions is not found") || // ex: sora-polkadot & sora-standalone
|
|
599
|
+
message?.includes("Execution, MethodNotFound, Metadata_metadata_versions")) {
|
|
600
|
+
return await rpcSend("state_getMetadata", [], true);
|
|
601
|
+
}
|
|
602
|
+
throw new Error("Failed to fetch metadata", { cause });
|
|
603
|
+
}
|
|
604
|
+
};
|
|
605
|
+
var normalizeMetadata = (metadata) => {
|
|
606
|
+
const hexMagicNumber = toHex4(u32.enc(MAGIC_NUMBER)).slice(2);
|
|
607
|
+
const magicNumberIndex = metadata.indexOf(hexMagicNumber);
|
|
608
|
+
if (magicNumberIndex === -1) throw new Error("Invalid metadata format: magic number not found");
|
|
609
|
+
return `0x${metadata.slice(magicNumberIndex)}`;
|
|
610
|
+
};
|
|
611
|
+
export {
|
|
612
|
+
MAX_SUPPORTED_METADATA_VERSION,
|
|
613
|
+
fetchBestMetadata,
|
|
614
|
+
getScaleApi
|
|
615
|
+
};
|
|
616
|
+
//# sourceMappingURL=index.mjs.map
|