@atomiqlabs/sdk 8.5.0 → 8.6.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (52) hide show
  1. package/dist/storage/UnifiedSwapStorage.js +13 -8
  2. package/dist/swapper/Swapper.d.ts +10 -15
  3. package/dist/swapper/Swapper.js +26 -26
  4. package/dist/swapper/SwapperFactory.d.ts +1 -0
  5. package/dist/swapper/SwapperFactory.js +9 -4
  6. package/dist/swaps/ISwap.d.ts +8 -0
  7. package/dist/swaps/ISwap.js +10 -2
  8. package/dist/swaps/ISwapWrapper.d.ts +23 -1
  9. package/dist/swaps/ISwapWrapper.js +88 -28
  10. package/dist/swaps/escrow_swaps/IEscrowSwapWrapper.js +4 -1
  11. package/dist/swaps/escrow_swaps/frombtc/IFromBTCSelfInitSwap.d.ts +2 -2
  12. package/dist/swaps/escrow_swaps/frombtc/IFromBTCSelfInitSwap.js +1 -1
  13. package/dist/swaps/escrow_swaps/frombtc/ln/FromBTCLNSwap.d.ts +2 -2
  14. package/dist/swaps/escrow_swaps/frombtc/ln/FromBTCLNSwap.js +16 -6
  15. package/dist/swaps/escrow_swaps/frombtc/ln/FromBTCLNWrapper.js +8 -2
  16. package/dist/swaps/escrow_swaps/frombtc/ln_auto/FromBTCLNAutoSwap.d.ts +1 -1
  17. package/dist/swaps/escrow_swaps/frombtc/ln_auto/FromBTCLNAutoSwap.js +14 -4
  18. package/dist/swaps/escrow_swaps/frombtc/ln_auto/FromBTCLNAutoWrapper.js +12 -9
  19. package/dist/swaps/escrow_swaps/frombtc/onchain/FromBTCSwap.d.ts +2 -1
  20. package/dist/swaps/escrow_swaps/frombtc/onchain/FromBTCSwap.js +7 -5
  21. package/dist/swaps/escrow_swaps/frombtc/onchain/FromBTCWrapper.js +8 -2
  22. package/dist/swaps/escrow_swaps/tobtc/IToBTCSwap.js +1 -1
  23. package/dist/swaps/escrow_swaps/tobtc/IToBTCWrapper.js +0 -6
  24. package/dist/swaps/escrow_swaps/tobtc/ln/ToBTCLNWrapper.js +8 -3
  25. package/dist/swaps/escrow_swaps/tobtc/onchain/ToBTCWrapper.js +8 -2
  26. package/dist/swaps/spv_swaps/SpvFromBTCSwap.d.ts +3 -0
  27. package/dist/swaps/spv_swaps/SpvFromBTCSwap.js +14 -4
  28. package/dist/swaps/spv_swaps/SpvFromBTCWrapper.js +1 -3
  29. package/dist/swaps/trusted/ln/LnForGasWrapper.js +0 -1
  30. package/dist/swaps/trusted/onchain/OnchainForGasWrapper.js +0 -1
  31. package/package.json +1 -1
  32. package/src/storage/UnifiedSwapStorage.ts +13 -8
  33. package/src/swapper/Swapper.ts +37 -30
  34. package/src/swapper/SwapperFactory.ts +12 -6
  35. package/src/swaps/ISwap.ts +11 -3
  36. package/src/swaps/ISwapWrapper.ts +104 -28
  37. package/src/swaps/escrow_swaps/IEscrowSwapWrapper.ts +5 -1
  38. package/src/swaps/escrow_swaps/frombtc/IFromBTCSelfInitSwap.ts +3 -3
  39. package/src/swaps/escrow_swaps/frombtc/ln/FromBTCLNSwap.ts +17 -8
  40. package/src/swaps/escrow_swaps/frombtc/ln/FromBTCLNWrapper.ts +8 -3
  41. package/src/swaps/escrow_swaps/frombtc/ln_auto/FromBTCLNAutoSwap.ts +13 -5
  42. package/src/swaps/escrow_swaps/frombtc/ln_auto/FromBTCLNAutoWrapper.ts +9 -8
  43. package/src/swaps/escrow_swaps/frombtc/onchain/FromBTCSwap.ts +9 -5
  44. package/src/swaps/escrow_swaps/frombtc/onchain/FromBTCWrapper.ts +7 -2
  45. package/src/swaps/escrow_swaps/tobtc/IToBTCSwap.ts +1 -1
  46. package/src/swaps/escrow_swaps/tobtc/IToBTCWrapper.ts +0 -3
  47. package/src/swaps/escrow_swaps/tobtc/ln/ToBTCLNWrapper.ts +7 -3
  48. package/src/swaps/escrow_swaps/tobtc/onchain/ToBTCWrapper.ts +7 -2
  49. package/src/swaps/spv_swaps/SpvFromBTCSwap.ts +19 -4
  50. package/src/swaps/spv_swaps/SpvFromBTCWrapper.ts +1 -3
  51. package/src/swaps/trusted/ln/LnForGasWrapper.ts +0 -1
  52. package/src/swaps/trusted/onchain/OnchainForGasWrapper.ts +0 -1
@@ -152,7 +152,7 @@ export declare class FromBTCLNSwap<T extends ChainType = ChainType> extends IFro
152
152
  * @inheritDoc
153
153
  * @internal
154
154
  */
155
- protected canCommit(): boolean;
155
+ protected canCommit(skipQuoteExpiryChecks?: boolean): boolean;
156
156
  /**
157
157
  * @inheritDoc
158
158
  */
@@ -400,7 +400,7 @@ export declare class FromBTCLNSwap<T extends ChainType = ChainType> extends IFro
400
400
  *
401
401
  * @throws {Error} If in invalid state (must be {@link FromBTCLNSwapState.CLAIM_COMMITED})
402
402
  */
403
- txsClaim(_signer?: T["Signer"] | T["NativeSigner"], secret?: string): Promise<T["TX"][]>;
403
+ txsClaim(_signer?: string | T["Signer"] | T["NativeSigner"], secret?: string): Promise<T["TX"][]>;
404
404
  /**
405
405
  * @inheritDoc
406
406
  *
@@ -224,8 +224,8 @@ class FromBTCLNSwap extends IFromBTCSelfInitSwap_1.IFromBTCSelfInitSwap {
224
224
  * @inheritDoc
225
225
  * @internal
226
226
  */
227
- canCommit() {
228
- return this._state === FromBTCLNSwapState.PR_PAID;
227
+ canCommit(skipQuoteExpiryChecks) {
228
+ return this._state === FromBTCLNSwapState.PR_PAID || (!!skipQuoteExpiryChecks && this._state === FromBTCLNSwapState.QUOTE_SOFT_EXPIRED);
229
229
  }
230
230
  /**
231
231
  * @inheritDoc
@@ -773,7 +773,7 @@ class FromBTCLNSwap extends IFromBTCSelfInitSwap_1.IFromBTCSelfInitSwap {
773
773
  return Promise.resolve();
774
774
  });
775
775
  this._commitTxId = result[result.length - 1];
776
- if (this._state === FromBTCLNSwapState.PR_PAID || this._state === FromBTCLNSwapState.QUOTE_SOFT_EXPIRED) {
776
+ if (this._state === FromBTCLNSwapState.PR_PAID || this._state === FromBTCLNSwapState.QUOTE_SOFT_EXPIRED || this._state === FromBTCLNSwapState.QUOTE_EXPIRED) {
777
777
  await this._saveAndEmit(FromBTCLNSwapState.CLAIM_COMMITED);
778
778
  }
779
779
  return this._commitTxId;
@@ -821,6 +821,18 @@ class FromBTCLNSwap extends IFromBTCSelfInitSwap_1.IFromBTCSelfInitSwap {
821
821
  * @internal
822
822
  */
823
823
  async _txsClaim(_signer, secret) {
824
+ let address = undefined;
825
+ if (_signer != null) {
826
+ if (typeof (_signer) === "string") {
827
+ address = _signer;
828
+ }
829
+ else if ((0, base_1.isAbstractSigner)(_signer)) {
830
+ address = _signer.getAddress();
831
+ }
832
+ else {
833
+ address = (await this.wrapper._chain.wrapSigner(_signer)).getAddress();
834
+ }
835
+ }
824
836
  if (this._data == null)
825
837
  throw new Error("Unknown data, wrong state?");
826
838
  const useSecret = secret ?? this.secret;
@@ -828,9 +840,7 @@ class FromBTCLNSwap extends IFromBTCSelfInitSwap_1.IFromBTCSelfInitSwap {
828
840
  throw new Error("Swap secret pre-image not known and not provided, please provide the swap secret pre-image as an argument");
829
841
  if (!this.isValidSecretPreimage(useSecret))
830
842
  throw new Error("Invalid swap secret pre-image provided!");
831
- return this.wrapper._contract.txsClaimWithSecret(_signer == null ?
832
- this._getInitiator() :
833
- ((0, base_1.isAbstractSigner)(_signer) ? _signer : await this.wrapper._chain.wrapSigner(_signer)), this._data, useSecret, true, true);
843
+ return this.wrapper._contract.txsClaimWithSecret(address ?? this._getInitiator(), this._data, useSecret, true, true);
834
844
  }
835
845
  /**
836
846
  * @inheritDoc
@@ -36,6 +36,7 @@ class FromBTCLNWrapper extends IFromBTCLNWrapper_1.IFromBTCLNWrapper {
36
36
  */
37
37
  constructor(chainIdentifier, unifiedStorage, unifiedChainEvents, chain, contract, prices, tokens, swapDataDeserializer, lnApi, options, events) {
38
38
  super(chainIdentifier, unifiedStorage, unifiedChainEvents, chain, contract, prices, tokens, swapDataDeserializer, lnApi, {
39
+ ...options,
39
40
  safetyFactor: options?.safetyFactor ?? 2,
40
41
  bitcoinBlocktime: options?.bitcoinBlocktime ?? 10 * 60,
41
42
  unsafeSkipLnNodeCheck: options?.unsafeSkipLnNodeCheck ?? false
@@ -199,8 +200,14 @@ class FromBTCLNWrapper extends IFromBTCLNWrapper_1.IFromBTCLNWrapper {
199
200
  feeRate: (0, Utils_1.throwIfUndefined)(_preFetches.feeRatePromise),
200
201
  additionalParams
201
202
  }, this._options.postRequestTimeout, abortController.signal, retryCount > 0 ? false : undefined);
203
+ let lnCapacityPromise;
204
+ if (!_options.unsafeSkipLnNodeCheck) {
205
+ lnCapacityPromise = this.preFetchLnCapacity(lnPublicKey);
206
+ }
207
+ else
208
+ lnPublicKey.catch(() => { });
202
209
  return {
203
- lnCapacityPromise: _options.unsafeSkipLnNodeCheck ? null : this.preFetchLnCapacity(lnPublicKey),
210
+ lnCapacityPromise,
204
211
  resp: await response
205
212
  };
206
213
  }, undefined, RequestError_1.RequestError, abortController.signal);
@@ -229,7 +236,6 @@ class FromBTCLNWrapper extends IFromBTCLNWrapper_1.IFromBTCLNWrapper {
229
236
  secret: secret?.toString("hex"),
230
237
  exactIn: amountData.exactIn ?? true
231
238
  });
232
- await quote._save();
233
239
  return quote;
234
240
  }
235
241
  catch (e) {
@@ -482,7 +482,7 @@ export declare class FromBTCLNAutoSwap<T extends ChainType = ChainType> extends
482
482
  *
483
483
  * @throws {Error} If in invalid state (must be {@link FromBTCLNAutoSwapState.CLAIM_COMMITED})
484
484
  */
485
- txsClaim(_signer?: T["Signer"] | T["NativeSigner"], secret?: string): Promise<T["TX"][]>;
485
+ txsClaim(_signer?: string | T["Signer"] | T["NativeSigner"], secret?: string): Promise<T["TX"][]>;
486
486
  /**
487
487
  * @inheritDoc
488
488
  *
@@ -441,7 +441,7 @@ class FromBTCLNAutoSwap extends IEscrowSwap_1.IEscrowSwap {
441
441
  * @internal
442
442
  */
443
443
  getInputAmountWithoutFee() {
444
- if (this.btcAmountGas == null || this.btcAmountSwap)
444
+ if (this.btcAmountGas == null || this.btcAmountSwap == null)
445
445
  return null;
446
446
  return this.getInputSwapAmountWithoutFee() + this.getInputGasAmountWithoutFee() - this.getWatchtowerFeeAmountBtc();
447
447
  }
@@ -963,6 +963,18 @@ class FromBTCLNAutoSwap extends IEscrowSwap_1.IEscrowSwap {
963
963
  * @throws {Error} If in invalid state (must be {@link FromBTCLNAutoSwapState.CLAIM_COMMITED})
964
964
  */
965
965
  async txsClaim(_signer, secret) {
966
+ let address = undefined;
967
+ if (_signer != null) {
968
+ if (typeof (_signer) === "string") {
969
+ address = _signer;
970
+ }
971
+ else if ((0, base_1.isAbstractSigner)(_signer)) {
972
+ address = _signer.getAddress();
973
+ }
974
+ else {
975
+ address = (await this.wrapper._chain.wrapSigner(_signer)).getAddress();
976
+ }
977
+ }
966
978
  if (this._state !== FromBTCLNAutoSwapState.CLAIM_COMMITED)
967
979
  throw new Error("Must be in CLAIM_COMMITED state!");
968
980
  if (this._data == null)
@@ -972,9 +984,7 @@ class FromBTCLNAutoSwap extends IEscrowSwap_1.IEscrowSwap {
972
984
  throw new Error("Swap secret pre-image not known and not provided, please provide the swap secret pre-image as an argument");
973
985
  if (!this.isValidSecretPreimage(useSecret))
974
986
  throw new Error("Invalid swap secret pre-image provided!");
975
- return await this.wrapper._contract.txsClaimWithSecret(_signer == null ?
976
- this._getInitiator() :
977
- ((0, base_1.isAbstractSigner)(_signer) ? _signer : await this.wrapper._chain.wrapSigner(_signer)), this._data, useSecret, true, true);
987
+ return await this.wrapper._contract.txsClaimWithSecret(address ?? this._getInitiator(), this._data, useSecret, true, true);
978
988
  }
979
989
  /**
980
990
  * @inheritDoc
@@ -39,6 +39,7 @@ class FromBTCLNAutoWrapper extends IFromBTCLNWrapper_1.IFromBTCLNWrapper {
39
39
  */
40
40
  constructor(chainIdentifier, unifiedStorage, unifiedChainEvents, chain, contract, prices, tokens, swapDataDeserializer, lnApi, messenger, options, events) {
41
41
  super(chainIdentifier, unifiedStorage, unifiedChainEvents, chain, contract, prices, tokens, swapDataDeserializer, lnApi, {
42
+ ...options,
42
43
  safetyFactor: options?.safetyFactor ?? 2,
43
44
  bitcoinBlocktime: options?.bitcoinBlocktime ?? 10 * 60,
44
45
  unsafeSkipLnNodeCheck: options?.unsafeSkipLnNodeCheck ?? false
@@ -99,12 +100,12 @@ class FromBTCLNAutoWrapper extends IFromBTCLNWrapper_1.IFromBTCLNWrapper {
99
100
  this.logger.error("processEventInitialize(" + swap.getId() + "): Error when processing event, escrow hashes don't match!");
100
101
  return false;
101
102
  }
102
- swap._commitTxId = event.meta?.txId;
103
103
  swap._commitedAt ??= Date.now();
104
104
  swap._state = FromBTCLNAutoSwap_1.FromBTCLNAutoSwapState.CLAIM_COMMITED;
105
- swap._broadcastSecret().catch(e => {
106
- this.logger.error("processEventInitialize(" + swap.getId() + "): Error when broadcasting swap secret: ", e);
107
- });
105
+ if (swap.hasSecretPreimage())
106
+ swap._broadcastSecret().catch(e => {
107
+ this.logger.error("processEventInitialize(" + swap.getId() + "): Error when broadcasting swap secret: ", e);
108
+ });
108
109
  return true;
109
110
  }
110
111
  return false;
@@ -115,7 +116,6 @@ class FromBTCLNAutoWrapper extends IFromBTCLNWrapper_1.IFromBTCLNWrapper {
115
116
  */
116
117
  processEventClaim(swap, event) {
117
118
  if (swap._state !== FromBTCLNAutoSwap_1.FromBTCLNAutoSwapState.FAILED && swap._state !== FromBTCLNAutoSwap_1.FromBTCLNAutoSwapState.CLAIM_CLAIMED) {
118
- swap._claimTxId = event.meta?.txId;
119
119
  swap._state = FromBTCLNAutoSwap_1.FromBTCLNAutoSwapState.CLAIM_CLAIMED;
120
120
  swap._setSwapSecret(event.result);
121
121
  return Promise.resolve(true);
@@ -128,7 +128,6 @@ class FromBTCLNAutoWrapper extends IFromBTCLNWrapper_1.IFromBTCLNWrapper {
128
128
  */
129
129
  processEventRefund(swap, event) {
130
130
  if (swap._state !== FromBTCLNAutoSwap_1.FromBTCLNAutoSwapState.CLAIM_CLAIMED && swap._state !== FromBTCLNAutoSwap_1.FromBTCLNAutoSwapState.FAILED) {
131
- swap._refundTxId ??= event.meta?.txId;
132
131
  swap._state = FromBTCLNAutoSwap_1.FromBTCLNAutoSwapState.FAILED;
133
132
  return Promise.resolve(true);
134
133
  }
@@ -275,8 +274,14 @@ class FromBTCLNAutoWrapper extends IFromBTCLNWrapper_1.IFromBTCLNWrapper {
275
274
  gasAmount: _options.gasAmount,
276
275
  claimerBounty: (0, Utils_1.throwIfUndefined)(_preFetches.claimerBountyPrefetch)
277
276
  }, this._options.postRequestTimeout, abortController.signal, retryCount > 0 ? false : undefined);
277
+ let lnCapacityPromise;
278
+ if (!_options.unsafeSkipLnNodeCheck) {
279
+ lnCapacityPromise = this.preFetchLnCapacity(lnPublicKey);
280
+ }
281
+ else
282
+ lnPublicKey.catch(() => { });
278
283
  return {
279
- lnCapacityPromise: _options.unsafeSkipLnNodeCheck ? undefined : this.preFetchLnCapacity(lnPublicKey),
284
+ lnCapacityPromise,
280
285
  resp: await response
281
286
  };
282
287
  }, undefined, RequestError_1.RequestError, abortController.signal);
@@ -313,8 +318,6 @@ class FromBTCLNAutoWrapper extends IFromBTCLNWrapper_1.IFromBTCLNWrapper {
313
318
  exactIn: amountData.exactIn ?? true
314
319
  };
315
320
  const quote = new FromBTCLNAutoSwap_1.FromBTCLNAutoSwap(this, swapInit);
316
- await quote._save();
317
- this.logger.debug("create(): Created new FromBTCLNAutoSwap quote, claimHash (pseudo escrowHash): ", quote._getEscrowHash());
318
321
  return quote;
319
322
  }
320
323
  catch (e) {
@@ -191,7 +191,7 @@ export declare class FromBTCSwap<T extends ChainType = ChainType> extends IFromB
191
191
  * @inheritDoc
192
192
  * @internal
193
193
  */
194
- protected canCommit(): boolean;
194
+ protected canCommit(skipQuoteExpiryChecks?: boolean): boolean;
195
195
  /**
196
196
  * @inheritDoc
197
197
  */
@@ -444,6 +444,7 @@ export declare class FromBTCSwap<T extends ChainType = ChainType> extends IFromB
444
444
  * @internal
445
445
  */
446
446
  _sync(save?: boolean, quoteDefinitelyExpired?: boolean, commitStatus?: SwapCommitState): Promise<boolean>;
447
+ private btcTxLastChecked?;
447
448
  /**
448
449
  * @inheritDoc
449
450
  * @internal
@@ -260,8 +260,8 @@ class FromBTCSwap extends IFromBTCSelfInitSwap_1.IFromBTCSelfInitSwap {
260
260
  * @inheritDoc
261
261
  * @internal
262
262
  */
263
- canCommit() {
264
- if (this._state !== FromBTCSwapState.PR_CREATED)
263
+ canCommit(skipQuoteExpiryChecks) {
264
+ if (this._state !== FromBTCSwapState.PR_CREATED && (!skipQuoteExpiryChecks || this._state !== FromBTCSwapState.QUOTE_SOFT_EXPIRED))
265
265
  return false;
266
266
  if (this.requiredConfirmations == null)
267
267
  return false;
@@ -742,7 +742,7 @@ class FromBTCSwap extends IFromBTCSelfInitSwap_1.IFromBTCSelfInitSwap {
742
742
  return Promise.resolve();
743
743
  });
744
744
  this._commitTxId = result[result.length - 1];
745
- if (this._state === FromBTCSwapState.PR_CREATED || this._state === FromBTCSwapState.QUOTE_SOFT_EXPIRED) {
745
+ if (this._state === FromBTCSwapState.PR_CREATED || this._state === FromBTCSwapState.QUOTE_SOFT_EXPIRED || this._state === FromBTCSwapState.QUOTE_EXPIRED) {
746
746
  await this._saveAndEmit(FromBTCSwapState.CLAIM_COMMITED);
747
747
  }
748
748
  return this._commitTxId;
@@ -1045,6 +1045,7 @@ class FromBTCSwap extends IFromBTCSelfInitSwap_1.IFromBTCSelfInitSwap {
1045
1045
  }
1046
1046
  if (this.address == null)
1047
1047
  return save;
1048
+ this.btcTxLastChecked = Date.now();
1048
1049
  const res = await this.getBitcoinPayment();
1049
1050
  if (res != null) {
1050
1051
  if (this.txId !== res.txId) {
@@ -1086,10 +1087,11 @@ class FromBTCSwap extends IFromBTCSelfInitSwap_1.IFromBTCSelfInitSwap {
1086
1087
  return true;
1087
1088
  }
1088
1089
  case FromBTCSwapState.EXPIRED:
1089
- //Check if bitcoin payment was received every 2 minutes
1090
- if (Math.floor(Date.now() / 1000) % 120 === 0) {
1090
+ //Check if bitcoin payment was received at least every 2 minutes
1091
+ if (this.btcTxLastChecked == null || Date.now() - this.btcTxLastChecked > 120000) {
1091
1092
  if (this.address != null)
1092
1093
  try {
1094
+ this.btcTxLastChecked = Date.now();
1093
1095
  const res = await this.getBitcoinPayment();
1094
1096
  if (res != null) {
1095
1097
  let shouldSave = false;
@@ -37,6 +37,7 @@ class FromBTCWrapper extends IFromBTCWrapper_1.IFromBTCWrapper {
37
37
  */
38
38
  constructor(chainIdentifier, unifiedStorage, unifiedChainEvents, chain, contract, prices, tokens, swapDataDeserializer, btcRelay, synchronizer, btcRpc, options, events) {
39
39
  super(chainIdentifier, unifiedStorage, unifiedChainEvents, chain, contract, prices, tokens, swapDataDeserializer, {
40
+ ...options,
40
41
  bitcoinNetwork: options?.bitcoinNetwork ?? utils_1.TEST_NETWORK,
41
42
  safetyFactor: options?.safetyFactor ?? 2,
42
43
  blocksTillTxConfirms: options?.blocksTillTxConfirms ?? 12,
@@ -295,8 +296,14 @@ class FromBTCWrapper extends IFromBTCWrapper_1.IFromBTCWrapper {
295
296
  feeRate: (0, Utils_1.throwIfUndefined)(feeRatePromise),
296
297
  additionalParams
297
298
  }, this._options.postRequestTimeout, abortController.signal, retryCount > 0 ? false : undefined);
299
+ let signDataPromise = _signDataPromise;
300
+ if (signDataPromise == null) {
301
+ signDataPromise = this.preFetchSignData(signDataPrefetch);
302
+ }
303
+ else
304
+ signDataPrefetch.catch(() => { });
298
305
  return {
299
- signDataPromise: _signDataPromise ?? this.preFetchSignData(signDataPrefetch),
306
+ signDataPromise,
300
307
  resp: await response
301
308
  };
302
309
  }, undefined, e => e instanceof RequestError_1.RequestError, abortController.signal);
@@ -323,7 +330,6 @@ class FromBTCWrapper extends IFromBTCWrapper_1.IFromBTCWrapper {
323
330
  exactIn: amountData.exactIn ?? true,
324
331
  requiredConfirmations: resp.confirmations
325
332
  });
326
- await quote._save();
327
333
  return quote;
328
334
  }
329
335
  catch (e) {
@@ -453,7 +453,7 @@ class IToBTCSwap extends IEscrowSelfInitSwap_1.IEscrowSelfInitSwap {
453
453
  * @throws {Error} When in invalid state (not {@link ToBTCSwapState.CREATED})
454
454
  */
455
455
  async txsCommit(skipChecks) {
456
- if (this._state !== ToBTCSwapState.CREATED)
456
+ if (this._state !== ToBTCSwapState.CREATED && (!skipChecks || this._state !== ToBTCSwapState.QUOTE_SOFT_EXPIRED))
457
457
  throw new Error("Must be in CREATED state!");
458
458
  if (this.signatureData == null)
459
459
  throw new Error("Init signature data not known, cannot commit!");
@@ -78,8 +78,6 @@ class IToBTCWrapper extends IEscrowSwapWrapper_1.IEscrowSwapWrapper {
78
78
  async processEventInitialize(swap, event) {
79
79
  if (swap._state === IToBTCSwap_1.ToBTCSwapState.CREATED || swap._state === IToBTCSwap_1.ToBTCSwapState.QUOTE_SOFT_EXPIRED) {
80
80
  swap._state = IToBTCSwap_1.ToBTCSwapState.COMMITED;
81
- if (swap._commitTxId == null)
82
- swap._commitTxId = event.meta?.txId;
83
81
  return true;
84
82
  }
85
83
  return false;
@@ -96,8 +94,6 @@ class IToBTCWrapper extends IEscrowSwapWrapper_1.IEscrowSwapWrapper {
96
94
  this.logger.warn(`processEventClaim(): Failed to set payment result ${event.result}: `, e);
97
95
  });
98
96
  swap._state = IToBTCSwap_1.ToBTCSwapState.CLAIMED;
99
- if (swap._claimTxId == null)
100
- swap._claimTxId = event.meta?.txId;
101
97
  return true;
102
98
  }
103
99
  return false;
@@ -108,8 +104,6 @@ class IToBTCWrapper extends IEscrowSwapWrapper_1.IEscrowSwapWrapper {
108
104
  processEventRefund(swap, event) {
109
105
  if (swap._state !== IToBTCSwap_1.ToBTCSwapState.CLAIMED && swap._state !== IToBTCSwap_1.ToBTCSwapState.REFUNDED) {
110
106
  swap._state = IToBTCSwap_1.ToBTCSwapState.REFUNDED;
111
- if (swap._refundTxId == null)
112
- swap._refundTxId = event.meta?.txId;
113
107
  return Promise.resolve(true);
114
108
  }
115
109
  return Promise.resolve(false);
@@ -23,6 +23,7 @@ const RetryUtils_1 = require("../../../../utils/RetryUtils");
23
23
  class ToBTCLNWrapper extends IToBTCWrapper_1.IToBTCWrapper {
24
24
  constructor(chainIdentifier, unifiedStorage, unifiedChainEvents, chain, contract, prices, tokens, swapDataDeserializer, options, events) {
25
25
  super(chainIdentifier, unifiedStorage, unifiedChainEvents, chain, contract, prices, tokens, swapDataDeserializer, {
26
+ ...options,
26
27
  paymentTimeoutSeconds: options?.paymentTimeoutSeconds ?? 5 * 24 * 60 * 60,
27
28
  lightningBaseFee: options?.lightningBaseFee ?? 10,
28
29
  lightningFeePPM: options?.lightningFeePPM ?? 2000
@@ -160,8 +161,14 @@ class ToBTCLNWrapper extends IToBTCWrapper_1.IToBTCWrapper {
160
161
  feeRate: (0, Utils_1.throwIfUndefined)(preFetches.feeRatePromise),
161
162
  additionalParams
162
163
  }, this._options.postRequestTimeout, abortController.signal, retryCount > 0 ? false : undefined);
164
+ let signDataPromise = preFetches.signDataPrefetchPromise;
165
+ if (signDataPromise == null) {
166
+ signDataPromise = this.preFetchSignData(signDataPrefetch);
167
+ }
168
+ else
169
+ signDataPrefetch.catch(() => { });
163
170
  return {
164
- signDataPromise: preFetches.signDataPrefetchPromise ?? this.preFetchSignData(signDataPrefetch),
171
+ signDataPromise,
165
172
  resp: await response
166
173
  };
167
174
  }, undefined, e => e instanceof RequestError_1.RequestError, abortController.signal);
@@ -196,7 +203,6 @@ class ToBTCLNWrapper extends IToBTCWrapper_1.IToBTCWrapper {
196
203
  pr,
197
204
  exactIn: false
198
205
  });
199
- await quote._save();
200
206
  return quote;
201
207
  }
202
208
  catch (e) {
@@ -346,7 +352,6 @@ class ToBTCLNWrapper extends IToBTCWrapper_1.IToBTCWrapper {
346
352
  pr: invoice,
347
353
  exactIn: true
348
354
  });
349
- await quote._save();
350
355
  return quote;
351
356
  }
352
357
  catch (e) {
@@ -35,6 +35,7 @@ class ToBTCWrapper extends IToBTCWrapper_1.IToBTCWrapper {
35
35
  */
36
36
  constructor(chainIdentifier, unifiedStorage, unifiedChainEvents, chain, contract, prices, tokens, swapDataDeserializer, btcRpc, options, events) {
37
37
  super(chainIdentifier, unifiedStorage, unifiedChainEvents, chain, contract, prices, tokens, swapDataDeserializer, {
38
+ ...options,
38
39
  bitcoinNetwork: options?.bitcoinNetwork ?? utils_1.TEST_NETWORK,
39
40
  safetyFactor: options?.safetyFactor ?? 2,
40
41
  maxConfirmations: options?.maxConfirmations ?? 6,
@@ -179,8 +180,14 @@ class ToBTCWrapper extends IToBTCWrapper_1.IToBTCWrapper {
179
180
  feeRate: (0, Utils_1.throwIfUndefined)(feeRatePromise),
180
181
  additionalParams
181
182
  }, this._options.postRequestTimeout, abortController.signal, retryCount > 0 ? false : undefined);
183
+ let signDataPromise = _signDataPromise;
184
+ if (signDataPromise == null) {
185
+ signDataPromise = this.preFetchSignData(signDataPrefetch);
186
+ }
187
+ else
188
+ signDataPrefetch.catch(() => { });
182
189
  return {
183
- signDataPromise: _signDataPromise ?? this.preFetchSignData(signDataPrefetch),
190
+ signDataPromise,
184
191
  resp: await response
185
192
  };
186
193
  }, undefined, RequestError_1.RequestError, abortController.signal);
@@ -218,7 +225,6 @@ class ToBTCWrapper extends IToBTCWrapper_1.IToBTCWrapper {
218
225
  requiredConfirmations: _options.confirmations,
219
226
  nonce
220
227
  });
221
- await quote._save();
222
228
  return quote;
223
229
  }
224
230
  catch (e) {
@@ -119,6 +119,7 @@ export declare function isSpvFromBTCSwapInit(obj: any): obj is SpvFromBTCSwapIni
119
119
  * @category Swaps/Bitcoin → Smart chain
120
120
  */
121
121
  export declare class SpvFromBTCSwap<T extends ChainType> extends ISwap<T, SpvFromBTCTypeDefinition<T>> implements IBTCWalletSwap, ISwapWithGasDrop<T>, IClaimableSwap<T, SpvFromBTCTypeDefinition<T>, SpvFromBTCSwapState> {
122
+ protected readonly currentVersion: number;
122
123
  readonly TYPE: SwapType.SPV_VAULT_FROM_BTC;
123
124
  /**
124
125
  * @internal
@@ -169,6 +170,7 @@ export declare class SpvFromBTCSwap<T extends ChainType> extends ISwap<T, SpvFro
169
170
  private readonly frontingFeeShare;
170
171
  private readonly executionFeeShare;
171
172
  private readonly gasPricingInfo?;
173
+ private posted?;
172
174
  /**
173
175
  * @internal
174
176
  */
@@ -599,6 +601,7 @@ export declare class SpvFromBTCSwap<T extends ChainType> extends ISwap<T, SpvFro
599
601
  * @internal
600
602
  */
601
603
  _setBitcoinTxId(txId: string): Promise<void>;
604
+ private btcTxLastChecked?;
602
605
  /**
603
606
  * @internal
604
607
  */
@@ -143,6 +143,7 @@ class SpvFromBTCSwap extends ISwap_1.ISwap {
143
143
  if (isSpvFromBTCSwapInit(initOrObject) && initOrObject.url != null)
144
144
  initOrObject.url += "/frombtc_spv";
145
145
  super(wrapper, initOrObject);
146
+ this.currentVersion = 2;
146
147
  this.TYPE = SwapType_1.SwapType.SPV_VAULT_FROM_BTC;
147
148
  /**
148
149
  * @internal
@@ -213,6 +214,7 @@ class SpvFromBTCSwap extends ISwap_1.ISwap {
213
214
  this._frontTxId = initOrObject.frontTxId;
214
215
  this.gasPricingInfo = (0, PriceInfoType_1.deserializePriceInfoType)(initOrObject.gasPricingInfo);
215
216
  this.btcTxConfirmedAt = initOrObject.btcTxConfirmedAt;
217
+ this.posted = initOrObject.posted;
216
218
  if (initOrObject.data != null)
217
219
  this._data = new this.wrapper._spvWithdrawalDataDeserializer(initOrObject.data);
218
220
  }
@@ -223,7 +225,12 @@ class SpvFromBTCSwap extends ISwap_1.ISwap {
223
225
  * @inheritDoc
224
226
  * @internal
225
227
  */
226
- upgradeVersion() { }
228
+ upgradeVersion() {
229
+ if (this.version === 1) {
230
+ this.posted = this.initiated && this._data != null;
231
+ this.version = 2;
232
+ }
233
+ }
227
234
  /**
228
235
  * @inheritDoc
229
236
  * @internal
@@ -723,6 +730,7 @@ class SpvFromBTCSwap extends ISwap_1.ISwap {
723
730
  }
724
731
  this._data = data;
725
732
  this.initiated = true;
733
+ this.posted = true;
726
734
  await this._saveAndEmit(SpvFromBTCSwapState.SIGNED);
727
735
  try {
728
736
  await IntermediaryAPI_1.IntermediaryAPI.initSpvFromBTC(this.chainIdentifier, this.url, {
@@ -895,7 +903,7 @@ class SpvFromBTCSwap extends ISwap_1.ISwap {
895
903
  async waitForBitcoinTransaction(updateCallback, checkIntervalSeconds, abortSignal) {
896
904
  if (this._state !== SpvFromBTCSwapState.POSTED &&
897
905
  this._state !== SpvFromBTCSwapState.BROADCASTED &&
898
- !(this._state === SpvFromBTCSwapState.QUOTE_SOFT_EXPIRED && this.initiated))
906
+ !(this._state === SpvFromBTCSwapState.QUOTE_SOFT_EXPIRED && this.posted))
899
907
  throw new Error("Must be in POSTED or BROADCASTED state!");
900
908
  if (this._data == null)
901
909
  throw new Error("Expected swap to have withdrawal data filled!");
@@ -1201,6 +1209,7 @@ class SpvFromBTCSwap extends ISwap_1.ISwap {
1201
1209
  executionFeeShare: this.executionFeeShare.toString(10),
1202
1210
  genesisSmartChainBlockHeight: this._genesisSmartChainBlockHeight,
1203
1211
  gasPricingInfo: (0, PriceInfoType_1.serializePriceInfoType)(this.gasPricingInfo),
1212
+ posted: this.posted,
1204
1213
  senderAddress: this._senderAddress,
1205
1214
  claimTxId: this._claimTxId,
1206
1215
  frontTxId: this._frontTxId,
@@ -1235,6 +1244,7 @@ class SpvFromBTCSwap extends ISwap_1.ISwap {
1235
1244
  if (this._data?.btcTx == null)
1236
1245
  return false;
1237
1246
  //Check if bitcoin payment was confirmed
1247
+ this.btcTxLastChecked = Date.now();
1238
1248
  const res = await this.getBitcoinPayment();
1239
1249
  if (res == null) {
1240
1250
  //Check inputs double-spent
@@ -1362,7 +1372,7 @@ class SpvFromBTCSwap extends ISwap_1.ISwap {
1362
1372
  return true;
1363
1373
  }
1364
1374
  }
1365
- if (this._state === SpvFromBTCSwapState.QUOTE_SOFT_EXPIRED && !this.initiated) {
1375
+ if (this._state === SpvFromBTCSwapState.QUOTE_SOFT_EXPIRED && !this.posted) {
1366
1376
  if (this.expiry < Date.now()) {
1367
1377
  this._state = SpvFromBTCSwapState.QUOTE_EXPIRED;
1368
1378
  if (save)
@@ -1370,7 +1380,7 @@ class SpvFromBTCSwap extends ISwap_1.ISwap {
1370
1380
  return true;
1371
1381
  }
1372
1382
  }
1373
- if (Math.floor(Date.now() / 1000) % 120 === 0) {
1383
+ if (this.btcTxLastChecked == null || Date.now() - this.btcTxLastChecked > 120000) {
1374
1384
  if (this._state === SpvFromBTCSwapState.POSTED ||
1375
1385
  this._state === SpvFromBTCSwapState.BROADCASTED) {
1376
1386
  try {
@@ -39,6 +39,7 @@ class SpvFromBTCWrapper extends ISwapWrapper_1.ISwapWrapper {
39
39
  */
40
40
  constructor(chainIdentifier, unifiedStorage, unifiedChainEvents, chain, contract, prices, tokens, spvWithdrawalDataDeserializer, btcRelay, synchronizer, btcRpc, options, events) {
41
41
  super(chainIdentifier, unifiedStorage, unifiedChainEvents, chain, prices, tokens, {
42
+ ...options,
42
43
  bitcoinNetwork: options?.bitcoinNetwork ?? utils_1.TEST_NETWORK,
43
44
  maxConfirmations: options?.maxConfirmations ?? 6,
44
45
  bitcoinBlocktime: options?.bitcoinBlocktime ?? 10 * 60,
@@ -89,7 +90,6 @@ class SpvFromBTCWrapper extends ISwapWrapper_1.ISwapWrapper {
89
90
  swap._state === SpvFromBTCSwap_1.SpvFromBTCSwapState.BROADCASTED || swap._state === SpvFromBTCSwap_1.SpvFromBTCSwapState.DECLINED ||
90
91
  swap._state === SpvFromBTCSwap_1.SpvFromBTCSwapState.QUOTE_SOFT_EXPIRED || swap._state === SpvFromBTCSwap_1.SpvFromBTCSwapState.BTC_TX_CONFIRMED) {
91
92
  swap._state = SpvFromBTCSwap_1.SpvFromBTCSwapState.FRONTED;
92
- swap._frontTxId = event.meta?.txId;
93
93
  await swap._setBitcoinTxId(event.btcTxId).catch(e => {
94
94
  this.logger.warn("processEventFront(): Failed to set bitcoin txId: ", e);
95
95
  });
@@ -103,7 +103,6 @@ class SpvFromBTCWrapper extends ISwapWrapper_1.ISwapWrapper {
103
103
  swap._state === SpvFromBTCSwap_1.SpvFromBTCSwapState.QUOTE_SOFT_EXPIRED || swap._state === SpvFromBTCSwap_1.SpvFromBTCSwapState.FRONTED ||
104
104
  swap._state === SpvFromBTCSwap_1.SpvFromBTCSwapState.BTC_TX_CONFIRMED) {
105
105
  swap._state = SpvFromBTCSwap_1.SpvFromBTCSwapState.CLAIMED;
106
- swap._claimTxId = event.meta?.txId;
107
106
  await swap._setBitcoinTxId(event.btcTxId).catch(e => {
108
107
  this.logger.warn("processEventClaim(): Failed to set bitcoin txId: ", e);
109
108
  });
@@ -506,7 +505,6 @@ class SpvFromBTCWrapper extends ISwapWrapper_1.ISwapWrapper {
506
505
  genesisSmartChainBlockHeight: await (0, Utils_1.throwIfUndefined)(finalizedBlockHeightPrefetchPromise, "Finalize block height promise failed!")
507
506
  };
508
507
  const quote = new SpvFromBTCSwap_1.SpvFromBTCSwap(this, swapInit);
509
- await quote._save();
510
508
  return quote;
511
509
  }
512
510
  catch (e) {
@@ -76,7 +76,6 @@ class LnForGasWrapper extends ISwapWrapper_1.ISwapWrapper {
76
76
  exactIn: false
77
77
  };
78
78
  const quote = new LnForGasSwap_1.LnForGasSwap(this, quoteInit);
79
- await quote._save();
80
79
  return quote;
81
80
  }
82
81
  }
@@ -86,7 +86,6 @@ class OnchainForGasWrapper extends ISwapWrapper_1.ISwapWrapper {
86
86
  exactIn: false,
87
87
  token
88
88
  });
89
- await quote._save();
90
89
  return quote;
91
90
  }
92
91
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@atomiqlabs/sdk",
3
- "version": "8.5.0",
3
+ "version": "8.6.2",
4
4
  "description": "atomiq labs SDK for cross-chain swaps between smart chains and bitcoin",
5
5
  "main": "./dist/index.js",
6
6
  "types:": "./dist/index.d.ts",
@@ -89,6 +89,7 @@ export class UnifiedSwapStorage<T extends ChainType> {
89
89
  }
90
90
  const value = reviver(rawObj);
91
91
  if(value==null) return;
92
+ value._persisted = true;
92
93
  if(!this.noWeakRefMap) this.weakRefCache.set(rawObj.id, new WeakRef<ISwap<T>>(value));
93
94
  result.push(value);
94
95
  });
@@ -101,36 +102,40 @@ export class UnifiedSwapStorage<T extends ChainType> {
101
102
  *
102
103
  * @param value Swap to save
103
104
  */
104
- save<S extends ISwap<T>>(value: S): Promise<void> {
105
+ async save<S extends ISwap<T>>(value: S): Promise<void> {
105
106
  if(!this.noWeakRefMap) this.weakRefCache.set(value.getId(), new WeakRef<ISwap<T>>(value));
106
- return this.storage.save(value.serialize());
107
+ await this.storage.save(value.serialize());
108
+ value._persisted = true;
107
109
  }
108
110
 
109
111
  /**
110
112
  * Saves multiple swaps to storage in a batch operation
111
113
  * @param values Array of swaps to save
112
114
  */
113
- saveAll<S extends ISwap<T>>(values: S[]): Promise<void> {
115
+ async saveAll<S extends ISwap<T>>(values: S[]): Promise<void> {
114
116
  if(!this.noWeakRefMap) values.forEach(value => this.weakRefCache.set(value.getId(), new WeakRef<ISwap<T>>(value)));
115
- return this.storage.saveAll(values.map(obj => obj.serialize()));
117
+ await this.storage.saveAll(values.map(obj => obj.serialize()));
118
+ values.forEach(value => value._persisted = true);
116
119
  }
117
120
 
118
121
  /**
119
122
  * Removes a swap from storage
120
123
  * @param value Swap to remove
121
124
  */
122
- remove<S extends ISwap<T>>(value: S): Promise<void> {
125
+ async remove<S extends ISwap<T>>(value: S): Promise<void> {
123
126
  if(!this.noWeakRefMap) this.weakRefCache.delete(value.getId());
124
- return this.storage.remove(value.serialize());
127
+ await this.storage.remove(value.serialize());
128
+ value._persisted = false;
125
129
  }
126
130
 
127
131
  /**
128
132
  * Removes multiple swaps from storage in a batch operation
129
133
  * @param values Array of swaps to remove
130
134
  */
131
- removeAll<S extends ISwap<T>>(values: S[]): Promise<void> {
135
+ async removeAll<S extends ISwap<T>>(values: S[]): Promise<void> {
132
136
  if(!this.noWeakRefMap) values.forEach(value => this.weakRefCache.delete(value.getId()));
133
- return this.storage.removeAll(values.map(obj => obj.serialize()));
137
+ await this.storage.removeAll(values.map(obj => obj.serialize()));
138
+ values.forEach(value => value._persisted = false);
134
139
  }
135
140
 
136
141
  }