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