@atomiqlabs/sdk 8.1.8 → 8.3.5

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 (261) hide show
  1. package/dist/bitcoin/coinselect2/utils.d.ts +6 -0
  2. package/dist/bitcoin/wallet/BitcoinWallet.d.ts +41 -5
  3. package/dist/bitcoin/wallet/BitcoinWallet.js +36 -1
  4. package/dist/bitcoin/wallet/IBitcoinWallet.d.ts +52 -2
  5. package/dist/bitcoin/wallet/IBitcoinWallet.js +2 -1
  6. package/dist/bitcoin/wallet/SingleAddressBitcoinWallet.d.ts +42 -7
  7. package/dist/bitcoin/wallet/SingleAddressBitcoinWallet.js +36 -1
  8. package/dist/enums/FeeType.d.ts +8 -1
  9. package/dist/enums/FeeType.js +8 -1
  10. package/dist/enums/SwapAmountType.d.ts +7 -0
  11. package/dist/enums/SwapAmountType.js +7 -0
  12. package/dist/enums/SwapDirection.d.ts +7 -0
  13. package/dist/enums/SwapDirection.js +7 -0
  14. package/dist/enums/SwapType.d.ts +62 -1
  15. package/dist/enums/SwapType.js +62 -1
  16. package/dist/errors/IntermediaryError.d.ts +4 -0
  17. package/dist/errors/IntermediaryError.js +1 -0
  18. package/dist/errors/RequestError.d.ts +15 -1
  19. package/dist/errors/RequestError.js +8 -0
  20. package/dist/errors/UserError.d.ts +1 -0
  21. package/dist/errors/UserError.js +1 -0
  22. package/dist/index.d.ts +5 -5
  23. package/dist/index.js +7 -6
  24. package/dist/intermediaries/Intermediary.d.ts +61 -14
  25. package/dist/intermediaries/Intermediary.js +38 -11
  26. package/dist/intermediaries/IntermediaryDiscovery.d.ts +62 -29
  27. package/dist/intermediaries/IntermediaryDiscovery.js +39 -24
  28. package/dist/prices/RedundantSwapPrice.d.ts +26 -5
  29. package/dist/prices/RedundantSwapPrice.js +22 -2
  30. package/dist/prices/SingleSwapPrice.d.ts +10 -7
  31. package/dist/prices/SingleSwapPrice.js +11 -8
  32. package/dist/prices/SwapPriceWithChain.d.ts +56 -19
  33. package/dist/prices/SwapPriceWithChain.js +62 -25
  34. package/dist/prices/abstract/IPriceProvider.d.ts +4 -4
  35. package/dist/prices/abstract/IPriceProvider.js +1 -1
  36. package/dist/prices/abstract/ISwapPrice.d.ts +95 -46
  37. package/dist/prices/abstract/ISwapPrice.js +104 -56
  38. package/dist/prices/providers/BinancePriceProvider.d.ts +8 -1
  39. package/dist/prices/providers/BinancePriceProvider.js +8 -1
  40. package/dist/prices/providers/CoinGeckoPriceProvider.d.ts +7 -1
  41. package/dist/prices/providers/CoinGeckoPriceProvider.js +7 -1
  42. package/dist/prices/providers/CoinPaprikaPriceProvider.d.ts +7 -1
  43. package/dist/prices/providers/CoinPaprikaPriceProvider.js +7 -1
  44. package/dist/prices/providers/CustomPriceProvider.d.ts +12 -1
  45. package/dist/prices/providers/CustomPriceProvider.js +12 -1
  46. package/dist/prices/providers/KrakenPriceProvider.d.ts +10 -1
  47. package/dist/prices/providers/KrakenPriceProvider.js +10 -1
  48. package/dist/prices/providers/OKXPriceProvider.d.ts +7 -1
  49. package/dist/prices/providers/OKXPriceProvider.js +7 -1
  50. package/dist/prices/providers/abstract/ExchangePriceProvider.d.ts +3 -0
  51. package/dist/prices/providers/abstract/ExchangePriceProvider.js +3 -0
  52. package/dist/storage/IUnifiedStorage.d.ts +19 -7
  53. package/dist/storage/UnifiedSwapStorage.d.ts +33 -3
  54. package/dist/storage/UnifiedSwapStorage.js +29 -1
  55. package/dist/storage-browser/IndexedDBUnifiedStorage.d.ts +31 -7
  56. package/dist/storage-browser/IndexedDBUnifiedStorage.js +29 -6
  57. package/dist/storage-browser/LocalStorageManager.d.ts +25 -1
  58. package/dist/storage-browser/LocalStorageManager.js +25 -1
  59. package/dist/swapper/Swapper.d.ts +380 -226
  60. package/dist/swapper/Swapper.js +383 -349
  61. package/dist/swapper/SwapperFactory.d.ts +66 -18
  62. package/dist/swapper/SwapperFactory.js +24 -3
  63. package/dist/swapper/SwapperUtils.d.ts +75 -28
  64. package/dist/swapper/SwapperUtils.js +107 -60
  65. package/dist/swapper/SwapperWithChain.d.ts +286 -91
  66. package/dist/swapper/SwapperWithChain.js +218 -64
  67. package/dist/swapper/SwapperWithSigner.d.ts +229 -80
  68. package/dist/swapper/SwapperWithSigner.js +190 -44
  69. package/dist/swaps/IAddressSwap.d.ts +12 -3
  70. package/dist/swaps/IAddressSwap.js +3 -2
  71. package/dist/swaps/IBTCWalletSwap.d.ts +26 -8
  72. package/dist/swaps/IBTCWalletSwap.js +3 -2
  73. package/dist/swaps/IClaimableSwap.d.ts +38 -6
  74. package/dist/swaps/IClaimableSwap.js +3 -2
  75. package/dist/swaps/IClaimableSwapWrapper.d.ts +11 -1
  76. package/dist/swaps/IRefundableSwap.d.ts +31 -5
  77. package/dist/swaps/IRefundableSwap.js +3 -2
  78. package/dist/swaps/ISwap.d.ts +162 -24
  79. package/dist/swaps/ISwap.js +92 -35
  80. package/dist/swaps/ISwapWithGasDrop.d.ts +8 -2
  81. package/dist/swaps/ISwapWithGasDrop.js +2 -1
  82. package/dist/swaps/ISwapWrapper.d.ts +161 -52
  83. package/dist/swaps/ISwapWrapper.js +131 -73
  84. package/dist/swaps/escrow_swaps/IEscrowSelfInitSwap.d.ts +51 -6
  85. package/dist/swaps/escrow_swaps/IEscrowSelfInitSwap.js +22 -12
  86. package/dist/swaps/escrow_swaps/IEscrowSwap.d.ts +65 -12
  87. package/dist/swaps/escrow_swaps/IEscrowSwap.js +38 -19
  88. package/dist/swaps/escrow_swaps/IEscrowSwapWrapper.d.ts +39 -9
  89. package/dist/swaps/escrow_swaps/IEscrowSwapWrapper.js +30 -21
  90. package/dist/swaps/escrow_swaps/frombtc/IFromBTCLNWrapper.d.ts +31 -15
  91. package/dist/swaps/escrow_swaps/frombtc/IFromBTCLNWrapper.js +33 -18
  92. package/dist/swaps/escrow_swaps/frombtc/IFromBTCSelfInitSwap.d.ts +97 -28
  93. package/dist/swaps/escrow_swaps/frombtc/IFromBTCSelfInitSwap.js +91 -27
  94. package/dist/swaps/escrow_swaps/frombtc/IFromBTCWrapper.d.ts +22 -9
  95. package/dist/swaps/escrow_swaps/frombtc/IFromBTCWrapper.js +24 -11
  96. package/dist/swaps/escrow_swaps/frombtc/ln/FromBTCLNSwap.d.ts +278 -60
  97. package/dist/swaps/escrow_swaps/frombtc/ln/FromBTCLNSwap.js +519 -241
  98. package/dist/swaps/escrow_swaps/frombtc/ln/FromBTCLNWrapper.d.ts +77 -26
  99. package/dist/swaps/escrow_swaps/frombtc/ln/FromBTCLNWrapper.js +132 -50
  100. package/dist/swaps/escrow_swaps/frombtc/ln_auto/FromBTCLNAutoSwap.d.ts +313 -52
  101. package/dist/swaps/escrow_swaps/frombtc/ln_auto/FromBTCLNAutoSwap.js +544 -194
  102. package/dist/swaps/escrow_swaps/frombtc/ln_auto/FromBTCLNAutoWrapper.d.ts +87 -26
  103. package/dist/swaps/escrow_swaps/frombtc/ln_auto/FromBTCLNAutoWrapper.js +147 -58
  104. package/dist/swaps/escrow_swaps/frombtc/onchain/FromBTCSwap.d.ts +222 -55
  105. package/dist/swaps/escrow_swaps/frombtc/onchain/FromBTCSwap.js +462 -244
  106. package/dist/swaps/escrow_swaps/frombtc/onchain/FromBTCWrapper.d.ts +77 -23
  107. package/dist/swaps/escrow_swaps/frombtc/onchain/FromBTCWrapper.js +116 -46
  108. package/dist/swaps/escrow_swaps/tobtc/IToBTCSwap.d.ts +195 -58
  109. package/dist/swaps/escrow_swaps/tobtc/IToBTCSwap.js +324 -191
  110. package/dist/swaps/escrow_swaps/tobtc/IToBTCWrapper.d.ts +30 -5
  111. package/dist/swaps/escrow_swaps/tobtc/IToBTCWrapper.js +44 -19
  112. package/dist/swaps/escrow_swaps/tobtc/ln/ToBTCLNSwap.d.ts +61 -20
  113. package/dist/swaps/escrow_swaps/tobtc/ln/ToBTCLNSwap.js +75 -32
  114. package/dist/swaps/escrow_swaps/tobtc/ln/ToBTCLNWrapper.d.ts +76 -50
  115. package/dist/swaps/escrow_swaps/tobtc/ln/ToBTCLNWrapper.js +106 -101
  116. package/dist/swaps/escrow_swaps/tobtc/onchain/ToBTCSwap.d.ts +37 -14
  117. package/dist/swaps/escrow_swaps/tobtc/onchain/ToBTCSwap.js +66 -20
  118. package/dist/swaps/escrow_swaps/tobtc/onchain/ToBTCWrapper.d.ts +46 -17
  119. package/dist/swaps/escrow_swaps/tobtc/onchain/ToBTCWrapper.js +82 -27
  120. package/dist/swaps/spv_swaps/SpvFromBTCSwap.d.ts +350 -88
  121. package/dist/swaps/spv_swaps/SpvFromBTCSwap.js +482 -215
  122. package/dist/swaps/spv_swaps/SpvFromBTCWrapper.d.ts +76 -24
  123. package/dist/swaps/spv_swaps/SpvFromBTCWrapper.js +247 -124
  124. package/dist/swaps/trusted/ln/LnForGasSwap.d.ts +148 -20
  125. package/dist/swaps/trusted/ln/LnForGasSwap.js +175 -45
  126. package/dist/swaps/trusted/ln/LnForGasWrapper.d.ts +29 -10
  127. package/dist/swaps/trusted/ln/LnForGasWrapper.js +30 -11
  128. package/dist/swaps/trusted/onchain/OnchainForGasSwap.d.ts +202 -49
  129. package/dist/swaps/trusted/onchain/OnchainForGasSwap.js +232 -80
  130. package/dist/swaps/trusted/onchain/OnchainForGasWrapper.d.ts +34 -12
  131. package/dist/swaps/trusted/onchain/OnchainForGasWrapper.js +33 -14
  132. package/dist/types/AmountData.d.ts +2 -1
  133. package/dist/types/CustomPriceFunction.d.ts +8 -2
  134. package/dist/types/PriceInfoType.d.ts +4 -4
  135. package/dist/types/PriceInfoType.js +3 -3
  136. package/dist/types/SwapExecutionAction.d.ts +85 -4
  137. package/dist/types/SwapWithSigner.d.ts +5 -2
  138. package/dist/types/SwapWithSigner.js +5 -2
  139. package/dist/types/Token.d.ts +11 -5
  140. package/dist/types/Token.js +6 -3
  141. package/dist/types/TokenAmount.d.ts +3 -0
  142. package/dist/types/TokenAmount.js +2 -0
  143. package/dist/types/fees/Fee.d.ts +3 -2
  144. package/dist/types/fees/FeeBreakdown.d.ts +3 -2
  145. package/dist/types/fees/PercentagePPM.d.ts +4 -2
  146. package/dist/types/fees/PercentagePPM.js +2 -1
  147. package/dist/types/lnurl/LNURLPay.d.ts +20 -12
  148. package/dist/types/lnurl/LNURLPay.js +8 -4
  149. package/dist/types/lnurl/LNURLWithdraw.d.ts +17 -10
  150. package/dist/types/lnurl/LNURLWithdraw.js +8 -4
  151. package/dist/types/wallets/LightningInvoiceCreateService.d.ts +24 -0
  152. package/dist/types/wallets/LightningInvoiceCreateService.js +15 -0
  153. package/dist/types/wallets/MinimalBitcoinWalletInterface.d.ts +3 -1
  154. package/dist/types/wallets/MinimalLightningNetworkWalletInterface.d.ts +4 -2
  155. package/dist/utils/BitcoinUtils.d.ts +1 -0
  156. package/dist/utils/BitcoinUtils.js +5 -1
  157. package/dist/utils/SwapUtils.d.ts +58 -1
  158. package/dist/utils/SwapUtils.js +55 -1
  159. package/dist/utils/TokenUtils.d.ts +10 -2
  160. package/dist/utils/TokenUtils.js +12 -4
  161. package/package.json +3 -3
  162. package/src/bitcoin/coinselect2/utils.ts +6 -0
  163. package/src/bitcoin/wallet/BitcoinWallet.ts +41 -5
  164. package/src/bitcoin/wallet/IBitcoinWallet.ts +57 -2
  165. package/src/bitcoin/wallet/SingleAddressBitcoinWallet.ts +42 -6
  166. package/src/enums/FeeType.ts +8 -1
  167. package/src/enums/SwapAmountType.ts +7 -0
  168. package/src/enums/SwapDirection.ts +7 -0
  169. package/src/enums/SwapType.ts +62 -2
  170. package/src/errors/IntermediaryError.ts +4 -0
  171. package/src/errors/RequestError.ts +15 -1
  172. package/src/errors/UserError.ts +1 -0
  173. package/src/index.ts +12 -5
  174. package/src/intermediaries/Intermediary.ts +61 -14
  175. package/src/intermediaries/IntermediaryDiscovery.ts +69 -34
  176. package/src/prices/RedundantSwapPrice.ts +26 -6
  177. package/src/prices/SingleSwapPrice.ts +11 -8
  178. package/src/prices/SwapPriceWithChain.ts +63 -26
  179. package/src/prices/abstract/IPriceProvider.ts +4 -4
  180. package/src/prices/abstract/ISwapPrice.ts +115 -66
  181. package/src/prices/providers/BinancePriceProvider.ts +8 -1
  182. package/src/prices/providers/CoinGeckoPriceProvider.ts +7 -1
  183. package/src/prices/providers/CoinPaprikaPriceProvider.ts +7 -1
  184. package/src/prices/providers/CustomPriceProvider.ts +12 -1
  185. package/src/prices/providers/KrakenPriceProvider.ts +10 -1
  186. package/src/prices/providers/OKXPriceProvider.ts +7 -1
  187. package/src/prices/providers/abstract/ExchangePriceProvider.ts +3 -0
  188. package/src/storage/IUnifiedStorage.ts +19 -7
  189. package/src/storage/UnifiedSwapStorage.ts +33 -3
  190. package/src/storage-browser/IndexedDBUnifiedStorage.ts +31 -8
  191. package/src/storage-browser/LocalStorageManager.ts +25 -1
  192. package/src/swapper/Swapper.ts +599 -390
  193. package/src/swapper/SwapperFactory.ts +73 -24
  194. package/src/swapper/SwapperUtils.ts +107 -60
  195. package/src/swapper/SwapperWithChain.ts +320 -81
  196. package/src/swapper/SwapperWithSigner.ts +263 -56
  197. package/src/swaps/IAddressSwap.ts +13 -3
  198. package/src/swaps/IBTCWalletSwap.ts +26 -10
  199. package/src/swaps/IClaimableSwap.ts +41 -6
  200. package/src/swaps/IClaimableSwapWrapper.ts +11 -2
  201. package/src/swaps/IRefundableSwap.ts +34 -5
  202. package/src/swaps/ISwap.ts +224 -85
  203. package/src/swaps/ISwapWithGasDrop.ts +8 -2
  204. package/src/swaps/ISwapWrapper.ts +216 -98
  205. package/src/swaps/escrow_swaps/IEscrowSelfInitSwap.ts +64 -18
  206. package/src/swaps/escrow_swaps/IEscrowSwap.ts +83 -37
  207. package/src/swaps/escrow_swaps/IEscrowSwapWrapper.ts +61 -30
  208. package/src/swaps/escrow_swaps/frombtc/IFromBTCLNWrapper.ts +37 -19
  209. package/src/swaps/escrow_swaps/frombtc/IFromBTCSelfInitSwap.ts +123 -50
  210. package/src/swaps/escrow_swaps/frombtc/IFromBTCWrapper.ts +24 -11
  211. package/src/swaps/escrow_swaps/frombtc/ln/FromBTCLNSwap.ts +562 -258
  212. package/src/swaps/escrow_swaps/frombtc/ln/FromBTCLNWrapper.ts +156 -62
  213. package/src/swaps/escrow_swaps/frombtc/ln_auto/FromBTCLNAutoSwap.ts +592 -227
  214. package/src/swaps/escrow_swaps/frombtc/ln_auto/FromBTCLNAutoWrapper.ts +177 -74
  215. package/src/swaps/escrow_swaps/frombtc/onchain/FromBTCSwap.ts +483 -245
  216. package/src/swaps/escrow_swaps/frombtc/onchain/FromBTCWrapper.ts +141 -59
  217. package/src/swaps/escrow_swaps/tobtc/IToBTCSwap.ts +350 -195
  218. package/src/swaps/escrow_swaps/tobtc/IToBTCWrapper.ts +48 -23
  219. package/src/swaps/escrow_swaps/tobtc/ln/ToBTCLNSwap.ts +87 -40
  220. package/src/swaps/escrow_swaps/tobtc/ln/ToBTCLNWrapper.ts +110 -110
  221. package/src/swaps/escrow_swaps/tobtc/onchain/ToBTCSwap.ts +89 -34
  222. package/src/swaps/escrow_swaps/tobtc/onchain/ToBTCWrapper.ts +101 -31
  223. package/src/swaps/spv_swaps/SpvFromBTCSwap.ts +556 -259
  224. package/src/swaps/spv_swaps/SpvFromBTCWrapper.ts +292 -148
  225. package/src/swaps/trusted/ln/LnForGasSwap.ts +186 -47
  226. package/src/swaps/trusted/ln/LnForGasWrapper.ts +34 -15
  227. package/src/swaps/trusted/onchain/OnchainForGasSwap.ts +262 -88
  228. package/src/swaps/trusted/onchain/OnchainForGasWrapper.ts +41 -19
  229. package/src/types/AmountData.ts +2 -1
  230. package/src/types/CustomPriceFunction.ts +8 -2
  231. package/src/types/PriceInfoType.ts +4 -4
  232. package/src/types/SwapExecutionAction.ts +97 -5
  233. package/src/types/SwapWithSigner.ts +8 -4
  234. package/src/types/Token.ts +12 -5
  235. package/src/types/TokenAmount.ts +3 -0
  236. package/src/types/fees/Fee.ts +3 -2
  237. package/src/types/fees/FeeBreakdown.ts +3 -2
  238. package/src/types/fees/PercentagePPM.ts +4 -2
  239. package/src/types/lnurl/LNURLPay.ts +20 -12
  240. package/src/types/lnurl/LNURLWithdraw.ts +17 -10
  241. package/src/types/wallets/LightningInvoiceCreateService.ts +30 -0
  242. package/src/types/wallets/MinimalBitcoinWalletInterface.ts +3 -1
  243. package/src/types/wallets/MinimalLightningNetworkWalletInterface.ts +4 -2
  244. package/src/utils/BitcoinUtils.ts +5 -0
  245. package/src/utils/SwapUtils.ts +63 -1
  246. package/src/utils/TokenUtils.ts +12 -4
  247. package/dist/bitcoin/BitcoinRpcWithAddressIndex.d.ts +0 -68
  248. package/dist/bitcoin/BitcoinRpcWithAddressIndex.js +0 -2
  249. package/dist/bitcoin/LightningNetworkApi.d.ts +0 -12
  250. package/dist/bitcoin/LightningNetworkApi.js +0 -2
  251. package/dist/bitcoin/mempool/MempoolApi.d.ts +0 -350
  252. package/dist/bitcoin/mempool/MempoolApi.js +0 -311
  253. package/dist/bitcoin/mempool/MempoolBitcoinBlock.d.ts +0 -44
  254. package/dist/bitcoin/mempool/MempoolBitcoinBlock.js +0 -48
  255. package/dist/bitcoin/mempool/MempoolBitcoinRpc.d.ts +0 -119
  256. package/dist/bitcoin/mempool/MempoolBitcoinRpc.js +0 -361
  257. package/dist/bitcoin/mempool/synchronizer/MempoolBtcRelaySynchronizer.d.ts +0 -22
  258. package/dist/bitcoin/mempool/synchronizer/MempoolBtcRelaySynchronizer.js +0 -105
  259. package/dist/errors/PaymentAuthError.d.ts +0 -11
  260. package/dist/errors/PaymentAuthError.js +0 -23
  261. package/src/errors/PaymentAuthError.ts +0 -26
@@ -17,56 +17,107 @@ const Token_1 = require("../../../../types/Token");
17
17
  const Logger_1 = require("../../../../utils/Logger");
18
18
  const TimeoutUtils_1 = require("../../../../utils/TimeoutUtils");
19
19
  const LNURLWithdraw_1 = require("../../../../types/lnurl/LNURLWithdraw");
20
+ const sha2_1 = require("@noble/hashes/sha2");
20
21
  /**
21
- * State enum for FromBTCLN swaps
22
- * @category Swaps
22
+ * State enum for legacy Lightning -> Smart chain swaps
23
+ * @category Swaps/Legacy/Lightning → Smart chain
23
24
  */
24
25
  var FromBTCLNSwapState;
25
26
  (function (FromBTCLNSwapState) {
27
+ /**
28
+ * Swap has failed as the user didn't settle the HTLC on the destination before expiration
29
+ */
26
30
  FromBTCLNSwapState[FromBTCLNSwapState["FAILED"] = -4] = "FAILED";
31
+ /**
32
+ * Swap has expired for good and there is no way how it can be executed anymore
33
+ */
27
34
  FromBTCLNSwapState[FromBTCLNSwapState["QUOTE_EXPIRED"] = -3] = "QUOTE_EXPIRED";
35
+ /**
36
+ * A swap is almost expired, and it should be presented to the user as expired, though
37
+ * there is still a chance that it will be processed
38
+ */
28
39
  FromBTCLNSwapState[FromBTCLNSwapState["QUOTE_SOFT_EXPIRED"] = -2] = "QUOTE_SOFT_EXPIRED";
40
+ /**
41
+ * Swap HTLC on the destination chain has expired, it is not safe anymore to settle (claim) the
42
+ * swap on the destination smart chain.
43
+ */
29
44
  FromBTCLNSwapState[FromBTCLNSwapState["EXPIRED"] = -1] = "EXPIRED";
45
+ /**
46
+ * Swap quote was created, use {@link FromBTCLNSwap.getAddress} or {@link FromBTCLNSwap.getHyperlink}
47
+ * to get the bolt11 lightning network invoice to pay to initiate the swap, then use the
48
+ * {@link FromBTCLNSwap.waitForPayment} to wait till the lightning network payment is received
49
+ * by the intermediary (LP)
50
+ */
30
51
  FromBTCLNSwapState[FromBTCLNSwapState["PR_CREATED"] = 0] = "PR_CREATED";
52
+ /**
53
+ * Lightning network payment has been received by the intermediary (LP), the user can now settle
54
+ * the swap on the destination smart chain side with {@link FromBTCLNSwap.commitAndClaim} (if
55
+ * the underlying chain supports it - check with {@link FromBTCLNSwap.canCommitAndClaimInOneShot}),
56
+ * or by calling {@link FromBTCLNSwap.commit} and {@link FromBTCLNSwap.claim} separately.
57
+ */
31
58
  FromBTCLNSwapState[FromBTCLNSwapState["PR_PAID"] = 1] = "PR_PAID";
59
+ /**
60
+ * Swap escrow HTLC has been created on the destination chain. Continue by claiming it with the
61
+ * {@link FromBTCLNSwap.claim} or {@link FromBTCLNSwap.txsClaim} function.
62
+ */
32
63
  FromBTCLNSwapState[FromBTCLNSwapState["CLAIM_COMMITED"] = 2] = "CLAIM_COMMITED";
64
+ /**
65
+ * Swap successfully settled and funds received on the destination chain
66
+ */
33
67
  FromBTCLNSwapState[FromBTCLNSwapState["CLAIM_CLAIMED"] = 3] = "CLAIM_CLAIMED";
34
68
  })(FromBTCLNSwapState = exports.FromBTCLNSwapState || (exports.FromBTCLNSwapState = {}));
35
69
  function isFromBTCLNSwapInit(obj) {
36
- return typeof obj.pr === "string" &&
37
- typeof obj.secret === "string" &&
70
+ return (obj.pr == null || typeof obj.pr === "string") &&
71
+ (obj.secret == null || typeof obj.secret === "string") &&
38
72
  (obj.lnurl == null || typeof (obj.lnurl) === "string") &&
39
73
  (obj.lnurlK1 == null || typeof (obj.lnurlK1) === "string") &&
40
74
  (obj.lnurlCallback == null || typeof (obj.lnurlCallback) === "string") &&
41
75
  (0, IEscrowSelfInitSwap_1.isIEscrowSelfInitSwapInit)(obj);
42
76
  }
43
77
  exports.isFromBTCLNSwapInit = isFromBTCLNSwapInit;
78
+ /**
79
+ * Legacy escrow (HTLC) based swap for Bitcoin Lightning -> Smart chains, requires manual settlement
80
+ * of the swap on the destination network once the lightning network payment is received by the LP.
81
+ *
82
+ * @category Swaps/Legacy/Lightning → Smart chain
83
+ */
44
84
  class FromBTCLNSwap extends IFromBTCSelfInitSwap_1.IFromBTCSelfInitSwap {
45
- getSwapData() {
46
- return this.data ?? this.initialSwapData;
85
+ /**
86
+ * Sets the LNURL data for the swap
87
+ *
88
+ * @internal
89
+ */
90
+ _setLNURLData(lnurl, lnurlK1, lnurlCallback) {
91
+ this.lnurl = lnurl;
92
+ this.lnurlK1 = lnurlK1;
93
+ this.lnurlCallback = lnurlCallback;
47
94
  }
48
95
  constructor(wrapper, initOrObject) {
49
96
  if (isFromBTCLNSwapInit(initOrObject) && initOrObject.url != null)
50
97
  initOrObject.url += "/frombtcln";
51
98
  super(wrapper, initOrObject);
52
- this.inputToken = Token_1.BitcoinTokens.BTCLN;
53
99
  this.TYPE = SwapType_1.SwapType.FROM_BTCLN;
100
+ /**
101
+ * @internal
102
+ */
103
+ this.inputToken = Token_1.BitcoinTokens.BTCLN;
54
104
  this.lnurlFailSignal = new AbortController();
55
105
  this.prPosted = false;
56
106
  if (isFromBTCLNSwapInit(initOrObject)) {
57
- this.state = FromBTCLNSwapState.PR_CREATED;
107
+ this._state = FromBTCLNSwapState.PR_CREATED;
58
108
  this.pr = initOrObject.pr;
59
109
  this.secret = initOrObject.secret;
60
110
  this.initialSwapData = initOrObject.initialSwapData;
61
111
  this.lnurl = initOrObject.lnurl;
62
112
  this.lnurlK1 = initOrObject.lnurlK1;
63
113
  this.lnurlCallback = initOrObject.lnurlCallback;
114
+ this.usesClaimHashAsId = true;
64
115
  }
65
116
  else {
66
117
  this.pr = initOrObject.pr;
67
118
  this.secret = initOrObject.secret;
68
119
  if (initOrObject.initialSwapData == null) {
69
- this.initialSwapData = this.data;
120
+ this.initialSwapData = this._data;
70
121
  }
71
122
  else {
72
123
  this.initialSwapData = base_1.SwapData.deserialize(initOrObject.initialSwapData);
@@ -75,34 +126,46 @@ class FromBTCLNSwap extends IFromBTCSelfInitSwap_1.IFromBTCSelfInitSwap {
75
126
  this.lnurlK1 = initOrObject.lnurlK1;
76
127
  this.lnurlCallback = initOrObject.lnurlCallback;
77
128
  this.prPosted = initOrObject.prPosted;
78
- if (this.state === FromBTCLNSwapState.PR_CREATED && this.data != null) {
79
- this.initialSwapData = this.data;
80
- delete this.data;
129
+ if (this._state === FromBTCLNSwapState.PR_CREATED && this._data != null) {
130
+ this.initialSwapData = this._data;
131
+ delete this._data;
81
132
  }
133
+ this.usesClaimHashAsId = initOrObject.usesClaimHashAsId ?? false;
82
134
  }
83
135
  this.tryRecomputeSwapPrice();
84
136
  this.logger = (0, Logger_1.getLogger)("FromBTCLN(" + this.getIdentifierHashString() + "): ");
85
137
  }
138
+ /**
139
+ * @inheritDoc
140
+ * @internal
141
+ */
142
+ getSwapData() {
143
+ return this._data ?? this.initialSwapData;
144
+ }
145
+ /**
146
+ * @inheritDoc
147
+ * @internal
148
+ */
86
149
  upgradeVersion() {
87
150
  if (this.version == null) {
88
- switch (this.state) {
151
+ switch (this._state) {
89
152
  case -2:
90
- this.state = FromBTCLNSwapState.QUOTE_EXPIRED;
153
+ this._state = FromBTCLNSwapState.QUOTE_EXPIRED;
91
154
  break;
92
155
  case -1:
93
- this.state = FromBTCLNSwapState.FAILED;
156
+ this._state = FromBTCLNSwapState.FAILED;
94
157
  break;
95
158
  case 0:
96
- this.state = FromBTCLNSwapState.PR_CREATED;
159
+ this._state = FromBTCLNSwapState.PR_CREATED;
97
160
  break;
98
161
  case 1:
99
- this.state = FromBTCLNSwapState.PR_PAID;
162
+ this._state = FromBTCLNSwapState.PR_PAID;
100
163
  break;
101
164
  case 2:
102
- this.state = FromBTCLNSwapState.CLAIM_COMMITED;
165
+ this._state = FromBTCLNSwapState.CLAIM_COMMITED;
103
166
  break;
104
167
  case 3:
105
- this.state = FromBTCLNSwapState.CLAIM_CLAIMED;
168
+ this._state = FromBTCLNSwapState.CLAIM_CLAIMED;
106
169
  break;
107
170
  }
108
171
  this.version = 1;
@@ -110,125 +173,217 @@ class FromBTCLNSwap extends IFromBTCSelfInitSwap_1.IFromBTCSelfInitSwap {
110
173
  }
111
174
  //////////////////////////////
112
175
  //// Getters & utils
176
+ /**
177
+ * @inheritDoc
178
+ * @internal
179
+ */
113
180
  getIdentifierHash() {
114
- const paymentHashBuffer = this.getPaymentHash();
115
- if (this.randomNonce == null)
116
- return paymentHashBuffer;
117
- return buffer_1.Buffer.concat([paymentHashBuffer, buffer_1.Buffer.from(this.randomNonce, "hex")]);
181
+ const idBuffer = this.usesClaimHashAsId
182
+ ? buffer_1.Buffer.from(this.getClaimHash(), "hex")
183
+ : this.getPaymentHash();
184
+ if (this._randomNonce == null)
185
+ return idBuffer;
186
+ return buffer_1.Buffer.concat([idBuffer, buffer_1.Buffer.from(this._randomNonce, "hex")]);
118
187
  }
188
+ /**
189
+ * Returns the payment hash of the swap and lightning network invoice, or `null` if not known (i.e. if
190
+ * the swap was recovered from on-chain data, the payment hash might not be known)
191
+ *
192
+ * @internal
193
+ */
119
194
  getPaymentHash() {
120
- const decodedPR = (0, bolt11_1.decode)(this.pr);
121
- if (decodedPR.tagsObject.payment_hash == null)
122
- throw new Error("Swap invoice doesn't contain payment hash field!");
123
- return buffer_1.Buffer.from(decodedPR.tagsObject.payment_hash, "hex");
195
+ if (this.pr == null)
196
+ return null;
197
+ if (this.pr.toLowerCase().startsWith("ln")) {
198
+ const parsed = (0, bolt11_1.decode)(this.pr);
199
+ if (parsed.tagsObject.payment_hash == null)
200
+ throw new Error("Swap invoice has no payment hash field!");
201
+ return buffer_1.Buffer.from(parsed.tagsObject.payment_hash, "hex");
202
+ }
203
+ return buffer_1.Buffer.from(this.pr, "hex");
124
204
  }
205
+ /**
206
+ * @inheritDoc
207
+ * @internal
208
+ */
125
209
  canCommit() {
126
- return this.state === FromBTCLNSwapState.PR_PAID;
210
+ return this._state === FromBTCLNSwapState.PR_PAID;
127
211
  }
212
+ /**
213
+ * @inheritDoc
214
+ */
128
215
  getInputAddress() {
129
- return this.lnurl ?? this.pr;
216
+ return this.lnurl ?? this.pr ?? null;
130
217
  }
218
+ /**
219
+ * @inheritDoc
220
+ */
131
221
  getInputTxId() {
132
- return this.getPaymentHash().toString("hex");
222
+ const paymentHash = this.getPaymentHash();
223
+ if (paymentHash == null)
224
+ return null;
225
+ return paymentHash.toString("hex");
133
226
  }
134
227
  /**
135
- * Returns the lightning network BOLT11 invoice that needs to be paid as an input to the swap
228
+ * Returns the lightning network BOLT11 invoice that needs to be paid as an input to the swap.
229
+ *
230
+ * In case the swap is recovered from on-chain data, the address returned might be just a payment hash,
231
+ * as it is impossible to retrieve the actual lightning network invoice paid purely from on-chain
232
+ * data.
136
233
  */
137
234
  getAddress() {
138
- return this.pr;
235
+ return this.pr ?? "";
139
236
  }
237
+ /**
238
+ * A hyperlink representation of the address + amount that the user needs to sends on the source chain.
239
+ * This is suitable to be displayed in a form of QR code.
240
+ *
241
+ * @remarks
242
+ * In case the swap is recovered from on-chain data, the address returned might be just a payment hash,
243
+ * as it is impossible to retrieve the actual lightning network invoice paid purely from on-chain
244
+ * data.
245
+ */
140
246
  getHyperlink() {
141
- return "lightning:" + this.pr.toUpperCase();
247
+ return this.pr == null ? "" : "lightning:" + this.pr.toUpperCase();
142
248
  }
143
249
  /**
144
250
  * Returns the timeout time (in UNIX milliseconds) when the swap will definitelly be considered as expired
145
251
  * if the LP doesn't make it expired sooner
146
252
  */
147
253
  getDefinitiveExpiryTime() {
254
+ if (this.pr == null || !this.pr.toLowerCase().startsWith("ln"))
255
+ return 0;
148
256
  const decoded = (0, bolt11_1.decode)(this.pr);
149
257
  if (decoded.timeExpireDate == null)
150
258
  throw new Error("Swap invoice doesn't contain expiry date field!");
151
259
  const finalCltvExpiryDelta = decoded.tagsObject.min_final_cltv_expiry ?? 144;
152
- const finalCltvExpiryDelay = finalCltvExpiryDelta * this.wrapper.options.bitcoinBlocktime * this.wrapper.options.safetyFactor;
260
+ const finalCltvExpiryDelay = finalCltvExpiryDelta * this.wrapper._options.bitcoinBlocktime * this.wrapper._options.safetyFactor;
153
261
  return (decoded.timeExpireDate + finalCltvExpiryDelay) * 1000;
154
262
  }
263
+ /**
264
+ * Returns timeout time (in UNIX milliseconds) when the swap htlc will expire
265
+ */
266
+ getHtlcTimeoutTime() {
267
+ if (this._data == null)
268
+ return null;
269
+ return Number(this.wrapper._getHtlcTimeout(this._data)) * 1000;
270
+ }
155
271
  /**
156
272
  * Returns timeout time (in UNIX milliseconds) when the LN invoice will expire
157
273
  */
158
274
  getTimeoutTime() {
275
+ if (this.pr == null || !this.pr.toLowerCase().startsWith("ln"))
276
+ return 0;
159
277
  const decoded = (0, bolt11_1.decode)(this.pr);
160
278
  if (decoded.timeExpireDate == null)
161
279
  throw new Error("Swap invoice doesn't contain expiry date field!");
162
280
  return (decoded.timeExpireDate * 1000);
163
281
  }
164
282
  /**
165
- * Returns timeout time (in UNIX milliseconds) when the swap htlc will expire
283
+ * @inheritDoc
166
284
  */
167
- getHtlcTimeoutTime() {
168
- if (this.data == null)
169
- return -1;
170
- return Number(this.wrapper.getHtlcTimeout(this.data)) * 1000;
171
- }
172
285
  isFinished() {
173
- return this.state === FromBTCLNSwapState.CLAIM_CLAIMED || this.state === FromBTCLNSwapState.QUOTE_EXPIRED || this.state === FromBTCLNSwapState.FAILED;
286
+ return this._state === FromBTCLNSwapState.CLAIM_CLAIMED || this._state === FromBTCLNSwapState.QUOTE_EXPIRED || this._state === FromBTCLNSwapState.FAILED;
174
287
  }
288
+ /**
289
+ * @inheritDoc
290
+ */
175
291
  isClaimable() {
176
- return this.state === FromBTCLNSwapState.CLAIM_COMMITED;
292
+ return this._state === FromBTCLNSwapState.CLAIM_COMMITED;
177
293
  }
294
+ /**
295
+ * @inheritDoc
296
+ */
178
297
  isSuccessful() {
179
- return this.state === FromBTCLNSwapState.CLAIM_CLAIMED;
298
+ return this._state === FromBTCLNSwapState.CLAIM_CLAIMED;
180
299
  }
300
+ /**
301
+ * @inheritDoc
302
+ */
181
303
  isFailed() {
182
- return this.state === FromBTCLNSwapState.FAILED || this.state === FromBTCLNSwapState.EXPIRED;
304
+ return this._state === FromBTCLNSwapState.FAILED || this._state === FromBTCLNSwapState.EXPIRED;
183
305
  }
306
+ /**
307
+ * @inheritDoc
308
+ */
184
309
  isQuoteExpired() {
185
- return this.state === FromBTCLNSwapState.QUOTE_EXPIRED;
310
+ return this._state === FromBTCLNSwapState.QUOTE_EXPIRED;
186
311
  }
312
+ /**
313
+ * @inheritDoc
314
+ */
187
315
  isQuoteSoftExpired() {
188
- return this.state === FromBTCLNSwapState.QUOTE_EXPIRED || this.state === FromBTCLNSwapState.QUOTE_SOFT_EXPIRED;
316
+ return this._state === FromBTCLNSwapState.QUOTE_EXPIRED || this._state === FromBTCLNSwapState.QUOTE_SOFT_EXPIRED;
189
317
  }
318
+ /**
319
+ * @inheritDoc
320
+ * @internal
321
+ */
190
322
  _verifyQuoteDefinitelyExpired() {
191
- if (this.state === FromBTCLNSwapState.PR_CREATED || (this.state === FromBTCLNSwapState.QUOTE_SOFT_EXPIRED && this.signatureData == null)) {
323
+ if (this._state === FromBTCLNSwapState.PR_CREATED || (this._state === FromBTCLNSwapState.QUOTE_SOFT_EXPIRED && this.signatureData == null)) {
192
324
  return Promise.resolve(this.getDefinitiveExpiryTime() < Date.now());
193
325
  }
194
326
  return super._verifyQuoteDefinitelyExpired();
195
327
  }
196
- verifyQuoteValid() {
197
- if (this.state === FromBTCLNSwapState.PR_CREATED ||
198
- (this.state === FromBTCLNSwapState.QUOTE_SOFT_EXPIRED && this.signatureData == null)) {
328
+ /**
329
+ * @inheritDoc
330
+ * @internal
331
+ */
332
+ _verifyQuoteValid() {
333
+ if (this._state === FromBTCLNSwapState.PR_CREATED ||
334
+ (this._state === FromBTCLNSwapState.QUOTE_SOFT_EXPIRED && this.signatureData == null)) {
199
335
  return Promise.resolve(this.getTimeoutTime() > Date.now());
200
336
  }
201
- return super.verifyQuoteValid();
337
+ return super._verifyQuoteValid();
202
338
  }
203
339
  //////////////////////////////
204
340
  //// Amounts & fees
341
+ /**
342
+ * @inheritDoc
343
+ */
205
344
  getInputToken() {
206
345
  return Token_1.BitcoinTokens.BTCLN;
207
346
  }
347
+ /**
348
+ * @inheritDoc
349
+ */
208
350
  getInput() {
351
+ if (this.pr == null || !this.pr.toLowerCase().startsWith("ln"))
352
+ return (0, TokenAmount_1.toTokenAmount)(null, this.inputToken, this.wrapper._prices, this.pricingInfo);
209
353
  const parsed = (0, bolt11_1.decode)(this.pr);
210
354
  if (parsed.millisatoshis == null)
211
355
  throw new Error("Swap invoice doesn't contain msat amount field!");
212
356
  const amount = (BigInt(parsed.millisatoshis) + 999n) / 1000n;
213
- return (0, TokenAmount_1.toTokenAmount)(amount, this.inputToken, this.wrapper.prices, this.pricingInfo);
357
+ return (0, TokenAmount_1.toTokenAmount)(amount, this.inputToken, this.wrapper._prices, this.pricingInfo);
214
358
  }
215
- async getSmartChainNetworkFee() {
216
- return (0, TokenAmount_1.toTokenAmount)(await this.getCommitAndClaimFee(), this.wrapper.getNativeToken(), this.wrapper.prices, this.pricingInfo);
359
+ /**
360
+ * @inheritDoc
361
+ */
362
+ getSmartChainNetworkFee() {
363
+ return this.getCommitAndClaimNetworkFee();
217
364
  }
365
+ /**
366
+ * @inheritDoc
367
+ */
218
368
  async hasEnoughForTxFees() {
219
369
  const [balance, feeRate] = await Promise.all([
220
- this.wrapper.contract.getBalance(this._getInitiator(), this.wrapper.chain.getNativeCurrencyAddress(), false),
221
- this.feeRate != null ? Promise.resolve(this.feeRate) : this.wrapper.contract.getInitFeeRate(this.getSwapData().getOfferer(), this.getSwapData().getClaimer(), this.getSwapData().getToken(), this.getSwapData().getClaimHash())
370
+ this.wrapper._contract.getBalance(this._getInitiator(), this.wrapper._chain.getNativeCurrencyAddress(), false),
371
+ this.feeRate != null ? Promise.resolve(this.feeRate) : this.wrapper._contract.getInitFeeRate(this.getSwapData().getOfferer(), this.getSwapData().getClaimer(), this.getSwapData().getToken(), this.getSwapData().getClaimHash())
222
372
  ]);
223
- const commitFee = await this.wrapper.contract.getCommitFee(this._getInitiator(), this.getSwapData(), feeRate);
224
- const claimFee = await this.wrapper.contract.getClaimFee(this._getInitiator(), this.getSwapData(), feeRate);
373
+ const commitFee = await this.wrapper._contract.getCommitFee(this._getInitiator(), this.getSwapData(), feeRate);
374
+ const claimFee = await this.wrapper._contract.getClaimFee(this._getInitiator(), this.getSwapData(), feeRate);
225
375
  const totalFee = commitFee + claimFee + this.getSwapData().getTotalDeposit();
226
376
  return {
227
377
  enoughBalance: balance >= totalFee,
228
- balance: (0, TokenAmount_1.toTokenAmount)(balance, this.wrapper.getNativeToken(), this.wrapper.prices, this.pricingInfo),
229
- required: (0, TokenAmount_1.toTokenAmount)(totalFee, this.wrapper.getNativeToken(), this.wrapper.prices, this.pricingInfo)
378
+ balance: (0, TokenAmount_1.toTokenAmount)(balance, this.wrapper._getNativeToken(), this.wrapper._prices, this.pricingInfo),
379
+ required: (0, TokenAmount_1.toTokenAmount)(totalFee, this.wrapper._getNativeToken(), this.wrapper._prices, this.pricingInfo)
230
380
  };
231
381
  }
382
+ isValidSecretPreimage(secret) {
383
+ const paymentHash = buffer_1.Buffer.from((0, sha2_1.sha256)(buffer_1.Buffer.from(secret, "hex")));
384
+ const claimHash = this.wrapper._contract.getHashForHtlc(paymentHash).toString("hex");
385
+ return this.getSwapData().getClaimHash() === claimHash;
386
+ }
232
387
  //////////////////////////////
233
388
  //// Execution
234
389
  /**
@@ -241,19 +396,23 @@ class FromBTCLNSwap extends IFromBTCSelfInitSwap_1.IFromBTCSelfInitSwap {
241
396
  * link, wallet is not required and the LN invoice can be paid externally as well (just pass null or undefined here)
242
397
  * @param callbacks Callbacks to track the progress of the swap
243
398
  * @param options Optional options for the swap like feeRate, AbortSignal, and timeouts/intervals
399
+ * @param secret A swap secret to use for the claim transaction, generally only needed if the swap
400
+ * was recovered from on-chain data, or the pre-image was generated outside the SDK
244
401
  */
245
- async execute(dstSigner, walletOrLnurlWithdraw, callbacks, options) {
246
- if (this.state === FromBTCLNSwapState.FAILED)
402
+ async execute(dstSigner, walletOrLnurlWithdraw, callbacks, options, secret) {
403
+ if (this._state === FromBTCLNSwapState.FAILED)
247
404
  throw new Error("Swap failed!");
248
- if (this.state === FromBTCLNSwapState.EXPIRED)
405
+ if (this._state === FromBTCLNSwapState.EXPIRED)
249
406
  throw new Error("Swap HTLC expired!");
250
- if (this.state === FromBTCLNSwapState.QUOTE_EXPIRED || this.state === FromBTCLNSwapState.QUOTE_SOFT_EXPIRED)
407
+ if (this._state === FromBTCLNSwapState.QUOTE_EXPIRED || this._state === FromBTCLNSwapState.QUOTE_SOFT_EXPIRED)
251
408
  throw new Error("Swap quote expired!");
252
- if (this.state === FromBTCLNSwapState.CLAIM_CLAIMED)
409
+ if (this._state === FromBTCLNSwapState.CLAIM_CLAIMED)
253
410
  throw new Error("Swap already settled!");
254
411
  let abortSignal = options?.abortSignal;
255
- if (this.state === FromBTCLNSwapState.PR_CREATED) {
412
+ if (this._state === FromBTCLNSwapState.PR_CREATED) {
256
413
  if (walletOrLnurlWithdraw != null && this.lnurl == null) {
414
+ if (this.pr == null || !this.pr.toLowerCase().startsWith("ln"))
415
+ throw new Error("Input lightning network invoice not available, the swap was probably recovered!");
257
416
  if (typeof (walletOrLnurlWithdraw) === "string" || (0, LNURLWithdraw_1.isLNURLWithdraw)(walletOrLnurlWithdraw)) {
258
417
  await this.settleWithLNURLWithdraw(walletOrLnurlWithdraw);
259
418
  }
@@ -270,30 +429,40 @@ class FromBTCLNSwap extends IFromBTCSelfInitSwap_1.IFromBTCSelfInitSwap {
270
429
  if (!paymentSuccess)
271
430
  throw new Error("Failed to receive lightning network payment");
272
431
  }
273
- if (this.state === FromBTCLNSwapState.PR_PAID || this.state === FromBTCLNSwapState.CLAIM_COMMITED) {
432
+ if (this._state === FromBTCLNSwapState.PR_PAID || this._state === FromBTCLNSwapState.CLAIM_COMMITED) {
274
433
  if (this.canCommitAndClaimInOneShot()) {
275
- await this.commitAndClaim(dstSigner, options?.abortSignal, undefined, callbacks?.onDestinationCommitSent, callbacks?.onDestinationClaimSent);
434
+ await this.commitAndClaim(dstSigner, options?.abortSignal, undefined, callbacks?.onDestinationCommitSent, callbacks?.onDestinationClaimSent, secret);
276
435
  }
277
436
  else {
278
- if (this.state === FromBTCLNSwapState.PR_PAID) {
437
+ if (this._state === FromBTCLNSwapState.PR_PAID) {
279
438
  await this.commit(dstSigner, options?.abortSignal, undefined, callbacks?.onDestinationCommitSent);
280
439
  if (options?.delayBetweenCommitAndClaimSeconds != null)
281
440
  await (0, TimeoutUtils_1.timeoutPromise)(options.delayBetweenCommitAndClaimSeconds * 1000, options?.abortSignal);
282
441
  }
283
- if (this.state === FromBTCLNSwapState.CLAIM_COMMITED) {
284
- await this.claim(dstSigner, options?.abortSignal, callbacks?.onDestinationClaimSent);
442
+ if (this._state === FromBTCLNSwapState.CLAIM_COMMITED) {
443
+ await this.claim(dstSigner, options?.abortSignal, callbacks?.onDestinationClaimSent, secret);
285
444
  }
286
445
  }
287
446
  }
288
447
  // @ts-ignore
289
- if (this.state === FromBTCLNSwapState.CLAIM_CLAIMED) {
448
+ if (this._state === FromBTCLNSwapState.CLAIM_CLAIMED) {
290
449
  if (callbacks?.onSwapSettled != null)
291
450
  callbacks.onSwapSettled(this.getOutputTxId());
292
451
  }
293
452
  }
294
- async txsExecute(options) {
295
- if (this.state === FromBTCLNSwapState.PR_CREATED) {
296
- if (!await this.verifyQuoteValid())
453
+ /**
454
+ * @inheritDoc
455
+ *
456
+ * @param options
457
+ * @param options.skipChecks Skip checks like making sure init signature is still valid and swap
458
+ * wasn't commited yet (this is handled on swap creation, if you commit right after quoting, you
459
+ * can use `skipChecks=true`)
460
+ * @param secret A swap secret to use for the claim transaction, generally only needed if the swap
461
+ * was recovered from on-chain data, or the pre-image was generated outside the SDK
462
+ */
463
+ async txsExecute(options, secret) {
464
+ if (this._state === FromBTCLNSwapState.PR_CREATED) {
465
+ if (!await this._verifyQuoteValid())
297
466
  throw new Error("Quote already expired or close to expiry!");
298
467
  return [
299
468
  {
@@ -302,18 +471,19 @@ class FromBTCLNSwap extends IFromBTCSelfInitSwap_1.IFromBTCSelfInitSwap {
302
471
  chain: "LIGHTNING",
303
472
  txs: [
304
473
  {
305
- address: this.pr,
474
+ type: "BOLT11_PAYMENT_REQUEST",
475
+ address: this.getAddress(),
306
476
  hyperlink: this.getHyperlink()
307
477
  }
308
478
  ]
309
479
  }
310
480
  ];
311
481
  }
312
- if (this.state === FromBTCLNSwapState.PR_PAID) {
313
- if (!await this.verifyQuoteValid())
482
+ if (this._state === FromBTCLNSwapState.PR_PAID) {
483
+ if (!await this._verifyQuoteValid())
314
484
  throw new Error("Quote already expired or close to expiry!");
315
485
  const txsCommit = await this.txsCommit(options?.skipChecks);
316
- const txsClaim = await this._txsClaim(undefined);
486
+ const txsClaim = await this._txsClaim(undefined, secret);
317
487
  return [
318
488
  {
319
489
  name: "Commit",
@@ -329,8 +499,8 @@ class FromBTCLNSwap extends IFromBTCSelfInitSwap_1.IFromBTCSelfInitSwap {
329
499
  },
330
500
  ];
331
501
  }
332
- if (this.state === FromBTCLNSwapState.CLAIM_COMMITED) {
333
- const txsClaim = await this.txsClaim();
502
+ if (this._state === FromBTCLNSwapState.CLAIM_COMMITED) {
503
+ const txsClaim = await this.txsClaim(undefined, secret);
334
504
  return [
335
505
  {
336
506
  name: "Claim",
@@ -348,26 +518,32 @@ class FromBTCLNSwap extends IFromBTCSelfInitSwap_1.IFromBTCSelfInitSwap {
348
518
  * Checks whether the LP received the LN payment and we can continue by committing & claiming the HTLC on-chain
349
519
  *
350
520
  * @param save If the new swap state should be saved
521
+ *
522
+ * @internal
351
523
  */
352
524
  async _checkIntermediaryPaymentReceived(save = true) {
353
- if (this.state === FromBTCLNSwapState.PR_PAID ||
354
- this.state === FromBTCLNSwapState.CLAIM_COMMITED ||
355
- this.state === FromBTCLNSwapState.CLAIM_CLAIMED ||
356
- this.state === FromBTCLNSwapState.FAILED)
525
+ if (this._state === FromBTCLNSwapState.PR_PAID ||
526
+ this._state === FromBTCLNSwapState.CLAIM_COMMITED ||
527
+ this._state === FromBTCLNSwapState.CLAIM_CLAIMED ||
528
+ this._state === FromBTCLNSwapState.FAILED ||
529
+ this._state === FromBTCLNSwapState.EXPIRED)
357
530
  return true;
358
- if (this.state === FromBTCLNSwapState.QUOTE_EXPIRED || (this.state === FromBTCLNSwapState.QUOTE_SOFT_EXPIRED && this.signatureData != null))
531
+ if (this._state === FromBTCLNSwapState.QUOTE_EXPIRED || (this._state === FromBTCLNSwapState.QUOTE_SOFT_EXPIRED && this.signatureData != null))
359
532
  return false;
360
533
  if (this.url == null)
361
534
  return false;
362
- const resp = await IntermediaryAPI_1.IntermediaryAPI.getPaymentAuthorization(this.url, this.getPaymentHash().toString("hex"));
535
+ const paymentHash = this.getPaymentHash();
536
+ if (paymentHash == null)
537
+ throw new Error("Failed to check LP payment received, payment hash not known (probably recovered swap?)");
538
+ const resp = await IntermediaryAPI_1.IntermediaryAPI.getPaymentAuthorization(this.url, paymentHash.toString("hex"));
363
539
  switch (resp.code) {
364
540
  case IntermediaryAPI_1.PaymentAuthorizationResponseCodes.AUTH_DATA:
365
- const data = new this.wrapper.swapDataDeserializer(resp.data.data);
541
+ const data = new this.wrapper._swapDataDeserializer(resp.data.data);
366
542
  try {
367
543
  await this.checkIntermediaryReturnedAuthData(this._getInitiator(), data, resp.data);
368
- this.expiry = await this.wrapper.contract.getInitAuthorizationExpiry(data, resp.data);
369
- this.state = FromBTCLNSwapState.PR_PAID;
370
- this.data = data;
544
+ this.expiry = await this.wrapper._contract.getInitAuthorizationExpiry(data, resp.data);
545
+ this._state = FromBTCLNSwapState.PR_PAID;
546
+ this._data = data;
371
547
  this.signatureData = {
372
548
  prefix: resp.data.prefix,
373
549
  timeout: resp.data.timeout,
@@ -381,7 +557,7 @@ class FromBTCLNSwap extends IFromBTCSelfInitSwap_1.IFromBTCSelfInitSwap {
381
557
  catch (e) { }
382
558
  return null;
383
559
  case IntermediaryAPI_1.PaymentAuthorizationResponseCodes.EXPIRED:
384
- this.state = FromBTCLNSwapState.QUOTE_EXPIRED;
560
+ this._state = FromBTCLNSwapState.QUOTE_EXPIRED;
385
561
  this.initiated = true;
386
562
  if (save)
387
563
  await this._saveAndEmit();
@@ -396,10 +572,12 @@ class FromBTCLNSwap extends IFromBTCSelfInitSwap_1.IFromBTCSelfInitSwap {
396
572
  * @param signer Smart chain signer's address initiating the swap
397
573
  * @param data Parsed swap data as returned by the intermediary
398
574
  * @param signature Signature data as returned by the intermediary
399
- * @protected
575
+ *
400
576
  * @throws {IntermediaryError} If the returned are not valid
401
577
  * @throws {SignatureVerificationError} If the returned signature is not valid
402
578
  * @throws {Error} If the swap is already committed on-chain
579
+ *
580
+ * @internal
403
581
  */
404
582
  async checkIntermediaryReturnedAuthData(signer, data, signature) {
405
583
  data.setClaimer(signer);
@@ -424,8 +602,8 @@ class FromBTCLNSwap extends IFromBTCSelfInitSwap_1.IFromBTCSelfInitSwap {
424
602
  if (data.hasSuccessAction())
425
603
  throw new IntermediaryError_1.IntermediaryError("Invalid has success action");
426
604
  await Promise.all([
427
- this.wrapper.contract.isValidInitAuthorization(this._getInitiator(), data, signature, this.feeRate),
428
- this.wrapper.contract.getCommitStatus(data.getClaimer(), data)
605
+ this.wrapper._contract.isValidInitAuthorization(this._getInitiator(), data, signature, this.feeRate),
606
+ this.wrapper._contract.getCommitStatus(data.getClaimer(), data)
429
607
  .then(status => {
430
608
  if (status?.type !== base_1.SwapCommitStateType.NOT_COMMITED)
431
609
  throw new Error("Swap already committed on-chain!");
@@ -433,16 +611,23 @@ class FromBTCLNSwap extends IFromBTCSelfInitSwap_1.IFromBTCSelfInitSwap {
433
611
  ]);
434
612
  }
435
613
  /**
436
- * Waits till an LN payment is received by the intermediary and client can continue commiting & claiming the HTLC
614
+ * Waits till a lightning network payment is received by the intermediary and client
615
+ * can continue by initiating (committing) & settling (claiming) the HTLC by calling
616
+ * either the {@link commitAndClaim} function (if the underlying chain allows commit
617
+ * and claim in a single transaction - check with {@link canCommitAndClaimInOneShot}).
618
+ * Or call {@link commit} and then {@link claim} separately.
619
+ *
620
+ * If this swap is using an LNURL-withdraw link as input, it automatically posts the
621
+ * generated invoice to the LNURL service to pay it.
437
622
  *
438
623
  * @param onPaymentReceived Callback as for when the LP reports having received the ln payment
439
624
  * @param abortSignal Abort signal to stop waiting for payment
440
- * @param checkIntervalSeconds How often to poll the intermediary for answer
625
+ * @param checkIntervalSeconds How often to poll the intermediary for answer (default 5 seconds)
441
626
  */
442
627
  async waitForPayment(onPaymentReceived, checkIntervalSeconds, abortSignal) {
443
628
  checkIntervalSeconds ??= 5;
444
- if (this.state !== FromBTCLNSwapState.PR_CREATED &&
445
- (this.state !== FromBTCLNSwapState.QUOTE_SOFT_EXPIRED || this.signatureData != null))
629
+ if (this._state !== FromBTCLNSwapState.PR_CREATED &&
630
+ (this._state !== FromBTCLNSwapState.QUOTE_SOFT_EXPIRED || this.signatureData != null))
446
631
  throw new Error("Must be in PR_CREATED state!");
447
632
  if (this.url == null)
448
633
  throw new Error("LP URL not known, cannot await the payment!");
@@ -451,6 +636,8 @@ class FromBTCLNSwap extends IFromBTCSelfInitSwap_1.IFromBTCSelfInitSwap {
451
636
  abortSignal.addEventListener("abort", () => abortController.abort(abortSignal.reason));
452
637
  let save = false;
453
638
  if (this.lnurl != null && this.lnurlK1 != null && this.lnurlCallback != null && !this.prPosted) {
639
+ if (this.pr == null || !this.pr.toLowerCase().startsWith("ln"))
640
+ throw new Error("Input lightning network invoice not available, the swap was probably recovered!");
454
641
  LNURL_1.LNURL.postInvoiceToLNURLWithdraw({ k1: this.lnurlK1, callback: this.lnurlCallback }, this.pr).catch(e => {
455
642
  this.lnurlFailSignal.abort(e);
456
643
  });
@@ -466,9 +653,12 @@ class FromBTCLNSwap extends IFromBTCSelfInitSwap_1.IFromBTCSelfInitSwap {
466
653
  let lnurlFailListener = () => abortController.abort(this.lnurlFailSignal.signal.reason);
467
654
  this.lnurlFailSignal.signal.addEventListener("abort", lnurlFailListener);
468
655
  this.lnurlFailSignal.signal.throwIfAborted();
656
+ const paymentHash = this.getPaymentHash();
657
+ if (paymentHash == null)
658
+ throw new Error("Swap payment hash not available, the swap was probably recovered!");
469
659
  let resp = { code: IntermediaryAPI_1.PaymentAuthorizationResponseCodes.PENDING, msg: "" };
470
660
  while (!abortController.signal.aborted && resp.code === IntermediaryAPI_1.PaymentAuthorizationResponseCodes.PENDING) {
471
- resp = await IntermediaryAPI_1.IntermediaryAPI.getPaymentAuthorization(this.url, this.getPaymentHash().toString("hex"));
661
+ resp = await IntermediaryAPI_1.IntermediaryAPI.getPaymentAuthorization(this.url, paymentHash.toString("hex"));
472
662
  if (resp.code === IntermediaryAPI_1.PaymentAuthorizationResponseCodes.PENDING)
473
663
  await (0, TimeoutUtils_1.timeoutPromise)(checkIntervalSeconds * 1000, abortController.signal);
474
664
  }
@@ -476,13 +666,13 @@ class FromBTCLNSwap extends IFromBTCSelfInitSwap_1.IFromBTCSelfInitSwap {
476
666
  abortController.signal.throwIfAborted();
477
667
  if (resp.code === IntermediaryAPI_1.PaymentAuthorizationResponseCodes.AUTH_DATA) {
478
668
  const sigData = resp.data;
479
- const swapData = new this.wrapper.swapDataDeserializer(resp.data.data);
669
+ const swapData = new this.wrapper._swapDataDeserializer(resp.data.data);
480
670
  await this.checkIntermediaryReturnedAuthData(this._getInitiator(), swapData, sigData);
481
- this.expiry = await this.wrapper.contract.getInitAuthorizationExpiry(swapData, sigData);
671
+ this.expiry = await this.wrapper._contract.getInitAuthorizationExpiry(swapData, sigData);
482
672
  if (onPaymentReceived != null)
483
673
  onPaymentReceived(this.getInputTxId());
484
- if (this.state === FromBTCLNSwapState.PR_CREATED || this.state === FromBTCLNSwapState.QUOTE_SOFT_EXPIRED) {
485
- this.data = swapData;
674
+ if (this._state === FromBTCLNSwapState.PR_CREATED || this._state === FromBTCLNSwapState.QUOTE_SOFT_EXPIRED) {
675
+ this._data = swapData;
486
676
  this.signatureData = {
487
677
  prefix: sigData.prefix,
488
678
  timeout: sigData.timeout,
@@ -492,7 +682,7 @@ class FromBTCLNSwap extends IFromBTCSelfInitSwap_1.IFromBTCSelfInitSwap {
492
682
  }
493
683
  return true;
494
684
  }
495
- if (this.state === FromBTCLNSwapState.PR_CREATED || this.state === FromBTCLNSwapState.QUOTE_SOFT_EXPIRED) {
685
+ if (this._state === FromBTCLNSwapState.PR_CREATED || this._state === FromBTCLNSwapState.QUOTE_SOFT_EXPIRED) {
496
686
  if (resp.code === IntermediaryAPI_1.PaymentAuthorizationResponseCodes.EXPIRED) {
497
687
  await this._saveAndEmit(FromBTCLNSwapState.QUOTE_EXPIRED);
498
688
  }
@@ -503,36 +693,34 @@ class FromBTCLNSwap extends IFromBTCSelfInitSwap_1.IFromBTCSelfInitSwap {
503
693
  //////////////////////////////
504
694
  //// Commit
505
695
  /**
506
- * Commits the swap on-chain, locking the tokens from the intermediary in an HTLC
696
+ * @inheritDoc
507
697
  *
508
- * @param _signer Signer to sign the transactions with, must be the same as used in the initialization
509
- * @param abortSignal Abort signal to stop waiting for the transaction confirmation and abort
510
- * @param skipChecks Skip checks like making sure init signature is still valid and swap wasn't commited yet
511
- * (this is handled when swap is created (quoted), if you commit right after quoting, you can use skipChecks=true)
512
- * @param onBeforeTxSent
513
698
  * @throws {Error} If invalid signer is provided that doesn't match the swap data
514
699
  */
515
700
  async commit(_signer, abortSignal, skipChecks, onBeforeTxSent) {
516
- const signer = (0, base_1.isAbstractSigner)(_signer) ? _signer : await this.wrapper.chain.wrapSigner(_signer);
701
+ const signer = (0, base_1.isAbstractSigner)(_signer) ? _signer : await this.wrapper._chain.wrapSigner(_signer);
517
702
  this.checkSigner(signer);
518
703
  let txCount = 0;
519
704
  const txs = await this.txsCommit(skipChecks);
520
- const result = await this.wrapper.chain.sendAndConfirm(signer, txs, true, abortSignal, undefined, (txId) => {
705
+ const result = await this.wrapper._chain.sendAndConfirm(signer, txs, true, abortSignal, undefined, (txId) => {
521
706
  txCount++;
522
707
  if (onBeforeTxSent != null && txCount === txs.length)
523
708
  onBeforeTxSent(txId);
524
709
  return Promise.resolve();
525
710
  });
526
- this.commitTxId = result[result.length - 1];
527
- if (this.state === FromBTCLNSwapState.PR_PAID || this.state === FromBTCLNSwapState.QUOTE_SOFT_EXPIRED) {
711
+ this._commitTxId = result[result.length - 1];
712
+ if (this._state === FromBTCLNSwapState.PR_PAID || this._state === FromBTCLNSwapState.QUOTE_SOFT_EXPIRED) {
528
713
  await this._saveAndEmit(FromBTCLNSwapState.CLAIM_COMMITED);
529
714
  }
530
- return this.commitTxId;
715
+ return this._commitTxId;
531
716
  }
717
+ /**
718
+ * @inheritDoc
719
+ */
532
720
  async waitTillCommited(abortSignal) {
533
- if (this.state === FromBTCLNSwapState.CLAIM_COMMITED || this.state === FromBTCLNSwapState.CLAIM_CLAIMED)
721
+ if (this._state === FromBTCLNSwapState.CLAIM_COMMITED || this._state === FromBTCLNSwapState.CLAIM_CLAIMED)
534
722
  return Promise.resolve();
535
- if (this.state !== FromBTCLNSwapState.PR_PAID && (this.state !== FromBTCLNSwapState.QUOTE_SOFT_EXPIRED && this.signatureData != null))
723
+ if (this._state !== FromBTCLNSwapState.PR_PAID && (this._state !== FromBTCLNSwapState.QUOTE_SOFT_EXPIRED && this.signatureData != null))
536
724
  throw new Error("Invalid state");
537
725
  const abortController = (0, Utils_1.extendAbortController)(abortSignal);
538
726
  const result = await Promise.race([
@@ -546,14 +734,14 @@ class FromBTCLNSwap extends IFromBTCSelfInitSwap_1.IFromBTCSelfInitSwap {
546
734
  this.logger.debug("waitTillCommited(): Resolved from watchdog - commited");
547
735
  if (result === false) {
548
736
  this.logger.debug("waitTillCommited(): Resolved from watchdog - signature expired");
549
- if (this.state === FromBTCLNSwapState.PR_PAID ||
550
- this.state === FromBTCLNSwapState.QUOTE_SOFT_EXPIRED) {
737
+ if (this._state === FromBTCLNSwapState.PR_PAID ||
738
+ this._state === FromBTCLNSwapState.QUOTE_SOFT_EXPIRED) {
551
739
  await this._saveAndEmit(FromBTCLNSwapState.QUOTE_EXPIRED);
552
740
  }
553
741
  return;
554
742
  }
555
- if (this.state === FromBTCLNSwapState.PR_PAID ||
556
- this.state === FromBTCLNSwapState.QUOTE_SOFT_EXPIRED) {
743
+ if (this._state === FromBTCLNSwapState.PR_PAID ||
744
+ this._state === FromBTCLNSwapState.QUOTE_SOFT_EXPIRED) {
557
745
  await this._saveAndEmit(FromBTCLNSwapState.CLAIM_COMMITED);
558
746
  }
559
747
  }
@@ -563,62 +751,71 @@ class FromBTCLNSwap extends IFromBTCSelfInitSwap_1.IFromBTCSelfInitSwap {
563
751
  * Unsafe txs claim getter without state checking!
564
752
  *
565
753
  * @param _signer
566
- * @private
754
+ * @param secret A swap secret to use for the claim transaction, generally only needed if the swap
755
+ * was recovered from on-chain data, or the pre-image was generated outside the SDK
756
+ *
757
+ * @internal
567
758
  */
568
- async _txsClaim(_signer) {
569
- if (this.data == null)
759
+ async _txsClaim(_signer, secret) {
760
+ if (this._data == null)
570
761
  throw new Error("Unknown data, wrong state?");
571
- return this.wrapper.contract.txsClaimWithSecret(_signer == null ?
762
+ const useSecret = secret ?? this.secret;
763
+ if (useSecret == null)
764
+ throw new Error("Swap secret pre-image not known and not provided, please provide the swap secret pre-image as an argument");
765
+ if (!this.isValidSecretPreimage(useSecret))
766
+ throw new Error("Invalid swap secret pre-image provided!");
767
+ return this.wrapper._contract.txsClaimWithSecret(_signer == null ?
572
768
  this._getInitiator() :
573
- ((0, base_1.isAbstractSigner)(_signer) ? _signer : await this.wrapper.chain.wrapSigner(_signer)), this.data, this.secret, true, true);
769
+ ((0, base_1.isAbstractSigner)(_signer) ? _signer : await this.wrapper._chain.wrapSigner(_signer)), this._data, useSecret, true, true);
574
770
  }
575
771
  /**
576
- * Returns transactions required for claiming the HTLC and finishing the swap by revealing the HTLC secret
577
- * (hash preimage)
772
+ * @inheritDoc
578
773
  *
579
774
  * @param _signer Optional signer address to use for claiming the swap, can also be different from the initializer
580
- * @throws {Error} If in invalid state (must be CLAIM_COMMITED)
775
+ * @param secret A swap secret to use for the claim transaction, generally only needed if the swap
776
+ * was recovered from on-chain data, or the pre-image was generated outside the SDK
777
+ *
778
+ * @throws {Error} If in invalid state (must be {@link FromBTCLNSwapState.CLAIM_COMMITED})
581
779
  */
582
- async txsClaim(_signer) {
583
- if (this.state !== FromBTCLNSwapState.CLAIM_COMMITED)
780
+ async txsClaim(_signer, secret) {
781
+ if (this._state !== FromBTCLNSwapState.CLAIM_COMMITED)
584
782
  throw new Error("Must be in CLAIM_COMMITED state!");
585
- return this._txsClaim(_signer);
783
+ return this._txsClaim(_signer, secret);
586
784
  }
587
785
  /**
588
- * Claims and finishes the swap
786
+ * @inheritDoc
589
787
  *
590
- * @param _signer Signer to sign the transactions with, can also be different to the initializer
591
- * @param abortSignal Abort signal to stop waiting for transaction confirmation
788
+ * @param _signer
789
+ * @param abortSignal
592
790
  * @param onBeforeTxSent
791
+ * @param secret A swap secret to use for the claim transaction, generally only needed if the swap
792
+ * was recovered from on-chain data, or the pre-image was generated outside the SDK
593
793
  */
594
- async claim(_signer, abortSignal, onBeforeTxSent) {
595
- const signer = (0, base_1.isAbstractSigner)(_signer) ? _signer : await this.wrapper.chain.wrapSigner(_signer);
794
+ async claim(_signer, abortSignal, onBeforeTxSent, secret) {
795
+ const signer = (0, base_1.isAbstractSigner)(_signer) ? _signer : await this.wrapper._chain.wrapSigner(_signer);
596
796
  let txCount = 0;
597
- const result = await this.wrapper.chain.sendAndConfirm(signer, await this.txsClaim(), true, abortSignal, undefined, (txId) => {
797
+ const result = await this.wrapper._chain.sendAndConfirm(signer, await this.txsClaim(_signer, secret), true, abortSignal, undefined, (txId) => {
598
798
  txCount++;
599
799
  if (onBeforeTxSent != null && txCount === 1)
600
800
  onBeforeTxSent(txId);
601
801
  return Promise.resolve();
602
802
  });
603
- this.claimTxId = result[0];
604
- if (this.state === FromBTCLNSwapState.CLAIM_COMMITED || this.state === FromBTCLNSwapState.EXPIRED || this.state === FromBTCLNSwapState.FAILED) {
803
+ this._claimTxId = result[0];
804
+ if (this._state === FromBTCLNSwapState.CLAIM_COMMITED || this._state === FromBTCLNSwapState.EXPIRED || this._state === FromBTCLNSwapState.FAILED) {
605
805
  await this._saveAndEmit(FromBTCLNSwapState.CLAIM_CLAIMED);
606
806
  }
607
807
  return result[0];
608
808
  }
609
809
  /**
610
- * Waits till the swap is successfully claimed
810
+ * @inheritDoc
611
811
  *
612
- * @param maxWaitTimeSeconds Maximum time in seconds to wait for the swap to be settled
613
- * @param abortSignal AbortSignal
614
- * @throws {Error} If swap is in invalid state (must be BTC_TX_CONFIRMED)
812
+ * @throws {Error} If swap is in invalid state (must be {@link FromBTCLNSwapState.CLAIM_COMMITED})
615
813
  * @throws {Error} If the LP refunded sooner than we were able to claim
616
- * @returns {boolean} whether the swap was claimed in time or not
617
814
  */
618
815
  async waitTillClaimed(maxWaitTimeSeconds, abortSignal) {
619
- if (this.state === FromBTCLNSwapState.CLAIM_CLAIMED)
816
+ if (this._state === FromBTCLNSwapState.CLAIM_CLAIMED)
620
817
  return Promise.resolve(true);
621
- if (this.state !== FromBTCLNSwapState.CLAIM_COMMITED)
818
+ if (this._state !== FromBTCLNSwapState.CLAIM_COMMITED)
622
819
  throw new Error("Invalid state (not CLAIM_COMMITED)");
623
820
  const abortController = new AbortController();
624
821
  if (abortSignal != null)
@@ -656,16 +853,16 @@ class FromBTCLNSwap extends IFromBTCSelfInitSwap_1.IFromBTCSelfInitSwap {
656
853
  }
657
854
  this.logger.debug("waitTillClaimed(): Resolved from watchdog");
658
855
  if (res?.type === base_1.SwapCommitStateType.PAID) {
659
- if (this.state !== FromBTCLNSwapState.CLAIM_CLAIMED) {
660
- this.claimTxId = await res.getClaimTxId();
856
+ if (this._state !== FromBTCLNSwapState.CLAIM_CLAIMED) {
857
+ this._claimTxId = await res.getClaimTxId();
661
858
  await this._saveAndEmit(FromBTCLNSwapState.CLAIM_CLAIMED);
662
859
  }
663
860
  }
664
861
  if (res?.type === base_1.SwapCommitStateType.NOT_COMMITED || res?.type === base_1.SwapCommitStateType.EXPIRED) {
665
- if (this.state !== FromBTCLNSwapState.CLAIM_CLAIMED &&
666
- this.state !== FromBTCLNSwapState.FAILED) {
862
+ if (this._state !== FromBTCLNSwapState.CLAIM_CLAIMED &&
863
+ this._state !== FromBTCLNSwapState.FAILED) {
667
864
  if (res.getRefundTxId != null)
668
- this.refundTxId = await res.getRefundTxId();
865
+ this._refundTxId = await res.getRefundTxId();
669
866
  await this._saveAndEmit(FromBTCLNSwapState.FAILED);
670
867
  }
671
868
  throw new Error("Swap expired while waiting for claim!");
@@ -675,10 +872,11 @@ class FromBTCLNSwap extends IFromBTCSelfInitSwap_1.IFromBTCSelfInitSwap {
675
872
  //////////////////////////////
676
873
  //// Commit & claim
677
874
  /**
678
- * Estimated transaction fee for commit & claim txs combined
875
+ * Estimated transaction fee for commit & claim transactions combined, required
876
+ * to settle the swap on the smart chain destination side.
679
877
  */
680
- async getCommitAndClaimFee() {
681
- const swapContract = this.wrapper.contract;
878
+ async getCommitAndClaimNetworkFee() {
879
+ const swapContract = this.wrapper._contract;
682
880
  const feeRate = this.feeRate ?? await swapContract.getInitFeeRate(this.getSwapData().getOfferer(), this.getSwapData().getClaimer(), this.getSwapData().getToken(), this.getSwapData().getClaimHash());
683
881
  const commitFee = await (swapContract.getRawCommitFee != null ?
684
882
  swapContract.getRawCommitFee(this._getInitiator(), this.getSwapData(), feeRate) :
@@ -686,57 +884,75 @@ class FromBTCLNSwap extends IFromBTCSelfInitSwap_1.IFromBTCSelfInitSwap {
686
884
  const claimFee = await (swapContract.getRawClaimFee != null ?
687
885
  swapContract.getRawClaimFee(this._getInitiator(), this.getSwapData(), feeRate) :
688
886
  swapContract.getClaimFee(this._getInitiator(), this.getSwapData(), feeRate));
689
- return commitFee + claimFee;
887
+ return (0, TokenAmount_1.toTokenAmount)(commitFee + claimFee, this.wrapper._getNativeToken(), this.wrapper._prices);
690
888
  }
889
+ /**
890
+ * Returns whether the underlying chain supports calling commit and claim in a single call,
891
+ * such that you can use the {@link commitAndClaim} function. If not you have to manually
892
+ * call {@link commit} first and then {@link claim}.
893
+ */
691
894
  canCommitAndClaimInOneShot() {
692
- return this.wrapper.contract.initAndClaimWithSecret != null;
895
+ return this.wrapper._contract.initAndClaimWithSecret != null;
693
896
  }
694
897
  /**
695
898
  * Returns transactions for both commit & claim operation together, such that they can be signed all at once by
696
- * the wallet. CAUTION: transactions must be sent sequentially, such that the claim (2nd) transaction is only
899
+ * the wallet. **WARNING**: transactions must be sent sequentially, such that the claim (2nd) transaction is only
697
900
  * sent after the commit (1st) transaction confirms. Failure to do so can reveal the HTLC pre-image too soon,
698
- * opening a possibility for the LP to steal funds.
901
+ * opening a possibility for the LP to steal funds!
699
902
  *
700
903
  * @param skipChecks Skip checks like making sure init signature is still valid and swap wasn't commited yet
701
904
  * (this is handled when swap is created (quoted), if you commit right after quoting, you can use skipChecks=true)
905
+ * @param secret A swap secret to use for the claim transaction, generally only needed if the swap
906
+ * was recovered from on-chain data, or the pre-image was generated outside the SDK
702
907
  *
703
908
  * @throws {Error} If in invalid state (must be PR_PAID or CLAIM_COMMITED)
704
909
  */
705
- async txsCommitAndClaim(skipChecks) {
706
- if (this.state === FromBTCLNSwapState.CLAIM_COMMITED)
707
- return await this.txsClaim();
708
- if (this.state !== FromBTCLNSwapState.PR_PAID &&
709
- (this.state !== FromBTCLNSwapState.QUOTE_SOFT_EXPIRED || this.signatureData == null))
910
+ async txsCommitAndClaim(skipChecks, secret) {
911
+ if (this._state === FromBTCLNSwapState.CLAIM_COMMITED)
912
+ return await this.txsClaim(undefined, secret);
913
+ if (this._state !== FromBTCLNSwapState.PR_PAID &&
914
+ (this._state !== FromBTCLNSwapState.QUOTE_SOFT_EXPIRED || this.signatureData == null))
710
915
  throw new Error("Must be in PR_PAID state!");
711
- if (this.data == null)
916
+ if (this._data == null)
712
917
  throw new Error("Unknown data, wrong state?");
918
+ const useSecret = secret ?? this.secret;
919
+ if (useSecret == null)
920
+ throw new Error("Swap secret pre-image not known and not provided, please provide the swap secret pre-image as second argument");
921
+ if (!this.isValidSecretPreimage(useSecret))
922
+ throw new Error("Invalid swap secret pre-image provided!");
713
923
  const initTxs = await this.txsCommit(skipChecks);
714
- const claimTxs = await this.wrapper.contract.txsClaimWithSecret(this._getInitiator(), this.data, this.secret, true, true, undefined, true);
924
+ const claimTxs = await this.wrapper._contract.txsClaimWithSecret(this._getInitiator(), this._data, useSecret, true, true, undefined, true);
715
925
  return initTxs.concat(claimTxs);
716
926
  }
717
927
  /**
718
- * Commits and claims the swap, in a way that the transactions can be signed together by the underlying provider and
719
- * then sent sequentially
928
+ * Commits and claims the swap, in a way that the transactions can be signed together by the provided signer and
929
+ * then automatically sent sequentially by the SDK. To check if the underlying chain supports this flow check
930
+ * the {@link canCommitAndClaimInOneShot} function.
720
931
  *
721
932
  * @param _signer Signer to sign the transactions with, must be the same as used in the initialization
722
933
  * @param abortSignal Abort signal to stop waiting for the transaction confirmation and abort
723
934
  * @param skipChecks Skip checks like making sure init signature is still valid and swap wasn't commited yet
724
935
  * (this is handled when swap is created (quoted), if you commit right after quoting, you can use skipChecks=true)
725
- * @param onBeforeCommitTxSent
726
- * @param onBeforeClaimTxSent
936
+ * @param onBeforeCommitTxSent Optional callback called before the initialization (commit) transaction is
937
+ * broadcasted
938
+ * @param onBeforeClaimTxSent Optional callback called before the settlement (claim) transaction is
939
+ * broadcasted
940
+ * @param secret A swap secret to use for the claim transaction, generally only needed if the swap
941
+ * was recovered from on-chain data, or the pre-image was generated outside the SDK
942
+ *
727
943
  * @throws {Error} If in invalid state (must be PR_PAID or CLAIM_COMMITED)
728
944
  * @throws {Error} If invalid signer is provided that doesn't match the swap data
729
945
  */
730
- async commitAndClaim(_signer, abortSignal, skipChecks, onBeforeCommitTxSent, onBeforeClaimTxSent) {
731
- const signer = (0, base_1.isAbstractSigner)(_signer) ? _signer : await this.wrapper.chain.wrapSigner(_signer);
946
+ async commitAndClaim(_signer, abortSignal, skipChecks, onBeforeCommitTxSent, onBeforeClaimTxSent, secret) {
947
+ const signer = (0, base_1.isAbstractSigner)(_signer) ? _signer : await this.wrapper._chain.wrapSigner(_signer);
732
948
  if (!this.canCommitAndClaimInOneShot())
733
949
  throw new Error("Cannot commitAndClaim in single action, please run commit and claim separately!");
734
950
  this.checkSigner(signer);
735
- if (this.state === FromBTCLNSwapState.CLAIM_COMMITED)
736
- return [await this.claim(signer, abortSignal, onBeforeClaimTxSent)];
951
+ if (this._state === FromBTCLNSwapState.CLAIM_COMMITED)
952
+ return [await this.claim(signer, abortSignal, onBeforeClaimTxSent, secret)];
737
953
  let txCount = 0;
738
- const txs = await this.txsCommitAndClaim(skipChecks);
739
- const result = await this.wrapper.chain.sendAndConfirm(signer, txs, true, abortSignal, undefined, (txId) => {
954
+ const txs = await this.txsCommitAndClaim(skipChecks, secret);
955
+ const result = await this.wrapper._chain.sendAndConfirm(signer, txs, true, abortSignal, undefined, (txId) => {
740
956
  txCount++;
741
957
  if (onBeforeCommitTxSent != null && txCount === 1)
742
958
  onBeforeCommitTxSent(txId);
@@ -744,9 +960,9 @@ class FromBTCLNSwap extends IFromBTCSelfInitSwap_1.IFromBTCSelfInitSwap {
744
960
  onBeforeClaimTxSent(txId);
745
961
  return Promise.resolve();
746
962
  });
747
- this.commitTxId = result[0] ?? this.commitTxId;
748
- this.claimTxId = result[result.length - 1] ?? this.claimTxId;
749
- if (this.state !== FromBTCLNSwapState.CLAIM_CLAIMED) {
963
+ this._commitTxId = result[0] ?? this._commitTxId;
964
+ this._claimTxId = result[result.length - 1] ?? this._claimTxId;
965
+ if (this._state !== FromBTCLNSwapState.CLAIM_CLAIMED) {
750
966
  await this._saveAndEmit(FromBTCLNSwapState.CLAIM_CLAIMED);
751
967
  }
752
968
  return result;
@@ -754,21 +970,29 @@ class FromBTCLNSwap extends IFromBTCSelfInitSwap_1.IFromBTCSelfInitSwap {
754
970
  //////////////////////////////
755
971
  //// LNURL
756
972
  /**
757
- * Is this an LNURL-withdraw swap?
973
+ * Whether this swap uses an LNURL-withdraw link
758
974
  */
759
975
  isLNURL() {
760
976
  return this.lnurl != null;
761
977
  }
762
978
  /**
763
- * Gets the used LNURL or null if this is not an LNURL-withdraw swap
979
+ * Gets the used LNURL or `null` if this is not an LNURL-withdraw swap
764
980
  */
765
981
  getLNURL() {
766
982
  return this.lnurl ?? null;
767
983
  }
768
984
  /**
769
- * Pay the generated lightning network invoice with LNURL-withdraw
985
+ * Pay the generated lightning network invoice with an LNURL-withdraw link, this
986
+ * is useful when you want to display a lightning payment QR code and also want to
987
+ * allow payments using LNURL-withdraw NFC cards.
988
+ *
989
+ * Note that the swap needs to be created **without** an LNURL to begin with for this function
990
+ * to work. If this swap is already using an LNURL-withdraw link, this function throws.
770
991
  */
771
992
  async settleWithLNURLWithdraw(lnurl) {
993
+ if (this._state !== FromBTCLNSwapState.PR_CREATED &&
994
+ (this._state !== FromBTCLNSwapState.QUOTE_SOFT_EXPIRED || this.signatureData != null))
995
+ throw new Error("Must be in PR_CREATED state!");
772
996
  if (this.lnurl != null)
773
997
  throw new Error("Cannot settle LNURL-withdraw swap with different LNURL");
774
998
  let lnurlParams;
@@ -781,6 +1005,8 @@ class FromBTCLNSwap extends IFromBTCSelfInitSwap_1.IFromBTCSelfInitSwap {
781
1005
  else {
782
1006
  lnurlParams = lnurl.params;
783
1007
  }
1008
+ if (this.pr == null || !this.pr.toLowerCase().startsWith("ln"))
1009
+ throw new Error("Input lightning network invoice not available, the swap was probably recovered!");
784
1010
  LNURL_1.LNURL.useLNURLWithdraw(lnurlParams, this.pr).catch(e => this.lnurlFailSignal.abort(e));
785
1011
  this.lnurl = lnurlParams.url;
786
1012
  this.lnurlCallback = lnurlParams.callback;
@@ -790,6 +1016,9 @@ class FromBTCLNSwap extends IFromBTCSelfInitSwap_1.IFromBTCSelfInitSwap {
790
1016
  }
791
1017
  //////////////////////////////
792
1018
  //// Storage
1019
+ /**
1020
+ * @inheritDoc
1021
+ */
793
1022
  serialize() {
794
1023
  return {
795
1024
  ...super.serialize(),
@@ -799,7 +1028,8 @@ class FromBTCLNSwap extends IFromBTCSelfInitSwap_1.IFromBTCSelfInitSwap {
799
1028
  lnurlK1: this.lnurlK1,
800
1029
  lnurlCallback: this.lnurlCallback,
801
1030
  prPosted: this.prPosted,
802
- initialSwapData: this.initialSwapData.serialize()
1031
+ initialSwapData: this.initialSwapData.serialize(),
1032
+ usesClaimHashAsId: this.usesClaimHashAsId
803
1033
  };
804
1034
  }
805
1035
  //////////////////////////////
@@ -811,70 +1041,61 @@ class FromBTCLNSwap extends IFromBTCSelfInitSwap_1.IFromBTCSelfInitSwap {
811
1041
  * @private
812
1042
  */
813
1043
  async syncStateFromChain(quoteDefinitelyExpired, commitStatus) {
814
- //Check for expiry before the getCommitStatus to prevent race conditions
815
- let quoteExpired = false;
816
- if (this.state === FromBTCLNSwapState.PR_PAID || (this.state === FromBTCLNSwapState.QUOTE_SOFT_EXPIRED && this.signatureData != null)) {
817
- quoteExpired = quoteDefinitelyExpired ?? await this._verifyQuoteDefinitelyExpired();
818
- }
819
- if (this.state === FromBTCLNSwapState.CLAIM_COMMITED || this.state === FromBTCLNSwapState.EXPIRED) {
820
- //Check if it's already successfully paid
821
- commitStatus ??= await this.wrapper.contract.getCommitStatus(this._getInitiator(), this.data);
822
- if (commitStatus?.type === base_1.SwapCommitStateType.PAID) {
823
- if (this.claimTxId == null)
824
- this.claimTxId = await commitStatus.getClaimTxId();
825
- this.state = FromBTCLNSwapState.CLAIM_CLAIMED;
826
- return true;
1044
+ if (this._state === FromBTCLNSwapState.PR_PAID ||
1045
+ (this._state === FromBTCLNSwapState.QUOTE_SOFT_EXPIRED && this.signatureData != null) ||
1046
+ this._state === FromBTCLNSwapState.CLAIM_COMMITED ||
1047
+ this._state === FromBTCLNSwapState.EXPIRED) {
1048
+ //Check for expiry before the getCommitStatus to prevent race conditions
1049
+ let quoteExpired = false;
1050
+ if (this._state === FromBTCLNSwapState.PR_PAID || (this._state === FromBTCLNSwapState.QUOTE_SOFT_EXPIRED && this.signatureData != null)) {
1051
+ quoteExpired = quoteDefinitelyExpired ?? await this._verifyQuoteDefinitelyExpired();
827
1052
  }
828
- if (commitStatus?.type === base_1.SwapCommitStateType.NOT_COMMITED || commitStatus?.type === base_1.SwapCommitStateType.EXPIRED) {
829
- if (this.refundTxId == null && commitStatus.getRefundTxId)
830
- this.refundTxId = await commitStatus.getRefundTxId();
831
- this.state = FromBTCLNSwapState.FAILED;
1053
+ //Check if it's already successfully paid
1054
+ commitStatus ??= await this.wrapper._contract.getCommitStatus(this._getInitiator(), this._data);
1055
+ if (commitStatus != null && await this._forciblySetOnchainState(commitStatus))
832
1056
  return true;
833
- }
834
- }
835
- if (this.state === FromBTCLNSwapState.PR_PAID || (this.state === FromBTCLNSwapState.QUOTE_SOFT_EXPIRED && this.signatureData != null)) {
836
- //Check if it's already committed
837
- commitStatus ??= await this.wrapper.contract.getCommitStatus(this._getInitiator(), this.data);
838
- switch (commitStatus?.type) {
839
- case base_1.SwapCommitStateType.COMMITED:
840
- this.state = FromBTCLNSwapState.CLAIM_COMMITED;
841
- return true;
842
- case base_1.SwapCommitStateType.EXPIRED:
843
- if (this.refundTxId == null && commitStatus.getRefundTxId)
844
- this.refundTxId = await commitStatus.getRefundTxId();
845
- this.state = FromBTCLNSwapState.QUOTE_EXPIRED;
1057
+ //Set the state on expiry here
1058
+ if (this._state === FromBTCLNSwapState.PR_PAID || (this._state === FromBTCLNSwapState.QUOTE_SOFT_EXPIRED && this.signatureData != null)) {
1059
+ if (quoteExpired) {
1060
+ this._state = FromBTCLNSwapState.QUOTE_EXPIRED;
846
1061
  return true;
847
- case base_1.SwapCommitStateType.PAID:
848
- if (this.claimTxId == null && commitStatus.getClaimTxId)
849
- this.claimTxId = await commitStatus.getClaimTxId();
850
- this.state = FromBTCLNSwapState.CLAIM_CLAIMED;
851
- return true;
852
- }
853
- }
854
- //Set the state on expiry here
855
- if (this.state === FromBTCLNSwapState.PR_PAID || (this.state === FromBTCLNSwapState.QUOTE_SOFT_EXPIRED && this.signatureData != null)) {
856
- if (quoteExpired) {
857
- this.state = FromBTCLNSwapState.QUOTE_EXPIRED;
858
- return true;
1062
+ }
859
1063
  }
860
1064
  }
861
1065
  return false;
862
1066
  }
1067
+ /**
1068
+ * @inheritDoc
1069
+ * @internal
1070
+ */
863
1071
  _shouldFetchExpiryStatus() {
864
- return this.state === FromBTCLNSwapState.PR_PAID || (this.state === FromBTCLNSwapState.QUOTE_SOFT_EXPIRED && this.signatureData != null);
1072
+ return this._state === FromBTCLNSwapState.PR_PAID || (this._state === FromBTCLNSwapState.QUOTE_SOFT_EXPIRED && this.signatureData != null);
865
1073
  }
866
- _shouldFetchCommitStatus() {
867
- return this.state === FromBTCLNSwapState.PR_PAID || (this.state === FromBTCLNSwapState.QUOTE_SOFT_EXPIRED && this.signatureData != null) ||
868
- this.state === FromBTCLNSwapState.CLAIM_COMMITED || this.state === FromBTCLNSwapState.EXPIRED;
1074
+ /**
1075
+ * @inheritDoc
1076
+ * @internal
1077
+ */
1078
+ _shouldFetchOnchainState() {
1079
+ return this._state === FromBTCLNSwapState.PR_PAID || (this._state === FromBTCLNSwapState.QUOTE_SOFT_EXPIRED && this.signatureData != null) ||
1080
+ this._state === FromBTCLNSwapState.CLAIM_COMMITED || this._state === FromBTCLNSwapState.EXPIRED;
869
1081
  }
1082
+ /**
1083
+ * Whether an intermediary (LP) should be contacted to get the state of this swap.
1084
+ *
1085
+ * @internal
1086
+ */
870
1087
  _shouldCheckIntermediary() {
871
- return this.state === FromBTCLNSwapState.PR_CREATED || (this.state === FromBTCLNSwapState.QUOTE_SOFT_EXPIRED && this.signatureData == null);
1088
+ return this._state === FromBTCLNSwapState.PR_CREATED || (this._state === FromBTCLNSwapState.QUOTE_SOFT_EXPIRED && this.signatureData == null);
872
1089
  }
1090
+ /**
1091
+ * @inheritDoc
1092
+ * @internal
1093
+ */
873
1094
  async _sync(save, quoteDefinitelyExpired, commitStatus, skipLpCheck) {
874
1095
  let changed = false;
875
- if (this.state === FromBTCLNSwapState.PR_CREATED || (this.state === FromBTCLNSwapState.QUOTE_SOFT_EXPIRED && this.signatureData == null)) {
876
- if (this.state != FromBTCLNSwapState.QUOTE_SOFT_EXPIRED && this.getTimeoutTime() < Date.now()) {
877
- this.state = FromBTCLNSwapState.QUOTE_SOFT_EXPIRED;
1096
+ if (this._state === FromBTCLNSwapState.PR_CREATED || (this._state === FromBTCLNSwapState.QUOTE_SOFT_EXPIRED && this.signatureData == null)) {
1097
+ if (this._state != FromBTCLNSwapState.QUOTE_SOFT_EXPIRED && this.getTimeoutTime() < Date.now()) {
1098
+ this._state = FromBTCLNSwapState.QUOTE_SOFT_EXPIRED;
878
1099
  changed ||= true;
879
1100
  }
880
1101
  if (!skipLpCheck)
@@ -886,24 +1107,70 @@ class FromBTCLNSwap extends IFromBTCSelfInitSwap_1.IFromBTCSelfInitSwap {
886
1107
  catch (e) {
887
1108
  this.logger.error("_sync(): Failed to synchronize swap, error: ", e);
888
1109
  }
889
- if (this.state === FromBTCLNSwapState.PR_CREATED || (this.state === FromBTCLNSwapState.QUOTE_SOFT_EXPIRED && this.signatureData == null)) {
1110
+ if (this._state === FromBTCLNSwapState.PR_CREATED || (this._state === FromBTCLNSwapState.QUOTE_SOFT_EXPIRED && this.signatureData == null)) {
890
1111
  if (await this._verifyQuoteDefinitelyExpired()) {
891
- this.state = FromBTCLNSwapState.QUOTE_EXPIRED;
1112
+ this._state = FromBTCLNSwapState.QUOTE_EXPIRED;
892
1113
  changed ||= true;
893
1114
  }
894
1115
  }
895
1116
  }
896
1117
  if (await this.syncStateFromChain(quoteDefinitelyExpired, commitStatus))
897
1118
  changed = true;
1119
+ if (this._state === FromBTCLNSwapState.CLAIM_COMMITED) {
1120
+ const expired = await this.wrapper._contract.isExpired(this._getInitiator(), this._data);
1121
+ if (expired) {
1122
+ this._state = FromBTCLNSwapState.EXPIRED;
1123
+ changed = true;
1124
+ }
1125
+ }
898
1126
  if (save && changed)
899
1127
  await this._saveAndEmit();
900
1128
  return changed;
901
1129
  }
1130
+ /**
1131
+ * @inheritDoc
1132
+ * @internal
1133
+ */
1134
+ async _forciblySetOnchainState(commitStatus) {
1135
+ switch (commitStatus.type) {
1136
+ case base_1.SwapCommitStateType.PAID:
1137
+ if (this._claimTxId == null)
1138
+ this._claimTxId = await commitStatus.getClaimTxId();
1139
+ if (this.secret == null || this.pr == null)
1140
+ this._setSwapSecret(await commitStatus.getClaimResult());
1141
+ this._state = FromBTCLNSwapState.CLAIM_CLAIMED;
1142
+ return true;
1143
+ case base_1.SwapCommitStateType.NOT_COMMITED:
1144
+ if (this._refundTxId == null && commitStatus.getRefundTxId)
1145
+ this._refundTxId = await commitStatus.getRefundTxId();
1146
+ if (this._refundTxId != null) {
1147
+ this._state = FromBTCLNSwapState.FAILED;
1148
+ return true;
1149
+ }
1150
+ break;
1151
+ case base_1.SwapCommitStateType.EXPIRED:
1152
+ if (this._refundTxId == null && commitStatus.getRefundTxId)
1153
+ this._refundTxId = await commitStatus.getRefundTxId();
1154
+ this._state = this._refundTxId == null ? FromBTCLNSwapState.QUOTE_EXPIRED : FromBTCLNSwapState.FAILED;
1155
+ return true;
1156
+ case base_1.SwapCommitStateType.COMMITED:
1157
+ if (this._state !== FromBTCLNSwapState.CLAIM_COMMITED && this._state !== FromBTCLNSwapState.EXPIRED) {
1158
+ this._state = FromBTCLNSwapState.CLAIM_COMMITED;
1159
+ return true;
1160
+ }
1161
+ break;
1162
+ }
1163
+ return false;
1164
+ }
1165
+ /**
1166
+ * @inheritDoc
1167
+ * @internal
1168
+ */
902
1169
  async _tick(save) {
903
- switch (this.state) {
1170
+ switch (this._state) {
904
1171
  case FromBTCLNSwapState.PR_CREATED:
905
1172
  if (this.getTimeoutTime() < Date.now()) {
906
- this.state = FromBTCLNSwapState.QUOTE_SOFT_EXPIRED;
1173
+ this._state = FromBTCLNSwapState.QUOTE_SOFT_EXPIRED;
907
1174
  if (save)
908
1175
  await this._saveAndEmit();
909
1176
  return true;
@@ -911,16 +1178,16 @@ class FromBTCLNSwap extends IFromBTCSelfInitSwap_1.IFromBTCSelfInitSwap {
911
1178
  break;
912
1179
  case FromBTCLNSwapState.PR_PAID:
913
1180
  if (this.expiry < Date.now()) {
914
- this.state = FromBTCLNSwapState.QUOTE_SOFT_EXPIRED;
1181
+ this._state = FromBTCLNSwapState.QUOTE_SOFT_EXPIRED;
915
1182
  if (save)
916
1183
  await this._saveAndEmit();
917
1184
  return true;
918
1185
  }
919
1186
  break;
920
1187
  case FromBTCLNSwapState.CLAIM_COMMITED:
921
- const expired = await this.wrapper.contract.isExpired(this._getInitiator(), this.data);
1188
+ const expired = await this.wrapper._contract.isExpired(this._getInitiator(), this._data);
922
1189
  if (expired) {
923
- this.state = FromBTCLNSwapState.EXPIRED;
1190
+ this._state = FromBTCLNSwapState.EXPIRED;
924
1191
  if (save)
925
1192
  await this._saveAndEmit();
926
1193
  return true;
@@ -929,5 +1196,16 @@ class FromBTCLNSwap extends IFromBTCSelfInitSwap_1.IFromBTCSelfInitSwap {
929
1196
  }
930
1197
  return false;
931
1198
  }
1199
+ /**
1200
+ * Forcibly sets the swap secret pre-image from on-chain data
1201
+ *
1202
+ * @internal
1203
+ */
1204
+ _setSwapSecret(secret) {
1205
+ this.secret = secret;
1206
+ if (this.pr == null) {
1207
+ this.pr = buffer_1.Buffer.from((0, sha2_1.sha256)(buffer_1.Buffer.from(secret, "hex"))).toString("hex");
1208
+ }
1209
+ }
932
1210
  }
933
1211
  exports.FromBTCLNSwap = FromBTCLNSwap;