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