polkadot-api 0.6.0 → 0.7.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.js CHANGED
@@ -3,7 +3,6 @@ var __defProp = Object.defineProperty;
3
3
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
4
  var __getOwnPropNames = Object.getOwnPropertyNames;
5
5
  var __hasOwnProp = Object.prototype.hasOwnProperty;
6
- var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
7
6
  var __export = (target, all) => {
8
7
  for (var name in all)
9
8
  __defProp(target, name, { get: all[name], enumerable: true });
@@ -17,120 +16,26 @@ var __copyProps = (to, from, except, desc) => {
17
16
  return to;
18
17
  };
19
18
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
20
- var __publicField = (obj, key, value) => {
21
- __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
22
- return value;
23
- };
24
19
 
25
20
  // src/index.ts
26
21
  var src_exports = {};
27
22
  __export(src_exports, {
28
- AccountId: () => import_substrate_bindings8.AccountId,
29
- Binary: () => import_substrate_bindings8.Binary,
30
- Enum: () => import_substrate_bindings8.Enum,
31
- FixedSizeBinary: () => import_substrate_bindings8.FixedSizeBinary,
32
- _Enum: () => import_substrate_bindings8._Enum,
23
+ AccountId: () => import_substrate_bindings9.AccountId,
24
+ Binary: () => import_substrate_bindings9.Binary,
25
+ Enum: () => import_substrate_bindings9.Enum,
26
+ FixedSizeBinary: () => import_substrate_bindings9.FixedSizeBinary,
27
+ _Enum: () => import_substrate_bindings9._Enum,
33
28
  createClient: () => createClient
34
29
  });
35
30
  module.exports = __toCommonJS(src_exports);
36
31
 
37
32
  // src/client.ts
33
+ var import_observable_client2 = require("@polkadot-api/observable-client");
38
34
  var import_substrate_client = require("@polkadot-api/substrate-client");
39
- var import_rxjs20 = require("rxjs");
35
+ var import_rxjs22 = require("rxjs");
40
36
 
41
37
  // src/constants.ts
42
- var import_rxjs2 = require("rxjs");
43
-
44
- // src/runtime.ts
45
38
  var import_rxjs = require("rxjs");
46
- var Runtime = class {
47
- constructor(ctx, checksums) {
48
- __publicField(this, "_ctx");
49
- __publicField(this, "_checksums");
50
- this._ctx = ctx;
51
- this._checksums = checksums;
52
- }
53
- };
54
- function getRuntimeContext(runtime) {
55
- return runtime._ctx;
56
- }
57
- function getImportedChecksum(runtime, idx) {
58
- return runtime._checksums[idx];
59
- }
60
- var createRuntime = (ctx, checksums) => new Runtime(ctx, checksums);
61
- var getRuntimeApi = (checksums, chainHead) => {
62
- let latestRuntime;
63
- let resolve = null;
64
- latestRuntime = new Promise((res) => {
65
- resolve = res;
66
- });
67
- const runtimeWithChecksums$ = (0, import_rxjs.combineLatest)([chainHead.runtime$, checksums]);
68
- runtimeWithChecksums$.subscribe(([x, checksums2]) => {
69
- if (x) {
70
- const runtime = createRuntime(x, checksums2);
71
- if (resolve) {
72
- resolve(runtime);
73
- resolve = null;
74
- } else {
75
- latestRuntime = Promise.resolve(runtime);
76
- }
77
- } else if (!resolve) {
78
- latestRuntime = new Promise((res) => {
79
- resolve = res;
80
- });
81
- }
82
- });
83
- const result = runtimeWithChecksums$.pipe(
84
- (0, import_rxjs.filter)(([x]) => Boolean(x)),
85
- (0, import_rxjs.map)(([x, checksums2]) => createRuntime(x, checksums2))
86
- );
87
- result.latest = () => latestRuntime;
88
- return result;
89
- };
90
- var compatibilityHelper = (runtimeApi, checksumIdx) => (getChecksum) => {
91
- function isCompatibleSync(runtime) {
92
- const ctx = getRuntimeContext(runtime);
93
- const checksum = getImportedChecksum(runtime, checksumIdx);
94
- return getChecksum(ctx) === checksum;
95
- }
96
- const isCompatible = (runtime) => {
97
- if (runtime) {
98
- return isCompatibleSync(runtime);
99
- }
100
- return runtimeApi.latest().then(isCompatibleSync);
101
- };
102
- const waitChecksums = async () => {
103
- const runtime = await runtimeApi.latest();
104
- return (ctx) => getChecksum(ctx) === getImportedChecksum(runtime, checksumIdx);
105
- };
106
- const compatibleRuntime$ = (chainHead, hash, error) => (0, import_rxjs.combineLatest)([chainHead.getRuntimeContext$(hash), waitChecksums()]).pipe(
107
- (0, import_rxjs.map)(([ctx, isCompatible2]) => {
108
- if (!isCompatible2(ctx)) {
109
- throw error();
110
- }
111
- return ctx;
112
- })
113
- );
114
- const withCompatibleRuntime = (chainHead, mapper, error) => (source$) => (0, import_rxjs.combineLatest)([
115
- source$.pipe(chainHead.withRuntime(mapper)),
116
- waitChecksums()
117
- ]).pipe(
118
- (0, import_rxjs.map)(([[x, ctx], isCompatible2]) => {
119
- if (!isCompatible2(ctx)) {
120
- throw error();
121
- }
122
- return [x, ctx];
123
- })
124
- );
125
- return {
126
- isCompatible,
127
- waitChecksums,
128
- withCompatibleRuntime,
129
- compatibleRuntime$
130
- };
131
- };
132
-
133
- // src/constants.ts
134
39
  var createConstantEntry = (palletName, name, chainHead, compatibilityHelper2) => {
135
40
  const { isCompatible, compatibleRuntime$ } = compatibilityHelper2(
136
41
  (ctx) => ctx.checksumBuilder.buildConstant(palletName, name)
@@ -151,11 +56,11 @@ var createConstantEntry = (palletName, name, chainHead, compatibilityHelper2) =>
151
56
  if (runtime) {
152
57
  if (!isCompatible(runtime))
153
58
  throw checksumError();
154
- return getValueWithContext(getRuntimeContext(runtime));
59
+ return getValueWithContext(runtime._getCtx());
155
60
  }
156
- return (0, import_rxjs2.firstValueFrom)(
61
+ return (0, import_rxjs.firstValueFrom)(
157
62
  compatibleRuntime$(chainHead, null, checksumError).pipe(
158
- (0, import_rxjs2.map)(getValueWithContext)
63
+ (0, import_rxjs.map)(getValueWithContext)
159
64
  )
160
65
  );
161
66
  };
@@ -166,9 +71,9 @@ var createConstantEntry = (palletName, name, chainHead, compatibilityHelper2) =>
166
71
  var import_rxjs7 = require("rxjs");
167
72
 
168
73
  // src/utils/shareLatest.ts
169
- var import_rxjs3 = require("rxjs");
170
- var shareLatest = (0, import_rxjs3.share)({
171
- connector: () => new import_rxjs3.ReplaySubject(1),
74
+ var import_rxjs2 = require("rxjs");
75
+ var shareLatest = (0, import_rxjs2.share)({
76
+ connector: () => new import_rxjs2.ReplaySubject(1),
172
77
  resetOnError: true,
173
78
  resetOnComplete: true,
174
79
  resetOnRefCountZero: true
@@ -176,7 +81,7 @@ var shareLatest = (0, import_rxjs3.share)({
176
81
 
177
82
  // src/utils/firstValueFromWithSignal.ts
178
83
  var import_utils = require("@polkadot-api/utils");
179
- var import_rxjs4 = require("rxjs");
84
+ var import_rxjs3 = require("rxjs");
180
85
  function firstValueFromWithSignal(source, signal) {
181
86
  return new Promise((resolve, reject) => {
182
87
  let subscription = null;
@@ -184,7 +89,7 @@ function firstValueFromWithSignal(source, signal) {
184
89
  const onAbort = signal ? () => {
185
90
  subscription?.unsubscribe();
186
91
  reject(new import_utils.AbortError());
187
- } : import_rxjs4.noop;
92
+ } : import_rxjs3.noop;
188
93
  subscription = source.subscribe({
189
94
  next: (value) => {
190
95
  resolve(value);
@@ -206,8 +111,8 @@ function firstValueFromWithSignal(source, signal) {
206
111
  }
207
112
 
208
113
  // src/utils/concatMapEager.ts
209
- var import_rxjs5 = require("rxjs");
210
- var concatMapEager = (mapper, concurrent = Infinity) => (source$) => new import_rxjs5.Observable((observer) => {
114
+ var import_rxjs4 = require("rxjs");
115
+ var concatMapEager = (mapper, concurrent = Infinity) => (source$) => new import_rxjs4.Observable((observer) => {
211
116
  let topSubscription;
212
117
  const queues = /* @__PURE__ */ new Map();
213
118
  const innerSubscriptions = /* @__PURE__ */ new Map();
@@ -264,7 +169,7 @@ var concatMapEager = (mapper, concurrent = Infinity) => (source$) => new import_
264
169
  const idx = mapperIdx++;
265
170
  queues.set(
266
171
  idx,
267
- (0, import_rxjs5.defer)(() => mapper(outterValue, idx))
172
+ (0, import_rxjs4.defer)(() => mapper(outterValue, idx))
268
173
  );
269
174
  if (innerSubscriptions.size < concurrent) {
270
175
  nextSubscription();
@@ -288,12 +193,12 @@ var concatMapEager = (mapper, concurrent = Infinity) => (source$) => new import_
288
193
  });
289
194
 
290
195
  // src/utils/raceMap.ts
291
- var import_rxjs6 = require("rxjs");
292
- var raceMap = (mapper, concurrent) => (source$) => new import_rxjs6.Observable((observer) => {
196
+ var import_rxjs5 = require("rxjs");
197
+ var raceMap = (mapper, concurrent) => (source$) => new import_rxjs5.Observable((observer) => {
293
198
  let innerSubscriptions = new Array();
294
199
  let isOuterDone = false;
295
200
  const createSubscription = (value) => {
296
- const sub = new import_rxjs6.Subscription();
201
+ const sub = new import_rxjs5.Subscription();
297
202
  innerSubscriptions.push(sub);
298
203
  if (innerSubscriptions.length > concurrent) {
299
204
  innerSubscriptions[0].unsubscribe();
@@ -337,6 +242,30 @@ var raceMap = (mapper, concurrent) => (source$) => new import_rxjs6.Observable((
337
242
  };
338
243
  });
339
244
 
245
+ // src/utils/continue-with.ts
246
+ var import_rxjs6 = require("rxjs");
247
+ var NOTIN = {};
248
+ var continueWith = (mapper) => (source) => new import_rxjs6.Observable((observer) => {
249
+ let latestValue = NOTIN;
250
+ let subscription = source.subscribe({
251
+ next(v) {
252
+ observer.next(latestValue = v);
253
+ },
254
+ error(e) {
255
+ observer.error(e);
256
+ },
257
+ complete() {
258
+ if (latestValue === NOTIN)
259
+ observer.complete();
260
+ else
261
+ subscription = mapper(latestValue).subscribe(observer);
262
+ }
263
+ });
264
+ return () => {
265
+ subscription.unsubscribe();
266
+ };
267
+ });
268
+
340
269
  // src/event.ts
341
270
  var createEventEntry = (pallet, name, chainHead, compatibilityHelper2) => {
342
271
  const { isCompatible, withCompatibleRuntime } = compatibilityHelper2(
@@ -367,16 +296,105 @@ var createEventEntry = (pallet, name, chainHead, compatibilityHelper2) => {
367
296
  );
368
297
  const watch = (f) => shared$.pipe((0, import_rxjs7.mergeMap)((x) => f ? x.filter((d) => f(d.payload)) : x));
369
298
  const pull = () => (0, import_rxjs7.firstValueFrom)(shared$);
370
- const filter2 = (events) => events.filter((e) => e.type === pallet && e.value.type === name).map((x) => x.value.value);
371
- return { watch, pull, filter: filter2, isCompatible };
299
+ const filter3 = (events) => events.filter((e) => e.type === pallet && e.value.type === name).map((x) => x.value.value);
300
+ return { watch, pull, filter: filter3, isCompatible };
372
301
  };
373
302
 
374
- // src/client.ts
375
- var import_observable_client2 = require("@polkadot-api/observable-client");
303
+ // src/runtime.ts
304
+ var import_rxjs8 = require("rxjs");
305
+ var Runtime = class _Runtime {
306
+ constructor(_ctx, _checksums, _descriptors) {
307
+ this._ctx = _ctx;
308
+ this._checksums = _checksums;
309
+ this._descriptors = _descriptors;
310
+ }
311
+ /**
312
+ * @access package - Internal implementation detail. Do not use.
313
+ */
314
+ static _create(ctx, checksums, descriptors) {
315
+ return new _Runtime(ctx, checksums, descriptors);
316
+ }
317
+ /**
318
+ * @access package - Internal implementation detail. Do not use.
319
+ */
320
+ _getCtx() {
321
+ return this._ctx;
322
+ }
323
+ /**
324
+ * @access package - Internal implementation detail. Do not use.
325
+ */
326
+ _getPalletChecksum(opType, pallet, name) {
327
+ return this._checksums[this._descriptors.pallets[pallet][opType][name]];
328
+ }
329
+ /**
330
+ * @access package - Internal implementation detail. Do not use.
331
+ */
332
+ _getApiChecksum(name, method) {
333
+ return this._checksums[this._descriptors.apis[name][method]];
334
+ }
335
+ };
336
+ var getRuntimeApi = (checksums, descriptors, chainHead) => {
337
+ const runtimeWithChecksums$ = (0, import_rxjs8.connectable)(
338
+ (0, import_rxjs8.combineLatest)([chainHead.runtime$, checksums, descriptors]).pipe(
339
+ (0, import_rxjs8.map)(
340
+ ([x, checksums2, descriptors2]) => x ? Runtime._create(x, checksums2, descriptors2) : null
341
+ )
342
+ ),
343
+ {
344
+ connector: () => new import_rxjs8.ReplaySubject(1)
345
+ }
346
+ );
347
+ runtimeWithChecksums$.connect();
348
+ const result = runtimeWithChecksums$.pipe(
349
+ (0, import_rxjs8.filter)((v) => Boolean(v))
350
+ );
351
+ result.latest = () => (0, import_rxjs8.firstValueFrom)(result);
352
+ return result;
353
+ };
354
+ var compatibilityHelper = (runtimeApi, getDescriptorChecksum) => (getChecksum) => {
355
+ function isCompatibleSync(runtime) {
356
+ return getChecksum(runtime._getCtx()) === getDescriptorChecksum(runtime);
357
+ }
358
+ const isCompatible = (runtime) => {
359
+ if (runtime) {
360
+ return isCompatibleSync(runtime);
361
+ }
362
+ return runtimeApi.latest().then(isCompatibleSync);
363
+ };
364
+ const waitChecksums = async () => {
365
+ const runtime = await runtimeApi.latest();
366
+ return (ctx) => getChecksum(ctx) === getDescriptorChecksum(runtime);
367
+ };
368
+ const compatibleRuntime$ = (chainHead, hash, error) => (0, import_rxjs8.combineLatest)([chainHead.getRuntimeContext$(hash), waitChecksums()]).pipe(
369
+ (0, import_rxjs8.map)(([ctx, isCompatible2]) => {
370
+ if (!isCompatible2(ctx)) {
371
+ throw error();
372
+ }
373
+ return ctx;
374
+ })
375
+ );
376
+ const withCompatibleRuntime = (chainHead, mapper, error) => (source$) => (0, import_rxjs8.combineLatest)([
377
+ source$.pipe(chainHead.withRuntime(mapper)),
378
+ waitChecksums()
379
+ ]).pipe(
380
+ (0, import_rxjs8.map)(([[x, ctx], isCompatible2]) => {
381
+ if (!isCompatible2(ctx)) {
382
+ throw error();
383
+ }
384
+ return [x, ctx];
385
+ })
386
+ );
387
+ return {
388
+ isCompatible,
389
+ waitChecksums,
390
+ withCompatibleRuntime,
391
+ compatibleRuntime$
392
+ };
393
+ };
376
394
 
377
395
  // src/runtime-call.ts
378
396
  var import_utils4 = require("@polkadot-api/utils");
379
- var import_rxjs8 = require("rxjs");
397
+ var import_rxjs9 = require("rxjs");
380
398
  var isOptionalArg = (lastArg) => {
381
399
  if (typeof lastArg !== "object")
382
400
  return false;
@@ -396,9 +414,9 @@ var createRuntimeCallEntry = (api, method, chainHead, compatibilityHelper2) => {
396
414
  const { signal, at: _at } = isLastArgOptional ? lastArg : {};
397
415
  const at = _at ?? null;
398
416
  const result$ = compatibleRuntime$(chainHead, at, checksumError).pipe(
399
- (0, import_rxjs8.mergeMap)((ctx) => {
417
+ (0, import_rxjs9.mergeMap)((ctx) => {
400
418
  const codecs = ctx.dynamicBuilder.buildRuntimeCall(api, method);
401
- return chainHead.call$(at, callName, (0, import_utils4.toHex)(codecs.args.enc(args))).pipe((0, import_rxjs8.map)(codecs.value.dec));
419
+ return chainHead.call$(at, callName, (0, import_utils4.toHex)(codecs.args.enc(args))).pipe((0, import_rxjs9.map)(codecs.value.dec));
402
420
  })
403
421
  );
404
422
  return firstValueFromWithSignal(result$, signal);
@@ -407,7 +425,7 @@ var createRuntimeCallEntry = (api, method, chainHead, compatibilityHelper2) => {
407
425
  };
408
426
 
409
427
  // src/storage.ts
410
- var import_rxjs9 = require("rxjs");
428
+ var import_rxjs10 = require("rxjs");
411
429
  var import_observable_client = require("@polkadot-api/observable-client");
412
430
  var isOptionalArg2 = (lastArg) => {
413
431
  if (typeof lastArg !== "object")
@@ -426,18 +444,18 @@ var createStorageEntry = (pallet, name, chainHead, compatibilityHelper2) => {
426
444
  const actualArgs = target === "best" || target === "finalized" ? args.slice(0, -1) : args;
427
445
  if (isSystemNumber)
428
446
  return chainHead.bestBlocks$.pipe(
429
- (0, import_rxjs9.map)((blocks) => blocks.at(target === "best" ? 0 : -1).number),
430
- (0, import_rxjs9.distinctUntilChanged)()
447
+ (0, import_rxjs10.map)((blocks) => blocks.at(target === "best" ? 0 : -1).number),
448
+ (0, import_rxjs10.distinctUntilChanged)()
431
449
  );
432
450
  return chainHead[target === "best" ? "best$" : "finalized$"].pipe(
433
- (0, import_rxjs9.debounceTime)(0),
451
+ (0, import_rxjs10.debounceTime)(0),
434
452
  withCompatibleRuntime(chainHead, (x) => x.hash, checksumError),
435
453
  raceMap(([block, ctx]) => {
436
454
  const codecs = ctx.dynamicBuilder.buildStorage(pallet, name);
437
- return chainHead.storage$(block.hash, "value", () => codecs.enc(...actualArgs)).pipe((0, import_rxjs9.map)((val) => ({ val, codecs })));
455
+ return chainHead.storage$(block.hash, "value", () => codecs.enc(...actualArgs)).pipe((0, import_rxjs10.map)((val) => ({ val, codecs })));
438
456
  }, 4),
439
- (0, import_rxjs9.distinctUntilChanged)((a, b) => a.val === b.val),
440
- (0, import_rxjs9.map)(
457
+ (0, import_rxjs10.distinctUntilChanged)((a, b) => a.val === b.val),
458
+ (0, import_rxjs10.map)(
441
459
  ({ val, codecs }) => val === null ? codecs.fallback : codecs.dec(val)
442
460
  )
443
461
  );
@@ -450,19 +468,19 @@ var createStorageEntry = (pallet, name, chainHead, compatibilityHelper2) => {
450
468
  let result$;
451
469
  if (isSystemNumber) {
452
470
  result$ = chainHead.bestBlocks$.pipe(
453
- (0, import_rxjs9.map)((blocks) => {
471
+ (0, import_rxjs10.map)((blocks) => {
454
472
  if (at === "finalized" || !at)
455
473
  return blocks.at(-1);
456
474
  if (at === "best")
457
475
  return blocks.at(0);
458
476
  return blocks.find((block) => block.hash === at);
459
477
  }),
460
- (0, import_rxjs9.map)((block) => {
478
+ (0, import_rxjs10.map)((block) => {
461
479
  if (!block)
462
480
  throw new import_observable_client.NotBestBlockError();
463
481
  return block.number;
464
482
  }),
465
- (0, import_rxjs9.distinctUntilChanged)()
483
+ (0, import_rxjs10.distinctUntilChanged)()
466
484
  );
467
485
  } else {
468
486
  const isCompatible2 = await waitChecksums();
@@ -524,160 +542,30 @@ var createStorageEntry = (pallet, name, chainHead, compatibilityHelper2) => {
524
542
  return { isCompatible, getValue, getValues, getEntries, watchValue };
525
543
  };
526
544
 
527
- // src/tx.ts
528
- var import_substrate_bindings = require("@polkadot-api/substrate-bindings");
529
- var import_utils6 = require("@polkadot-api/utils");
530
- var import_rxjs10 = require("rxjs");
545
+ // src/tx/tx.ts
546
+ var import_substrate_bindings8 = require("@polkadot-api/substrate-bindings");
547
+ var import_utils19 = require("@polkadot-api/utils");
548
+ var import_rxjs21 = require("rxjs");
531
549
  var import_signer = require("@polkadot-api/signer");
532
- var getTxSuccessFromSystemEvents = (systemEvents, txIdx) => {
533
- const events = systemEvents.filter((x) => x.phase.type === "ApplyExtrinsic" && x.phase.value === txIdx).map((x) => x.event);
534
- const lastEvent = events[events.length - 1];
535
- const ok = lastEvent.type === "System" && lastEvent.value.type === "ExtrinsicSuccess";
536
- return { ok, events };
537
- };
538
- var accountIdEnc = (0, import_substrate_bindings.AccountId)().enc;
539
- var getSubmitFns = (chainHead, client) => {
540
- const tx$ = (tx) => (0, import_rxjs10.concat)(
541
- chainHead.finalized$.pipe(
542
- (0, import_rxjs10.take)(1),
543
- (0, import_rxjs10.mergeMap)((finalized) => chainHead.validateTx$(tx, finalized.hash)),
544
- (0, import_rxjs10.map)((isValid) => {
545
- if (!isValid)
546
- throw new Error("Invalid");
547
- return { type: "broadcasted" };
548
- })
549
- ),
550
- new import_rxjs10.Observable((observer) => {
551
- const subscription = chainHead.trackTx$(tx).subscribe(observer);
552
- subscription.add(
553
- client.broadcastTx$(tx).subscribe({
554
- error(e) {
555
- observer.error(e);
556
- }
557
- })
558
- );
559
- return subscription;
560
- })
561
- );
562
- const submit$ = (transaction) => tx$(transaction).pipe(
563
- (0, import_rxjs10.mergeMap)((result) => {
564
- return result.type !== "finalized" ? (0, import_rxjs10.of)(result) : chainHead.eventsAt$(result.block.hash).pipe(
565
- (0, import_rxjs10.map)((events) => ({
566
- ...result,
567
- ...getTxSuccessFromSystemEvents(
568
- events,
569
- Number(result.block.index)
570
- )
571
- }))
572
- );
573
- })
574
- );
575
- const submit = async (transaction) => (0, import_rxjs10.lastValueFrom)(submit$(transaction)).then((x) => {
576
- if (x.type !== "finalized")
577
- throw null;
578
- const result = { ...x };
579
- delete result.type;
580
- return result;
581
- });
582
- return { submit$, submit };
583
- };
584
- var queryInfoRawDec = (0, import_substrate_bindings.Tuple)(import_substrate_bindings.compact, import_substrate_bindings.compact, import_substrate_bindings.u8, import_substrate_bindings.u128).dec;
585
- var queryInfoDec = (input) => queryInfoRawDec(input)[3];
586
- var fakeSignature = new Uint8Array(64);
587
- var getFakeSignature = () => fakeSignature;
588
- var createTxEntry = (pallet, name, assetChecksum, chainHead, submits, signer, compatibilityHelper2) => {
589
- const { isCompatible, compatibleRuntime$ } = compatibilityHelper2(
590
- (ctx) => ctx.checksumBuilder.buildCall(pallet, name)
591
- );
592
- const checksumError = () => new Error(`Incompatible runtime entry Tx(${pallet}.${name})`);
593
- const fn = (arg) => {
594
- const getCallDataWithContext = ({ dynamicBuilder, asset: [assetEnc, assetCheck] }, arg2, hinted = {}) => {
595
- let returnHinted = hinted;
596
- if (hinted.asset) {
597
- if (assetChecksum !== assetCheck)
598
- throw new Error(`Incompatible runtime asset`);
599
- returnHinted = { ...hinted, asset: assetEnc(hinted.asset) };
600
- }
601
- const { location, codec } = dynamicBuilder.buildCall(pallet, name);
602
- return {
603
- callData: import_substrate_bindings.Binary.fromBytes(
604
- (0, import_utils6.mergeUint8)(new Uint8Array(location), codec.enc(arg2))
605
- ),
606
- hinted: returnHinted
607
- };
608
- };
609
- const getCallData$ = (arg2, hinted = {}) => compatibleRuntime$(chainHead, null, checksumError).pipe(
610
- (0, import_rxjs10.map)((ctx) => getCallDataWithContext(ctx, arg2, hinted))
611
- );
612
- const getEncodedData = (runtime) => {
613
- if (runtime) {
614
- if (!isCompatible(runtime)) {
615
- throw checksumError();
616
- }
617
- return getCallDataWithContext(getRuntimeContext(runtime), arg).callData;
618
- }
619
- return (0, import_rxjs10.firstValueFrom)(getCallData$(arg).pipe((0, import_rxjs10.map)((x) => x.callData)));
620
- };
621
- const sign$ = (from, _hinted) => getCallData$(arg, _hinted).pipe(
622
- (0, import_rxjs10.withLatestFrom)(chainHead.finalized$),
623
- (0, import_rxjs10.take)(1),
624
- (0, import_rxjs10.mergeMap)(
625
- ([{ callData, hinted }, finalized]) => signer(from, callData.asBytes(), finalized, hinted)
626
- )
627
- );
628
- const sign = (from, _hinted) => (0, import_rxjs10.firstValueFrom)(sign$(from, _hinted)).then(import_utils6.toHex);
629
- const signAndSubmit = (from, _hinted) => sign(from, _hinted).then(submits.submit);
630
- const signSubmitAndWatch = (from, _hinted) => sign$(from, _hinted).pipe(
631
- (0, import_rxjs10.mergeMap)((result) => {
632
- const tx = (0, import_utils6.toHex)(result);
633
- return submits.submit$(tx).pipe((0, import_rxjs10.startWith)({ type: "signed", tx }));
634
- })
635
- );
636
- const getEstimatedFees = async (from, _hinted) => {
637
- const fakeSigner = (0, import_signer.getPolkadotSigner)(
638
- from instanceof Uint8Array ? from : accountIdEnc(from),
639
- "Sr25519",
640
- getFakeSignature
641
- );
642
- const encoded = (0, import_utils6.fromHex)(await sign(fakeSigner, _hinted));
643
- const args = (0, import_utils6.toHex)((0, import_utils6.mergeUint8)(encoded, import_substrate_bindings.u32.enc(encoded.length)));
644
- return (0, import_rxjs10.firstValueFrom)(
645
- chainHead.call$(null, "TransactionPaymentApi_query_info", args).pipe((0, import_rxjs10.map)(queryInfoDec))
646
- );
647
- };
648
- return {
649
- getEstimatedFees,
650
- decodedCall: {
651
- type: pallet,
652
- value: (0, import_substrate_bindings.Enum)(name, arg)
653
- },
654
- getEncodedData,
655
- sign,
656
- signSubmitAndWatch,
657
- signAndSubmit
658
- };
659
- };
660
- return Object.assign(fn, { isCompatible });
661
- };
662
550
 
663
- // src/get-create-tx.ts
551
+ // src/tx/create-tx.ts
664
552
  var import_rxjs19 = require("rxjs");
665
553
 
666
- // src/signed-extensions/user/ChargeTransactionPayment.ts
667
- var import_substrate_bindings3 = require("@polkadot-api/substrate-bindings");
554
+ // src/tx/signed-extensions/user/ChargeTransactionPayment.ts
555
+ var import_substrate_bindings2 = require("@polkadot-api/substrate-bindings");
668
556
  var import_rxjs12 = require("rxjs");
669
557
 
670
- // src/signed-extensions/utils.ts
558
+ // src/tx/signed-extensions/utils.ts
671
559
  var import_rxjs11 = require("rxjs");
672
- var import_substrate_bindings2 = require("@polkadot-api/substrate-bindings");
560
+ var import_substrate_bindings = require("@polkadot-api/substrate-bindings");
673
561
  var import_metadata_builders = require("@polkadot-api/metadata-builders");
674
- var import_utils7 = require("@polkadot-api/utils");
562
+ var import_utils6 = require("@polkadot-api/utils");
675
563
  var empty = new Uint8Array();
676
- var genesisHashStorageKey = (0, import_substrate_bindings2.Storage)("System")("BlockHash", import_rxjs11.noop, [
677
- import_substrate_bindings2.u32,
678
- import_substrate_bindings2.Twox64Concat
564
+ var genesisHashStorageKey = (0, import_substrate_bindings.Storage)("System")("BlockHash", import_rxjs11.noop, [
565
+ import_substrate_bindings.u32,
566
+ import_substrate_bindings.Twox64Concat
679
567
  ]).enc(0);
680
- var genesisHashFromCtx = (ctx) => ctx.chainHead.storage$(ctx.at, "value", () => genesisHashStorageKey, null).pipe((0, import_rxjs11.map)((result) => (0, import_utils7.fromHex)(result)));
568
+ var genesisHashFromCtx = (ctx) => ctx.chainHead.storage$(ctx.at, "value", () => genesisHashStorageKey, null).pipe((0, import_rxjs11.map)((result) => (0, import_utils6.fromHex)(result)));
681
569
  var systemVersionProp$ = (propName, metadata) => {
682
570
  const lookupFn = (0, import_metadata_builders.getLookupFn)(metadata.lookup);
683
571
  const dynamicBuilder = (0, import_metadata_builders.getDynamicBuilder)(metadata);
@@ -692,16 +580,16 @@ var systemVersionProp$ = (propName, metadata) => {
692
580
  return (0, import_rxjs11.of)(valueEnc(systemVersionDec(constant.value)[propName]));
693
581
  };
694
582
 
695
- // src/signed-extensions/user/ChargeTransactionPayment.ts
583
+ // src/tx/signed-extensions/user/ChargeTransactionPayment.ts
696
584
  var ChargeTransactionPayment = (tip) => (0, import_rxjs12.of)({
697
- value: import_substrate_bindings3.compactBn.enc(tip),
585
+ value: import_substrate_bindings2.compactBn.enc(tip),
698
586
  additionalSigned: empty
699
587
  });
700
588
 
701
- // src/signed-extensions/user/CheckMortality.ts
589
+ // src/tx/signed-extensions/user/CheckMortality.ts
702
590
  var import_rxjs13 = require("rxjs");
703
- var import_substrate_bindings4 = require("@polkadot-api/substrate-bindings");
704
- var import_utils9 = require("@polkadot-api/utils");
591
+ var import_substrate_bindings3 = require("@polkadot-api/substrate-bindings");
592
+ var import_utils8 = require("@polkadot-api/utils");
705
593
  function trailingZeroes(n) {
706
594
  let i = 0;
707
595
  while (!(n & 1)) {
@@ -710,13 +598,13 @@ function trailingZeroes(n) {
710
598
  }
711
599
  return i;
712
600
  }
713
- var mortal = (0, import_substrate_bindings4.enhanceEncoder)(
714
- (0, import_substrate_bindings4.Bytes)(2).enc,
601
+ var mortal = (0, import_substrate_bindings3.enhanceEncoder)(
602
+ (0, import_substrate_bindings3.Bytes)(2).enc,
715
603
  (value) => {
716
604
  const factor = Math.max(value.period >> 12, 1);
717
605
  const left = Math.min(Math.max(trailingZeroes(value.period) - 1, 1), 15);
718
606
  const right = value.phase / factor << 4;
719
- return import_substrate_bindings4.u16.enc(left | right);
607
+ return import_substrate_bindings3.u16.enc(left | right);
720
608
  }
721
609
  );
722
610
  var zero = new Uint8Array([0]);
@@ -730,7 +618,7 @@ var CheckMortality = (input, ctx) => {
730
618
  );
731
619
  const { period, blockNumber } = input;
732
620
  return (0, import_rxjs13.of)({
733
- additionalSigned: (0, import_utils9.fromHex)(ctx.at),
621
+ additionalSigned: (0, import_utils8.fromHex)(ctx.at),
734
622
  value: mortal({
735
623
  period,
736
624
  phase: blockNumber % period
@@ -738,12 +626,12 @@ var CheckMortality = (input, ctx) => {
738
626
  });
739
627
  };
740
628
 
741
- // src/signed-extensions/user/ChargeAssetTxPayment.ts
629
+ // src/tx/signed-extensions/user/ChargeAssetTxPayment.ts
742
630
  var import_rxjs14 = require("rxjs");
743
- var import_substrate_bindings5 = require("@polkadot-api/substrate-bindings");
744
- var encoder = (0, import_substrate_bindings5.Struct)({
745
- tip: import_substrate_bindings5.compact,
746
- asset: (0, import_substrate_bindings5.Option)((0, import_substrate_bindings5.Bytes)(Infinity))
631
+ var import_substrate_bindings4 = require("@polkadot-api/substrate-bindings");
632
+ var encoder = (0, import_substrate_bindings4.Struct)({
633
+ tip: import_substrate_bindings4.compact,
634
+ asset: (0, import_substrate_bindings4.Option)((0, import_substrate_bindings4.Bytes)(Infinity))
747
635
  }).enc;
748
636
  var ChargeAssetTxPayment = (tip, asset) => (0, import_rxjs14.of)({
749
637
  value: encoder({
@@ -753,220 +641,462 @@ var ChargeAssetTxPayment = (tip, asset) => (0, import_rxjs14.of)({
753
641
  additionalSigned: empty
754
642
  });
755
643
 
756
- // src/signed-extensions/chain/index.ts
644
+ // src/tx/signed-extensions/chain/index.ts
757
645
  var chain_exports = {};
758
646
  __export(chain_exports, {
759
647
  CheckGenesis: () => CheckGenesis,
760
648
  CheckNonce: () => CheckNonce,
761
649
  CheckSpecVersion: () => CheckSpecVersion,
762
- CheckTxVersion: () => CheckTxVersion
650
+ CheckTxVersion: () => CheckTxVersion,
651
+ getNonce: () => getNonce
763
652
  });
764
653
 
765
- // src/signed-extensions/chain/CheckGenesis.ts
654
+ // src/tx/signed-extensions/chain/CheckGenesis.ts
766
655
  var import_rxjs15 = require("rxjs");
767
656
  var CheckGenesis = (ctx) => genesisHashFromCtx(ctx).pipe(
768
657
  (0, import_rxjs15.map)((additionalSigned) => ({ value: empty, additionalSigned }))
769
658
  );
770
659
 
771
- // src/signed-extensions/chain/CheckNonce.ts
660
+ // src/tx/signed-extensions/chain/CheckNonce.ts
772
661
  var import_rxjs16 = require("rxjs");
773
- var import_substrate_bindings6 = require("@polkadot-api/substrate-bindings");
774
- var import_utils14 = require("@polkadot-api/utils");
662
+ var import_substrate_bindings5 = require("@polkadot-api/substrate-bindings");
663
+ var import_utils13 = require("@polkadot-api/utils");
664
+ var NONCE_RUNTIME_CALL = "AccountNonceApi_account_nonce";
775
665
  var lenToDecoder = {
776
- 1: import_substrate_bindings6.u8.dec,
777
- 2: import_substrate_bindings6.u16.dec,
778
- 4: import_substrate_bindings6.u32.dec,
779
- 8: import_substrate_bindings6.u64.dec
666
+ 1: import_substrate_bindings5.u8.dec,
667
+ 2: import_substrate_bindings5.u16.dec,
668
+ 4: import_substrate_bindings5.u32.dec,
669
+ 8: import_substrate_bindings5.u64.dec
780
670
  };
781
- var CheckNonce = (ctx) => ctx.chainHead.call$(ctx.at, "AccountNonceApi_account_nonce", (0, import_utils14.toHex)(ctx.from)).pipe(
782
- (0, import_rxjs16.map)((result) => {
783
- const bytes = (0, import_utils14.fromHex)(result);
671
+ var getNonce = (input) => (0, import_rxjs16.of)({ value: import_substrate_bindings5.compact.enc(input), additionalSigned: empty });
672
+ var CheckNonce = (ctx) => ctx.chainHead.call$(ctx.at, NONCE_RUNTIME_CALL, (0, import_utils13.toHex)(ctx.from)).pipe(
673
+ (0, import_rxjs16.mergeMap)((result) => {
674
+ const bytes = (0, import_utils13.fromHex)(result);
784
675
  const decoder = lenToDecoder[bytes.length];
785
676
  if (!decoder)
786
- throw new Error("AccountNonceApi_account_nonce retrieved wrong data");
787
- return import_substrate_bindings6.compact.enc(decoder(bytes));
788
- }),
789
- (0, import_rxjs16.map)((value) => ({ value, additionalSigned: empty }))
677
+ throw new Error(`${NONCE_RUNTIME_CALL} retrieved wrong data`);
678
+ return getNonce(decoder(bytes));
679
+ })
790
680
  );
791
681
 
792
- // src/signed-extensions/chain/CheckSpecVersion.ts
682
+ // src/tx/signed-extensions/chain/CheckSpecVersion.ts
793
683
  var import_rxjs17 = require("rxjs");
794
684
  var CheckSpecVersion = ({ metadata }) => systemVersionProp$("spec_version", metadata).pipe(
795
685
  (0, import_rxjs17.map)((additionalSigned) => ({ additionalSigned, value: empty }))
796
686
  );
797
687
 
798
- // src/signed-extensions/chain/CheckTxVersion.ts
688
+ // src/tx/signed-extensions/chain/CheckTxVersion.ts
799
689
  var import_rxjs18 = require("rxjs");
800
690
  var CheckTxVersion = ({ metadata }) => systemVersionProp$("transaction_version", metadata).pipe(
801
691
  (0, import_rxjs18.map)((additionalSigned) => ({ additionalSigned, value: empty }))
802
692
  );
803
693
 
804
- // src/get-create-tx.ts
805
- var import_substrate_bindings7 = require("@polkadot-api/substrate-bindings");
806
- var getCreateTx = (chainHead) => {
807
- return (signer, callData, atBlock, hinted) => {
808
- return chainHead.getRuntimeContext$(atBlock.hash).pipe(
809
- (0, import_rxjs19.take)(1),
810
- (0, import_rxjs19.mergeMap)((ctx) => {
811
- const signedExtensionsCtx = {
812
- metadata: ctx.metadata,
813
- chainHead,
694
+ // src/tx/create-tx.ts
695
+ var import_substrate_bindings6 = require("@polkadot-api/substrate-bindings");
696
+ var createTx = (chainHead, signer, callData, atBlock, hinted = {}) => chainHead.getRuntimeContext$(atBlock.hash).pipe(
697
+ (0, import_rxjs19.take)(1),
698
+ (0, import_rxjs19.mergeMap)((ctx) => {
699
+ const signedExtensionsCtx = {
700
+ metadata: ctx.metadata,
701
+ chainHead,
702
+ callData,
703
+ at: atBlock.hash,
704
+ from: signer.publicKey
705
+ };
706
+ const mortality = !hinted.mortality ? { period: 64, blockNumber: atBlock.number } : hinted.mortality.mortal ? { period: hinted.mortality.period, blockNumber: atBlock.number } : void 0;
707
+ return (0, import_rxjs19.combineLatest)(
708
+ ctx.metadata.extrinsic.signedExtensions.map(
709
+ ({ identifier, type, additionalSigned }) => {
710
+ if (identifier === "CheckMortality")
711
+ return CheckMortality(mortality, signedExtensionsCtx);
712
+ if (identifier === "ChargeTransactionPayment")
713
+ return ChargeTransactionPayment(hinted.tip ?? 0n);
714
+ if (identifier === "ChargeAssetTxPayment")
715
+ return ChargeAssetTxPayment(hinted.tip ?? 0n, hinted.asset);
716
+ if (identifier === "CheckNonce" && "nonce" in hinted)
717
+ return getNonce(hinted.nonce);
718
+ const fn = chain_exports[identifier];
719
+ if (!fn) {
720
+ if (ctx.dynamicBuilder.buildDefinition(type) === import_substrate_bindings6._void && ctx.dynamicBuilder.buildDefinition(additionalSigned) === import_substrate_bindings6._void)
721
+ return (0, import_rxjs19.of)({
722
+ value: empty,
723
+ additionalSigned: empty
724
+ });
725
+ throw new Error(`Unsupported signed-extension: ${identifier}`);
726
+ }
727
+ return fn(signedExtensionsCtx);
728
+ }
729
+ )
730
+ ).pipe(
731
+ (0, import_rxjs19.mergeMap)(
732
+ (signedExtensions) => signer.sign(
814
733
  callData,
815
- at: atBlock.hash,
816
- from: signer.publicKey
817
- };
818
- const mortality = !hinted?.mortality ? { period: 64, blockNumber: atBlock.number } : hinted.mortality.mortal ? { period: hinted.mortality.period, blockNumber: atBlock.number } : void 0;
819
- return (0, import_rxjs19.combineLatest)(
820
- ctx.metadata.extrinsic.signedExtensions.map(
821
- ({ identifier, type, additionalSigned }) => {
822
- if (identifier === "CheckMortality")
823
- return CheckMortality(mortality, signedExtensionsCtx);
824
- if (identifier === "ChargeTransactionPayment")
825
- return ChargeTransactionPayment(hinted?.tip ?? 0n);
826
- if (identifier === "ChargeAssetTxPayment")
827
- return ChargeAssetTxPayment(hinted?.tip ?? 0n, hinted?.asset);
828
- const fn = chain_exports[identifier];
829
- if (!fn) {
830
- if (ctx.dynamicBuilder.buildDefinition(type) === import_substrate_bindings7._void && ctx.dynamicBuilder.buildDefinition(additionalSigned) === import_substrate_bindings7._void)
831
- return (0, import_rxjs19.of)({
832
- value: empty,
833
- additionalSigned: empty
834
- });
835
- throw new Error(`Unsupported signed-extension: ${identifier}`);
836
- }
837
- return fn(signedExtensionsCtx);
838
- }
839
- )
840
- ).pipe(
841
- (0, import_rxjs19.mergeMap)(
842
- (signedExtensions) => signer.sign(
843
- callData,
844
- Object.fromEntries(
845
- ctx.metadata.extrinsic.signedExtensions.map(
846
- ({ identifier }, idx) => [
847
- identifier,
848
- { identifier, ...signedExtensions[idx] }
849
- ]
850
- )
851
- ),
852
- ctx.metadataRaw,
853
- atBlock.number
734
+ Object.fromEntries(
735
+ ctx.metadata.extrinsic.signedExtensions.map(
736
+ ({ identifier }, idx) => [
737
+ identifier,
738
+ { identifier, ...signedExtensions[idx] }
739
+ ]
854
740
  )
855
- )
856
- );
857
- })
741
+ ),
742
+ ctx.metadataRaw,
743
+ atBlock.number
744
+ )
745
+ )
858
746
  );
859
- };
860
- };
747
+ })
748
+ );
861
749
 
862
- // src/client.ts
863
- var createTypedApi = (descriptors, createTxFromSigner, chainHead, submitFns) => {
864
- const runtimeApi = getRuntimeApi(descriptors.checksums, chainHead);
865
- const { pallets, apis: runtimeApis } = descriptors;
866
- const query = {};
867
- for (const pallet in pallets) {
868
- query[pallet] || (query[pallet] = {});
869
- const [stgEntries] = pallets[pallet];
870
- for (const name in stgEntries) {
871
- query[pallet][name] = createStorageEntry(
872
- pallet,
873
- name,
874
- chainHead,
875
- compatibilityHelper(runtimeApi, stgEntries[name])
876
- );
750
+ // src/tx/submit-fns.ts
751
+ var import_substrate_bindings7 = require("@polkadot-api/substrate-bindings");
752
+ var import_rxjs20 = require("rxjs");
753
+ var import_utils18 = require("@polkadot-api/utils");
754
+ var hashFromTx = (tx) => (0, import_utils18.toHex)((0, import_substrate_bindings7.Blake2256)((0, import_utils18.fromHex)(tx)));
755
+ var computeState = (analized$, blocks$) => new import_rxjs20.Observable((observer) => {
756
+ const analyzedBlocks = /* @__PURE__ */ new Map();
757
+ let pinnedBlocks;
758
+ let latestState;
759
+ const computeNextState = () => {
760
+ let current = pinnedBlocks.best;
761
+ let analyzed = analyzedBlocks.get(current);
762
+ while (!analyzed) {
763
+ const block = pinnedBlocks.blocks.get(current);
764
+ if (!block)
765
+ break;
766
+ analyzed = analyzedBlocks.get(current = block.parent);
877
767
  }
878
- }
879
- const tx = {};
880
- for (const pallet in pallets) {
881
- tx[pallet] || (tx[pallet] = {});
882
- const [, txEntries] = pallets[pallet];
883
- for (const name in txEntries) {
884
- tx[pallet][name] = createTxEntry(
885
- pallet,
886
- name,
887
- descriptors.asset,
888
- chainHead,
889
- submitFns,
890
- createTxFromSigner,
891
- compatibilityHelper(runtimeApi, txEntries[name])
892
- );
768
+ if (!analyzed)
769
+ return;
770
+ const isFinalized = pinnedBlocks.blocks.get(analyzed.hash).number <= pinnedBlocks.blocks.get(pinnedBlocks.finalized).number;
771
+ const found = analyzed.found.type;
772
+ if (found && typeof latestState === "object" && latestState.hash === analyzed.hash) {
773
+ if (isFinalized)
774
+ observer.complete();
775
+ return;
893
776
  }
894
- }
895
- const events = {};
896
- for (const pallet in pallets) {
897
- events[pallet] || (events[pallet] = {});
898
- const [, , evEntries] = pallets[pallet];
899
- for (const name in evEntries) {
900
- events[pallet][name] = createEventEntry(
901
- pallet,
902
- name,
903
- chainHead,
904
- compatibilityHelper(runtimeApi, evEntries[name])
905
- );
777
+ observer.next(
778
+ latestState = found ? {
779
+ hash: analyzed.hash,
780
+ ...analyzed.found
781
+ } : analyzed.found.isValid
782
+ );
783
+ if (isFinalized) {
784
+ if (found)
785
+ observer.complete();
786
+ else if (!analyzed.found.isValid)
787
+ observer.error(new Error("Invalid"));
906
788
  }
907
- }
908
- const constants = {};
909
- for (const pallet in pallets) {
910
- constants[pallet] || (constants[pallet] = {});
911
- const [, , , , ctEntries] = pallets[pallet];
912
- for (const name in ctEntries) {
913
- constants[pallet][name] = createConstantEntry(
914
- pallet,
915
- name,
916
- chainHead,
917
- compatibilityHelper(runtimeApi, ctEntries[name])
918
- );
789
+ };
790
+ const subscription = blocks$.pipe(
791
+ (0, import_rxjs20.distinctUntilChanged)(
792
+ (a, b) => a.finalized === b.finalized && a.best === b.best
793
+ )
794
+ ).subscribe({
795
+ next: (pinned) => {
796
+ pinnedBlocks = pinned;
797
+ if (analyzedBlocks.size === 0)
798
+ return;
799
+ computeNextState();
800
+ },
801
+ error(e) {
802
+ observer.error(e);
919
803
  }
920
- }
921
- const apis = {};
922
- for (const api in runtimeApis) {
923
- apis[api] || (apis[api] = {});
924
- const methods = runtimeApis[api];
925
- for (const method in methods) {
926
- apis[api][method] = createRuntimeCallEntry(
927
- api,
928
- method,
929
- chainHead,
930
- compatibilityHelper(runtimeApi, methods[method])
804
+ });
805
+ subscription.add(
806
+ analized$.subscribe({
807
+ next: (block) => {
808
+ analyzedBlocks.set(block.hash, block);
809
+ computeNextState();
810
+ },
811
+ error(e) {
812
+ observer.error(e);
813
+ }
814
+ })
815
+ );
816
+ return subscription;
817
+ }).pipe((0, import_rxjs20.distinctUntilChanged)((a, b) => a === b));
818
+ var getTxSuccessFromSystemEvents = (systemEvents, txIdx) => {
819
+ const events = systemEvents.filter((x) => x.phase.type === "ApplyExtrinsic" && x.phase.value === txIdx).map((x) => x.event);
820
+ const lastEvent = events[events.length - 1];
821
+ const ok = lastEvent.type === "System" && lastEvent.value.type === "ExtrinsicSuccess";
822
+ return { ok, events };
823
+ };
824
+ var submit$ = (chainHead, broadcastTx$, tx, at, emitSign = false) => {
825
+ const txHash = hashFromTx(tx);
826
+ const getTxEvent = (type, rest) => ({
827
+ type,
828
+ txHash,
829
+ ...rest
830
+ });
831
+ const at$ = chainHead.pinnedBlocks$.pipe(
832
+ (0, import_rxjs20.take)(1),
833
+ (0, import_rxjs20.map)((blocks) => blocks.blocks.get(at)?.hash ?? blocks.finalized)
834
+ );
835
+ const validate$ = at$.pipe(
836
+ (0, import_rxjs20.mergeMap)(
837
+ (at2) => chainHead.validateTx$(at2, tx).pipe(
838
+ (0, import_rxjs20.filter)((x) => !x),
839
+ (0, import_rxjs20.map)(() => {
840
+ throw new Error("Invalid");
841
+ })
842
+ )
843
+ )
844
+ );
845
+ const track$ = new import_rxjs20.Observable((observer) => {
846
+ const subscription = chainHead.trackTx$(tx).subscribe(observer);
847
+ subscription.add(
848
+ broadcastTx$(tx).subscribe({
849
+ error(e) {
850
+ observer.error(e);
851
+ }
852
+ })
853
+ );
854
+ return subscription;
855
+ });
856
+ const bestBlockState$ = computeState(track$, chainHead.pinnedBlocks$).pipe(
857
+ (0, import_rxjs20.map)((x) => {
858
+ if (x === true || x === false)
859
+ return getTxEvent("txBestBlocksState", {
860
+ found: false,
861
+ isValid: x
862
+ });
863
+ return getTxEvent("txBestBlocksState", {
864
+ found: true,
865
+ block: {
866
+ index: x.index,
867
+ hash: x.hash
868
+ },
869
+ ...getTxSuccessFromSystemEvents(x.events, x.index)
870
+ });
871
+ })
872
+ );
873
+ return (0, import_rxjs20.concat)(
874
+ emitSign ? (0, import_rxjs20.of)(getTxEvent("signed", {})) : import_rxjs20.EMPTY,
875
+ validate$,
876
+ (0, import_rxjs20.of)(getTxEvent("broadcasted", {})),
877
+ bestBlockState$.pipe(
878
+ continueWith(
879
+ ({ found, type, ...rest }) => found ? (0, import_rxjs20.of)(getTxEvent("finalized", rest)) : import_rxjs20.EMPTY
880
+ )
881
+ )
882
+ );
883
+ };
884
+ var submit = async (chainHead, broadcastTx$, transaction, at) => (0, import_rxjs20.lastValueFrom)(submit$(chainHead, broadcastTx$, transaction, at)).then((x) => {
885
+ if (x.type !== "finalized")
886
+ throw null;
887
+ const result = { ...x };
888
+ delete result.type;
889
+ return result;
890
+ });
891
+
892
+ // src/tx/tx.ts
893
+ var accountIdEnc = (0, import_substrate_bindings8.AccountId)().enc;
894
+ var queryInfoRawDec = (0, import_substrate_bindings8.Tuple)(import_substrate_bindings8.compact, import_substrate_bindings8.compact, import_substrate_bindings8.u8, import_substrate_bindings8.u128).dec;
895
+ var queryInfoDec = (input) => queryInfoRawDec(input)[3];
896
+ var fakeSignature = new Uint8Array(64);
897
+ var getFakeSignature = () => fakeSignature;
898
+ var createTxEntry = (pallet, name, assetChecksum, chainHead, broadcast, compatibilityHelper2) => {
899
+ const { isCompatible, compatibleRuntime$ } = compatibilityHelper2(
900
+ (ctx) => ctx.checksumBuilder.buildCall(pallet, name)
901
+ );
902
+ const checksumError = () => new Error(`Incompatible runtime entry Tx(${pallet}.${name})`);
903
+ const fn = (arg) => {
904
+ const getCallDataWithContext = ({ dynamicBuilder, asset: [assetEnc, assetCheck] }, arg2, txOptions = {}) => {
905
+ let returnOptions = txOptions;
906
+ if (txOptions.asset) {
907
+ if (assetChecksum !== assetCheck)
908
+ throw new Error(`Incompatible runtime asset`);
909
+ returnOptions = { ...txOptions, asset: assetEnc(txOptions.asset) };
910
+ }
911
+ const { location, codec } = dynamicBuilder.buildCall(pallet, name);
912
+ return {
913
+ callData: import_substrate_bindings8.Binary.fromBytes(
914
+ (0, import_utils19.mergeUint8)(new Uint8Array(location), codec.enc(arg2))
915
+ ),
916
+ options: returnOptions
917
+ };
918
+ };
919
+ const getCallData$ = (arg2, options = {}) => compatibleRuntime$(chainHead, null, checksumError).pipe(
920
+ (0, import_rxjs21.map)((ctx) => getCallDataWithContext(ctx, arg2, options))
921
+ );
922
+ const getEncodedData = (runtime) => {
923
+ if (!runtime)
924
+ return (0, import_rxjs21.firstValueFrom)(getCallData$(arg).pipe((0, import_rxjs21.map)((x) => x.callData)));
925
+ if (!isCompatible(runtime))
926
+ throw checksumError();
927
+ return getCallDataWithContext(runtime._getCtx(), arg).callData;
928
+ };
929
+ const sign$ = (from, { ..._options }, atBlock) => getCallData$(arg, _options).pipe(
930
+ (0, import_rxjs21.mergeMap)(
931
+ ({ callData, options }) => createTx(chainHead, from, callData.asBytes(), atBlock, options)
932
+ )
933
+ );
934
+ const _sign = (from, { at, ..._options } = {}) => {
935
+ return (!at || at === "finalized" ? chainHead.finalized$ : at === "best" ? chainHead.best$ : chainHead.bestBlocks$.pipe(
936
+ (0, import_rxjs21.map)((x) => x.find((b) => b.hash === at))
937
+ )).pipe(
938
+ (0, import_rxjs21.take)(1),
939
+ (0, import_rxjs21.mergeMap)(
940
+ (atBlock) => atBlock ? sign$(from, _options, atBlock).pipe(
941
+ (0, import_rxjs21.map)((signed) => ({
942
+ tx: (0, import_utils19.toHex)(signed),
943
+ block: atBlock
944
+ }))
945
+ ) : (0, import_rxjs21.throwError)(() => new Error(`Uknown block ${at}`))
946
+ )
947
+ );
948
+ };
949
+ const sign = (from, options) => (0, import_rxjs21.firstValueFrom)(_sign(from, options)).then((x) => x.tx);
950
+ const signAndSubmit = (from, _options) => (0, import_rxjs21.firstValueFrom)(_sign(from, _options)).then(
951
+ ({ tx, block }) => submit(chainHead, broadcast, tx, block.hash)
952
+ );
953
+ const signSubmitAndWatch = (from, _options) => _sign(from, _options).pipe(
954
+ (0, import_rxjs21.mergeMap)(
955
+ ({ tx, block }) => submit$(chainHead, broadcast, tx, block.hash, true)
956
+ )
957
+ );
958
+ const getEstimatedFees = async (from, _options) => {
959
+ const fakeSigner = (0, import_signer.getPolkadotSigner)(
960
+ from instanceof Uint8Array ? from : accountIdEnc(from),
961
+ "Sr25519",
962
+ getFakeSignature
963
+ );
964
+ const encoded = (0, import_utils19.fromHex)(await sign(fakeSigner, _options));
965
+ const args = (0, import_utils19.toHex)((0, import_utils19.mergeUint8)(encoded, import_substrate_bindings8.u32.enc(encoded.length)));
966
+ return (0, import_rxjs21.firstValueFrom)(
967
+ chainHead.call$(null, "TransactionPaymentApi_query_info", args).pipe((0, import_rxjs21.map)(queryInfoDec))
931
968
  );
969
+ };
970
+ return {
971
+ getEstimatedFees,
972
+ decodedCall: {
973
+ type: pallet,
974
+ value: (0, import_substrate_bindings8.Enum)(name, arg)
975
+ },
976
+ getEncodedData,
977
+ sign,
978
+ signSubmitAndWatch,
979
+ signAndSubmit
980
+ };
981
+ };
982
+ return Object.assign(fn, { isCompatible });
983
+ };
984
+
985
+ // src/client.ts
986
+ var createTypedApi = (chainDefinition, chainHead, broadcast$) => {
987
+ const runtime = getRuntimeApi(
988
+ chainDefinition.checksums,
989
+ chainDefinition.descriptors,
990
+ chainHead
991
+ );
992
+ const target = {};
993
+ const createProxy = (propCall) => new Proxy(target, {
994
+ get(_, prop) {
995
+ return propCall(prop);
932
996
  }
933
- }
997
+ });
998
+ const createProxyPath = (pathCall) => {
999
+ const cache = {};
1000
+ return createProxy((a) => {
1001
+ if (!cache[a])
1002
+ cache[a] = {};
1003
+ return createProxy((b) => {
1004
+ if (!cache[a][b])
1005
+ cache[a][b] = pathCall(a, b);
1006
+ return cache[a][b];
1007
+ });
1008
+ });
1009
+ };
1010
+ const query = createProxyPath(
1011
+ (pallet, name) => createStorageEntry(
1012
+ pallet,
1013
+ name,
1014
+ chainHead,
1015
+ compatibilityHelper(
1016
+ runtime,
1017
+ (r) => r._getPalletChecksum(0 /* Storage */, pallet, name)
1018
+ )
1019
+ )
1020
+ );
1021
+ const tx = createProxyPath(
1022
+ (pallet, name) => createTxEntry(
1023
+ pallet,
1024
+ name,
1025
+ chainDefinition.asset,
1026
+ chainHead,
1027
+ broadcast$,
1028
+ compatibilityHelper(
1029
+ runtime,
1030
+ (r) => r._getPalletChecksum(1 /* Tx */, pallet, name)
1031
+ )
1032
+ )
1033
+ );
1034
+ const event = createProxyPath(
1035
+ (pallet, name) => createEventEntry(
1036
+ pallet,
1037
+ name,
1038
+ chainHead,
1039
+ compatibilityHelper(
1040
+ runtime,
1041
+ (r) => r._getPalletChecksum(2 /* Event */, pallet, name)
1042
+ )
1043
+ )
1044
+ );
1045
+ const constants = createProxyPath(
1046
+ (pallet, name) => createConstantEntry(
1047
+ pallet,
1048
+ name,
1049
+ chainHead,
1050
+ compatibilityHelper(
1051
+ runtime,
1052
+ (r) => r._getPalletChecksum(4 /* Const */, pallet, name)
1053
+ )
1054
+ )
1055
+ );
1056
+ const apis = createProxyPath(
1057
+ (api, method) => createRuntimeCallEntry(
1058
+ api,
1059
+ method,
1060
+ chainHead,
1061
+ compatibilityHelper(runtime, (r) => r._getApiChecksum(api, method))
1062
+ )
1063
+ );
934
1064
  return {
935
1065
  query,
936
1066
  tx,
937
- event: events,
1067
+ event,
938
1068
  apis,
939
1069
  constants,
940
- runtime: runtimeApi
1070
+ runtime
941
1071
  };
942
1072
  };
943
1073
  function createClient(provider) {
944
1074
  const rawClient = (0, import_substrate_client.createClient)(provider);
945
1075
  const client = (0, import_observable_client2.getObservableClient)(rawClient);
946
1076
  const chainHead = client.chainHead$();
947
- const createTxFromSigner = getCreateTx(chainHead);
948
- const submitFns = getSubmitFns(chainHead, client);
949
- const { submit, submit$: submitAndWatch } = submitFns;
950
1077
  const { getChainSpecData } = rawClient;
1078
+ const _request = rawClient.request;
1079
+ const { broadcastTx$ } = client;
951
1080
  return {
952
1081
  getChainSpecData,
953
1082
  finalizedBlock$: chainHead.finalized$,
954
- getFinalizedBlock: () => (0, import_rxjs20.firstValueFrom)(chainHead.finalized$),
1083
+ getFinalizedBlock: () => (0, import_rxjs22.firstValueFrom)(chainHead.finalized$),
955
1084
  bestBlocks$: chainHead.bestBlocks$,
956
- getBestBlocks: () => (0, import_rxjs20.firstValueFrom)(chainHead.bestBlocks$),
1085
+ getBestBlocks: () => (0, import_rxjs22.firstValueFrom)(chainHead.bestBlocks$),
957
1086
  watchBlockBody: chainHead.body$,
958
- getBlockBody: (hash) => (0, import_rxjs20.firstValueFrom)(chainHead.body$(hash)),
959
- getBlockHeader: (hash) => (0, import_rxjs20.firstValueFrom)(chainHead.header$(hash ?? null)),
960
- submit,
961
- submitAndWatch,
962
- getTypedApi: (descriptors) => createTypedApi(descriptors, createTxFromSigner, chainHead, submitFns),
1087
+ getBlockBody: (hash) => (0, import_rxjs22.firstValueFrom)(chainHead.body$(hash)),
1088
+ getBlockHeader: (hash) => (0, import_rxjs22.firstValueFrom)(chainHead.header$(hash ?? null)),
1089
+ submit: (...args) => submit(chainHead, broadcastTx$, ...args),
1090
+ submitAndWatch: (...args) => submit$(chainHead, broadcastTx$, ...args),
1091
+ getTypedApi: (chainDefinition) => createTypedApi(chainDefinition, chainHead, broadcastTx$),
963
1092
  destroy: () => {
964
1093
  chainHead.unfollow();
965
1094
  client.destroy();
966
- }
1095
+ },
1096
+ _request
967
1097
  };
968
1098
  }
969
1099
 
970
1100
  // src/re-exports.ts
971
- var import_substrate_bindings8 = require("@polkadot-api/substrate-bindings");
1101
+ var import_substrate_bindings9 = require("@polkadot-api/substrate-bindings");
972
1102
  //# sourceMappingURL=index.js.map