@argonprotocol/mainchain 1.3.12 → 1.3.14

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/browser/index.js CHANGED
@@ -20,8 +20,15 @@ export { GenericAddress, GenericBlock, GenericEvent } from '@polkadot/types/gene
20
20
  export { BTreeMap, Bool, Bytes, Compact, Enum, Null, Option, Range, Result, Struct, Text, Tuple, U256, U8aFixed, Vec, bool, i128, u128, u16, u32, u64, u8 } from '@polkadot/types-codec';
21
21
 
22
22
  var __defProp = Object.defineProperty;
23
+ var __typeError = (msg) => {
24
+ throw TypeError(msg);
25
+ };
23
26
  var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
24
27
  var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
28
+ var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg);
29
+ var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
30
+ var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
31
+ var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), member.set(obj, value), value);
25
32
 
26
33
  // src/WageProtector.ts
27
34
  var WageProtector = class _WageProtector {
@@ -77,163 +84,6 @@ var WageProtector = class _WageProtector {
77
84
  });
78
85
  }
79
86
  };
80
-
81
- // src/TxSubmitter.ts
82
- function logExtrinsicResult(result) {
83
- const json = result.status.toJSON();
84
- const status = Object.keys(json)[0];
85
- console.debug('Transaction update: "%s"', status, json[status]);
86
- }
87
- var TxSubmitter = class {
88
- constructor(client, tx, pair) {
89
- this.client = client;
90
- this.tx = tx;
91
- this.pair = pair;
92
- }
93
- async feeEstimate(tip) {
94
- const { partialFee } = await this.tx.paymentInfo(this.pair, { tip });
95
- return partialFee.toBigInt();
96
- }
97
- async canAfford(options = {}) {
98
- const { tip, unavailableBalance } = options;
99
- const account = await this.client.query.system.account(this.pair.address);
100
- let availableBalance = account.data.free.toBigInt();
101
- const userBalance = availableBalance;
102
- if (unavailableBalance) {
103
- availableBalance -= unavailableBalance;
104
- }
105
- const existentialDeposit = options.includeExistentialDeposit ? this.client.consts.balances.existentialDeposit.toBigInt() : 0n;
106
- const fees = await this.feeEstimate(tip);
107
- const totalCharge = fees + (tip ?? 0n);
108
- const canAfford = availableBalance >= totalCharge + existentialDeposit;
109
- return { canAfford, availableBalance: userBalance, txFee: fees };
110
- }
111
- async submit(options = {}) {
112
- const { logResults, waitForBlock, useLatestNonce, ...apiOptions } = options;
113
- await waitForLoad();
114
- const result = new TxResult(this.client, logResults);
115
- result.txProgressCallback = options.txProgressCallback;
116
- let toHuman = this.tx.toHuman().method;
117
- const txString = [];
118
- let api = formatCall(toHuman);
119
- const args = [];
120
- if (api === "proxy.proxy") {
121
- toHuman = toHuman.args.call;
122
- txString.push("Proxy");
123
- api = formatCall(toHuman);
124
- }
125
- if (api.startsWith("utility.batch")) {
126
- const calls = toHuman.args.calls.map(formatCall).join(", ");
127
- txString.push(`Batch[${calls}]`);
128
- } else {
129
- txString.push(api);
130
- args.push(toHuman.args);
131
- }
132
- args.unshift(txString.join("->"));
133
- if (useLatestNonce && !apiOptions.nonce) {
134
- apiOptions.nonce = await this.client.rpc.system.accountNextIndex(this.pair.address);
135
- }
136
- console.log("Submitting transaction from %s:", this.pair.address, ...args);
137
- await this.tx.signAndSend(this.pair, apiOptions, result.onResult.bind(result));
138
- if (waitForBlock) {
139
- await result.inBlockPromise;
140
- }
141
- return result;
142
- }
143
- };
144
- function formatCall(call) {
145
- return `${call.section}.${call.method}`;
146
- }
147
- var TxResult = class {
148
- constructor(client, shouldLog = false) {
149
- this.client = client;
150
- this.shouldLog = shouldLog;
151
- __publicField(this, "inBlockPromise");
152
- __publicField(this, "finalizedPromise");
153
- __publicField(this, "status");
154
- __publicField(this, "events", []);
155
- /**
156
- * The index of the batch that was interrupted, if any.
157
- */
158
- __publicField(this, "batchInterruptedIndex");
159
- __publicField(this, "includedInBlock");
160
- /**
161
- * The final fee paid for the transaction, including the fee tip.
162
- */
163
- __publicField(this, "finalFee");
164
- /**
165
- * The fee tip paid for the transaction.
166
- */
167
- __publicField(this, "finalFeeTip");
168
- __publicField(this, "txProgressCallback");
169
- __publicField(this, "inBlockResolve");
170
- __publicField(this, "inBlockReject");
171
- __publicField(this, "finalizedResolve");
172
- __publicField(this, "finalizedReject");
173
- this.inBlockPromise = new Promise((resolve, reject) => {
174
- this.inBlockResolve = resolve;
175
- this.inBlockReject = reject;
176
- });
177
- this.finalizedPromise = new Promise((resolve, reject) => {
178
- this.finalizedResolve = resolve;
179
- this.finalizedReject = reject;
180
- });
181
- this.inBlockPromise.catch(() => null);
182
- this.finalizedPromise.catch(() => null);
183
- }
184
- onResult(result) {
185
- this.status = result.status;
186
- if (this.shouldLog) {
187
- logExtrinsicResult(result);
188
- }
189
- const { events, status, dispatchError, isFinalized } = result;
190
- if (status.isInBlock) {
191
- this.includedInBlock = new Uint8Array(status.asInBlock);
192
- let encounteredError = dispatchError;
193
- let batchErrorIndex;
194
- for (const event of events) {
195
- this.events.push(event.event);
196
- if (this.client.events.utility.BatchInterrupted.is(event.event)) {
197
- batchErrorIndex = event.event.data[0].toNumber();
198
- this.batchInterruptedIndex = batchErrorIndex;
199
- encounteredError = event.event.data[1];
200
- }
201
- if (this.client.events.transactionPayment.TransactionFeePaid.is(event.event)) {
202
- const [_who, actualFee, tip] = event.event.data;
203
- this.finalFee = actualFee.toBigInt();
204
- this.finalFeeTip = tip.toBigInt();
205
- }
206
- }
207
- if (encounteredError) {
208
- const error = dispatchErrorToExtrinsicError(
209
- this.client,
210
- encounteredError,
211
- batchErrorIndex,
212
- this.finalFee
213
- );
214
- this.reject(error);
215
- } else {
216
- this.inBlockResolve(new Uint8Array(status.asInBlock));
217
- }
218
- }
219
- if (isFinalized) {
220
- this.finalizedResolve(status.asFinalized);
221
- }
222
- if (this.txProgressCallback) {
223
- let percent = 0;
224
- if (result.status.isBroadcast) {
225
- percent = 50;
226
- } else if (result.status.isInBlock) {
227
- percent = 100;
228
- }
229
- this.txProgressCallback(percent, this);
230
- }
231
- }
232
- reject(error) {
233
- this.inBlockReject(error);
234
- this.finalizedReject(error);
235
- }
236
- };
237
87
  var { ROUND_FLOOR } = BigNumber2;
238
88
  var MICROGONS_PER_ARGON = 1e6;
239
89
  function formatArgons(microgons) {
@@ -279,7 +129,7 @@ function dispatchErrorToString(client, error) {
279
129
  }
280
130
  return message;
281
131
  }
282
- var ExtrinsicError2 = class extends Error {
132
+ var ExtrinsicError = class extends Error {
283
133
  constructor(errorCode, details, batchInterruptedIndex, txFee = 0n) {
284
134
  super(errorCode);
285
135
  this.errorCode = errorCode;
@@ -298,9 +148,9 @@ function dispatchErrorToExtrinsicError(client, error, batchInterruptedIndex, txF
298
148
  if (error.isModule) {
299
149
  const decoded = client.registry.findMetaError(error.asModule);
300
150
  const { docs, name, section } = decoded;
301
- return new ExtrinsicError2(`${section}.${name}`, docs.join(" "), batchInterruptedIndex, txFee);
151
+ return new ExtrinsicError(`${section}.${name}`, docs.join(" "), batchInterruptedIndex, txFee);
302
152
  }
303
- return new ExtrinsicError2(error.toString(), void 0, batchInterruptedIndex, txFee);
153
+ return new ExtrinsicError(error.toString(), void 0, batchInterruptedIndex, txFee);
304
154
  }
305
155
  function checkForExtrinsicSuccess(events, client) {
306
156
  return new Promise((resolve, reject) => {
@@ -320,6 +170,246 @@ function checkForExtrinsicSuccess(events, client) {
320
170
  });
321
171
  }
322
172
 
173
+ // src/TxResult.ts
174
+ var _isBroadcast, _submissionError;
175
+ var TxResult = class {
176
+ constructor(client, extrinsic) {
177
+ this.client = client;
178
+ this.extrinsic = extrinsic;
179
+ __privateAdd(this, _isBroadcast, false);
180
+ __privateAdd(this, _submissionError);
181
+ __publicField(this, "waitForFinalizedBlock");
182
+ __publicField(this, "waitForInFirstBlock");
183
+ __publicField(this, "events", []);
184
+ __publicField(this, "extrinsicError");
185
+ __publicField(this, "extrinsicIndex");
186
+ __publicField(this, "txProgressCallback");
187
+ /**
188
+ * The index of the batch that was interrupted, if any.
189
+ */
190
+ __publicField(this, "batchInterruptedIndex");
191
+ __publicField(this, "blockHash");
192
+ __publicField(this, "blockNumber");
193
+ /**
194
+ * The final fee paid for the transaction, including the fee tip.
195
+ */
196
+ __publicField(this, "finalFee");
197
+ /**
198
+ * The fee tip paid for the transaction.
199
+ */
200
+ __publicField(this, "finalFeeTip");
201
+ __publicField(this, "txProgress", 0);
202
+ __publicField(this, "isFinalized", false);
203
+ __publicField(this, "finalizedResolve");
204
+ __publicField(this, "finalizedReject");
205
+ __publicField(this, "inBlockResolve");
206
+ __publicField(this, "inBlockReject");
207
+ this.waitForFinalizedBlock = new Promise((resolve, reject) => {
208
+ this.finalizedResolve = resolve;
209
+ this.finalizedReject = reject;
210
+ });
211
+ this.waitForInFirstBlock = new Promise((resolve, reject) => {
212
+ this.inBlockResolve = resolve;
213
+ this.inBlockReject = reject;
214
+ });
215
+ this.waitForFinalizedBlock.catch(() => null);
216
+ this.waitForInFirstBlock.catch(() => null);
217
+ }
218
+ set isBroadcast(value) {
219
+ __privateSet(this, _isBroadcast, value);
220
+ this.updateProgress();
221
+ }
222
+ get isBroadcast() {
223
+ return __privateGet(this, _isBroadcast);
224
+ }
225
+ set submissionError(value) {
226
+ if (value) {
227
+ __privateSet(this, _submissionError, value);
228
+ this.finalizedReject(value);
229
+ this.inBlockReject(value);
230
+ this.updateProgress();
231
+ }
232
+ }
233
+ get submissionError() {
234
+ return __privateGet(this, _submissionError);
235
+ }
236
+ async setSeenInBlock(block) {
237
+ const { blockHash, blockNumber, events } = block;
238
+ if (blockHash !== this.blockHash) {
239
+ this.parseEvents(events);
240
+ this.blockHash = blockHash;
241
+ this.blockNumber = blockNumber ?? await this.client.rpc.chain.getHeader(blockHash).then((h) => h.number.toNumber());
242
+ this.extrinsicIndex = block.extrinsicIndex;
243
+ this.updateProgress();
244
+ if (this.extrinsicError) {
245
+ this.inBlockReject(this.extrinsicError);
246
+ } else {
247
+ this.inBlockResolve(blockHash);
248
+ }
249
+ }
250
+ }
251
+ setFinalized() {
252
+ this.isFinalized = true;
253
+ this.updateProgress();
254
+ let error = this.extrinsicError ?? this.submissionError;
255
+ if (!error && !this.blockHash) {
256
+ error = new Error("Cannot finalize transaction before it is included in a block");
257
+ }
258
+ if (error) {
259
+ this.finalizedReject(error);
260
+ this.inBlockReject(error);
261
+ } else {
262
+ this.finalizedResolve(this.blockHash);
263
+ this.inBlockResolve(this.blockHash);
264
+ }
265
+ }
266
+ onSubscriptionResult(result) {
267
+ const { events, status, isFinalized, txIndex } = result;
268
+ const extrinsicEvents = events.map((x) => x.event);
269
+ if (status.isBroadcast) {
270
+ this.isBroadcast = true;
271
+ if (result.internalError) this.submissionError = result.internalError;
272
+ }
273
+ if (status.isInBlock) {
274
+ void this.setSeenInBlock({
275
+ blockHash: Uint8Array.from(status.asInBlock),
276
+ events: extrinsicEvents,
277
+ extrinsicIndex: txIndex
278
+ });
279
+ }
280
+ if (isFinalized) {
281
+ this.setFinalized();
282
+ }
283
+ }
284
+ updateProgress() {
285
+ if (this.isFinalized || this.submissionError) {
286
+ this.txProgress = 100;
287
+ } else if (this.blockNumber) {
288
+ const elapsedBlocks = this.blockNumber - this.extrinsic.submittedAtBlockNumber;
289
+ const FINALIZATION_BLOCKS = 5;
290
+ const remainingPercent = Math.max(0, FINALIZATION_BLOCKS - elapsedBlocks) * 20;
291
+ const percent = 100 - remainingPercent;
292
+ this.txProgress = Math.min(percent, 99);
293
+ } else if (this.extrinsic.submittedAtBlockNumber) {
294
+ this.txProgress = 10;
295
+ }
296
+ this.txProgressCallback?.(this.txProgress);
297
+ }
298
+ parseEvents(events) {
299
+ let encounteredError;
300
+ for (const event of events) {
301
+ if (this.client.events.system.ExtrinsicFailed.is(event)) {
302
+ const { dispatchError } = event.data;
303
+ encounteredError ?? (encounteredError = dispatchError);
304
+ }
305
+ if (this.client.events.utility.BatchInterrupted.is(event)) {
306
+ const { index, error } = event.data;
307
+ this.batchInterruptedIndex = index.toNumber();
308
+ encounteredError = error;
309
+ }
310
+ if (this.client.events.transactionPayment.TransactionFeePaid.is(event)) {
311
+ const { actualFee, tip } = event.data;
312
+ this.finalFee = actualFee.toBigInt();
313
+ this.finalFeeTip = tip.toBigInt();
314
+ }
315
+ }
316
+ if (encounteredError) {
317
+ this.extrinsicError = dispatchErrorToExtrinsicError(
318
+ this.client,
319
+ encounteredError,
320
+ this.batchInterruptedIndex,
321
+ this.finalFee
322
+ );
323
+ } else {
324
+ this.extrinsicError = void 0;
325
+ }
326
+ this.events = events;
327
+ }
328
+ };
329
+ _isBroadcast = new WeakMap();
330
+ _submissionError = new WeakMap();
331
+
332
+ // src/TxSubmitter.ts
333
+ var TxSubmitter = class {
334
+ constructor(client, tx, pair) {
335
+ this.client = client;
336
+ this.tx = tx;
337
+ this.pair = pair;
338
+ }
339
+ async feeEstimate(tip) {
340
+ const { partialFee } = await this.tx.paymentInfo(this.pair, { tip });
341
+ return partialFee.toBigInt();
342
+ }
343
+ async canAfford(options = {}) {
344
+ const { tip, unavailableBalance } = options;
345
+ const account = await this.client.query.system.account(this.pair.address);
346
+ let availableBalance = account.data.free.toBigInt();
347
+ const userBalance = availableBalance;
348
+ if (unavailableBalance) {
349
+ availableBalance -= unavailableBalance;
350
+ }
351
+ const existentialDeposit = options.includeExistentialDeposit ? this.client.consts.balances.existentialDeposit.toBigInt() : 0n;
352
+ const fees = await this.feeEstimate(tip);
353
+ const totalCharge = fees + (tip ?? 0n);
354
+ const canAfford = availableBalance >= totalCharge + existentialDeposit;
355
+ return { canAfford, availableBalance: userBalance, txFee: fees };
356
+ }
357
+ async submit(options = {}) {
358
+ const { useLatestNonce, ...apiOptions } = options;
359
+ await waitForLoad();
360
+ const blockHeight = await this.client.rpc.chain.getHeader().then((h) => h.number.toNumber());
361
+ if (options.logResults) {
362
+ this.logRequest();
363
+ }
364
+ if (useLatestNonce && !apiOptions.nonce) {
365
+ apiOptions.nonce = await this.client.rpc.system.accountNextIndex(this.pair.address);
366
+ }
367
+ const signedTx = await this.tx.signAsync(this.pair, apiOptions);
368
+ const txHash = signedTx.hash.toHex();
369
+ const result = new TxResult(this.client, {
370
+ signedHash: txHash,
371
+ method: signedTx.method.toHuman(),
372
+ accountAddress: this.pair.address,
373
+ submittedTime: /* @__PURE__ */ new Date(),
374
+ submittedAtBlockNumber: blockHeight
375
+ });
376
+ if (options.disableAutomaticTxTracking !== true) {
377
+ await signedTx.send(result.onSubscriptionResult.bind(result));
378
+ } else {
379
+ try {
380
+ await signedTx.send();
381
+ result.isBroadcast = true;
382
+ } catch (error) {
383
+ result.submissionError = error;
384
+ }
385
+ }
386
+ return result;
387
+ }
388
+ logRequest() {
389
+ let toHuman = this.tx.toHuman().method;
390
+ const txString = [];
391
+ let api = formatCall(toHuman);
392
+ const args = [];
393
+ if (api === "proxy.proxy") {
394
+ toHuman = toHuman.args.call;
395
+ txString.push("Proxy");
396
+ api = formatCall(toHuman);
397
+ }
398
+ if (api.startsWith("utility.batch")) {
399
+ const calls = toHuman.args.calls.map(formatCall).join(", ");
400
+ txString.push(`Batch[${calls}]`);
401
+ } else {
402
+ txString.push(api);
403
+ args.push(toHuman.args);
404
+ }
405
+ args.unshift(txString.join("->"));
406
+ console.log("Submitting transaction from %s:", this.pair.address, ...args);
407
+ }
408
+ };
409
+ function formatCall(call) {
410
+ return `${call.section}.${call.method}`;
411
+ }
412
+
323
413
  // src/keyringUtils.ts
324
414
  function keyringFromSuri(suri, cryptoType = "sr25519") {
325
415
  return new Keyring({ type: cryptoType }).createFromUri(suri);
@@ -512,29 +602,29 @@ var Vault = class _Vault {
512
602
  );
513
603
  }
514
604
  const result = await tx.submit({
515
- tip,
516
- useLatestNonce: true,
517
- waitForBlock: true,
518
- txProgressCallback
605
+ ...args,
606
+ useLatestNonce: true
519
607
  });
520
- await result.inBlockPromise;
521
- let vaultId;
522
- for (const event of result.events) {
523
- if (client.events.vaults.VaultCreated.is(event)) {
524
- vaultId = event.data.vaultId.toNumber();
525
- break;
608
+ const tickDuration = config.tickDurationMillis ?? await client.query.ticks.genesisTicker().then((x) => x.tickDurationMillis.toNumber());
609
+ async function getVault() {
610
+ await result.waitForFinalizedBlock;
611
+ let vaultId;
612
+ for (const event of result.events) {
613
+ if (client.events.vaults.VaultCreated.is(event)) {
614
+ vaultId = event.data.vaultId.toNumber();
615
+ break;
616
+ }
526
617
  }
618
+ if (vaultId === void 0) {
619
+ throw new Error("Vault creation failed, no VaultCreated event found");
620
+ }
621
+ const rawVault = await client.query.vaults.vaultsById(vaultId);
622
+ if (rawVault.isNone) {
623
+ throw new Error("Vault creation failed, vault not found");
624
+ }
625
+ return new _Vault(vaultId, rawVault.unwrap(), tickDuration);
527
626
  }
528
- if (vaultId === void 0) {
529
- throw new Error("Vault creation failed, no VaultCreated event found");
530
- }
531
- const rawVault = await client.query.vaults.vaultsById(vaultId);
532
- if (rawVault.isNone) {
533
- throw new Error("Vault creation failed, vault not found");
534
- }
535
- const tickDuration = config.tickDurationMillis ?? await client.query.ticks.genesisTicker().then((x) => x.tickDurationMillis.toNumber());
536
- const vault = new _Vault(vaultId, rawVault.unwrap(), tickDuration);
537
- return { vault, txResult: result };
627
+ return { getVault, txResult: result };
538
628
  }
539
629
  };
540
630
  function toFixedNumber(value, decimals) {
@@ -667,7 +757,7 @@ var BitcoinLocks = class {
667
757
  const signature = u8aToHex(vaultSignature);
668
758
  const tx = client.tx.bitcoinLocks.cosignRelease(utxoId, signature);
669
759
  const submitter = new TxSubmitter(client, tx, argonKeyring);
670
- return await submitter.submit({ txProgressCallback });
760
+ return await submitter.submit(args);
671
761
  }
672
762
  async getBitcoinLock(utxoId) {
673
763
  const utxoRaw = await this.client.query.bitcoinLocks.locksByUtxoId(utxoId);
@@ -836,9 +926,8 @@ var BitcoinLocks = class {
836
926
  return { tx, securityFee, txFee, canAfford, availableBalance, txFeePlusTip: txFee + tip };
837
927
  }
838
928
  async getBitcoinLockFromTxResult(txResult) {
839
- const client = this.client;
840
- const blockHash = await txResult.inBlockPromise;
841
- const blockHeight = await client.at(blockHash).then((x) => x.query.system.number()).then((x) => x.toNumber());
929
+ await txResult.waitForFinalizedBlock;
930
+ const blockHeight = txResult.blockNumber;
842
931
  const utxoId = await this.getUtxoIdFromEvents(txResult.events) ?? 0;
843
932
  if (utxoId === 0) {
844
933
  throw new Error("Bitcoin lock creation failed, no UTXO ID found in transaction events");
@@ -850,7 +939,7 @@ var BitcoinLocks = class {
850
939
  return { lock, createdAtHeight: blockHeight, txResult };
851
940
  }
852
941
  async initializeLock(args) {
853
- const { argonKeyring, tip = 0n, txProgressCallback } = args;
942
+ const { argonKeyring } = args;
854
943
  const client = this.client;
855
944
  const { tx, securityFee, canAfford, txFeePlusTip } = await this.createInitializeLockTx(args);
856
945
  if (!canAfford) {
@@ -859,16 +948,9 @@ var BitcoinLocks = class {
859
948
  );
860
949
  }
861
950
  const submitter = new TxSubmitter(client, tx, argonKeyring);
862
- const txResult = await submitter.submit({
863
- waitForBlock: true,
864
- logResults: true,
865
- tip,
866
- txProgressCallback
867
- });
868
- const { lock, createdAtHeight } = await this.getBitcoinLockFromTxResult(txResult);
951
+ const txResult = await submitter.submit({ logResults: true, ...args });
869
952
  return {
870
- lock,
871
- createdAtHeight,
953
+ getLock: () => this.getBitcoinLockFromTxResult(txResult),
872
954
  txResult,
873
955
  securityFee
874
956
  };
@@ -884,8 +966,7 @@ var BitcoinLocks = class {
884
966
  priceIndex,
885
967
  releaseRequest: { bitcoinNetworkFee, toScriptPubkey },
886
968
  argonKeyring,
887
- tip = 0n,
888
- txProgressCallback
969
+ tip = 0n
889
970
  } = args;
890
971
  if (!toScriptPubkey.startsWith("0x")) {
891
972
  throw new Error("toScriptPubkey must be a hex string starting with 0x");
@@ -905,18 +986,10 @@ var BitcoinLocks = class {
905
986
  `Insufficient funds to release lock. Available: ${formatArgons(canAfford.availableBalance)}, Required: ${formatArgons(redemptionPrice + canAfford.txFee + tip)}`
906
987
  );
907
988
  }
908
- const txResult = await submitter.submit({
909
- waitForBlock: true,
989
+ return submitter.submit({
910
990
  logResults: true,
911
- tip,
912
- txProgressCallback
991
+ ...args
913
992
  });
914
- const blockHash = await txResult.inBlockPromise;
915
- const blockHeight = await client.at(blockHash).then((x) => x.query.system.number()).then((x) => x.toNumber());
916
- return {
917
- blockHash,
918
- blockHeight
919
- };
920
993
  }
921
994
  async releasePrice(priceIndex, lock) {
922
995
  return await this.getRedemptionRate(priceIndex, lock);
@@ -963,41 +1036,43 @@ var BitcoinLocks = class {
963
1036
  )}`
964
1037
  );
965
1038
  }
966
- const submission = await txSubmitter.submit({
967
- waitForBlock: true,
968
- tip,
969
- txProgressCallback
970
- });
971
- const ratchetEvent = submission.events.find(
972
- (x) => client.events.bitcoinLocks.BitcoinLockRatcheted.is(x)
973
- );
974
- if (!ratchetEvent) {
975
- throw new Error(`Ratchet event not found in transaction events`);
976
- }
977
- const blockHash = await submission.inBlockPromise;
978
- const api = await client.at(blockHash);
979
- const blockHeight = await api.query.system.number().then((x) => x.toNumber());
980
- const bitcoinBlockHeight = await api.query.bitcoinUtxos.confirmedBitcoinBlockTip().then((x) => x.unwrap().blockHeight.toNumber());
981
- const {
982
- amountBurned,
983
- liquidityPromised: liquidityPromisedRaw,
984
- newPeggedPrice,
985
- originalPeggedPrice
986
- } = ratchetEvent.data;
987
- const liquidityPromised = liquidityPromisedRaw.toBigInt();
988
- let mintAmount = liquidityPromised;
989
- if (liquidityPromised > originalPeggedPrice.toBigInt()) {
990
- mintAmount -= originalPeggedPrice.toBigInt();
991
- }
1039
+ const txResult = await txSubmitter.submit(args);
1040
+ const getRatchetResult = async () => {
1041
+ const blockHash = await txResult.waitForFinalizedBlock;
1042
+ const ratchetEvent = txResult.events.find(
1043
+ (x) => client.events.bitcoinLocks.BitcoinLockRatcheted.is(x)
1044
+ );
1045
+ if (!ratchetEvent) {
1046
+ throw new Error(`Ratchet event not found in transaction events`);
1047
+ }
1048
+ const api = await client.at(blockHash);
1049
+ const bitcoinBlockHeight = await api.query.bitcoinUtxos.confirmedBitcoinBlockTip().then((x) => x.unwrap().blockHeight.toNumber());
1050
+ const {
1051
+ amountBurned,
1052
+ liquidityPromised: liquidityPromisedRaw,
1053
+ newPeggedPrice,
1054
+ originalPeggedPrice,
1055
+ securityFee
1056
+ } = ratchetEvent.data;
1057
+ const liquidityPromised = liquidityPromisedRaw.toBigInt();
1058
+ let mintAmount = liquidityPromised;
1059
+ if (liquidityPromised > originalPeggedPrice.toBigInt()) {
1060
+ mintAmount -= originalPeggedPrice.toBigInt();
1061
+ }
1062
+ return {
1063
+ txFee: txResult.finalFee ?? 0n,
1064
+ blockHeight: txResult.blockNumber,
1065
+ bitcoinBlockHeight,
1066
+ pendingMint: mintAmount,
1067
+ liquidityPromised,
1068
+ newPeggedPrice: newPeggedPrice.toBigInt(),
1069
+ burned: amountBurned.toBigInt(),
1070
+ securityFee: securityFee.toBigInt()
1071
+ };
1072
+ };
992
1073
  return {
993
- txFee: submission.finalFee ?? 0n,
994
- securityFee: ratchetPrice.ratchetingFee,
995
- pendingMint: mintAmount,
996
- liquidityPromised,
997
- newPeggedPrice: newPeggedPrice.toBigInt(),
998
- burned: amountBurned.toBigInt(),
999
- blockHeight,
1000
- bitcoinBlockHeight
1074
+ txResult,
1075
+ getRatchetResult
1001
1076
  };
1002
1077
  }
1003
1078
  };
@@ -1071,6 +1146,6 @@ async function getClient(host, options) {
1071
1146
  return await ApiPromise.create({ provider, noInitWarn: true, ...options ?? {} });
1072
1147
  }
1073
1148
 
1074
- export { BitcoinLocks, ExtrinsicError2 as ExtrinsicError, FIXED_U128_DECIMALS, MICROGONS_PER_ARGON, PERMILL_DECIMALS, PriceIndex, SATS_PER_BTC, TxResult, TxSubmitter, Vault, WageProtector, checkForExtrinsicSuccess, createKeyringPair, dispatchErrorToExtrinsicError, dispatchErrorToString, formatArgons, fromFixedNumber, getAuthorFromHeader, getClient, getTickFromHeader, gettersToObject, keyringFromSuri, toFixedNumber, waitForLoad };
1149
+ export { BitcoinLocks, ExtrinsicError, FIXED_U128_DECIMALS, MICROGONS_PER_ARGON, PERMILL_DECIMALS, PriceIndex, SATS_PER_BTC, TxResult, TxSubmitter, Vault, WageProtector, checkForExtrinsicSuccess, createKeyringPair, dispatchErrorToExtrinsicError, dispatchErrorToString, formatArgons, fromFixedNumber, getAuthorFromHeader, getClient, getTickFromHeader, gettersToObject, keyringFromSuri, toFixedNumber, waitForLoad };
1075
1150
  //# sourceMappingURL=index.js.map
1076
1151
  //# sourceMappingURL=index.js.map