@atomiqlabs/sdk 8.8.3 → 8.9.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.
Files changed (130) hide show
  1. package/api/index.d.ts +1 -0
  2. package/api/index.js +3 -0
  3. package/dist/ApiList.d.ts +37 -0
  4. package/dist/ApiList.js +30 -0
  5. package/dist/api/ApiEndpoints.d.ts +393 -0
  6. package/dist/api/ApiEndpoints.js +2 -0
  7. package/dist/api/ApiParser.d.ts +10 -0
  8. package/dist/api/ApiParser.js +134 -0
  9. package/dist/api/ApiTypes.d.ts +157 -0
  10. package/dist/api/ApiTypes.js +75 -0
  11. package/dist/api/SerializedAction.d.ts +40 -0
  12. package/dist/api/SerializedAction.js +59 -0
  13. package/dist/api/SwapperApi.d.ts +50 -0
  14. package/dist/api/SwapperApi.js +431 -0
  15. package/dist/api/index.d.ts +5 -0
  16. package/dist/api/index.js +24 -0
  17. package/dist/events/UnifiedSwapEventListener.d.ts +4 -3
  18. package/dist/events/UnifiedSwapEventListener.js +8 -2
  19. package/dist/http/HttpUtils.d.ts +4 -2
  20. package/dist/http/HttpUtils.js +10 -4
  21. package/dist/http/paramcoders/client/StreamingFetchPromise.d.ts +2 -1
  22. package/dist/http/paramcoders/client/StreamingFetchPromise.js +3 -2
  23. package/dist/index.d.ts +1 -0
  24. package/dist/index.js +1 -0
  25. package/dist/intermediaries/IntermediaryDiscovery.d.ts +7 -2
  26. package/dist/intermediaries/IntermediaryDiscovery.js +4 -4
  27. package/dist/intermediaries/apis/IntermediaryAPI.d.ts +171 -14
  28. package/dist/intermediaries/apis/IntermediaryAPI.js +174 -28
  29. package/dist/intermediaries/auth/SignedKeyBasedAuth.d.ts +14 -0
  30. package/dist/intermediaries/auth/SignedKeyBasedAuth.js +68 -0
  31. package/dist/storage/IUnifiedStorage.d.ts +45 -3
  32. package/dist/storage/UnifiedSwapStorage.d.ts +8 -2
  33. package/dist/storage/UnifiedSwapStorage.js +46 -8
  34. package/dist/swapper/Swapper.d.ts +41 -3
  35. package/dist/swapper/Swapper.js +93 -48
  36. package/dist/swapper/SwapperUtils.d.ts +18 -2
  37. package/dist/swapper/SwapperUtils.js +39 -1
  38. package/dist/swaps/ISwap.d.ts +70 -9
  39. package/dist/swaps/ISwap.js +28 -6
  40. package/dist/swaps/ISwapWrapper.d.ts +11 -1
  41. package/dist/swaps/ISwapWrapper.js +23 -3
  42. package/dist/swaps/escrow_swaps/IEscrowSwap.d.ts +1 -1
  43. package/dist/swaps/escrow_swaps/IEscrowSwap.js +4 -2
  44. package/dist/swaps/escrow_swaps/IEscrowSwapWrapper.d.ts +2 -1
  45. package/dist/swaps/escrow_swaps/IEscrowSwapWrapper.js +2 -2
  46. package/dist/swaps/escrow_swaps/frombtc/IFromBTCLNWrapper.d.ts +3 -1
  47. package/dist/swaps/escrow_swaps/frombtc/IFromBTCLNWrapper.js +3 -2
  48. package/dist/swaps/escrow_swaps/frombtc/ln/FromBTCLNSwap.d.ts +47 -31
  49. package/dist/swaps/escrow_swaps/frombtc/ln/FromBTCLNSwap.js +201 -67
  50. package/dist/swaps/escrow_swaps/frombtc/ln/FromBTCLNWrapper.d.ts +3 -1
  51. package/dist/swaps/escrow_swaps/frombtc/ln/FromBTCLNWrapper.js +6 -6
  52. package/dist/swaps/escrow_swaps/frombtc/ln_auto/FromBTCLNAutoSwap.d.ts +82 -15
  53. package/dist/swaps/escrow_swaps/frombtc/ln_auto/FromBTCLNAutoSwap.js +304 -98
  54. package/dist/swaps/escrow_swaps/frombtc/ln_auto/FromBTCLNAutoWrapper.d.ts +3 -1
  55. package/dist/swaps/escrow_swaps/frombtc/ln_auto/FromBTCLNAutoWrapper.js +6 -6
  56. package/dist/swaps/escrow_swaps/frombtc/onchain/FromBTCSwap.d.ts +75 -42
  57. package/dist/swaps/escrow_swaps/frombtc/onchain/FromBTCSwap.js +424 -87
  58. package/dist/swaps/escrow_swaps/frombtc/onchain/FromBTCWrapper.d.ts +3 -1
  59. package/dist/swaps/escrow_swaps/frombtc/onchain/FromBTCWrapper.js +7 -7
  60. package/dist/swaps/escrow_swaps/tobtc/IToBTCSwap.d.ts +54 -11
  61. package/dist/swaps/escrow_swaps/tobtc/IToBTCSwap.js +214 -41
  62. package/dist/swaps/escrow_swaps/tobtc/ln/ToBTCLNWrapper.d.ts +2 -1
  63. package/dist/swaps/escrow_swaps/tobtc/ln/ToBTCLNWrapper.js +7 -8
  64. package/dist/swaps/escrow_swaps/tobtc/onchain/ToBTCWrapper.d.ts +3 -1
  65. package/dist/swaps/escrow_swaps/tobtc/onchain/ToBTCWrapper.js +5 -5
  66. package/dist/swaps/spv_swaps/SpvFromBTCSwap.d.ts +76 -19
  67. package/dist/swaps/spv_swaps/SpvFromBTCSwap.js +290 -51
  68. package/dist/swaps/spv_swaps/SpvFromBTCWrapper.d.ts +3 -1
  69. package/dist/swaps/spv_swaps/SpvFromBTCWrapper.js +5 -5
  70. package/dist/swaps/trusted/ln/LnForGasSwap.d.ts +53 -12
  71. package/dist/swaps/trusted/ln/LnForGasSwap.js +163 -49
  72. package/dist/swaps/trusted/ln/LnForGasWrapper.js +1 -2
  73. package/dist/swaps/trusted/onchain/OnchainForGasSwap.d.ts +14 -13
  74. package/dist/swaps/trusted/onchain/OnchainForGasSwap.js +30 -47
  75. package/dist/swaps/trusted/onchain/OnchainForGasWrapper.d.ts +3 -1
  76. package/dist/swaps/trusted/onchain/OnchainForGasWrapper.js +4 -4
  77. package/dist/types/SwapExecutionAction.d.ts +141 -34
  78. package/dist/types/SwapExecutionAction.js +104 -0
  79. package/dist/types/SwapExecutionStep.d.ts +144 -0
  80. package/dist/types/SwapExecutionStep.js +87 -0
  81. package/dist/types/TokenAmount.d.ts +6 -0
  82. package/dist/types/TokenAmount.js +26 -1
  83. package/dist/utils/BitcoinUtils.d.ts +2 -0
  84. package/dist/utils/BitcoinUtils.js +34 -1
  85. package/dist/utils/Utils.d.ts +3 -1
  86. package/dist/utils/Utils.js +7 -1
  87. package/package.json +7 -4
  88. package/src/api/ApiEndpoints.ts +427 -0
  89. package/src/api/ApiParser.ts +138 -0
  90. package/src/api/ApiTypes.ts +229 -0
  91. package/src/api/SerializedAction.ts +97 -0
  92. package/src/api/SwapperApi.ts +545 -0
  93. package/src/api/index.ts +5 -0
  94. package/src/events/UnifiedSwapEventListener.ts +11 -3
  95. package/src/http/HttpUtils.ts +10 -4
  96. package/src/http/paramcoders/client/StreamingFetchPromise.ts +4 -2
  97. package/src/index.ts +1 -0
  98. package/src/intermediaries/IntermediaryDiscovery.ts +9 -2
  99. package/src/intermediaries/apis/IntermediaryAPI.ts +314 -30
  100. package/src/intermediaries/auth/SignedKeyBasedAuth.ts +69 -0
  101. package/src/storage/IUnifiedStorage.ts +45 -4
  102. package/src/storage/UnifiedSwapStorage.ts +42 -8
  103. package/src/swapper/Swapper.ts +134 -52
  104. package/src/swapper/SwapperUtils.ts +42 -2
  105. package/src/swaps/ISwap.ts +88 -16
  106. package/src/swaps/ISwapWrapper.ts +28 -3
  107. package/src/swaps/escrow_swaps/IEscrowSwap.ts +5 -3
  108. package/src/swaps/escrow_swaps/IEscrowSwapWrapper.ts +3 -1
  109. package/src/swaps/escrow_swaps/frombtc/IFromBTCLNWrapper.ts +4 -1
  110. package/src/swaps/escrow_swaps/frombtc/ln/FromBTCLNSwap.ts +264 -67
  111. package/src/swaps/escrow_swaps/frombtc/ln/FromBTCLNWrapper.ts +6 -4
  112. package/src/swaps/escrow_swaps/frombtc/ln_auto/FromBTCLNAutoSwap.ts +390 -89
  113. package/src/swaps/escrow_swaps/frombtc/ln_auto/FromBTCLNAutoWrapper.ts +6 -4
  114. package/src/swaps/escrow_swaps/frombtc/onchain/FromBTCSwap.ts +548 -94
  115. package/src/swaps/escrow_swaps/frombtc/onchain/FromBTCWrapper.ts +7 -5
  116. package/src/swaps/escrow_swaps/tobtc/IToBTCSwap.ts +276 -45
  117. package/src/swaps/escrow_swaps/tobtc/ln/ToBTCLNWrapper.ts +7 -6
  118. package/src/swaps/escrow_swaps/tobtc/onchain/ToBTCWrapper.ts +5 -3
  119. package/src/swaps/spv_swaps/SpvFromBTCSwap.ts +393 -57
  120. package/src/swaps/spv_swaps/SpvFromBTCWrapper.ts +5 -3
  121. package/src/swaps/trusted/ln/LnForGasSwap.ts +211 -47
  122. package/src/swaps/trusted/ln/LnForGasWrapper.ts +1 -2
  123. package/src/swaps/trusted/onchain/OnchainForGasSwap.ts +32 -51
  124. package/src/swaps/trusted/onchain/OnchainForGasWrapper.ts +5 -3
  125. package/src/types/SwapExecutionAction.ts +266 -43
  126. package/src/types/SwapExecutionStep.ts +224 -0
  127. package/src/types/TokenAmount.ts +36 -2
  128. package/src/utils/BitcoinUtils.ts +32 -0
  129. package/src/utils/Utils.ts +10 -1
  130. package/src/intermediaries/apis/TrustedIntermediaryAPI.ts +0 -258
@@ -497,66 +497,166 @@ class FromBTCLNSwap extends IFromBTCSelfInitSwap_1.IFromBTCSelfInitSwap {
497
497
  return true;
498
498
  }
499
499
  /**
500
- * @inheritDoc
501
- *
502
- * @param options
503
- * @param options.skipChecks Skip checks like making sure init signature is still valid and swap
504
- * wasn't commited yet (this is handled on swap creation, if you commit right after quoting, you
505
- * can use `skipChecks=true`)
506
- * @param options.secret A swap secret to use for the claim transaction, generally only needed if the swap
507
- * was recovered from on-chain data, or the pre-image was generated outside the SDK
500
+ * @internal
508
501
  */
509
- async txsExecute(options) {
510
- if (this._state === FromBTCLNSwapState.PR_CREATED) {
511
- if (!await this._verifyQuoteValid())
512
- throw new Error("Quote already expired or close to expiry!");
513
- return [
514
- {
515
- name: "Payment",
516
- description: "Initiates the swap by paying up the lightning network invoice",
517
- chain: "LIGHTNING",
518
- txs: [
519
- {
520
- type: "BOLT11_PAYMENT_REQUEST",
521
- address: this.getAddress(),
522
- hyperlink: this.getHyperlink()
523
- }
524
- ]
502
+ async _getExecutionStatus(options) {
503
+ if (options?.secret != null)
504
+ this.setSecretPreimage(options.secret);
505
+ const state = this._state;
506
+ let lightningPaymentStatus = "inactive";
507
+ let destinationSettlementStatus = "inactive";
508
+ let buildCurrentAction = async () => undefined;
509
+ switch (state) {
510
+ case FromBTCLNSwapState.PR_CREATED: {
511
+ const quoteValid = await this._verifyQuoteValid();
512
+ lightningPaymentStatus = quoteValid ? "awaiting" : "soft_expired";
513
+ if (quoteValid && this.pr != null && this.pr.toLowerCase().startsWith("ln")) {
514
+ buildCurrentAction = this._buildLightningPaymentAction.bind(this);
515
+ }
516
+ break;
517
+ }
518
+ case FromBTCLNSwapState.QUOTE_SOFT_EXPIRED:
519
+ if (this.signatureData == null) {
520
+ lightningPaymentStatus = "soft_expired";
521
+ }
522
+ else {
523
+ lightningPaymentStatus = "received";
524
+ destinationSettlementStatus = "soft_expired";
525
+ }
526
+ break;
527
+ case FromBTCLNSwapState.PR_PAID:
528
+ case FromBTCLNSwapState.CLAIM_COMMITED:
529
+ lightningPaymentStatus = "received";
530
+ destinationSettlementStatus = "awaiting_manual";
531
+ if ((state !== FromBTCLNSwapState.PR_PAID || await this._verifyQuoteValid()) &&
532
+ this.hasSecretPreimage()) {
533
+ buildCurrentAction = this._buildClaimSmartChainTxAction.bind(this);
525
534
  }
526
- ];
535
+ break;
536
+ case FromBTCLNSwapState.CLAIM_CLAIMED:
537
+ lightningPaymentStatus = "confirmed";
538
+ destinationSettlementStatus = "settled";
539
+ break;
540
+ case FromBTCLNSwapState.EXPIRED:
541
+ case FromBTCLNSwapState.FAILED:
542
+ lightningPaymentStatus = "expired";
543
+ destinationSettlementStatus = "expired";
544
+ break;
545
+ case FromBTCLNSwapState.QUOTE_EXPIRED:
546
+ if (this.signatureData == null) {
547
+ lightningPaymentStatus = "expired";
548
+ }
549
+ else {
550
+ lightningPaymentStatus = "expired";
551
+ destinationSettlementStatus = "expired";
552
+ }
553
+ break;
527
554
  }
528
- if (this._state === FromBTCLNSwapState.PR_PAID) {
529
- if (!await this._verifyQuoteValid())
530
- throw new Error("Quote already expired or close to expiry!");
531
- const txsCommit = await this.txsCommit(options?.skipChecks);
532
- const txsClaim = await this._txsClaim(undefined, options?.secret);
533
- return [
555
+ return {
556
+ steps: [
534
557
  {
535
- name: "Commit",
536
- description: `Creates the HTLC escrow on the ${this.chainIdentifier} side`,
537
- chain: this.chainIdentifier,
538
- txs: txsCommit
558
+ type: "Payment",
559
+ side: "source",
560
+ chain: "LIGHTNING",
561
+ title: "Lightning payment",
562
+ description: "Pay the Lightning network invoice to initiate the swap",
563
+ status: lightningPaymentStatus,
564
+ initTxId: this.getInputTxId(),
565
+ settleTxId: lightningPaymentStatus === "confirmed" ? this.getInputTxId() : undefined
539
566
  },
540
567
  {
541
- name: "Claim",
542
- description: `Settles & claims the funds from the HTLC escrow on the ${this.chainIdentifier} side`,
568
+ type: "Settlement",
569
+ side: "destination",
543
570
  chain: this.chainIdentifier,
544
- txs: txsClaim
545
- },
546
- ];
571
+ title: "Destination settlement",
572
+ description: `Manually settle the swap on the ${this.chainIdentifier} side`,
573
+ status: destinationSettlementStatus,
574
+ initTxId: this._commitTxId,
575
+ settleTxId: this._claimTxId
576
+ }
577
+ ],
578
+ buildCurrentAction,
579
+ state
580
+ };
581
+ }
582
+ /**
583
+ * @internal
584
+ */
585
+ async _buildLightningPaymentAction() {
586
+ return {
587
+ type: "SendToAddress",
588
+ name: "Deposit on Lightning",
589
+ description: "Pay the lightning network invoice to initiate the swap",
590
+ chain: "LIGHTNING",
591
+ txs: [{
592
+ type: "BOLT11_PAYMENT_REQUEST",
593
+ address: this.getAddress(),
594
+ hyperlink: this.getHyperlink(),
595
+ amount: this.getInput()
596
+ }],
597
+ waitForTransactions: async (maxWaitTimeSeconds, pollIntervalSeconds, abortSignal) => {
598
+ const abortController = (0, Utils_1.extendAbortController)(abortSignal, maxWaitTimeSeconds, "Timed out waiting for lightning payment");
599
+ const success = await this.waitForPayment(undefined, pollIntervalSeconds, abortController.signal);
600
+ if (!success)
601
+ throw new Error("Quote expired while waiting for Lightning payment");
602
+ return this.getInputTxId();
603
+ }
604
+ };
605
+ }
606
+ /**
607
+ * @inheritDoc
608
+ * @internal
609
+ */
610
+ async _submitExecutionTransactions(txs, abortSignal, requiredStates, idempotent) {
611
+ const parsedTxs = [];
612
+ for (let tx of txs) {
613
+ parsedTxs.push(typeof (tx) === "string" ? await this.wrapper._chain.deserializeSignedTx(tx) : tx);
614
+ }
615
+ if (idempotent) {
616
+ // Handle idempotent calls
617
+ if (this.wrapper._chain.getTxId != null) {
618
+ const txIds = await Promise.all(parsedTxs.map(tx => this.wrapper._chain.getTxId(tx)));
619
+ const foundTxId = txIds.find(txId => this._commitTxId === txId || this._claimTxId === txId);
620
+ if (foundTxId != null)
621
+ return txIds;
622
+ }
623
+ }
624
+ if (requiredStates != null && !requiredStates.includes(this._state))
625
+ throw new Error("Swap state has changed before transactions were submitted!");
626
+ if (this._state === FromBTCLNSwapState.PR_PAID || this._state === FromBTCLNSwapState.QUOTE_SOFT_EXPIRED) {
627
+ if (!await this._verifyQuoteValid())
628
+ throw new Error("Quote is already expired!");
629
+ const txIds = await this.wrapper._chain.sendSignedAndConfirm(parsedTxs, true, abortSignal, false);
630
+ await this.waitTillCommited(abortSignal);
631
+ await this.waitTillClaimed(undefined, abortSignal);
632
+ return txIds;
547
633
  }
548
634
  if (this._state === FromBTCLNSwapState.CLAIM_COMMITED) {
549
- const txsClaim = await this.txsClaim(undefined, options?.secret);
550
- return [
551
- {
552
- name: "Claim",
553
- description: `Settles & claims the funds from the HTLC escrow on the ${this.chainIdentifier} side`,
554
- chain: this.chainIdentifier,
555
- txs: txsClaim
556
- },
557
- ];
635
+ const txIds = await this.wrapper._chain.sendSignedAndConfirm(parsedTxs, true, abortSignal, false);
636
+ await this.waitTillClaimed(undefined, abortSignal);
637
+ return txIds;
558
638
  }
559
- throw new Error("Invalid swap state to obtain execution txns, required PR_CREATED, PR_PAID or CLAIM_COMMITED");
639
+ throw new Error("Invalid swap state for transaction submission!");
640
+ }
641
+ /**
642
+ * @internal
643
+ */
644
+ async _buildClaimSmartChainTxAction(actionOptions) {
645
+ return {
646
+ type: "SignSmartChainTransaction",
647
+ name: "Settle manually",
648
+ description: "Create the HTLC escrow and settle the swap on the destination smart chain",
649
+ chain: this.chainIdentifier,
650
+ txs: await this.prepareTransactions(this.txsCommitAndClaim(actionOptions?.skipChecks, actionOptions?.secret)),
651
+ submitTransactions: async (txs, abortSignal, idempotent) => {
652
+ return this._submitExecutionTransactions(txs, abortSignal, [
653
+ FromBTCLNSwapState.PR_PAID,
654
+ FromBTCLNSwapState.QUOTE_SOFT_EXPIRED,
655
+ FromBTCLNSwapState.CLAIM_COMMITED
656
+ ], idempotent);
657
+ },
658
+ requiredSigner: this._getInitiator()
659
+ };
560
660
  }
561
661
  /**
562
662
  * @inheritDoc
@@ -568,13 +668,27 @@ class FromBTCLNSwap extends IFromBTCSelfInitSwap_1.IFromBTCSelfInitSwap {
568
668
  * @param options.secret A swap secret to use for the claim transaction, generally only needed if the swap
569
669
  * was recovered from on-chain data, or the pre-image was generated outside the SDK
570
670
  */
571
- async getCurrentActions(options) {
572
- try {
573
- return await this.txsExecute(options);
574
- }
575
- catch (e) {
576
- return [];
577
- }
671
+ async getExecutionAction(options) {
672
+ const executionStatus = await this._getExecutionStatus(options);
673
+ return executionStatus.buildCurrentAction(options);
674
+ }
675
+ /**
676
+ * @inheritDoc
677
+ */
678
+ // TODO: Figure how we gonna trigger an LNURL-withdraw with the execution actions
679
+ async getExecutionStatus(options) {
680
+ const executionStatus = await this._getExecutionStatus(options);
681
+ return {
682
+ steps: executionStatus.steps,
683
+ currentAction: options?.skipBuildingAction ? undefined : await executionStatus.buildCurrentAction(options),
684
+ stateInfo: this._getStateInfo(executionStatus.state)
685
+ };
686
+ }
687
+ /**
688
+ * @inheritDoc
689
+ */
690
+ async getExecutionSteps() {
691
+ return (await this._getExecutionStatus()).steps;
578
692
  }
579
693
  //////////////////////////////
580
694
  //// Payment
@@ -599,7 +713,7 @@ class FromBTCLNSwap extends IFromBTCSelfInitSwap_1.IFromBTCSelfInitSwap {
599
713
  const paymentHash = this.getPaymentHash();
600
714
  if (paymentHash == null)
601
715
  throw new Error("Failed to check LP payment received, payment hash not known (probably recovered swap?)");
602
- const resp = await IntermediaryAPI_1.IntermediaryAPI.getPaymentAuthorization(this.url, paymentHash.toString("hex"));
716
+ const resp = await this.wrapper._lpApi.getPaymentAuthorization(this.url, paymentHash.toString("hex"));
603
717
  switch (resp.code) {
604
718
  case IntermediaryAPI_1.PaymentAuthorizationResponseCodes.AUTH_DATA:
605
719
  const data = new (this.wrapper._swapDataDeserializer(this._contractVersion))(resp.data.data);
@@ -722,7 +836,7 @@ class FromBTCLNSwap extends IFromBTCSelfInitSwap_1.IFromBTCSelfInitSwap {
722
836
  throw new Error("Swap payment hash not available, the swap was probably recovered!");
723
837
  let resp = { code: IntermediaryAPI_1.PaymentAuthorizationResponseCodes.PENDING, msg: "" };
724
838
  while (!abortController.signal.aborted && resp.code === IntermediaryAPI_1.PaymentAuthorizationResponseCodes.PENDING) {
725
- resp = await IntermediaryAPI_1.IntermediaryAPI.getPaymentAuthorization(this.url, paymentHash.toString("hex"));
839
+ resp = await this.wrapper._lpApi.getPaymentAuthorization(this.url, paymentHash.toString("hex"));
726
840
  if (resp.code === IntermediaryAPI_1.PaymentAuthorizationResponseCodes.PENDING)
727
841
  await (0, TimeoutUtils_1.timeoutPromise)(checkIntervalSeconds * 1000, abortController.signal);
728
842
  }
@@ -792,11 +906,13 @@ class FromBTCLNSwap extends IFromBTCSelfInitSwap_1.IFromBTCSelfInitSwap {
792
906
  this.waitTillState(FromBTCLNSwapState.CLAIM_COMMITED, "gte", abortController.signal).then(() => 0)
793
907
  ]);
794
908
  abortController.abort();
795
- if (result === 0)
909
+ if (result === 0) {
796
910
  this.logger.debug("waitTillCommited(): Resolved from state changed");
797
- if (result === true)
911
+ }
912
+ else if (result != null) {
798
913
  this.logger.debug("waitTillCommited(): Resolved from watchdog - commited");
799
- if (result === false) {
914
+ }
915
+ if (result === null) {
800
916
  this.logger.debug("waitTillCommited(): Resolved from watchdog - signature expired");
801
917
  if (this._state === FromBTCLNSwapState.PR_PAID ||
802
918
  this._state === FromBTCLNSwapState.QUOTE_SOFT_EXPIRED) {
@@ -806,6 +922,8 @@ class FromBTCLNSwap extends IFromBTCSelfInitSwap_1.IFromBTCSelfInitSwap {
806
922
  }
807
923
  if (this._state === FromBTCLNSwapState.PR_PAID ||
808
924
  this._state === FromBTCLNSwapState.QUOTE_SOFT_EXPIRED) {
925
+ if (typeof (result) === "object" && result.getInitTxId != null && this._commitTxId == null)
926
+ this._commitTxId = await result.getInitTxId();
809
927
  await this._saveAndEmit(FromBTCLNSwapState.CLAIM_COMMITED);
810
928
  }
811
929
  }
@@ -1208,6 +1326,8 @@ class FromBTCLNSwap extends IFromBTCSelfInitSwap_1.IFromBTCSelfInitSwap {
1208
1326
  async _forciblySetOnchainState(commitStatus) {
1209
1327
  switch (commitStatus.type) {
1210
1328
  case base_1.SwapCommitStateType.PAID:
1329
+ if (this._commitTxId == null && commitStatus.getInitTxId != null)
1330
+ this._commitTxId = await commitStatus.getInitTxId();
1211
1331
  if (this._claimTxId == null)
1212
1332
  this._claimTxId = await commitStatus.getClaimTxId();
1213
1333
  if (this.secret == null || this.pr == null)
@@ -1215,24 +1335,38 @@ class FromBTCLNSwap extends IFromBTCSelfInitSwap_1.IFromBTCSelfInitSwap {
1215
1335
  this._state = FromBTCLNSwapState.CLAIM_CLAIMED;
1216
1336
  return true;
1217
1337
  case base_1.SwapCommitStateType.NOT_COMMITED:
1218
- if (this._refundTxId == null && commitStatus.getRefundTxId)
1338
+ let changed = false;
1339
+ if (this._commitTxId == null && commitStatus.getInitTxId != null) {
1340
+ this._commitTxId = await commitStatus.getInitTxId();
1341
+ changed = true;
1342
+ }
1343
+ if (this._refundTxId == null && commitStatus.getRefundTxId) {
1219
1344
  this._refundTxId = await commitStatus.getRefundTxId();
1345
+ changed = true;
1346
+ }
1220
1347
  if (this._refundTxId != null) {
1221
1348
  this._state = FromBTCLNSwapState.FAILED;
1222
- return true;
1349
+ changed = true;
1223
1350
  }
1224
- break;
1351
+ return changed;
1225
1352
  case base_1.SwapCommitStateType.EXPIRED:
1353
+ if (this._commitTxId == null && commitStatus.getInitTxId != null)
1354
+ this._commitTxId = await commitStatus.getInitTxId();
1226
1355
  if (this._refundTxId == null && commitStatus.getRefundTxId)
1227
1356
  this._refundTxId = await commitStatus.getRefundTxId();
1228
1357
  this._state = this._refundTxId == null ? FromBTCLNSwapState.QUOTE_EXPIRED : FromBTCLNSwapState.FAILED;
1229
1358
  return true;
1230
1359
  case base_1.SwapCommitStateType.COMMITED:
1360
+ let save = false;
1361
+ if (this._commitTxId == null && commitStatus.getInitTxId != null) {
1362
+ this._commitTxId = await commitStatus.getInitTxId();
1363
+ save = true;
1364
+ }
1231
1365
  if (this._state !== FromBTCLNSwapState.CLAIM_COMMITED && this._state !== FromBTCLNSwapState.EXPIRED) {
1232
1366
  this._state = FromBTCLNSwapState.CLAIM_COMMITED;
1233
- return true;
1367
+ save = true;
1234
1368
  }
1235
- break;
1369
+ return save;
1236
1370
  }
1237
1371
  return false;
1238
1372
  }
@@ -6,6 +6,7 @@ import { ChainType, ClaimEvent, InitializeEvent, LightningNetworkApi, RefundEven
6
6
  import { Intermediary } from "../../../../intermediaries/Intermediary";
7
7
  import { Buffer } from "buffer";
8
8
  import { SwapType } from "../../../../enums/SwapType";
9
+ import { IntermediaryAPI } from "../../../../intermediaries/apis/IntermediaryAPI";
9
10
  import { ISwapPrice } from "../../../../prices/abstract/ISwapPrice";
10
11
  import { EventEmitter } from "events";
11
12
  import { ISwapWrapperOptions, WrapperCtorTokens } from "../../../ISwapWrapper";
@@ -83,6 +84,7 @@ export declare class FromBTCLNWrapper<T extends ChainType> extends IFromBTCLNWra
83
84
  * @param tokens
84
85
  * @param versionedContracts
85
86
  * @param lnApi
87
+ * @param lpApi
86
88
  * @param options
87
89
  * @param events Instance to use for emitting events
88
90
  */
@@ -91,7 +93,7 @@ export declare class FromBTCLNWrapper<T extends ChainType> extends IFromBTCLNWra
91
93
  swapContract: T["Contract"];
92
94
  swapDataConstructor: new (data: any) => T["Data"];
93
95
  };
94
- }, lnApi: LightningNetworkApi, options?: AllOptional<FromBTCLNWrapperOptions>, events?: EventEmitter<{
96
+ }, lnApi: LightningNetworkApi, lpApi: IntermediaryAPI, options?: AllOptional<FromBTCLNWrapperOptions>, events?: EventEmitter<{
95
97
  swapState: [ISwap];
96
98
  }>);
97
99
  /**
@@ -10,7 +10,6 @@ const UserError_1 = require("../../../../errors/UserError");
10
10
  const IntermediaryError_1 = require("../../../../errors/IntermediaryError");
11
11
  const SwapType_1 = require("../../../../enums/SwapType");
12
12
  const Utils_1 = require("../../../../utils/Utils");
13
- const IntermediaryAPI_1 = require("../../../../intermediaries/apis/IntermediaryAPI");
14
13
  const RequestError_1 = require("../../../../errors/RequestError");
15
14
  const IFromBTCLNWrapper_1 = require("../IFromBTCLNWrapper");
16
15
  const RetryUtils_1 = require("../../../../utils/RetryUtils");
@@ -31,11 +30,12 @@ class FromBTCLNWrapper extends IFromBTCLNWrapper_1.IFromBTCLNWrapper {
31
30
  * @param tokens
32
31
  * @param versionedContracts
33
32
  * @param lnApi
33
+ * @param lpApi
34
34
  * @param options
35
35
  * @param events Instance to use for emitting events
36
36
  */
37
- constructor(chainIdentifier, unifiedStorage, unifiedChainEvents, chain, prices, tokens, versionedContracts, lnApi, options, events) {
38
- super(chainIdentifier, unifiedStorage, unifiedChainEvents, chain, prices, tokens, versionedContracts, lnApi, {
37
+ constructor(chainIdentifier, unifiedStorage, unifiedChainEvents, chain, prices, tokens, versionedContracts, lnApi, lpApi, options, events) {
38
+ super(chainIdentifier, unifiedStorage, unifiedChainEvents, chain, prices, tokens, versionedContracts, lnApi, lpApi, {
39
39
  ...options,
40
40
  safetyFactor: options?.safetyFactor ?? 2,
41
41
  bitcoinBlocktime: options?.bitcoinBlocktime ?? 10 * 60,
@@ -193,7 +193,7 @@ class FromBTCLNWrapper extends IFromBTCLNWrapper_1.IFromBTCLNWrapper {
193
193
  const abortController = (0, Utils_1.extendAbortController)(_abortController.signal);
194
194
  const liquidityPromise = this.preFetchIntermediaryLiquidity(amountData, lp, abortController, version);
195
195
  const { lnCapacityPromise, resp } = await (0, RetryUtils_1.tryWithRetries)(async (retryCount) => {
196
- const { lnPublicKey, response } = IntermediaryAPI_1.IntermediaryAPI.initFromBTCLN(this.chainIdentifier, lp.url, nativeTokenAddress, {
196
+ const { lnPublicKey, response } = this._lpApi.initFromBTCLN(this.chainIdentifier, lp.url, nativeTokenAddress, {
197
197
  paymentHash,
198
198
  amount: amountData.amount,
199
199
  claimer: recipient,
@@ -201,7 +201,7 @@ class FromBTCLNWrapper extends IFromBTCLNWrapper_1.IFromBTCLNWrapper {
201
201
  description: _options.description,
202
202
  descriptionHash: _options.descriptionHash,
203
203
  exactOut: !amountData.exactIn,
204
- feeRate: (0, Utils_1.throwIfUndefined)(_preFetches.feeRatePromise[version]),
204
+ feeRate: (0, Utils_1.throwIfUndefined)(_preFetches.feeRatePromise[version], "Network fee rate pre-fetch failed!"),
205
205
  additionalParams
206
206
  }, this._options.postRequestTimeout, abortController.signal, retryCount > 0 ? false : undefined);
207
207
  let lnCapacityPromise;
@@ -226,7 +226,7 @@ class FromBTCLNWrapper extends IFromBTCLNWrapper_1.IFromBTCLNWrapper {
226
226
  this.verifyReturnedData(resp, amountData, lp, _options, decodedPr, paymentHash);
227
227
  const [pricingInfo] = await Promise.all([
228
228
  this.verifyReturnedPrice(lp.services[SwapType_1.SwapType.FROM_BTCLN], false, amountIn, resp.total, amountData.token, { swapFeeBtc }, _preFetches.pricePrefetchPromise, _preFetches.usdPricePrefetchPromise, abortController.signal),
229
- this.verifyIntermediaryLiquidity(resp.total, (0, Utils_1.throwIfUndefined)(liquidityPromise)),
229
+ this.verifyIntermediaryLiquidity(resp.total, (0, Utils_1.throwIfUndefined)(liquidityPromise, "LP liquidity pre-fetch failed!")),
230
230
  lnCapacityPromise != null ? this.verifyLnNodeCapacity(lp, decodedPr, lnCapacityPromise, abortController.signal) : Promise.resolve()
231
231
  ]);
232
232
  const quote = new FromBTCLNSwap_1.FromBTCLNSwap(this, {
@@ -16,7 +16,9 @@ import { BtcToken, SCToken } from "../../../../types/Token";
16
16
  import { LoggerType } from "../../../../utils/Logger";
17
17
  import { LNURLWithdraw } from "../../../../types/lnurl/LNURLWithdraw";
18
18
  import { PriceInfoType } from "../../../../types/PriceInfoType";
19
- import { SwapExecutionAction } from "../../../../types/SwapExecutionAction";
19
+ import { SwapExecutionActionSendToAddress, SwapExecutionActionSignSmartChainTx, SwapExecutionActionWait } from "../../../../types/SwapExecutionAction";
20
+ import { SwapExecutionStepPayment, SwapExecutionStepSettlement } from "../../../../types/SwapExecutionStep";
21
+ import { SwapStateInfo } from "../../../../types/SwapStateInfo";
20
22
  /**
21
23
  * State enum for FromBTCLNAuto swaps
22
24
  * @category Swaps/Lightning → Smart chain
@@ -368,7 +370,7 @@ export declare class FromBTCLNAutoSwap<T extends ChainType = ChainType> extends
368
370
  *
369
371
  * @throws {Error} If an invalid secret preimage is provided
370
372
  */
371
- setSecretPreimage(secret: string): void;
373
+ setSecretPreimage(secret: string): Promise<void>;
372
374
  /**
373
375
  * Returns whether the secret preimage for this swap is known
374
376
  */
@@ -395,19 +397,40 @@ export declare class FromBTCLNAutoSwap<T extends ChainType = ChainType> extends
395
397
  maxWaitTillAutomaticSettlementSeconds?: number;
396
398
  secret?: string;
397
399
  }): Promise<boolean>;
400
+ /**
401
+ * @internal
402
+ */
403
+ protected _getExecutionStatus(options?: {
404
+ maxWaitTillAutomaticSettlementSeconds?: number;
405
+ secret?: string;
406
+ }): Promise<{
407
+ steps: [SwapExecutionStepPayment<"LIGHTNING">, SwapExecutionStepSettlement<T["ChainId"], "awaiting_automatic" | "awaiting_manual">];
408
+ buildCurrentAction: (actionOptions?: {
409
+ manualSettlementSmartChainSigner?: string | T["Signer"] | T["NativeSigner"];
410
+ }) => Promise<SwapExecutionActionSendToAddress<true> | SwapExecutionActionWait<"LP" | "SETTLEMENT"> | SwapExecutionActionSignSmartChainTx<T> | undefined>;
411
+ state: number;
412
+ }>;
413
+ /**
414
+ * @internal
415
+ */
416
+ private _buildLightningPaymentAction;
417
+ /**
418
+ * @internal
419
+ */
420
+ private _buildWaitLpAction;
421
+ /**
422
+ * @internal
423
+ */
424
+ private _buildWaitSettlementAction;
398
425
  /**
399
426
  * @inheritDoc
427
+ * @internal
400
428
  */
401
- txsExecute(): Promise<{
402
- name: "Payment";
403
- description: string;
404
- chain: "LIGHTNING";
405
- txs: {
406
- type: "BOLT11_PAYMENT_REQUEST";
407
- address: string;
408
- hyperlink: string;
409
- }[];
410
- }[]>;
429
+ _submitExecutionTransactions(txs: (T["SignedTXType"] | string)[], abortSignal?: AbortSignal, requiredStates?: FromBTCLNAutoSwapState[], idempotent?: boolean): Promise<string[]>;
430
+ /**
431
+ * @internal
432
+ */
433
+ private _buildClaimSmartChainTxAction;
411
434
  /**
412
435
  *
413
436
  * @param options.manualSettlementSmartChainSigner Optional smart chain signer to create a manual claim (settlement) transaction
@@ -416,11 +439,36 @@ export declare class FromBTCLNAutoSwap<T extends ChainType = ChainType> extends
416
439
  * @param options.secret A swap secret to broadcast to watchtowers, generally only needed if the swap
417
440
  * was recovered from on-chain data, or the pre-image was generated outside the SDK
418
441
  */
419
- getCurrentActions(options?: {
442
+ getExecutionAction(options?: {
420
443
  manualSettlementSmartChainSigner?: string | T["Signer"] | T["NativeSigner"];
421
444
  maxWaitTillAutomaticSettlementSeconds?: number;
422
445
  secret?: string;
423
- }): Promise<SwapExecutionAction<T>[]>;
446
+ }): Promise<SwapExecutionActionSendToAddress<true> | SwapExecutionActionWait<"LP" | "SETTLEMENT"> | SwapExecutionActionSignSmartChainTx<T> | undefined>;
447
+ /**
448
+ * @inheritDoc
449
+ */
450
+ getExecutionStatus(options?: {
451
+ skipBuildingAction?: boolean;
452
+ manualSettlementSmartChainSigner?: string | T["Signer"] | T["NativeSigner"];
453
+ maxWaitTillAutomaticSettlementSeconds?: number;
454
+ secret?: string;
455
+ }): Promise<{
456
+ steps: [
457
+ SwapExecutionStepPayment<"LIGHTNING">,
458
+ SwapExecutionStepSettlement<T["ChainId"], "awaiting_automatic" | "awaiting_manual">
459
+ ];
460
+ currentAction: SwapExecutionActionSendToAddress<true> | SwapExecutionActionWait<"LP" | "SETTLEMENT"> | SwapExecutionActionSignSmartChainTx<T> | undefined;
461
+ stateInfo: SwapStateInfo<FromBTCLNAutoSwapState>;
462
+ }>;
463
+ /**
464
+ * @inheritDoc
465
+ */
466
+ getExecutionSteps(options?: {
467
+ maxWaitTillAutomaticSettlementSeconds?: number;
468
+ }): Promise<[
469
+ SwapExecutionStepPayment<"LIGHTNING">,
470
+ SwapExecutionStepSettlement<T["ChainId"], "awaiting_automatic" | "awaiting_manual">
471
+ ]>;
424
472
  /**
425
473
  * Checks whether the LP received the LN payment
426
474
  *
@@ -439,6 +487,24 @@ export declare class FromBTCLNAutoSwap<T extends ChainType = ChainType> extends
439
487
  * @internal
440
488
  */
441
489
  _saveRealSwapData(data: T["Data"], save?: boolean): Promise<boolean>;
490
+ /**
491
+ * Waits till a lightning network payment is received by the intermediary, and the intermediary
492
+ * initiates the swap HTLC on the smart chain side. After the HTLC is initiated you can wait
493
+ * for an automatic settlement by the watchtowers with the {@link waitTillClaimed} function,
494
+ * or settle manually using the {@link claim} or {@link txsClaim} functions.
495
+ *
496
+ * If this swap is using an LNURL-withdraw link as input, it automatically posts the
497
+ * generated invoice to the LNURL service to pay it.
498
+ *
499
+ * @remarks For internal use, rather use {@link waitForPayment} which properly waits till the LP also
500
+ * offers a swap HTLC.
501
+ *
502
+ * @param abortSignal Abort signal to stop waiting for payment
503
+ * @param checkIntervalSeconds How often to poll the intermediary for answer (default 5 seconds)
504
+ *
505
+ * @internal
506
+ */
507
+ _waitForLpPaymentReceived(checkIntervalSeconds?: number, abortSignal?: AbortSignal): Promise<boolean>;
442
508
  /**
443
509
  * Checks the data returned by the intermediary in the payment auth request
444
510
  *
@@ -501,12 +567,13 @@ export declare class FromBTCLNAutoSwap<T extends ChainType = ChainType> extends
501
567
  * @param abortSignal AbortSignal
502
568
  * @param secret A swap secret to broadcast to watchtowers, generally only needed if the swap
503
569
  * was recovered from on-chain data, or the pre-image was generated outside the SDK
570
+ * @param pollIntervalSeconds How often to poll via the watchdog
504
571
  *
505
572
  * @throws {Error} If swap is in invalid state (must be {@link FromBTCLNAutoSwapState.CLAIM_COMMITED})
506
573
  * @throws {Error} If the LP refunded sooner than we were able to claim
507
574
  * @returns {boolean} whether the swap was claimed in time or not
508
575
  */
509
- waitTillClaimed(maxWaitTimeSeconds?: number, abortSignal?: AbortSignal, secret?: string): Promise<boolean>;
576
+ waitTillClaimed(maxWaitTimeSeconds?: number, abortSignal?: AbortSignal, secret?: string, pollIntervalSeconds?: number): Promise<boolean>;
510
577
  /**
511
578
  * Whether this swap uses an LNURL-withdraw link
512
579
  */