@talismn/sapi 0.0.12 → 0.1.1

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 (35) hide show
  1. package/dist/index.d.mts +111 -0
  2. package/dist/index.d.ts +111 -0
  3. package/dist/index.js +648 -0
  4. package/dist/index.js.map +1 -0
  5. package/dist/index.mjs +609 -0
  6. package/dist/index.mjs.map +1 -0
  7. package/package.json +24 -20
  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/types.d.ts +0 -24
  27. package/dist/declarations/src/index.d.ts +0 -3
  28. package/dist/declarations/src/log.d.ts +0 -2
  29. package/dist/declarations/src/sapi.d.ts +0 -57
  30. package/dist/declarations/src/types.d.ts +0 -18
  31. package/dist/talismn-sapi.cjs.d.ts +0 -1
  32. package/dist/talismn-sapi.cjs.dev.js +0 -586
  33. package/dist/talismn-sapi.cjs.js +0 -7
  34. package/dist/talismn-sapi.cjs.prod.js +0 -586
  35. package/dist/talismn-sapi.esm.js +0 -578
@@ -1,578 +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
- }) => ({
314
- chainId,
315
- send,
316
- submit: (...args) => {
317
- if (submit) return submit(...args);
318
- throw new Error("submit handler not provided");
319
- }
320
- });
321
-
322
- const getPayloadWithMetadataHash = (chain, chainInfo, payload) => {
323
- if (!chain.hasCheckMetadataHash || !payload.signedExtensions.includes("CheckMetadataHash")) return {
324
- payload,
325
- txMetadata: undefined
326
- };
327
- try {
328
- const {
329
- decimals,
330
- symbol: tokenSymbol
331
- } = chain.token;
332
- const {
333
- base58Prefix,
334
- specName,
335
- specVersion
336
- } = chainInfo;
337
- const metadataHashInputs = {
338
- tokenSymbol,
339
- decimals,
340
- base58Prefix,
341
- specName,
342
- specVersion
343
- };
344
-
345
- // since ultimately this needs a V15 object, would be nice if this accepted one directly as input
346
- const merkleizedMetadata = merkleizeMetadata(chain.hexMetadata, metadataHashInputs);
347
- const metadataHash = toHex(merkleizedMetadata.digest());
348
- log.log("metadataHash", metadataHash, metadataHashInputs);
349
- const payloadWithMetadataHash = {
350
- ...payload,
351
- mode: 1,
352
- metadataHash,
353
- withSignedTransaction: true
354
- };
355
-
356
- // TODO do this without PJS / registry => waiting for @polkadot-api/tx-utils
357
- // const { extra, additionalSigned } = getSignedExtensionValues(payload, metadata)
358
- // const badExtPayload = mergeUint8([fromHex(payload.method), ...extra, ...additionalSigned])
359
-
360
- const registry = getTypeRegistry(chain, payload);
361
- const extPayload = registry.createType("ExtrinsicPayload", payloadWithMetadataHash);
362
- const barePayload = extPayload.toU8a(true);
363
- const txMetadata = merkleizedMetadata.getProofForExtrinsicPayload(barePayload);
364
- return {
365
- payload: payloadWithMetadataHash,
366
- txMetadata
367
- };
368
- } catch (err) {
369
- log.error("Failed to get shortened metadata", {
370
- error: err
371
- });
372
- return {
373
- payload,
374
- txMetadata: undefined
375
- };
376
- }
377
- };
378
-
379
- const getStorageValue = async (chain, pallet, entry, keys, at) => {
380
- const storageCodec = chain.builder.buildStorage(pallet, entry);
381
- const stateKey = storageCodec.keys.enc(...keys);
382
- const hexValue = await getSendRequestResult(chain, "state_getStorage", [stateKey, at]);
383
- if (!hexValue) return null; // caller will need to expect null when applicable
384
-
385
- return storageCodec.value.dec(hexValue);
386
- };
387
-
388
- //////////////////////////////////////////////////////////////////////////////////////////////////////////////
389
- //////////////////////////// Utilities from PAPI /////////////////////////////
390
- //////////////////////////////////////////////////////////////////////////////////////////////////////////////
391
-
392
- const toPjsHex = (value, minByteLen) => {
393
- let inner = value.toString(16);
394
- inner = (inner.length % 2 ? "0" : "") + inner;
395
- const nPaddedBytes = Math.max(0, (minByteLen || 0) - inner.length / 2);
396
- return "0x" + "00".repeat(nPaddedBytes) + inner;
397
- };
398
- const mortal = enhanceEncoder(Bytes(2).enc, value => {
399
- const factor = Math.max(value.period >> 12, 1);
400
- const left = Math.min(Math.max(trailingZeroes(value.period) - 1, 1), 15);
401
- const right = value.phase / factor << 4;
402
- return u16.enc(left | right);
403
- });
404
- function trailingZeroes(n) {
405
- let i = 0;
406
- while (!(n & 1)) {
407
- i++;
408
- n >>= 1;
409
- }
410
- return i;
411
- }
412
-
413
- const ERA_PERIOD = 64; // validity period in blocks, used for mortal era
414
-
415
- const getSignerPayloadJSON = async (chain, palletName, methodName, args, signerConfig, chainInfo) => {
416
- const {
417
- codec,
418
- location
419
- } = chain.builder.buildCall(palletName, methodName);
420
- const method = Binary.fromBytes(mergeUint8([new Uint8Array(location), codec.enc(args)]));
421
-
422
- // on unstable networks with lots of forks (ex: westend asset hub as of june 2025),
423
- // using a finalized block as reference for mortality is necessary for txs to get through
424
- let blockHash = await getSendRequestResult(chain, "chain_getFinalizedHead", [], false);
425
- 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", [])]);
426
- if (!genesisHash) throw new Error("Genesis hash not found");
427
- if (!blockHash) throw new Error("Block hash not found");
428
- let blockNumber = blockNumberFinalized;
429
-
430
- // on Autonomys the finalized block hash is wrong (7000 blocks behind),
431
- // if we use it to craft a tx it will be invalid
432
- // => if finalized block number is more than 32 blocks behind, use current - 16
433
- if (blockNumberCurrent - blockNumberFinalized > 32) {
434
- blockNumber = blockNumberCurrent - 16;
435
- const binBlockHash = await getStorageValue(chain, "System", "BlockHash", [blockNumber]);
436
- blockHash = binBlockHash.asHex();
437
- }
438
- const era = mortal({
439
- period: ERA_PERIOD,
440
- phase: blockNumber % ERA_PERIOD
441
- });
442
- const signedExtensions = chain.metadata.extrinsic.signedExtensions.map(ext => ext.identifier);
443
- const basePayload = {
444
- address: signerConfig.address,
445
- genesisHash: genesisHash.asHex(),
446
- blockHash,
447
- method: method.asHex(),
448
- signedExtensions,
449
- nonce: toPjsHex(nonce, 4),
450
- specVersion: toPjsHex(chainInfo.specVersion, 4),
451
- transactionVersion: toPjsHex(chainInfo.transactionVersion, 4),
452
- blockNumber: toPjsHex(blockNumber, 4),
453
- era: toHex(era),
454
- tip: toPjsHex(0, 16),
455
- // TODO gas station (required for Astar)
456
- assetId: undefined,
457
- version: 4
458
- };
459
- const {
460
- payload,
461
- txMetadata
462
- } = getPayloadWithMetadataHash(chain, chainInfo, basePayload);
463
- const shortMetadata = txMetadata ? u8aToHex(txMetadata) : undefined;
464
-
465
- // Avail support
466
- if (payload.signedExtensions.includes("CheckAppId")) payload.appId = 0;
467
- log.log("[sapi] payload", {
468
- newPayload: payload,
469
- txMetadata
470
- });
471
- return {
472
- payload,
473
- txMetadata,
474
- // TODO remove
475
- shortMetadata
476
- };
477
- };
478
-
479
- const getScaleApi = (connector, hexMetadata, token, hasCheckMetadataHash, signedExtensions, registryTypes) => {
480
- const {
481
- unifiedMetadata: metadata,
482
- lookupFn: lookup,
483
- builder
484
- } = parseMetadataRpc(hexMetadata);
485
- const chain = {
486
- connector: getSapiConnector(connector),
487
- hexMetadata,
488
- token,
489
- hasCheckMetadataHash,
490
- signedExtensions,
491
- registryTypes,
492
- metadata,
493
- lookup,
494
- builder,
495
- metadataRpc: hexMetadata
496
- };
497
- const chainInfo = getChainInfo(chain);
498
- const {
499
- specName,
500
- specVersion,
501
- base58Prefix
502
- } = chainInfo;
503
- return {
504
- id: `${connector.chainId}::${specName}::${specVersion}`,
505
- chainId: connector.chainId,
506
- specName,
507
- specVersion,
508
- hasCheckMetadataHash,
509
- base58Prefix,
510
- token: chain.token,
511
- chain,
512
- getConstant: (pallet, constant) => getConstantValue(chain, pallet, constant),
513
- getStorage: (pallet, entry, keys, at) => getStorageValue(chain, pallet, entry, keys, at),
514
- getDecodedCall: (pallet, method, args) => getDecodedCall(pallet, method, args),
515
- getDecodedCallFromPayload: payload => getDecodedCallFromPayload(chain, payload),
516
- getExtrinsicPayload: (pallet, method, args, config) => getSignerPayloadJSON(chain, pallet, method, args, config, chainInfo),
517
- getFeeEstimate: payload => getFeeEstimate(chain, payload, chainInfo),
518
- getRuntimeCallValue: (apiName, method, args) => getRuntimeCallResult(chain, apiName, method, args),
519
- getTypeRegistry: payload => getTypeRegistry(chain, payload),
520
- submit: (payload, signature, txInfo) => chain.connector.submit(payload, signature, txInfo),
521
- getCallDocs: (pallet, method) => getCallDocs(chain, pallet, method),
522
- getDryRunCall: (from, decodedCall) => getDryRunCall(chain, from, decodedCall),
523
- isApiAvailable: (name, method) => isApiAvailable(chain, name, method)
524
- };
525
- };
526
-
527
- const MAGIC_NUMBER = 1635018093;
528
-
529
- // 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?)
530
- const MAX_SUPPORTED_METADATA_VERSION = 15; // v16 sometimes outputs different metadata hashes, ignore v16 until that is fixed in PAPI
531
-
532
- /**
533
- * Fetches the highest supported version of metadata from the chain.
534
- *
535
- * @param rpcSend
536
- * @returns hex-encoded metadata starting with the magic number
537
- */
538
- const fetchBestMetadata = async (rpcSend, allowLegacyFallback) => {
539
- try {
540
- // fetch available versions of metadata
541
- const metadataVersions = await rpcSend("state_call", ["Metadata_metadata_versions", "0x"], true);
542
- const availableVersions = Vector(u32).dec(metadataVersions);
543
- const bestVersion = Math.max(...availableVersions.filter(v => v <= MAX_SUPPORTED_METADATA_VERSION));
544
- const metadata = await rpcSend("state_call", ["Metadata_metadata_at_version", toHex(u32.enc(bestVersion))], true);
545
- return normalizeMetadata(metadata);
546
- } catch (cause) {
547
- // if the chain doesnt support the Metadata pallet, fallback to legacy rpc provided metadata (V14)
548
- const message = cause?.message;
549
- if (allowLegacyFallback || message?.includes("is not found") ||
550
- // ex: crust standalone
551
- message?.includes("Module doesn't have export Metadata_metadata_versions") ||
552
- // ex: 3DPass
553
- message?.includes("Exported method Metadata_metadata_versions is not found") ||
554
- // ex: sora-polkadot & sora-standalone
555
- message?.includes("Execution, MethodNotFound, Metadata_metadata_versions") // ex: stafi
556
- ) {
557
- return await rpcSend("state_getMetadata", [], true);
558
- }
559
-
560
- // otherwise throw so it can be handled by the caller
561
- throw new Error("Failed to fetch metadata", {
562
- cause
563
- });
564
- }
565
- };
566
-
567
- /**
568
- * Removes everything before the magic number in the metadata.
569
- * This ensures Opaque metadata is usable by pjs
570
- */
571
- const normalizeMetadata = metadata => {
572
- const hexMagicNumber = toHex(u32.enc(MAGIC_NUMBER)).slice(2);
573
- const magicNumberIndex = metadata.indexOf(hexMagicNumber);
574
- if (magicNumberIndex === -1) throw new Error("Invalid metadata format: magic number not found");
575
- return `0x${metadata.slice(magicNumberIndex)}`;
576
- };
577
-
578
- export { MAX_SUPPORTED_METADATA_VERSION, fetchBestMetadata, getScaleApi };