@argonprotocol/mainchain 1.3.11 → 1.3.13

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,158 +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(this.client, encounteredError, batchErrorIndex);
209
- this.reject(error);
210
- } else {
211
- this.inBlockResolve(new Uint8Array(status.asInBlock));
212
- }
213
- }
214
- if (isFinalized) {
215
- this.finalizedResolve(status.asFinalized);
216
- }
217
- if (this.txProgressCallback) {
218
- let percent = 0;
219
- if (result.status.isBroadcast) {
220
- percent = 50;
221
- } else if (result.status.isInBlock) {
222
- percent = 100;
223
- }
224
- this.txProgressCallback(percent, this);
225
- }
226
- }
227
- reject(error) {
228
- this.inBlockReject(error);
229
- this.finalizedReject(error);
230
- }
231
- };
232
87
  var { ROUND_FLOOR } = BigNumber2;
233
88
  var MICROGONS_PER_ARGON = 1e6;
234
89
  function formatArgons(microgons) {
@@ -274,12 +129,13 @@ function dispatchErrorToString(client, error) {
274
129
  }
275
130
  return message;
276
131
  }
277
- var ExtrinsicError2 = class extends Error {
278
- constructor(errorCode, details, batchInterruptedIndex) {
132
+ var ExtrinsicError = class extends Error {
133
+ constructor(errorCode, details, batchInterruptedIndex, txFee = 0n) {
279
134
  super(errorCode);
280
135
  this.errorCode = errorCode;
281
136
  this.details = details;
282
137
  this.batchInterruptedIndex = batchInterruptedIndex;
138
+ this.txFee = txFee;
283
139
  }
284
140
  toString() {
285
141
  if (this.batchInterruptedIndex !== void 0) {
@@ -288,13 +144,13 @@ var ExtrinsicError2 = class extends Error {
288
144
  return `${this.errorCode} ${this.details ?? ""}`;
289
145
  }
290
146
  };
291
- function dispatchErrorToExtrinsicError(client, error, batchInterruptedIndex) {
147
+ function dispatchErrorToExtrinsicError(client, error, batchInterruptedIndex, txFee) {
292
148
  if (error.isModule) {
293
149
  const decoded = client.registry.findMetaError(error.asModule);
294
150
  const { docs, name, section } = decoded;
295
- return new ExtrinsicError2(`${section}.${name}`, docs.join(" "), batchInterruptedIndex);
151
+ return new ExtrinsicError(`${section}.${name}`, docs.join(" "), batchInterruptedIndex, txFee);
296
152
  }
297
- return new ExtrinsicError2(error.toString(), void 0, batchInterruptedIndex);
153
+ return new ExtrinsicError(error.toString(), void 0, batchInterruptedIndex, txFee);
298
154
  }
299
155
  function checkForExtrinsicSuccess(events, client) {
300
156
  return new Promise((resolve, reject) => {
@@ -314,6 +170,246 @@ function checkForExtrinsicSuccess(events, client) {
314
170
  });
315
171
  }
316
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
+
317
413
  // src/keyringUtils.ts
318
414
  function keyringFromSuri(suri, cryptoType = "sr25519") {
319
415
  return new Keyring({ type: cryptoType }).createFromUri(suri);
@@ -506,29 +602,29 @@ var Vault = class _Vault {
506
602
  );
507
603
  }
508
604
  const result = await tx.submit({
509
- tip,
510
- useLatestNonce: true,
511
- waitForBlock: true,
512
- txProgressCallback
605
+ ...args,
606
+ useLatestNonce: true
513
607
  });
514
- await result.inBlockPromise;
515
- let vaultId;
516
- for (const event of result.events) {
517
- if (client.events.vaults.VaultCreated.is(event)) {
518
- vaultId = event.data.vaultId.toNumber();
519
- 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
+ }
520
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);
521
626
  }
522
- if (vaultId === void 0) {
523
- throw new Error("Vault creation failed, no VaultCreated event found");
524
- }
525
- const rawVault = await client.query.vaults.vaultsById(vaultId);
526
- if (rawVault.isNone) {
527
- throw new Error("Vault creation failed, vault not found");
528
- }
529
- const tickDuration = config.tickDurationMillis ?? await client.query.ticks.genesisTicker().then((x) => x.tickDurationMillis.toNumber());
530
- const vault = new _Vault(vaultId, rawVault.unwrap(), tickDuration);
531
- return { vault, txResult: result };
627
+ return { getVault, txResult: result };
532
628
  }
533
629
  };
534
630
  function toFixedNumber(value, decimals) {
@@ -661,7 +757,7 @@ var BitcoinLocks = class {
661
757
  const signature = u8aToHex(vaultSignature);
662
758
  const tx = client.tx.bitcoinLocks.cosignRelease(utxoId, signature);
663
759
  const submitter = new TxSubmitter(client, tx, argonKeyring);
664
- return await submitter.submit({ txProgressCallback });
760
+ return await submitter.submit(args);
665
761
  }
666
762
  async getBitcoinLock(utxoId) {
667
763
  const utxoRaw = await this.client.query.bitcoinLocks.locksByUtxoId(utxoId);
@@ -827,17 +923,11 @@ var BitcoinLocks = class {
827
923
  unavailableBalance: securityFee + (args.reducedBalanceBy ?? 0n),
828
924
  includeExistentialDeposit: true
829
925
  });
830
- if (!canAfford) {
831
- throw new Error(
832
- `Insufficient funds to initialize lock. Available: ${formatArgons(availableBalance)}, Required: ${satoshis}`
833
- );
834
- }
835
- return { tx, securityFee, txFee };
926
+ return { tx, securityFee, txFee, canAfford, availableBalance, txFeePlusTip: txFee + tip };
836
927
  }
837
928
  async getBitcoinLockFromTxResult(txResult) {
838
- const client = this.client;
839
- const blockHash = await txResult.inBlockPromise;
840
- 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;
841
931
  const utxoId = await this.getUtxoIdFromEvents(txResult.events) ?? 0;
842
932
  if (utxoId === 0) {
843
933
  throw new Error("Bitcoin lock creation failed, no UTXO ID found in transaction events");
@@ -849,20 +939,18 @@ var BitcoinLocks = class {
849
939
  return { lock, createdAtHeight: blockHeight, txResult };
850
940
  }
851
941
  async initializeLock(args) {
852
- const { argonKeyring, tip = 0n, txProgressCallback } = args;
942
+ const { argonKeyring } = args;
853
943
  const client = this.client;
854
- const { tx, securityFee } = await this.createInitializeLockTx(args);
944
+ const { tx, securityFee, canAfford, txFeePlusTip } = await this.createInitializeLockTx(args);
945
+ if (!canAfford) {
946
+ throw new Error(
947
+ `Insufficient funds to initialize bitcoin lock. Required security fee: ${formatArgons(securityFee)}, Tx fee plus tip: ${formatArgons(txFeePlusTip)}`
948
+ );
949
+ }
855
950
  const submitter = new TxSubmitter(client, tx, argonKeyring);
856
- const txResult = await submitter.submit({
857
- waitForBlock: true,
858
- logResults: true,
859
- tip,
860
- txProgressCallback
861
- });
862
- const { lock, createdAtHeight } = await this.getBitcoinLockFromTxResult(txResult);
951
+ const txResult = await submitter.submit({ logResults: true, ...args });
863
952
  return {
864
- lock,
865
- createdAtHeight,
953
+ getLock: () => this.getBitcoinLockFromTxResult(txResult),
866
954
  txResult,
867
955
  securityFee
868
956
  };
@@ -878,8 +966,7 @@ var BitcoinLocks = class {
878
966
  priceIndex,
879
967
  releaseRequest: { bitcoinNetworkFee, toScriptPubkey },
880
968
  argonKeyring,
881
- tip,
882
- txProgressCallback
969
+ tip = 0n
883
970
  } = args;
884
971
  if (!toScriptPubkey.startsWith("0x")) {
885
972
  throw new Error("toScriptPubkey must be a hex string starting with 0x");
@@ -896,21 +983,13 @@ var BitcoinLocks = class {
896
983
  });
897
984
  if (!canAfford.canAfford) {
898
985
  throw new Error(
899
- `Insufficient funds to release lock. Available: ${formatArgons(canAfford.availableBalance)}, Required: ${formatArgons(redemptionPrice)}`
986
+ `Insufficient funds to release lock. Available: ${formatArgons(canAfford.availableBalance)}, Required: ${formatArgons(redemptionPrice + canAfford.txFee + tip)}`
900
987
  );
901
988
  }
902
- const txResult = await submitter.submit({
903
- waitForBlock: true,
989
+ return submitter.submit({
904
990
  logResults: true,
905
- tip,
906
- txProgressCallback
991
+ ...args
907
992
  });
908
- const blockHash = await txResult.inBlockPromise;
909
- const blockHeight = await client.at(blockHash).then((x) => x.query.system.number()).then((x) => x.toNumber());
910
- return {
911
- blockHash,
912
- blockHeight
913
- };
914
993
  }
915
994
  async releasePrice(priceIndex, lock) {
916
995
  return await this.getRedemptionRate(priceIndex, lock);
@@ -957,41 +1036,43 @@ var BitcoinLocks = class {
957
1036
  )}`
958
1037
  );
959
1038
  }
960
- const submission = await txSubmitter.submit({
961
- waitForBlock: true,
962
- tip,
963
- txProgressCallback
964
- });
965
- const ratchetEvent = submission.events.find(
966
- (x) => client.events.bitcoinLocks.BitcoinLockRatcheted.is(x)
967
- );
968
- if (!ratchetEvent) {
969
- throw new Error(`Ratchet event not found in transaction events`);
970
- }
971
- const blockHash = await submission.inBlockPromise;
972
- const api = await client.at(blockHash);
973
- const blockHeight = await api.query.system.number().then((x) => x.toNumber());
974
- const bitcoinBlockHeight = await api.query.bitcoinUtxos.confirmedBitcoinBlockTip().then((x) => x.unwrap().blockHeight.toNumber());
975
- const {
976
- amountBurned,
977
- liquidityPromised: liquidityPromisedRaw,
978
- newPeggedPrice,
979
- originalPeggedPrice
980
- } = ratchetEvent.data;
981
- const liquidityPromised = liquidityPromisedRaw.toBigInt();
982
- let mintAmount = liquidityPromised;
983
- if (liquidityPromised > originalPeggedPrice.toBigInt()) {
984
- mintAmount -= originalPeggedPrice.toBigInt();
985
- }
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
+ };
986
1073
  return {
987
- txFee: submission.finalFee ?? 0n,
988
- securityFee: ratchetPrice.ratchetingFee,
989
- pendingMint: mintAmount,
990
- liquidityPromised,
991
- newPeggedPrice: newPeggedPrice.toBigInt(),
992
- burned: amountBurned.toBigInt(),
993
- blockHeight,
994
- bitcoinBlockHeight
1074
+ txResult,
1075
+ getRatchetResult
995
1076
  };
996
1077
  }
997
1078
  };
@@ -1065,6 +1146,6 @@ async function getClient(host, options) {
1065
1146
  return await ApiPromise.create({ provider, noInitWarn: true, ...options ?? {} });
1066
1147
  }
1067
1148
 
1068
- 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 };
1069
1150
  //# sourceMappingURL=index.js.map
1070
1151
  //# sourceMappingURL=index.js.map