@talismn/sapi 0.0.0-pr2277-20251211070508 → 0.0.0-pr2295-20260110031023

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