polkadot-api 1.1.0 → 1.2.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.
package/dist/index.d.ts CHANGED
@@ -319,9 +319,15 @@ type TxEventsPayload = {
319
319
  };
320
320
  } & ({
321
321
  ok: true;
322
+ /**
323
+ * Dispatch Error found at `System.ExtrinsicFailed` event.
324
+ */
322
325
  dispatchError?: undefined;
323
326
  } | {
324
327
  ok: false;
328
+ /**
329
+ * Dispatch Error found at `System.ExtrinsicFailed` event.
330
+ */
325
331
  dispatchError: {
326
332
  type: string;
327
333
  value: unknown;
@@ -331,6 +337,9 @@ type TxFinalized = {
331
337
  type: "finalized";
332
338
  txHash: HexString;
333
339
  } & TxEventsPayload;
340
+ type TxFinalizedPayload = {
341
+ txHash: HexString;
342
+ } & TxEventsPayload;
334
343
  type TxOptions<Asset> = Partial<void extends Asset ? {
335
344
  /**
336
345
  * Block to target the transaction against. Default: `"finalized"`
@@ -383,7 +392,6 @@ type TxOptions<Asset> = Partial<void extends Asset ? {
383
392
  */
384
393
  nonce: number;
385
394
  }>;
386
- type TxFinalizedPayload = Omit<TxFinalized, "type">;
387
395
  type TxPromise<Asset> = (from: PolkadotSigner, txOptions?: TxOptions<Asset>) => Promise<TxFinalizedPayload>;
388
396
  type TxObservable<Asset> = (from: PolkadotSigner, txOptions?: TxOptions<Asset>) => Observable<TxEvent>;
389
397
  interface TxCall {
@@ -468,6 +476,26 @@ interface TxEntry<D, Arg extends {} | undefined, Pallet extends string, Name ext
468
476
  */
469
477
  (...args: Arg extends undefined ? [] : [data: Arg]): Transaction<Arg, Pallet, Name, Asset>;
470
478
  }
479
+ interface TxFromBinary<Asset> {
480
+ /**
481
+ * Asynchronously create the transaction object from a binary call data ready
482
+ * to sign, submit, estimate fees, etc.
483
+ *
484
+ * @param callData SCALE-encoded call data.
485
+ * @returns Transaction object.
486
+ */
487
+ (callData: Binary): Promise<Transaction<any, any, any, Asset>>;
488
+ /**
489
+ * Synchronously create the transaction object from a binary call data ready
490
+ * to sign, submit, estimate fees, etc.
491
+ *
492
+ * @param callData SCALE-encoded call data.
493
+ * @param compatibilityToken Token from got with `await
494
+ * typedApi.compatibilityToken`
495
+ * @returns Transaction object.
496
+ */
497
+ (callData: Binary, compatibilityToken: CompatibilityToken): Transaction<any, any, any, Asset>;
498
+ }
471
499
 
472
500
  declare class InvalidTxError extends Error {
473
501
  error: any;
@@ -510,6 +538,7 @@ type ConstApi<D, A extends Record<string, Record<string, any>>> = {
510
538
  type TypedApi<D extends ChainDefinition> = {
511
539
  query: StorageApi<D, QueryFromPalletsDef<D["descriptors"]["pallets"]>>;
512
540
  tx: TxApi<D, TxFromPalletsDef<D["descriptors"]["pallets"]>, D["asset"]["_type"]>;
541
+ txFromCallData: TxFromBinary<D["asset"]["_type"]>;
513
542
  event: EvApi<D, EventsFromPalletsDef<D["descriptors"]["pallets"]>>;
514
543
  apis: RuntimeCallsApi<D, D["descriptors"]["apis"]>;
515
544
  constants: ConstApi<D, ConstFromPalletsDef<D["descriptors"]["pallets"]>>;
@@ -630,6 +659,13 @@ interface PolkadotClient {
630
659
  type FixedSizeArray<L extends number, T> = Array<T> & {
631
660
  length: L;
632
661
  };
662
+ type TxCallData = {
663
+ type: string;
664
+ value: {
665
+ type: string;
666
+ value: any;
667
+ };
668
+ };
633
669
 
634
670
  /**
635
671
  * This is the top-level export for `polkadot-api`.
@@ -654,4 +690,4 @@ type FixedSizeArray<L extends number, T> = Array<T> & {
654
690
  */
655
691
  declare function createClient(provider: JsonRpcProvider): PolkadotClient;
656
692
 
657
- export { type ApisTypedef, type ChainDefinition, type ConstFromPalletsDef, type DescriptorEntry, type ErrorsFromPalletsDef, type EventPhase, type EventsFromPalletsDef, type FixedSizeArray, InvalidTxError, type PalletsTypedef, type PlainDescriptor, type PolkadotClient, type QueryFromPalletsDef, type RuntimeDescriptor, type StorageDescriptor, type Transaction, type TransactionValidityError, type TxBestBlocksState, type TxBroadcastEvent, type TxBroadcasted, type TxCall, type TxDescriptor, type TxEntry, type TxEvent, type TxEventsPayload, type TxFinalized, type TxFinalizedPayload, type TxFromPalletsDef, type TxInBestBlocksFound, type TxInBestBlocksNotFound, type TxObservable, type TxOptions, type TxPromise, type TxSignFn, type TxSigned, type TypedApi, createClient };
693
+ export { type ApisTypedef, type ChainDefinition, type ConstFromPalletsDef, type DescriptorEntry, type ErrorsFromPalletsDef, type EventPhase, type EventsFromPalletsDef, type FixedSizeArray, InvalidTxError, type PalletsTypedef, type PlainDescriptor, type PolkadotClient, type QueryFromPalletsDef, type RuntimeDescriptor, type StorageDescriptor, type Transaction, type TransactionValidityError, type TxBestBlocksState, type TxBroadcastEvent, type TxBroadcasted, type TxCall, type TxCallData, type TxDescriptor, type TxEntry, type TxEvent, type TxEventsPayload, type TxFinalized, type TxFinalizedPayload, type TxFromPalletsDef, type TxInBestBlocksFound, type TxInBestBlocksNotFound, type TxObservable, type TxOptions, type TxPromise, type TxSignFn, type TxSigned, type TypedApi, createClient };
package/dist/index.js CHANGED
@@ -22,7 +22,6 @@ var OpType = /* @__PURE__ */ ((OpType2) => {
22
22
  OpType2["Storage"] = "storage";
23
23
  OpType2["Tx"] = "tx";
24
24
  OpType2["Event"] = "events";
25
- OpType2["Error"] = "errors";
26
25
  OpType2["Const"] = "constants";
27
26
  return OpType2;
28
27
  })(OpType || {});
@@ -162,6 +161,8 @@ const createConstantEntry = (palletName, name, {
162
161
  (p) => p.name === palletName
163
162
  );
164
163
  const constant = pallet?.constants.find((c) => c.name === name);
164
+ if (constant == null)
165
+ throw new Error(`Runtime entry Constant(${palletName}.${name}) not found`);
165
166
  const result = ctx.dynamicBuilder.buildConstant(palletName, name).dec(constant.value);
166
167
  cachedResults.set(ctx, result);
167
168
  return result;
@@ -377,6 +378,13 @@ const createEventEntry = (pallet, name, chainHead, {
377
378
  const shared$ = chainHead.finalized$.pipe(
378
379
  withCompatibleRuntime(chainHead, (x) => x.hash),
379
380
  rxjs.map(([block, runtime, ctx]) => {
381
+ const eventsIdx = ctx.lookup.metadata.pallets.find(
382
+ (p) => p.name === pallet
383
+ )?.events;
384
+ if (eventsIdx == null || ctx.lookup.metadata.lookup[eventsIdx].def.tag !== "variant" || ctx.lookup.metadata.lookup[eventsIdx].def.value.find(
385
+ (ev) => ev.name === name
386
+ ) == null)
387
+ throw new Error(`Runtime entry Event(${pallet}.${name}) not found`);
380
388
  if (!argsAreCompatible(runtime, ctx, null)) throw compatibilityError();
381
389
  return [block, runtime, ctx];
382
390
  }),
@@ -424,8 +432,13 @@ const createRuntimeCallEntry = (api, method, chainHead, {
424
432
  const at = _at ?? null;
425
433
  const result$ = compatibleRuntime$(chainHead, at).pipe(
426
434
  rxjs.mergeMap(([runtime, ctx]) => {
435
+ let codecs;
436
+ try {
437
+ codecs = ctx.dynamicBuilder.buildRuntimeCall(api, method);
438
+ } catch {
439
+ throw new Error(`Runtime entry RuntimeCall(${callName}) not found`);
440
+ }
427
441
  if (!argsAreCompatible(runtime, ctx, args)) throw compatibilityError();
428
- const codecs = ctx.dynamicBuilder.buildRuntimeCall(api, method);
429
442
  return chainHead.call$(at, callName, utils.toHex(codecs.args.enc(args))).pipe(
430
443
  rxjs.map(codecs.value.dec),
431
444
  rxjs.map((value) => {
@@ -453,6 +466,13 @@ const createStorageEntry = (pallet, name, chainHead, {
453
466
  const isSystemNumber = pallet === "System" && name === "Number";
454
467
  const incompatibleError = () => new Error(`Incompatible runtime entry Storage(${pallet}.${name})`);
455
468
  const invalidArgs = (args) => new Error(`Invalid Arguments calling ${pallet}.${name}(${args})`);
469
+ const getCodec = (ctx) => {
470
+ try {
471
+ return ctx.dynamicBuilder.buildStorage(pallet, name);
472
+ } catch {
473
+ throw new Error(`Runtime entry Storage(${pallet}.${name}) not found`);
474
+ }
475
+ };
456
476
  const watchValue = (...args) => {
457
477
  const target = args[args.length - 1];
458
478
  const actualArgs = target === "best" || target === "finalized" ? args.slice(0, -1) : args;
@@ -465,9 +485,9 @@ const createStorageEntry = (pallet, name, chainHead, {
465
485
  rxjs.debounceTime(0),
466
486
  withCompatibleRuntime(chainHead, (x) => x.hash),
467
487
  raceMap(([block, runtime, ctx]) => {
488
+ const codecs = getCodec(ctx);
468
489
  if (!argsAreCompatible(runtime, ctx, actualArgs))
469
490
  throw incompatibleError();
470
- const codecs = ctx.dynamicBuilder.buildStorage(pallet, name);
471
491
  return chainHead.storage$(block.hash, "value", () => codecs.enc(...actualArgs)).pipe(
472
492
  rxjs.map((val) => {
473
493
  if (!valuesAreCompatible(runtime, ctx, val))
@@ -507,7 +527,7 @@ const createStorageEntry = (pallet, name, chainHead, {
507
527
  at,
508
528
  "value",
509
529
  (ctx) => {
510
- const codecs = ctx.dynamicBuilder.buildStorage(pallet, name);
530
+ const codecs = getCodec(ctx);
511
531
  const actualArgs = args.length === codecs.len ? args : args.slice(0, -1);
512
532
  if (args !== actualArgs && !isLastArgOptional) throw invalidArgs(args);
513
533
  if (!argsAreCompatible(descriptors, ctx, actualArgs))
@@ -516,7 +536,7 @@ const createStorageEntry = (pallet, name, chainHead, {
516
536
  },
517
537
  null,
518
538
  (data, ctx) => {
519
- const codecs = ctx.dynamicBuilder.buildStorage(pallet, name);
539
+ const codecs = getCodec(ctx);
520
540
  const value = data === null ? codecs.fallback : codecs.dec(data);
521
541
  if (!valuesAreCompatible(descriptors, ctx, value))
522
542
  throw incompatibleError();
@@ -536,9 +556,9 @@ const createStorageEntry = (pallet, name, chainHead, {
536
556
  at,
537
557
  "descendantsValues",
538
558
  (ctx) => {
559
+ const codecs = getCodec(ctx);
539
560
  if (minCompatLevel(getCompatibilityLevels(descriptors, ctx)) === metadataCompatibility.CompatibilityLevel.Incompatible)
540
561
  throw incompatibleError();
541
- const codecs = ctx.dynamicBuilder.buildStorage(pallet, name);
542
562
  if (args.length > codecs.len) throw invalidArgs(args);
543
563
  const actualArgs = args.length > 0 && isLastArgOptional ? args.slice(0, -1) : args;
544
564
  if (args.length === codecs.len && actualArgs === args)
@@ -547,7 +567,7 @@ const createStorageEntry = (pallet, name, chainHead, {
547
567
  },
548
568
  null,
549
569
  (values, ctx) => {
550
- const codecs = ctx.dynamicBuilder.buildStorage(pallet, name);
570
+ const codecs = getCodec(ctx);
551
571
  if (values.some(
552
572
  ({ value }) => !valuesAreCompatible(descriptors, ctx, value)
553
573
  ))
@@ -925,13 +945,19 @@ const createTxEntry = (pallet, name, chainHead, broadcast, {
925
945
  compatibleRuntime$,
926
946
  argsAreCompatible,
927
947
  getRuntimeTypedef
928
- }) => {
948
+ }, checkCompatibility) => {
929
949
  const fn = (arg) => {
930
950
  const getCallDataWithContext = (runtime, arg2, txOptions = {}) => {
931
951
  const ctx = getCompatibilityApi(runtime).runtime();
932
- if (!argsAreCompatible(runtime, ctx, arg2))
933
- throw new Error(`Incompatible runtime entry Tx(${pallet}.${name})`);
934
952
  const { dynamicBuilder, assetId, lookup } = ctx;
953
+ let codecs;
954
+ try {
955
+ codecs = dynamicBuilder.buildCall(pallet, name);
956
+ } catch {
957
+ throw new Error(`Runtime entry Tx(${pallet}.${name}) not found`);
958
+ }
959
+ if (checkCompatibility && !argsAreCompatible(runtime, ctx, arg2))
960
+ throw new Error(`Incompatible runtime entry Tx(${pallet}.${name})`);
935
961
  let returnOptions = txOptions;
936
962
  if (txOptions.asset) {
937
963
  if (assetId == null || !metadataCompatibility.isCompatible(
@@ -945,7 +971,7 @@ const createTxEntry = (pallet, name, chainHead, broadcast, {
945
971
  asset: dynamicBuilder.buildDefinition(assetId).enc(txOptions.asset)
946
972
  };
947
973
  }
948
- const { location, codec } = dynamicBuilder.buildCall(pallet, name);
974
+ const { location, codec } = codecs;
949
975
  return {
950
976
  callData: substrateBindings.Binary.fromBytes(
951
977
  utils.mergeUint8(new Uint8Array(location), codec.enc(arg2))
@@ -1072,7 +1098,8 @@ const createTypedApi = (compatibilityToken, chainHead, broadcast$) => {
1072
1098
  compatibilityToken,
1073
1099
  (r) => r.getPalletEntryPoint(OpType.Tx, pallet, name),
1074
1100
  (ctx) => getEnumEntry(ctx, "args", getPallet(ctx, pallet).calls, name)
1075
- )
1101
+ ),
1102
+ true
1076
1103
  )
1077
1104
  );
1078
1105
  const event = createProxyPath(
@@ -1114,8 +1141,32 @@ const createTypedApi = (compatibilityToken, chainHead, broadcast$) => {
1114
1141
  )
1115
1142
  )
1116
1143
  );
1144
+ const _callDataTx = (callData, token) => {
1145
+ const { lookup, dynamicBuilder } = getCompatibilityApi(token).runtime();
1146
+ try {
1147
+ const decoded = dynamicBuilder.buildDefinition(lookup.call).dec(callData.asBytes());
1148
+ const pallet = decoded.type;
1149
+ const call = decoded.value.type;
1150
+ const args = decoded.value.value;
1151
+ return createTxEntry(
1152
+ pallet,
1153
+ call,
1154
+ chainHead,
1155
+ broadcast$,
1156
+ compatibilityHelper(
1157
+ compatibilityToken,
1158
+ (r) => r.getPalletEntryPoint(OpType.Tx, pallet, call),
1159
+ (ctx) => getEnumEntry(ctx, "args", getPallet(ctx, pallet).calls, call)
1160
+ ),
1161
+ false
1162
+ )(args);
1163
+ } catch {
1164
+ throw new Error("createTx: invalid call data");
1165
+ }
1166
+ };
1117
1167
  return {
1118
1168
  query,
1169
+ txFromCallData: (callData, token) => token ? _callDataTx(callData, token) : compatibilityToken.then((t) => _callDataTx(callData, t)),
1119
1170
  tx,
1120
1171
  event,
1121
1172
  apis,