@atomiqlabs/sdk 8.9.1 → 8.9.3

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 (366) hide show
  1. package/LICENSE +201 -201
  2. package/README.md +1760 -1760
  3. package/api/index.d.ts +1 -1
  4. package/api/index.js +3 -3
  5. package/dist/ApiList.d.ts +37 -37
  6. package/dist/ApiList.js +30 -30
  7. package/dist/SmartChainAssets.d.ts +181 -181
  8. package/dist/SmartChainAssets.js +181 -181
  9. package/dist/api/ApiEndpoints.d.ts +393 -393
  10. package/dist/api/ApiEndpoints.js +2 -2
  11. package/dist/api/ApiParser.d.ts +10 -10
  12. package/dist/api/ApiParser.js +134 -134
  13. package/dist/api/ApiTypes.d.ts +157 -157
  14. package/dist/api/ApiTypes.js +75 -75
  15. package/dist/api/SerializedAction.d.ts +40 -40
  16. package/dist/api/SerializedAction.js +59 -59
  17. package/dist/api/SwapperApi.d.ts +50 -50
  18. package/dist/api/SwapperApi.js +431 -431
  19. package/dist/api/index.d.ts +5 -5
  20. package/dist/api/index.js +24 -24
  21. package/dist/bitcoin/coinselect2/accumulative.d.ts +7 -7
  22. package/dist/bitcoin/coinselect2/accumulative.js +52 -52
  23. package/dist/bitcoin/coinselect2/blackjack.d.ts +7 -7
  24. package/dist/bitcoin/coinselect2/blackjack.js +38 -38
  25. package/dist/bitcoin/coinselect2/index.d.ts +20 -20
  26. package/dist/bitcoin/coinselect2/index.js +69 -69
  27. package/dist/bitcoin/coinselect2/utils.d.ts +82 -82
  28. package/dist/bitcoin/coinselect2/utils.js +158 -158
  29. package/dist/bitcoin/wallet/BitcoinWallet.d.ts +113 -113
  30. package/dist/bitcoin/wallet/BitcoinWallet.js +335 -335
  31. package/dist/bitcoin/wallet/IBitcoinWallet.d.ts +116 -116
  32. package/dist/bitcoin/wallet/IBitcoinWallet.js +21 -21
  33. package/dist/bitcoin/wallet/SingleAddressBitcoinWallet.d.ts +106 -106
  34. package/dist/bitcoin/wallet/SingleAddressBitcoinWallet.js +196 -196
  35. package/dist/enums/FeeType.d.ts +15 -15
  36. package/dist/enums/FeeType.js +19 -19
  37. package/dist/enums/SwapAmountType.d.ts +15 -15
  38. package/dist/enums/SwapAmountType.js +19 -19
  39. package/dist/enums/SwapDirection.d.ts +15 -15
  40. package/dist/enums/SwapDirection.js +19 -19
  41. package/dist/enums/SwapSide.d.ts +15 -15
  42. package/dist/enums/SwapSide.js +19 -19
  43. package/dist/enums/SwapType.d.ts +75 -75
  44. package/dist/enums/SwapType.js +79 -79
  45. package/dist/errors/IntermediaryError.d.ts +13 -13
  46. package/dist/errors/IntermediaryError.js +27 -27
  47. package/dist/errors/RequestError.d.ts +32 -32
  48. package/dist/errors/RequestError.js +54 -54
  49. package/dist/errors/UserError.d.ts +8 -8
  50. package/dist/errors/UserError.js +16 -16
  51. package/dist/events/UnifiedSwapEventListener.d.ts +24 -24
  52. package/dist/events/UnifiedSwapEventListener.js +138 -138
  53. package/dist/http/HttpUtils.d.ts +29 -29
  54. package/dist/http/HttpUtils.js +97 -97
  55. package/dist/http/paramcoders/IParamReader.d.ts +8 -8
  56. package/dist/http/paramcoders/IParamReader.js +2 -2
  57. package/dist/http/paramcoders/ParamDecoder.d.ts +44 -44
  58. package/dist/http/paramcoders/ParamDecoder.js +137 -137
  59. package/dist/http/paramcoders/ParamEncoder.d.ts +20 -20
  60. package/dist/http/paramcoders/ParamEncoder.js +36 -36
  61. package/dist/http/paramcoders/SchemaVerifier.d.ts +26 -26
  62. package/dist/http/paramcoders/SchemaVerifier.js +145 -145
  63. package/dist/http/paramcoders/client/ResponseParamDecoder.d.ts +11 -11
  64. package/dist/http/paramcoders/client/ResponseParamDecoder.js +57 -57
  65. package/dist/http/paramcoders/client/StreamParamEncoder.d.ts +13 -13
  66. package/dist/http/paramcoders/client/StreamParamEncoder.js +26 -26
  67. package/dist/http/paramcoders/client/StreamingFetchPromise.d.ts +17 -17
  68. package/dist/http/paramcoders/client/StreamingFetchPromise.js +175 -175
  69. package/dist/index.d.ts +86 -86
  70. package/dist/index.js +159 -159
  71. package/dist/intermediaries/Intermediary.d.ts +178 -178
  72. package/dist/intermediaries/Intermediary.js +166 -166
  73. package/dist/intermediaries/IntermediaryDiscovery.d.ts +216 -216
  74. package/dist/intermediaries/IntermediaryDiscovery.js +424 -424
  75. package/dist/intermediaries/apis/IntermediaryAPI.d.ts +607 -607
  76. package/dist/intermediaries/apis/IntermediaryAPI.js +764 -764
  77. package/dist/intermediaries/apis/TrustedIntermediaryAPI.d.ts +155 -155
  78. package/dist/intermediaries/apis/TrustedIntermediaryAPI.js +137 -137
  79. package/dist/intermediaries/auth/SignedKeyBasedAuth.d.ts +14 -14
  80. package/dist/intermediaries/auth/SignedKeyBasedAuth.js +68 -68
  81. package/dist/lnurl/LNURL.d.ts +102 -102
  82. package/dist/lnurl/LNURL.js +321 -321
  83. package/dist/prices/RedundantSwapPrice.d.ts +110 -110
  84. package/dist/prices/RedundantSwapPrice.js +222 -222
  85. package/dist/prices/SingleSwapPrice.d.ts +34 -34
  86. package/dist/prices/SingleSwapPrice.js +44 -44
  87. package/dist/prices/SwapPriceWithChain.d.ts +107 -107
  88. package/dist/prices/SwapPriceWithChain.js +128 -128
  89. package/dist/prices/abstract/ICachedSwapPrice.d.ts +28 -28
  90. package/dist/prices/abstract/ICachedSwapPrice.js +62 -62
  91. package/dist/prices/abstract/IPriceProvider.d.ts +81 -81
  92. package/dist/prices/abstract/IPriceProvider.js +74 -74
  93. package/dist/prices/abstract/ISwapPrice.d.ts +168 -168
  94. package/dist/prices/abstract/ISwapPrice.js +279 -279
  95. package/dist/prices/providers/BinancePriceProvider.d.ts +23 -23
  96. package/dist/prices/providers/BinancePriceProvider.js +30 -30
  97. package/dist/prices/providers/CoinGeckoPriceProvider.d.ts +23 -23
  98. package/dist/prices/providers/CoinGeckoPriceProvider.js +29 -29
  99. package/dist/prices/providers/CoinPaprikaPriceProvider.d.ts +25 -25
  100. package/dist/prices/providers/CoinPaprikaPriceProvider.js +29 -29
  101. package/dist/prices/providers/CustomPriceProvider.d.ts +24 -24
  102. package/dist/prices/providers/CustomPriceProvider.js +35 -35
  103. package/dist/prices/providers/KrakenPriceProvider.d.ts +38 -38
  104. package/dist/prices/providers/KrakenPriceProvider.js +45 -45
  105. package/dist/prices/providers/OKXPriceProvider.d.ts +34 -34
  106. package/dist/prices/providers/OKXPriceProvider.js +29 -29
  107. package/dist/prices/providers/abstract/ExchangePriceProvider.d.ts +17 -17
  108. package/dist/prices/providers/abstract/ExchangePriceProvider.js +21 -21
  109. package/dist/prices/providers/abstract/HttpPriceProvider.d.ts +7 -7
  110. package/dist/prices/providers/abstract/HttpPriceProvider.js +12 -12
  111. package/dist/storage/IUnifiedStorage.d.ts +127 -127
  112. package/dist/storage/IUnifiedStorage.js +2 -2
  113. package/dist/storage/UnifiedSwapStorage.d.ts +120 -120
  114. package/dist/storage/UnifiedSwapStorage.js +154 -154
  115. package/dist/storage-browser/IndexedDBUnifiedStorage.d.ts +63 -63
  116. package/dist/storage-browser/IndexedDBUnifiedStorage.js +298 -298
  117. package/dist/storage-browser/LocalStorageManager.d.ts +49 -49
  118. package/dist/storage-browser/LocalStorageManager.js +93 -93
  119. package/dist/swapper/Swapper.d.ts +770 -770
  120. package/dist/swapper/Swapper.js +1758 -1758
  121. package/dist/swapper/SwapperFactory.d.ts +135 -135
  122. package/dist/swapper/SwapperFactory.js +162 -162
  123. package/dist/swapper/SwapperUtils.d.ts +222 -222
  124. package/dist/swapper/SwapperUtils.js +519 -519
  125. package/dist/swapper/SwapperWithChain.d.ts +404 -404
  126. package/dist/swapper/SwapperWithChain.js +469 -469
  127. package/dist/swapper/SwapperWithSigner.d.ts +322 -322
  128. package/dist/swapper/SwapperWithSigner.js +318 -318
  129. package/dist/swaps/IAddressSwap.d.ts +22 -22
  130. package/dist/swaps/IAddressSwap.js +14 -14
  131. package/dist/swaps/IBTCWalletSwap.d.ts +73 -73
  132. package/dist/swaps/IBTCWalletSwap.js +18 -18
  133. package/dist/swaps/IClaimableSwap.d.ts +49 -49
  134. package/dist/swaps/IClaimableSwap.js +15 -15
  135. package/dist/swaps/IClaimableSwapWrapper.d.ts +15 -15
  136. package/dist/swaps/IClaimableSwapWrapper.js +2 -2
  137. package/dist/swaps/IRefundableSwap.d.ts +43 -43
  138. package/dist/swaps/IRefundableSwap.js +14 -14
  139. package/dist/swaps/ISwap.d.ts +453 -453
  140. package/dist/swaps/ISwap.js +371 -371
  141. package/dist/swaps/ISwapWithGasDrop.d.ts +21 -21
  142. package/dist/swaps/ISwapWithGasDrop.js +12 -12
  143. package/dist/swaps/ISwapWrapper.d.ts +295 -295
  144. package/dist/swaps/ISwapWrapper.js +373 -373
  145. package/dist/swaps/escrow_swaps/IEscrowSelfInitSwap.d.ts +98 -98
  146. package/dist/swaps/escrow_swaps/IEscrowSelfInitSwap.js +126 -126
  147. package/dist/swaps/escrow_swaps/IEscrowSwap.d.ts +139 -139
  148. package/dist/swaps/escrow_swaps/IEscrowSwap.js +172 -172
  149. package/dist/swaps/escrow_swaps/IEscrowSwapWrapper.d.ts +129 -129
  150. package/dist/swaps/escrow_swaps/IEscrowSwapWrapper.js +167 -167
  151. package/dist/swaps/escrow_swaps/frombtc/IFromBTCLNWrapper.d.ts +107 -107
  152. package/dist/swaps/escrow_swaps/frombtc/IFromBTCLNWrapper.js +130 -130
  153. package/dist/swaps/escrow_swaps/frombtc/IFromBTCSelfInitSwap.d.ts +162 -162
  154. package/dist/swaps/escrow_swaps/frombtc/IFromBTCSelfInitSwap.js +190 -190
  155. package/dist/swaps/escrow_swaps/frombtc/IFromBTCWrapper.d.ts +64 -64
  156. package/dist/swaps/escrow_swaps/frombtc/IFromBTCWrapper.js +82 -82
  157. package/dist/swaps/escrow_swaps/frombtc/ln/FromBTCLNSwap.d.ts +547 -547
  158. package/dist/swaps/escrow_swaps/frombtc/ln/FromBTCLNSwap.js +1419 -1419
  159. package/dist/swaps/escrow_swaps/frombtc/ln/FromBTCLNWrapper.d.ts +192 -192
  160. package/dist/swaps/escrow_swaps/frombtc/ln/FromBTCLNWrapper.js +432 -432
  161. package/dist/swaps/escrow_swaps/frombtc/ln_auto/FromBTCLNAutoSwap.d.ts +650 -650
  162. package/dist/swaps/escrow_swaps/frombtc/ln_auto/FromBTCLNAutoSwap.js +1577 -1577
  163. package/dist/swaps/escrow_swaps/frombtc/ln_auto/FromBTCLNAutoWrapper.d.ts +237 -237
  164. package/dist/swaps/escrow_swaps/frombtc/ln_auto/FromBTCLNAutoWrapper.js +525 -525
  165. package/dist/swaps/escrow_swaps/frombtc/onchain/FromBTCSwap.d.ts +491 -491
  166. package/dist/swaps/escrow_swaps/frombtc/onchain/FromBTCSwap.js +1463 -1463
  167. package/dist/swaps/escrow_swaps/frombtc/onchain/FromBTCWrapper.d.ts +204 -204
  168. package/dist/swaps/escrow_swaps/frombtc/onchain/FromBTCWrapper.js +406 -406
  169. package/dist/swaps/escrow_swaps/tobtc/IToBTCSwap.d.ts +446 -446
  170. package/dist/swaps/escrow_swaps/tobtc/IToBTCSwap.js +1097 -1097
  171. package/dist/swaps/escrow_swaps/tobtc/IToBTCWrapper.d.ts +68 -68
  172. package/dist/swaps/escrow_swaps/tobtc/IToBTCWrapper.js +117 -117
  173. package/dist/swaps/escrow_swaps/tobtc/ln/ToBTCLNSwap.d.ts +127 -127
  174. package/dist/swaps/escrow_swaps/tobtc/ln/ToBTCLNSwap.js +256 -256
  175. package/dist/swaps/escrow_swaps/tobtc/ln/ToBTCLNWrapper.d.ts +252 -252
  176. package/dist/swaps/escrow_swaps/tobtc/ln/ToBTCLNWrapper.js +535 -535
  177. package/dist/swaps/escrow_swaps/tobtc/onchain/ToBTCSwap.d.ts +73 -73
  178. package/dist/swaps/escrow_swaps/tobtc/onchain/ToBTCSwap.js +155 -155
  179. package/dist/swaps/escrow_swaps/tobtc/onchain/ToBTCWrapper.d.ts +134 -134
  180. package/dist/swaps/escrow_swaps/tobtc/onchain/ToBTCWrapper.js +286 -286
  181. package/dist/swaps/spv_swaps/SpvFromBTCSwap.d.ts +694 -694
  182. package/dist/swaps/spv_swaps/SpvFromBTCSwap.js +1687 -1687
  183. package/dist/swaps/spv_swaps/SpvFromBTCWrapper.d.ts +259 -259
  184. package/dist/swaps/spv_swaps/SpvFromBTCWrapper.js +947 -947
  185. package/dist/swaps/trusted/ln/LnForGasSwap.d.ts +302 -302
  186. package/dist/swaps/trusted/ln/LnForGasSwap.js +625 -625
  187. package/dist/swaps/trusted/ln/LnForGasWrapper.d.ts +40 -40
  188. package/dist/swaps/trusted/ln/LnForGasWrapper.js +82 -82
  189. package/dist/swaps/trusted/onchain/OnchainForGasSwap.d.ts +343 -343
  190. package/dist/swaps/trusted/onchain/OnchainForGasSwap.js +698 -698
  191. package/dist/swaps/trusted/onchain/OnchainForGasWrapper.d.ts +71 -71
  192. package/dist/swaps/trusted/onchain/OnchainForGasWrapper.js +93 -93
  193. package/dist/types/AmountData.d.ts +10 -10
  194. package/dist/types/AmountData.js +2 -2
  195. package/dist/types/CustomPriceFunction.d.ts +11 -11
  196. package/dist/types/CustomPriceFunction.js +2 -2
  197. package/dist/types/PriceInfoType.d.ts +28 -28
  198. package/dist/types/PriceInfoType.js +57 -57
  199. package/dist/types/SwapExecutionAction.d.ts +195 -195
  200. package/dist/types/SwapExecutionAction.js +106 -106
  201. package/dist/types/SwapExecutionStep.d.ts +144 -144
  202. package/dist/types/SwapExecutionStep.js +87 -87
  203. package/dist/types/SwapStateInfo.d.ts +5 -5
  204. package/dist/types/SwapStateInfo.js +2 -2
  205. package/dist/types/SwapWithSigner.d.ts +17 -17
  206. package/dist/types/SwapWithSigner.js +43 -43
  207. package/dist/types/Token.d.ts +99 -99
  208. package/dist/types/Token.js +76 -76
  209. package/dist/types/TokenAmount.d.ts +75 -75
  210. package/dist/types/TokenAmount.js +85 -85
  211. package/dist/types/fees/Fee.d.ts +50 -50
  212. package/dist/types/fees/Fee.js +2 -2
  213. package/dist/types/fees/FeeBreakdown.d.ts +11 -11
  214. package/dist/types/fees/FeeBreakdown.js +2 -2
  215. package/dist/types/fees/PercentagePPM.d.ts +17 -17
  216. package/dist/types/fees/PercentagePPM.js +18 -18
  217. package/dist/types/lnurl/LNURLPay.d.ts +61 -61
  218. package/dist/types/lnurl/LNURLPay.js +31 -31
  219. package/dist/types/lnurl/LNURLWithdraw.d.ts +48 -48
  220. package/dist/types/lnurl/LNURLWithdraw.js +27 -27
  221. package/dist/types/wallets/LightningInvoiceCreateService.d.ts +24 -24
  222. package/dist/types/wallets/LightningInvoiceCreateService.js +15 -15
  223. package/dist/types/wallets/MinimalBitcoinWalletInterface.d.ts +23 -23
  224. package/dist/types/wallets/MinimalBitcoinWalletInterface.js +2 -2
  225. package/dist/types/wallets/MinimalLightningNetworkWalletInterface.d.ts +9 -9
  226. package/dist/types/wallets/MinimalLightningNetworkWalletInterface.js +2 -2
  227. package/dist/utils/AutomaticClockDriftCorrection.d.ts +1 -1
  228. package/dist/utils/AutomaticClockDriftCorrection.js +70 -70
  229. package/dist/utils/BitcoinUtils.d.ts +18 -18
  230. package/dist/utils/BitcoinUtils.js +174 -174
  231. package/dist/utils/BitcoinWalletUtils.d.ts +7 -7
  232. package/dist/utils/BitcoinWalletUtils.js +14 -14
  233. package/dist/utils/Logger.d.ts +7 -7
  234. package/dist/utils/Logger.js +12 -12
  235. package/dist/utils/RetryUtils.d.ts +22 -22
  236. package/dist/utils/RetryUtils.js +67 -67
  237. package/dist/utils/SwapUtils.d.ts +88 -88
  238. package/dist/utils/SwapUtils.js +72 -72
  239. package/dist/utils/TimeoutUtils.d.ts +17 -17
  240. package/dist/utils/TimeoutUtils.js +55 -55
  241. package/dist/utils/TokenUtils.d.ts +19 -19
  242. package/dist/utils/TokenUtils.js +37 -37
  243. package/dist/utils/TypeUtils.d.ts +7 -7
  244. package/dist/utils/TypeUtils.js +2 -2
  245. package/dist/utils/Utils.d.ts +69 -69
  246. package/dist/utils/Utils.js +214 -214
  247. package/package.json +46 -46
  248. package/src/SmartChainAssets.ts +186 -186
  249. package/src/api/ApiEndpoints.ts +427 -427
  250. package/src/api/ApiParser.ts +138 -138
  251. package/src/api/ApiTypes.ts +229 -229
  252. package/src/api/SerializedAction.ts +97 -97
  253. package/src/api/SwapperApi.ts +545 -545
  254. package/src/api/index.ts +5 -5
  255. package/src/bitcoin/coinselect2/accumulative.ts +69 -69
  256. package/src/bitcoin/coinselect2/blackjack.ts +50 -50
  257. package/src/bitcoin/coinselect2/index.ts +93 -93
  258. package/src/bitcoin/coinselect2/utils.ts +236 -236
  259. package/src/bitcoin/wallet/BitcoinWallet.ts +439 -439
  260. package/src/bitcoin/wallet/IBitcoinWallet.ts +140 -140
  261. package/src/bitcoin/wallet/SingleAddressBitcoinWallet.ts +225 -225
  262. package/src/enums/FeeType.ts +15 -15
  263. package/src/enums/SwapAmountType.ts +16 -16
  264. package/src/enums/SwapDirection.ts +15 -15
  265. package/src/enums/SwapSide.ts +16 -16
  266. package/src/enums/SwapType.ts +75 -75
  267. package/src/errors/IntermediaryError.ts +28 -28
  268. package/src/errors/RequestError.ts +64 -64
  269. package/src/errors/UserError.ts +15 -15
  270. package/src/events/UnifiedSwapEventListener.ts +181 -181
  271. package/src/http/HttpUtils.ts +97 -97
  272. package/src/http/paramcoders/IParamReader.ts +9 -9
  273. package/src/http/paramcoders/ParamDecoder.ts +145 -145
  274. package/src/http/paramcoders/ParamEncoder.ts +40 -40
  275. package/src/http/paramcoders/SchemaVerifier.ts +153 -153
  276. package/src/http/paramcoders/client/ResponseParamDecoder.ts +57 -57
  277. package/src/http/paramcoders/client/StreamParamEncoder.ts +28 -28
  278. package/src/http/paramcoders/client/StreamingFetchPromise.ts +194 -194
  279. package/src/index.ts +141 -141
  280. package/src/intermediaries/Intermediary.ts +280 -280
  281. package/src/intermediaries/IntermediaryDiscovery.ts +548 -548
  282. package/src/intermediaries/apis/IntermediaryAPI.ts +1247 -1247
  283. package/src/intermediaries/auth/SignedKeyBasedAuth.ts +69 -69
  284. package/src/lnurl/LNURL.ts +402 -402
  285. package/src/prices/RedundantSwapPrice.ts +264 -264
  286. package/src/prices/SingleSwapPrice.ts +50 -50
  287. package/src/prices/SwapPriceWithChain.ts +194 -194
  288. package/src/prices/abstract/ICachedSwapPrice.ts +85 -85
  289. package/src/prices/abstract/IPriceProvider.ts +127 -127
  290. package/src/prices/abstract/ISwapPrice.ts +390 -390
  291. package/src/prices/providers/BinancePriceProvider.ts +48 -48
  292. package/src/prices/providers/CoinGeckoPriceProvider.ts +46 -46
  293. package/src/prices/providers/CoinPaprikaPriceProvider.ts +49 -49
  294. package/src/prices/providers/CustomPriceProvider.ts +40 -40
  295. package/src/prices/providers/KrakenPriceProvider.ts +83 -83
  296. package/src/prices/providers/OKXPriceProvider.ts +59 -59
  297. package/src/prices/providers/abstract/ExchangePriceProvider.ts +31 -31
  298. package/src/prices/providers/abstract/HttpPriceProvider.ts +14 -14
  299. package/src/storage/IUnifiedStorage.ts +136 -136
  300. package/src/storage/UnifiedSwapStorage.ts +175 -175
  301. package/src/storage-browser/IndexedDBUnifiedStorage.ts +350 -350
  302. package/src/storage-browser/LocalStorageManager.ts +106 -106
  303. package/src/swapper/Swapper.ts +2570 -2570
  304. package/src/swapper/SwapperFactory.ts +307 -307
  305. package/src/swapper/SwapperUtils.ts +610 -610
  306. package/src/swapper/SwapperWithChain.ts +707 -707
  307. package/src/swapper/SwapperWithSigner.ts +511 -511
  308. package/src/swaps/IAddressSwap.ts +30 -30
  309. package/src/swaps/IBTCWalletSwap.ts +92 -92
  310. package/src/swaps/IClaimableSwap.ts +65 -65
  311. package/src/swaps/IClaimableSwapWrapper.ts +17 -17
  312. package/src/swaps/IRefundableSwap.ts +58 -58
  313. package/src/swaps/ISwap.ts +775 -775
  314. package/src/swaps/ISwapWithGasDrop.ts +25 -25
  315. package/src/swaps/ISwapWrapper.ts +564 -564
  316. package/src/swaps/escrow_swaps/IEscrowSelfInitSwap.ts +217 -217
  317. package/src/swaps/escrow_swaps/IEscrowSwap.ts +271 -271
  318. package/src/swaps/escrow_swaps/IEscrowSwapWrapper.ts +284 -284
  319. package/src/swaps/escrow_swaps/frombtc/IFromBTCLNWrapper.ts +172 -172
  320. package/src/swaps/escrow_swaps/frombtc/IFromBTCSelfInitSwap.ts +300 -300
  321. package/src/swaps/escrow_swaps/frombtc/IFromBTCWrapper.ts +107 -107
  322. package/src/swaps/escrow_swaps/frombtc/ln/FromBTCLNSwap.ts +1670 -1671
  323. package/src/swaps/escrow_swaps/frombtc/ln/FromBTCLNWrapper.ts +603 -603
  324. package/src/swaps/escrow_swaps/frombtc/ln_auto/FromBTCLNAutoSwap.ts +1883 -1883
  325. package/src/swaps/escrow_swaps/frombtc/ln_auto/FromBTCLNAutoWrapper.ts +752 -752
  326. package/src/swaps/escrow_swaps/frombtc/onchain/FromBTCSwap.ts +1753 -1753
  327. package/src/swaps/escrow_swaps/frombtc/onchain/FromBTCWrapper.ts +612 -612
  328. package/src/swaps/escrow_swaps/tobtc/IToBTCSwap.ts +1327 -1327
  329. package/src/swaps/escrow_swaps/tobtc/IToBTCWrapper.ts +138 -138
  330. package/src/swaps/escrow_swaps/tobtc/ln/ToBTCLNSwap.ts +304 -304
  331. package/src/swaps/escrow_swaps/tobtc/ln/ToBTCLNWrapper.ts +787 -787
  332. package/src/swaps/escrow_swaps/tobtc/onchain/ToBTCSwap.ts +206 -206
  333. package/src/swaps/escrow_swaps/tobtc/onchain/ToBTCWrapper.ts +403 -403
  334. package/src/swaps/spv_swaps/SpvFromBTCSwap.ts +2148 -2148
  335. package/src/swaps/spv_swaps/SpvFromBTCWrapper.ts +1238 -1238
  336. package/src/swaps/trusted/ln/LnForGasSwap.ts +753 -753
  337. package/src/swaps/trusted/ln/LnForGasWrapper.ts +90 -90
  338. package/src/swaps/trusted/onchain/OnchainForGasSwap.ts +843 -843
  339. package/src/swaps/trusted/onchain/OnchainForGasWrapper.ts +133 -133
  340. package/src/types/AmountData.ts +9 -9
  341. package/src/types/CustomPriceFunction.ts +11 -11
  342. package/src/types/PriceInfoType.ts +66 -66
  343. package/src/types/SwapExecutionAction.ts +323 -323
  344. package/src/types/SwapExecutionStep.ts +224 -224
  345. package/src/types/SwapStateInfo.ts +6 -6
  346. package/src/types/SwapWithSigner.ts +61 -61
  347. package/src/types/Token.ts +163 -163
  348. package/src/types/TokenAmount.ts +167 -167
  349. package/src/types/fees/Fee.ts +56 -56
  350. package/src/types/fees/FeeBreakdown.ts +11 -11
  351. package/src/types/fees/PercentagePPM.ts +26 -26
  352. package/src/types/lnurl/LNURLPay.ts +79 -79
  353. package/src/types/lnurl/LNURLWithdraw.ts +61 -61
  354. package/src/types/wallets/LightningInvoiceCreateService.ts +30 -30
  355. package/src/types/wallets/MinimalBitcoinWalletInterface.ts +21 -21
  356. package/src/types/wallets/MinimalLightningNetworkWalletInterface.ts +9 -9
  357. package/src/utils/AutomaticClockDriftCorrection.ts +71 -71
  358. package/src/utils/BitcoinUtils.ts +164 -164
  359. package/src/utils/BitcoinWalletUtils.ts +15 -15
  360. package/src/utils/Logger.ts +14 -14
  361. package/src/utils/RetryUtils.ts +78 -78
  362. package/src/utils/SwapUtils.ts +99 -99
  363. package/src/utils/TimeoutUtils.ts +49 -49
  364. package/src/utils/TokenUtils.ts +33 -33
  365. package/src/utils/TypeUtils.ts +8 -8
  366. package/src/utils/Utils.ts +221 -221
@@ -1,1419 +1,1419 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.FromBTCLNSwap = exports.isFromBTCLNSwapInit = exports.FromBTCLNSwapState = void 0;
4
- const bolt11_1 = require("@atomiqlabs/bolt11");
5
- const IFromBTCSelfInitSwap_1 = require("../IFromBTCSelfInitSwap");
6
- const SwapType_1 = require("../../../../enums/SwapType");
7
- const base_1 = require("@atomiqlabs/base");
8
- const buffer_1 = require("buffer");
9
- const LNURL_1 = require("../../../../lnurl/LNURL");
10
- const UserError_1 = require("../../../../errors/UserError");
11
- const IntermediaryAPI_1 = require("../../../../intermediaries/apis/IntermediaryAPI");
12
- const IntermediaryError_1 = require("../../../../errors/IntermediaryError");
13
- const Utils_1 = require("../../../../utils/Utils");
14
- const IEscrowSelfInitSwap_1 = require("../../IEscrowSelfInitSwap");
15
- const TokenAmount_1 = require("../../../../types/TokenAmount");
16
- const Token_1 = require("../../../../types/Token");
17
- const Logger_1 = require("../../../../utils/Logger");
18
- const TimeoutUtils_1 = require("../../../../utils/TimeoutUtils");
19
- const LNURLWithdraw_1 = require("../../../../types/lnurl/LNURLWithdraw");
20
- const sha2_1 = require("@noble/hashes/sha2");
21
- /**
22
- * State enum for legacy Lightning -> Smart chain swaps
23
- * @category Swaps/Legacy/Lightning → Smart chain
24
- */
25
- var FromBTCLNSwapState;
26
- (function (FromBTCLNSwapState) {
27
- /**
28
- * Swap has failed as the user didn't settle the HTLC on the destination before expiration
29
- */
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
- */
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
- */
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
- */
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
- */
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
- */
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
- */
63
- FromBTCLNSwapState[FromBTCLNSwapState["CLAIM_COMMITED"] = 2] = "CLAIM_COMMITED";
64
- /**
65
- * Swap successfully settled and funds received on the destination chain
66
- */
67
- FromBTCLNSwapState[FromBTCLNSwapState["CLAIM_CLAIMED"] = 3] = "CLAIM_CLAIMED";
68
- })(FromBTCLNSwapState = exports.FromBTCLNSwapState || (exports.FromBTCLNSwapState = {}));
69
- const FromBTCLNSwapStateDescription = {
70
- [FromBTCLNSwapState.FAILED]: "Swap has failed as the user didn't settle the HTLC on the destination before expiration",
71
- [FromBTCLNSwapState.QUOTE_EXPIRED]: "Swap has expired for good and there is no way how it can be executed anymore",
72
- [FromBTCLNSwapState.QUOTE_SOFT_EXPIRED]: "Swap is expired, though there is still a chance that it will be processed",
73
- [FromBTCLNSwapState.EXPIRED]: "Swap HTLC on the destination chain has expired, it is not safe anymore to settle (claim) the swap on the destination smart chain.",
74
- [FromBTCLNSwapState.PR_CREATED]: "Swap quote was created, pay the bolt11 lightning network invoice to initiate the swap, then use the wait till the lightning network payment is received by the intermediary (LP)",
75
- [FromBTCLNSwapState.PR_PAID]: "Lightning network payment has been received by the intermediary (LP), the user can now settle the swap on the destination smart chain side.",
76
- [FromBTCLNSwapState.CLAIM_COMMITED]: "Swap escrow HTLC has been created on the destination chain. Continue by claiming it.",
77
- [FromBTCLNSwapState.CLAIM_CLAIMED]: "Swap successfully settled and funds received on the destination chain"
78
- };
79
- function isFromBTCLNSwapInit(obj) {
80
- return (obj.pr == null || typeof obj.pr === "string") &&
81
- (obj.secret == null || typeof obj.secret === "string") &&
82
- (obj.lnurl == null || typeof (obj.lnurl) === "string") &&
83
- (obj.lnurlK1 == null || typeof (obj.lnurlK1) === "string") &&
84
- (obj.lnurlCallback == null || typeof (obj.lnurlCallback) === "string") &&
85
- (0, IEscrowSelfInitSwap_1.isIEscrowSelfInitSwapInit)(obj);
86
- }
87
- exports.isFromBTCLNSwapInit = isFromBTCLNSwapInit;
88
- /**
89
- * Legacy escrow (HTLC) based swap for Bitcoin Lightning -> Smart chains, requires manual settlement
90
- * of the swap on the destination network once the lightning network payment is received by the LP.
91
- *
92
- * @category Swaps/Legacy/Lightning → Smart chain
93
- */
94
- class FromBTCLNSwap extends IFromBTCSelfInitSwap_1.IFromBTCSelfInitSwap {
95
- /**
96
- * Sets the LNURL data for the swap
97
- *
98
- * @internal
99
- */
100
- _setLNURLData(lnurl, lnurlK1, lnurlCallback) {
101
- this.lnurl = lnurl;
102
- this.lnurlK1 = lnurlK1;
103
- this.lnurlCallback = lnurlCallback;
104
- }
105
- constructor(wrapper, initOrObject) {
106
- if (isFromBTCLNSwapInit(initOrObject) && initOrObject.url != null)
107
- initOrObject.url += "/frombtcln";
108
- super(wrapper, initOrObject);
109
- this.TYPE = SwapType_1.SwapType.FROM_BTCLN;
110
- /**
111
- * @internal
112
- */
113
- this.swapStateName = (state) => FromBTCLNSwapState[state];
114
- /**
115
- * @internal
116
- */
117
- this.swapStateDescription = FromBTCLNSwapStateDescription;
118
- /**
119
- * @internal
120
- */
121
- this.inputToken = Token_1.BitcoinTokens.BTCLN;
122
- this.lnurlFailSignal = new AbortController();
123
- this.prPosted = false;
124
- if (isFromBTCLNSwapInit(initOrObject)) {
125
- this._state = FromBTCLNSwapState.PR_CREATED;
126
- this.pr = initOrObject.pr;
127
- this.secret = initOrObject.secret;
128
- this.initialSwapData = initOrObject.initialSwapData;
129
- this.lnurl = initOrObject.lnurl;
130
- this.lnurlK1 = initOrObject.lnurlK1;
131
- this.lnurlCallback = initOrObject.lnurlCallback;
132
- this.usesClaimHashAsId = true;
133
- }
134
- else {
135
- this.pr = initOrObject.pr;
136
- this.secret = initOrObject.secret;
137
- if (initOrObject.initialSwapData == null) {
138
- this.initialSwapData = this._data;
139
- }
140
- else {
141
- this.initialSwapData = base_1.SwapData.deserialize(initOrObject.initialSwapData);
142
- }
143
- this.lnurl = initOrObject.lnurl;
144
- this.lnurlK1 = initOrObject.lnurlK1;
145
- this.lnurlCallback = initOrObject.lnurlCallback;
146
- this.prPosted = initOrObject.prPosted;
147
- if (this._state === FromBTCLNSwapState.PR_CREATED && this._data != null) {
148
- this.initialSwapData = this._data;
149
- delete this._data;
150
- }
151
- this.usesClaimHashAsId = initOrObject.usesClaimHashAsId ?? false;
152
- }
153
- this.tryRecomputeSwapPrice();
154
- this.logger = (0, Logger_1.getLogger)("FromBTCLN(" + this.getIdentifierHashString() + "): ");
155
- }
156
- /**
157
- * @inheritDoc
158
- * @internal
159
- */
160
- getSwapData() {
161
- return this._data ?? this.initialSwapData;
162
- }
163
- /**
164
- * @inheritDoc
165
- * @internal
166
- */
167
- upgradeVersion() {
168
- if (this.version == null) {
169
- switch (this._state) {
170
- case -2:
171
- this._state = FromBTCLNSwapState.QUOTE_EXPIRED;
172
- break;
173
- case -1:
174
- this._state = FromBTCLNSwapState.FAILED;
175
- break;
176
- case 0:
177
- this._state = FromBTCLNSwapState.PR_CREATED;
178
- break;
179
- case 1:
180
- this._state = FromBTCLNSwapState.PR_PAID;
181
- break;
182
- case 2:
183
- this._state = FromBTCLNSwapState.CLAIM_COMMITED;
184
- break;
185
- case 3:
186
- this._state = FromBTCLNSwapState.CLAIM_CLAIMED;
187
- break;
188
- }
189
- this.version = 1;
190
- }
191
- }
192
- //////////////////////////////
193
- //// Getters & utils
194
- /**
195
- * @inheritDoc
196
- * @internal
197
- */
198
- getIdentifierHash() {
199
- const idBuffer = this.usesClaimHashAsId
200
- ? buffer_1.Buffer.from(this.getClaimHash(), "hex")
201
- : this.getPaymentHash();
202
- if (this._randomNonce == null)
203
- return idBuffer;
204
- return buffer_1.Buffer.concat([idBuffer, buffer_1.Buffer.from(this._randomNonce, "hex")]);
205
- }
206
- /**
207
- * Returns the payment hash of the swap and lightning network invoice, or `null` if not known (i.e. if
208
- * the swap was recovered from on-chain data, the payment hash might not be known)
209
- *
210
- * @internal
211
- */
212
- getPaymentHash() {
213
- if (this.pr == null)
214
- return null;
215
- if (this.pr.toLowerCase().startsWith("ln")) {
216
- const parsed = (0, bolt11_1.decode)(this.pr);
217
- if (parsed.tagsObject.payment_hash == null)
218
- throw new Error("Swap invoice has no payment hash field!");
219
- return buffer_1.Buffer.from(parsed.tagsObject.payment_hash, "hex");
220
- }
221
- return buffer_1.Buffer.from(this.pr, "hex");
222
- }
223
- /**
224
- * @inheritDoc
225
- * @internal
226
- */
227
- canCommit(skipQuoteExpiryChecks) {
228
- return this._state === FromBTCLNSwapState.PR_PAID || (!!skipQuoteExpiryChecks && this._state === FromBTCLNSwapState.QUOTE_SOFT_EXPIRED);
229
- }
230
- /**
231
- * @inheritDoc
232
- */
233
- getInputAddress() {
234
- return this.lnurl ?? this.pr ?? null;
235
- }
236
- /**
237
- * @inheritDoc
238
- */
239
- getInputTxId() {
240
- const paymentHash = this.getPaymentHash();
241
- if (paymentHash == null)
242
- return null;
243
- return paymentHash.toString("hex");
244
- }
245
- /**
246
- * Returns the lightning network BOLT11 invoice that needs to be paid as an input to the swap.
247
- *
248
- * In case the swap is recovered from on-chain data, the address returned might be just a payment hash,
249
- * as it is impossible to retrieve the actual lightning network invoice paid purely from on-chain
250
- * data.
251
- */
252
- getAddress() {
253
- return this.pr ?? "";
254
- }
255
- /**
256
- * A hyperlink representation of the address + amount that the user needs to sends on the source chain.
257
- * This is suitable to be displayed in a form of QR code.
258
- *
259
- * @remarks
260
- * In case the swap is recovered from on-chain data, the address returned might be just a payment hash,
261
- * as it is impossible to retrieve the actual lightning network invoice paid purely from on-chain
262
- * data.
263
- */
264
- getHyperlink() {
265
- return this.pr == null ? "" : "lightning:" + this.pr.toUpperCase();
266
- }
267
- /**
268
- * Returns the timeout time (in UNIX milliseconds) when the swap will definitelly be considered as expired
269
- * if the LP doesn't make it expired sooner
270
- */
271
- getDefinitiveExpiryTime() {
272
- if (this.pr == null || !this.pr.toLowerCase().startsWith("ln"))
273
- return 0;
274
- const decoded = (0, bolt11_1.decode)(this.pr);
275
- if (decoded.timeExpireDate == null)
276
- throw new Error("Swap invoice doesn't contain expiry date field!");
277
- const finalCltvExpiryDelta = decoded.tagsObject.min_final_cltv_expiry ?? 144;
278
- const finalCltvExpiryDelay = finalCltvExpiryDelta * this.wrapper._options.bitcoinBlocktime * this.wrapper._options.safetyFactor;
279
- return (decoded.timeExpireDate + finalCltvExpiryDelay) * 1000;
280
- }
281
- /**
282
- * Returns timeout time (in UNIX milliseconds) when the swap htlc will expire
283
- */
284
- getHtlcTimeoutTime() {
285
- if (this._data == null)
286
- return null;
287
- return Number(this.wrapper._getHtlcTimeout(this._data)) * 1000;
288
- }
289
- /**
290
- * Returns timeout time (in UNIX milliseconds) when the LN invoice will expire
291
- */
292
- getTimeoutTime() {
293
- if (this.pr == null || !this.pr.toLowerCase().startsWith("ln"))
294
- return 0;
295
- const decoded = (0, bolt11_1.decode)(this.pr);
296
- if (decoded.timeExpireDate == null)
297
- throw new Error("Swap invoice doesn't contain expiry date field!");
298
- return (decoded.timeExpireDate * 1000);
299
- }
300
- /**
301
- * @inheritDoc
302
- */
303
- isFinished() {
304
- return this._state === FromBTCLNSwapState.CLAIM_CLAIMED || this._state === FromBTCLNSwapState.QUOTE_EXPIRED || this._state === FromBTCLNSwapState.FAILED;
305
- }
306
- /**
307
- * @inheritDoc
308
- */
309
- isClaimable() {
310
- return this._state === FromBTCLNSwapState.CLAIM_COMMITED;
311
- }
312
- /**
313
- * @inheritDoc
314
- */
315
- isSuccessful() {
316
- return this._state === FromBTCLNSwapState.CLAIM_CLAIMED;
317
- }
318
- /**
319
- * @inheritDoc
320
- */
321
- isFailed() {
322
- return this._state === FromBTCLNSwapState.FAILED || this._state === FromBTCLNSwapState.EXPIRED;
323
- }
324
- /**
325
- * @inheritDoc
326
- */
327
- isInProgress() {
328
- return (this._state === FromBTCLNSwapState.PR_CREATED && this.initiated) ||
329
- (this._state === FromBTCLNSwapState.QUOTE_SOFT_EXPIRED && this.initiated) ||
330
- this._state === FromBTCLNSwapState.PR_PAID ||
331
- this._state === FromBTCLNSwapState.CLAIM_COMMITED;
332
- }
333
- /**
334
- * @inheritDoc
335
- */
336
- isQuoteExpired() {
337
- return this._state === FromBTCLNSwapState.QUOTE_EXPIRED;
338
- }
339
- /**
340
- * @inheritDoc
341
- */
342
- isQuoteSoftExpired() {
343
- return this._state === FromBTCLNSwapState.QUOTE_EXPIRED || this._state === FromBTCLNSwapState.QUOTE_SOFT_EXPIRED;
344
- }
345
- /**
346
- * @inheritDoc
347
- * @internal
348
- */
349
- _verifyQuoteDefinitelyExpired() {
350
- if (this._state === FromBTCLNSwapState.PR_CREATED || (this._state === FromBTCLNSwapState.QUOTE_SOFT_EXPIRED && this.signatureData == null)) {
351
- return Promise.resolve(this.getDefinitiveExpiryTime() < Date.now());
352
- }
353
- return super._verifyQuoteDefinitelyExpired();
354
- }
355
- /**
356
- * @inheritDoc
357
- * @internal
358
- */
359
- _verifyQuoteValid() {
360
- if (this._state === FromBTCLNSwapState.PR_CREATED ||
361
- (this._state === FromBTCLNSwapState.QUOTE_SOFT_EXPIRED && this.signatureData == null)) {
362
- return Promise.resolve(this.getTimeoutTime() > Date.now());
363
- }
364
- return super._verifyQuoteValid();
365
- }
366
- //////////////////////////////
367
- //// Amounts & fees
368
- /**
369
- * @inheritDoc
370
- */
371
- getInputToken() {
372
- return Token_1.BitcoinTokens.BTCLN;
373
- }
374
- /**
375
- * @inheritDoc
376
- */
377
- getInput() {
378
- if (this.pr == null || !this.pr.toLowerCase().startsWith("ln"))
379
- return (0, TokenAmount_1.toTokenAmount)(null, this.inputToken, this.wrapper._prices, this.pricingInfo);
380
- const parsed = (0, bolt11_1.decode)(this.pr);
381
- if (parsed.millisatoshis == null)
382
- throw new Error("Swap invoice doesn't contain msat amount field!");
383
- const amount = (BigInt(parsed.millisatoshis) + 999n) / 1000n;
384
- return (0, TokenAmount_1.toTokenAmount)(amount, this.inputToken, this.wrapper._prices, this.pricingInfo);
385
- }
386
- /**
387
- * @inheritDoc
388
- */
389
- getSmartChainNetworkFee() {
390
- return this.getCommitAndClaimNetworkFee();
391
- }
392
- /**
393
- * @inheritDoc
394
- */
395
- async hasEnoughForTxFees() {
396
- const [balance, feeRate] = await Promise.all([
397
- this._contract.getBalance(this._getInitiator(), this.wrapper._chain.getNativeCurrencyAddress(), false),
398
- this.feeRate != null ? Promise.resolve(this.feeRate) : this._contract.getInitFeeRate(this.getSwapData().getOfferer(), this.getSwapData().getClaimer(), this.getSwapData().getToken(), this.getSwapData().getClaimHash())
399
- ]);
400
- const commitFee = await this._contract.getCommitFee(this._getInitiator(), this.getSwapData(), feeRate);
401
- const claimFee = await this._contract.getClaimFee(this._getInitiator(), this.getSwapData(), feeRate);
402
- const totalFee = commitFee + claimFee + this.getSwapData().getTotalDeposit();
403
- return {
404
- enoughBalance: balance >= totalFee,
405
- balance: (0, TokenAmount_1.toTokenAmount)(balance, this.wrapper._getNativeToken(), this.wrapper._prices, this.pricingInfo),
406
- required: (0, TokenAmount_1.toTokenAmount)(totalFee, this.wrapper._getNativeToken(), this.wrapper._prices, this.pricingInfo)
407
- };
408
- }
409
- isValidSecretPreimage(secret) {
410
- const paymentHash = buffer_1.Buffer.from((0, sha2_1.sha256)(buffer_1.Buffer.from(secret, "hex")));
411
- const claimHash = this._contract.getHashForHtlc(paymentHash).toString("hex");
412
- return this.getSwapData().getClaimHash() === claimHash;
413
- }
414
- /**
415
- * Sets the secret preimage for the swap, in case it is not known already
416
- *
417
- * @param secret Secret preimage that matches the expected payment hash
418
- *
419
- * @throws {Error} If an invalid secret preimage is provided
420
- */
421
- setSecretPreimage(secret) {
422
- if (!this.isValidSecretPreimage(secret))
423
- throw new Error("Invalid secret preimage provided, hash doesn't match!");
424
- this.secret = secret;
425
- }
426
- /**
427
- * Returns whether the secret preimage for this swap is known
428
- */
429
- hasSecretPreimage() {
430
- return this.secret != null;
431
- }
432
- //////////////////////////////
433
- //// Execution
434
- /**
435
- * Executes the swap with the provided bitcoin lightning network wallet or LNURL
436
- *
437
- * @param dstSigner Signer on the destination network, needs to have the same address as the one specified when
438
- * quote was created, this is required for legacy swaps because the destination wallet needs to actively claim
439
- * the swap funds on the destination (this also means you need native token to cover gas costs)
440
- * @param walletOrLnurlWithdraw Bitcoin lightning wallet to use to pay the lightning network invoice, or an LNURL-withdraw
441
- * link, wallet is not required and the LN invoice can be paid externally as well (just pass null or undefined here)
442
- * @param callbacks Callbacks to track the progress of the swap
443
- * @param options Optional options for the swap like feeRate, AbortSignal, and timeouts/intervals
444
- * @param options.secret A swap secret to use for the claim transaction, generally only needed if the swap
445
- * was recovered from on-chain data, or the pre-image was generated outside the SDK
446
- */
447
- async execute(dstSigner, walletOrLnurlWithdraw, callbacks, options) {
448
- if (this._state === FromBTCLNSwapState.FAILED)
449
- throw new Error("Swap failed!");
450
- if (this._state === FromBTCLNSwapState.EXPIRED)
451
- throw new Error("Swap HTLC expired!");
452
- if (this._state === FromBTCLNSwapState.QUOTE_EXPIRED || this._state === FromBTCLNSwapState.QUOTE_SOFT_EXPIRED)
453
- throw new Error("Swap quote expired!");
454
- if (this._state === FromBTCLNSwapState.CLAIM_CLAIMED)
455
- throw new Error("Swap already settled!");
456
- let abortSignal = options?.abortSignal;
457
- if (this._state === FromBTCLNSwapState.PR_CREATED) {
458
- if (walletOrLnurlWithdraw != null && this.lnurl == null) {
459
- if (this.pr == null || !this.pr.toLowerCase().startsWith("ln"))
460
- throw new Error("Input lightning network invoice not available, the swap was probably recovered!");
461
- if (typeof (walletOrLnurlWithdraw) === "string" || (0, LNURLWithdraw_1.isLNURLWithdraw)(walletOrLnurlWithdraw)) {
462
- await this.settleWithLNURLWithdraw(walletOrLnurlWithdraw);
463
- }
464
- else {
465
- const paymentPromise = walletOrLnurlWithdraw.payInvoice(this.pr);
466
- const abortController = new AbortController();
467
- paymentPromise.catch(e => abortController.abort(e));
468
- if (options?.abortSignal != null)
469
- options.abortSignal.addEventListener("abort", () => abortController.abort(options?.abortSignal?.reason));
470
- abortSignal = abortController.signal;
471
- }
472
- }
473
- const paymentSuccess = await this.waitForPayment(callbacks?.onSourceTransactionReceived, options?.lightningTxCheckIntervalSeconds, abortSignal);
474
- if (!paymentSuccess)
475
- throw new Error("Failed to receive lightning network payment");
476
- }
477
- if (this._state === FromBTCLNSwapState.PR_PAID || this._state === FromBTCLNSwapState.CLAIM_COMMITED) {
478
- if (this.canCommitAndClaimInOneShot()) {
479
- await this.commitAndClaim(dstSigner, options?.abortSignal, undefined, callbacks?.onDestinationCommitSent, callbacks?.onDestinationClaimSent, options?.secret);
480
- }
481
- else {
482
- if (this._state === FromBTCLNSwapState.PR_PAID) {
483
- await this.commit(dstSigner, options?.abortSignal, undefined, callbacks?.onDestinationCommitSent);
484
- if (options?.delayBetweenCommitAndClaimSeconds != null)
485
- await (0, TimeoutUtils_1.timeoutPromise)(options.delayBetweenCommitAndClaimSeconds * 1000, options?.abortSignal);
486
- }
487
- if (this._state === FromBTCLNSwapState.CLAIM_COMMITED) {
488
- await this.claim(dstSigner, options?.abortSignal, callbacks?.onDestinationClaimSent, options?.secret);
489
- }
490
- }
491
- }
492
- // @ts-ignore
493
- if (this._state === FromBTCLNSwapState.CLAIM_CLAIMED) {
494
- if (callbacks?.onSwapSettled != null)
495
- callbacks.onSwapSettled(this.getOutputTxId());
496
- }
497
- return true;
498
- }
499
- /**
500
- * @internal
501
- */
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);
534
- }
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;
554
- }
555
- return {
556
- steps: [
557
- {
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
566
- },
567
- {
568
- type: "Settlement",
569
- side: "destination",
570
- chain: this.chainIdentifier,
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;
633
- }
634
- if (this._state === FromBTCLNSwapState.CLAIM_COMMITED) {
635
- const txIds = await this.wrapper._chain.sendSignedAndConfirm(parsedTxs, true, abortSignal, false);
636
- await this.waitTillClaimed(undefined, abortSignal);
637
- return txIds;
638
- }
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
- };
660
- }
661
- /**
662
- * @inheritDoc
663
- *
664
- * @param options
665
- * @param options.skipChecks Skip checks like making sure init signature is still valid and swap
666
- * wasn't commited yet (this is handled on swap creation, if you commit right after quoting, you
667
- * can use `skipChecks=true`)
668
- * @param options.secret A swap secret to use for the claim transaction, generally only needed if the swap
669
- * was recovered from on-chain data, or the pre-image was generated outside the SDK
670
- */
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;
692
- }
693
- //////////////////////////////
694
- //// Payment
695
- /**
696
- * Checks whether the LP received the LN payment and we can continue by committing & claiming the HTLC on-chain
697
- *
698
- * @param save If the new swap state should be saved
699
- *
700
- * @internal
701
- */
702
- async _checkIntermediaryPaymentReceived(save = true) {
703
- if (this._state === FromBTCLNSwapState.PR_PAID ||
704
- this._state === FromBTCLNSwapState.CLAIM_COMMITED ||
705
- this._state === FromBTCLNSwapState.CLAIM_CLAIMED ||
706
- this._state === FromBTCLNSwapState.FAILED ||
707
- this._state === FromBTCLNSwapState.EXPIRED)
708
- return true;
709
- if (this._state === FromBTCLNSwapState.QUOTE_EXPIRED || (this._state === FromBTCLNSwapState.QUOTE_SOFT_EXPIRED && this.signatureData != null))
710
- return false;
711
- if (this.url == null)
712
- return false;
713
- const paymentHash = this.getPaymentHash();
714
- if (paymentHash == null)
715
- throw new Error("Failed to check LP payment received, payment hash not known (probably recovered swap?)");
716
- const resp = await this.wrapper._lpApi.getPaymentAuthorization(this.url, paymentHash.toString("hex"));
717
- switch (resp.code) {
718
- case IntermediaryAPI_1.PaymentAuthorizationResponseCodes.AUTH_DATA:
719
- const data = new (this.wrapper._swapDataDeserializer(this._contractVersion))(resp.data.data);
720
- try {
721
- await this.checkIntermediaryReturnedAuthData(this._getInitiator(), data, resp.data);
722
- this.expiry = await this._contract.getInitAuthorizationExpiry(data, resp.data);
723
- this._state = FromBTCLNSwapState.PR_PAID;
724
- this._data = data;
725
- this.signatureData = {
726
- prefix: resp.data.prefix,
727
- timeout: resp.data.timeout,
728
- signature: resp.data.signature
729
- };
730
- this.initiated = true;
731
- if (save)
732
- await this._saveAndEmit();
733
- return true;
734
- }
735
- catch (e) { }
736
- return null;
737
- case IntermediaryAPI_1.PaymentAuthorizationResponseCodes.EXPIRED:
738
- this._state = FromBTCLNSwapState.QUOTE_EXPIRED;
739
- this.initiated = true;
740
- if (save)
741
- await this._saveAndEmit();
742
- return false;
743
- default:
744
- return null;
745
- }
746
- }
747
- /**
748
- * Checks the data returned by the intermediary in the payment auth request
749
- *
750
- * @param signer Smart chain signer's address initiating the swap
751
- * @param data Parsed swap data as returned by the intermediary
752
- * @param signature Signature data as returned by the intermediary
753
- *
754
- * @throws {IntermediaryError} If the returned are not valid
755
- * @throws {SignatureVerificationError} If the returned signature is not valid
756
- * @throws {Error} If the swap is already committed on-chain
757
- *
758
- * @internal
759
- */
760
- async checkIntermediaryReturnedAuthData(signer, data, signature) {
761
- data.setClaimer(signer);
762
- if (data.getType() !== base_1.ChainSwapType.HTLC)
763
- throw new IntermediaryError_1.IntermediaryError("Invalid swap type");
764
- if (!data.isOfferer(this.getSwapData().getOfferer()))
765
- throw new IntermediaryError_1.IntermediaryError("Invalid offerer used");
766
- if (!data.isClaimer(this._getInitiator()))
767
- throw new IntermediaryError_1.IntermediaryError("Invalid claimer used");
768
- if (!data.isToken(this.getSwapData().getToken()))
769
- throw new IntermediaryError_1.IntermediaryError("Invalid token used");
770
- if (data.getSecurityDeposit() > this.getSwapData().getSecurityDeposit())
771
- throw new IntermediaryError_1.IntermediaryError("Invalid security deposit!");
772
- if (data.getClaimerBounty() !== 0n)
773
- throw new IntermediaryError_1.IntermediaryError("Invalid claimer bounty!");
774
- if (data.getAmount() < this.getSwapData().getAmount())
775
- throw new IntermediaryError_1.IntermediaryError("Invalid amount received!");
776
- if (data.getClaimHash() !== this.getSwapData().getClaimHash())
777
- throw new IntermediaryError_1.IntermediaryError("Invalid payment hash used!");
778
- if (!data.isDepositToken(this.getSwapData().getDepositToken()))
779
- throw new IntermediaryError_1.IntermediaryError("Invalid deposit token used!");
780
- if (data.hasSuccessAction())
781
- throw new IntermediaryError_1.IntermediaryError("Invalid has success action");
782
- await Promise.all([
783
- this._contract.isValidInitAuthorization(this._getInitiator(), data, signature, this.feeRate),
784
- this._contract.getCommitStatus(data.getClaimer(), data)
785
- .then(status => {
786
- if (status?.type !== base_1.SwapCommitStateType.NOT_COMMITED)
787
- throw new Error("Swap already committed on-chain!");
788
- })
789
- ]);
790
- }
791
- /**
792
- * Waits till a lightning network payment is received by the intermediary and client
793
- * can continue by initiating (committing) & settling (claiming) the HTLC by calling
794
- * either the {@link commitAndClaim} function (if the underlying chain allows commit
795
- * and claim in a single transaction - check with {@link canCommitAndClaimInOneShot}).
796
- * Or call {@link commit} and then {@link claim} separately.
797
- *
798
- * If this swap is using an LNURL-withdraw link as input, it automatically posts the
799
- * generated invoice to the LNURL service to pay it.
800
- *
801
- * @param onPaymentReceived Callback as for when the LP reports having received the ln payment
802
- * @param abortSignal Abort signal to stop waiting for payment
803
- * @param checkIntervalSeconds How often to poll the intermediary for answer (default 5 seconds)
804
- */
805
- async waitForPayment(onPaymentReceived, checkIntervalSeconds, abortSignal) {
806
- checkIntervalSeconds ??= 5;
807
- if (this._state !== FromBTCLNSwapState.PR_CREATED &&
808
- (this._state !== FromBTCLNSwapState.QUOTE_SOFT_EXPIRED || this.signatureData != null))
809
- throw new Error("Must be in PR_CREATED state!");
810
- if (this.url == null)
811
- throw new Error("LP URL not known, cannot await the payment!");
812
- const abortController = new AbortController();
813
- if (abortSignal != null)
814
- abortSignal.addEventListener("abort", () => abortController.abort(abortSignal.reason));
815
- let save = false;
816
- if (this.lnurl != null && this.lnurlK1 != null && this.lnurlCallback != null && !this.prPosted) {
817
- if (this.pr == null || !this.pr.toLowerCase().startsWith("ln"))
818
- throw new Error("Input lightning network invoice not available, the swap was probably recovered!");
819
- LNURL_1.LNURL.postInvoiceToLNURLWithdraw({ k1: this.lnurlK1, callback: this.lnurlCallback }, this.pr).catch(e => {
820
- this.lnurlFailSignal.abort(e);
821
- });
822
- this.prPosted = true;
823
- save ||= true;
824
- }
825
- if (!this.initiated) {
826
- this.initiated = true;
827
- save ||= true;
828
- }
829
- if (save)
830
- await this._saveAndEmit();
831
- let lnurlFailListener = () => abortController.abort(this.lnurlFailSignal.signal.reason);
832
- this.lnurlFailSignal.signal.addEventListener("abort", lnurlFailListener);
833
- this.lnurlFailSignal.signal.throwIfAborted();
834
- const paymentHash = this.getPaymentHash();
835
- if (paymentHash == null)
836
- throw new Error("Swap payment hash not available, the swap was probably recovered!");
837
- let resp = { code: IntermediaryAPI_1.PaymentAuthorizationResponseCodes.PENDING, msg: "" };
838
- while (!abortController.signal.aborted && resp.code === IntermediaryAPI_1.PaymentAuthorizationResponseCodes.PENDING) {
839
- resp = await this.wrapper._lpApi.getPaymentAuthorization(this.url, paymentHash.toString("hex"));
840
- if (resp.code === IntermediaryAPI_1.PaymentAuthorizationResponseCodes.PENDING)
841
- await (0, TimeoutUtils_1.timeoutPromise)(checkIntervalSeconds * 1000, abortController.signal);
842
- }
843
- this.lnurlFailSignal.signal.removeEventListener("abort", lnurlFailListener);
844
- abortController.signal.throwIfAborted();
845
- if (resp.code === IntermediaryAPI_1.PaymentAuthorizationResponseCodes.AUTH_DATA) {
846
- const sigData = resp.data;
847
- const swapData = new (this.wrapper._swapDataDeserializer(this._contractVersion))(resp.data.data);
848
- await this.checkIntermediaryReturnedAuthData(this._getInitiator(), swapData, sigData);
849
- this.expiry = await this._contract.getInitAuthorizationExpiry(swapData, sigData);
850
- if (onPaymentReceived != null)
851
- onPaymentReceived(this.getInputTxId());
852
- if (this._state === FromBTCLNSwapState.PR_CREATED || this._state === FromBTCLNSwapState.QUOTE_SOFT_EXPIRED) {
853
- this._data = swapData;
854
- this.signatureData = {
855
- prefix: sigData.prefix,
856
- timeout: sigData.timeout,
857
- signature: sigData.signature
858
- };
859
- await this._saveAndEmit(FromBTCLNSwapState.PR_PAID);
860
- }
861
- return true;
862
- }
863
- if (this._state === FromBTCLNSwapState.PR_CREATED || this._state === FromBTCLNSwapState.QUOTE_SOFT_EXPIRED) {
864
- if (resp.code === IntermediaryAPI_1.PaymentAuthorizationResponseCodes.EXPIRED) {
865
- await this._saveAndEmit(FromBTCLNSwapState.QUOTE_EXPIRED);
866
- }
867
- return false;
868
- }
869
- throw new IntermediaryError_1.IntermediaryError("Invalid response from the LP");
870
- }
871
- //////////////////////////////
872
- //// Commit
873
- /**
874
- * @inheritDoc
875
- *
876
- * @throws {Error} If invalid signer is provided that doesn't match the swap data
877
- */
878
- async commit(_signer, abortSignal, skipChecks, onBeforeTxSent) {
879
- const signer = (0, base_1.isAbstractSigner)(_signer) ? _signer : await this.wrapper._chain.wrapSigner(_signer);
880
- this.checkSigner(signer);
881
- let txCount = 0;
882
- const txs = await this.txsCommit(skipChecks);
883
- const result = await this.wrapper._chain.sendAndConfirm(signer, txs, true, abortSignal, undefined, (txId) => {
884
- txCount++;
885
- if (onBeforeTxSent != null && txCount === txs.length)
886
- onBeforeTxSent(txId);
887
- return Promise.resolve();
888
- });
889
- this._commitTxId = result[result.length - 1];
890
- if (this._state === FromBTCLNSwapState.PR_PAID || this._state === FromBTCLNSwapState.QUOTE_SOFT_EXPIRED || this._state === FromBTCLNSwapState.QUOTE_EXPIRED) {
891
- await this._saveAndEmit(FromBTCLNSwapState.CLAIM_COMMITED);
892
- }
893
- return this._commitTxId;
894
- }
895
- /**
896
- * @inheritDoc
897
- */
898
- async waitTillCommited(abortSignal) {
899
- if (this._state === FromBTCLNSwapState.CLAIM_COMMITED || this._state === FromBTCLNSwapState.CLAIM_CLAIMED)
900
- return Promise.resolve();
901
- if (this._state !== FromBTCLNSwapState.PR_PAID && (this._state !== FromBTCLNSwapState.QUOTE_SOFT_EXPIRED && this.signatureData != null))
902
- throw new Error("Invalid state");
903
- const abortController = (0, Utils_1.extendAbortController)(abortSignal);
904
- const result = await Promise.race([
905
- this.watchdogWaitTillCommited(undefined, abortController.signal),
906
- this.waitTillState(FromBTCLNSwapState.CLAIM_COMMITED, "gte", abortController.signal).then(() => 0)
907
- ]);
908
- abortController.abort();
909
- if (result === 0) {
910
- this.logger.debug("waitTillCommited(): Resolved from state changed");
911
- }
912
- else if (result != null) {
913
- this.logger.debug("waitTillCommited(): Resolved from watchdog - commited");
914
- }
915
- if (result === null) {
916
- this.logger.debug("waitTillCommited(): Resolved from watchdog - signature expired");
917
- if (this._state === FromBTCLNSwapState.PR_PAID ||
918
- this._state === FromBTCLNSwapState.QUOTE_SOFT_EXPIRED) {
919
- await this._saveAndEmit(FromBTCLNSwapState.QUOTE_EXPIRED);
920
- }
921
- return;
922
- }
923
- if (this._state === FromBTCLNSwapState.PR_PAID ||
924
- this._state === FromBTCLNSwapState.QUOTE_SOFT_EXPIRED) {
925
- if (typeof (result) === "object" && result.getInitTxId != null && this._commitTxId == null)
926
- this._commitTxId = await result.getInitTxId();
927
- await this._saveAndEmit(FromBTCLNSwapState.CLAIM_COMMITED);
928
- }
929
- }
930
- //////////////////////////////
931
- //// Claim
932
- /**
933
- * Unsafe txs claim getter without state checking!
934
- *
935
- * @param _signer
936
- * @param secret A swap secret to use for the claim transaction, generally only needed if the swap
937
- * was recovered from on-chain data, or the pre-image was generated outside the SDK
938
- *
939
- * @internal
940
- */
941
- async _txsClaim(_signer, secret) {
942
- let address = undefined;
943
- if (_signer != null) {
944
- if (typeof (_signer) === "string") {
945
- address = _signer;
946
- }
947
- else if ((0, base_1.isAbstractSigner)(_signer)) {
948
- address = _signer.getAddress();
949
- }
950
- else {
951
- address = (await this.wrapper._chain.wrapSigner(_signer)).getAddress();
952
- }
953
- }
954
- if (this._data == null)
955
- throw new Error("Unknown data, wrong state?");
956
- const useSecret = secret ?? this.secret;
957
- if (useSecret == null)
958
- throw new Error("Swap secret pre-image not known and not provided, please provide the swap secret pre-image as an argument");
959
- if (!this.isValidSecretPreimage(useSecret))
960
- throw new Error("Invalid swap secret pre-image provided!");
961
- return this._contract.txsClaimWithSecret(address ?? this._getInitiator(), this._data, useSecret, true, true);
962
- }
963
- /**
964
- * @inheritDoc
965
- *
966
- * @param _signer Optional signer address to use for claiming the swap, can also be different from the initializer
967
- * @param secret A swap secret to use for the claim transaction, generally only needed if the swap
968
- * was recovered from on-chain data, or the pre-image was generated outside the SDK
969
- *
970
- * @throws {Error} If in invalid state (must be {@link FromBTCLNSwapState.CLAIM_COMMITED})
971
- */
972
- async txsClaim(_signer, secret) {
973
- if (this._state !== FromBTCLNSwapState.CLAIM_COMMITED)
974
- throw new Error("Must be in CLAIM_COMMITED state!");
975
- return this._txsClaim(_signer, secret);
976
- }
977
- /**
978
- * @inheritDoc
979
- *
980
- * @param _signer
981
- * @param abortSignal
982
- * @param onBeforeTxSent
983
- * @param secret A swap secret to use for the claim transaction, generally only needed if the swap
984
- * was recovered from on-chain data, or the pre-image was generated outside the SDK
985
- */
986
- async claim(_signer, abortSignal, onBeforeTxSent, secret) {
987
- const signer = (0, base_1.isAbstractSigner)(_signer) ? _signer : await this.wrapper._chain.wrapSigner(_signer);
988
- let txCount = 0;
989
- const result = await this.wrapper._chain.sendAndConfirm(signer, await this.txsClaim(_signer, secret), true, abortSignal, undefined, (txId) => {
990
- txCount++;
991
- if (onBeforeTxSent != null && txCount === 1)
992
- onBeforeTxSent(txId);
993
- return Promise.resolve();
994
- });
995
- this._claimTxId = result[0];
996
- if (this._state === FromBTCLNSwapState.CLAIM_COMMITED || this._state === FromBTCLNSwapState.EXPIRED || this._state === FromBTCLNSwapState.FAILED) {
997
- await this._saveAndEmit(FromBTCLNSwapState.CLAIM_CLAIMED);
998
- }
999
- return result[0];
1000
- }
1001
- /**
1002
- * @inheritDoc
1003
- *
1004
- * @throws {Error} If swap is in invalid state (must be {@link FromBTCLNSwapState.CLAIM_COMMITED})
1005
- * @throws {Error} If the LP refunded sooner than we were able to claim
1006
- */
1007
- async waitTillClaimed(maxWaitTimeSeconds, abortSignal) {
1008
- if (this._state === FromBTCLNSwapState.CLAIM_CLAIMED)
1009
- return Promise.resolve(true);
1010
- if (this._state !== FromBTCLNSwapState.CLAIM_COMMITED)
1011
- throw new Error("Invalid state (not CLAIM_COMMITED)");
1012
- const abortController = new AbortController();
1013
- if (abortSignal != null)
1014
- abortSignal.addEventListener("abort", () => abortController.abort(abortSignal.reason));
1015
- let timedOut = false;
1016
- if (maxWaitTimeSeconds != null) {
1017
- const timeout = setTimeout(() => {
1018
- timedOut = true;
1019
- abortController.abort();
1020
- }, maxWaitTimeSeconds * 1000);
1021
- abortController.signal.addEventListener("abort", () => clearTimeout(timeout));
1022
- }
1023
- let res;
1024
- try {
1025
- res = await Promise.race([
1026
- this.watchdogWaitTillResult(undefined, abortController.signal),
1027
- this.waitTillState(FromBTCLNSwapState.CLAIM_CLAIMED, "eq", abortController.signal).then(() => 0),
1028
- this.waitTillState(FromBTCLNSwapState.EXPIRED, "eq", abortController.signal).then(() => 1),
1029
- ]);
1030
- abortController.abort();
1031
- }
1032
- catch (e) {
1033
- abortController.abort();
1034
- if (timedOut)
1035
- return false;
1036
- throw e;
1037
- }
1038
- if (res === 0) {
1039
- this.logger.debug("waitTillClaimed(): Resolved from state change (CLAIM_CLAIMED)");
1040
- return true;
1041
- }
1042
- if (res === 1) {
1043
- this.logger.debug("waitTillClaimed(): Resolved from state change (EXPIRED)");
1044
- throw new Error("Swap expired during claiming");
1045
- }
1046
- this.logger.debug("waitTillClaimed(): Resolved from watchdog");
1047
- if (res?.type === base_1.SwapCommitStateType.PAID) {
1048
- if (this._state !== FromBTCLNSwapState.CLAIM_CLAIMED) {
1049
- this._claimTxId = await res.getClaimTxId();
1050
- await this._saveAndEmit(FromBTCLNSwapState.CLAIM_CLAIMED);
1051
- }
1052
- }
1053
- if (res?.type === base_1.SwapCommitStateType.NOT_COMMITED || res?.type === base_1.SwapCommitStateType.EXPIRED) {
1054
- if (this._state !== FromBTCLNSwapState.CLAIM_CLAIMED &&
1055
- this._state !== FromBTCLNSwapState.FAILED) {
1056
- if (res.getRefundTxId != null)
1057
- this._refundTxId = await res.getRefundTxId();
1058
- await this._saveAndEmit(FromBTCLNSwapState.FAILED);
1059
- }
1060
- throw new Error("Swap expired while waiting for claim!");
1061
- }
1062
- return true;
1063
- }
1064
- //////////////////////////////
1065
- //// Commit & claim
1066
- /**
1067
- * Estimated transaction fee for commit & claim transactions combined, required
1068
- * to settle the swap on the smart chain destination side.
1069
- */
1070
- async getCommitAndClaimNetworkFee() {
1071
- const swapContract = this._contract;
1072
- const feeRate = this.feeRate ?? await swapContract.getInitFeeRate(this.getSwapData().getOfferer(), this.getSwapData().getClaimer(), this.getSwapData().getToken(), this.getSwapData().getClaimHash());
1073
- const commitFee = await (swapContract.getRawCommitFee != null ?
1074
- swapContract.getRawCommitFee(this._getInitiator(), this.getSwapData(), feeRate) :
1075
- swapContract.getCommitFee(this._getInitiator(), this.getSwapData(), feeRate));
1076
- const claimFee = await (swapContract.getRawClaimFee != null ?
1077
- swapContract.getRawClaimFee(this._getInitiator(), this.getSwapData(), feeRate) :
1078
- swapContract.getClaimFee(this._getInitiator(), this.getSwapData(), feeRate));
1079
- return (0, TokenAmount_1.toTokenAmount)(commitFee + claimFee, this.wrapper._getNativeToken(), this.wrapper._prices);
1080
- }
1081
- /**
1082
- * Returns whether the underlying chain supports calling commit and claim in a single call,
1083
- * such that you can use the {@link commitAndClaim} function. If not you have to manually
1084
- * call {@link commit} first and then {@link claim}.
1085
- */
1086
- canCommitAndClaimInOneShot() {
1087
- return this._contract.initAndClaimWithSecret != null;
1088
- }
1089
- /**
1090
- * Returns transactions for both commit & claim operation together, such that they can be signed all at once by
1091
- * the wallet. **WARNING**: transactions must be sent sequentially, such that the claim (2nd) transaction is only
1092
- * sent after the commit (1st) transaction confirms. Failure to do so can reveal the HTLC pre-image too soon,
1093
- * opening a possibility for the LP to steal funds!
1094
- *
1095
- * @param skipChecks Skip checks like making sure init signature is still valid and swap wasn't commited yet
1096
- * (this is handled when swap is created (quoted), if you commit right after quoting, you can use skipChecks=true)
1097
- * @param secret A swap secret to use for the claim transaction, generally only needed if the swap
1098
- * was recovered from on-chain data, or the pre-image was generated outside the SDK
1099
- *
1100
- * @throws {Error} If in invalid state (must be PR_PAID or CLAIM_COMMITED)
1101
- */
1102
- async txsCommitAndClaim(skipChecks, secret) {
1103
- if (this._state === FromBTCLNSwapState.CLAIM_COMMITED)
1104
- return await this.txsClaim(undefined, secret);
1105
- if (this._state !== FromBTCLNSwapState.PR_PAID &&
1106
- (this._state !== FromBTCLNSwapState.QUOTE_SOFT_EXPIRED || this.signatureData == null))
1107
- throw new Error("Must be in PR_PAID state!");
1108
- if (this._data == null)
1109
- throw new Error("Unknown data, wrong state?");
1110
- const useSecret = secret ?? this.secret;
1111
- if (useSecret == null)
1112
- throw new Error("Swap secret pre-image not known and not provided, please provide the swap secret pre-image as second argument");
1113
- if (!this.isValidSecretPreimage(useSecret))
1114
- throw new Error("Invalid swap secret pre-image provided!");
1115
- const initTxs = await this.txsCommit(skipChecks);
1116
- const claimTxs = await this._contract.txsClaimWithSecret(this._getInitiator(), this._data, useSecret, true, true, undefined, true);
1117
- return initTxs.concat(claimTxs);
1118
- }
1119
- /**
1120
- * Commits and claims the swap, in a way that the transactions can be signed together by the provided signer and
1121
- * then automatically sent sequentially by the SDK. To check if the underlying chain supports this flow check
1122
- * the {@link canCommitAndClaimInOneShot} function.
1123
- *
1124
- * @param _signer Signer to sign the transactions with, must be the same as used in the initialization
1125
- * @param abortSignal Abort signal to stop waiting for the transaction confirmation and abort
1126
- * @param skipChecks Skip checks like making sure init signature is still valid and swap wasn't commited yet
1127
- * (this is handled when swap is created (quoted), if you commit right after quoting, you can use skipChecks=true)
1128
- * @param onBeforeCommitTxSent Optional callback called before the initialization (commit) transaction is
1129
- * broadcasted
1130
- * @param onBeforeClaimTxSent Optional callback called before the settlement (claim) transaction is
1131
- * broadcasted
1132
- * @param secret A swap secret to use for the claim transaction, generally only needed if the swap
1133
- * was recovered from on-chain data, or the pre-image was generated outside the SDK
1134
- *
1135
- * @throws {Error} If in invalid state (must be PR_PAID or CLAIM_COMMITED)
1136
- * @throws {Error} If invalid signer is provided that doesn't match the swap data
1137
- */
1138
- async commitAndClaim(_signer, abortSignal, skipChecks, onBeforeCommitTxSent, onBeforeClaimTxSent, secret) {
1139
- const signer = (0, base_1.isAbstractSigner)(_signer) ? _signer : await this.wrapper._chain.wrapSigner(_signer);
1140
- if (!this.canCommitAndClaimInOneShot())
1141
- throw new Error("Cannot commitAndClaim in single action, please run commit and claim separately!");
1142
- this.checkSigner(signer);
1143
- if (this._state === FromBTCLNSwapState.CLAIM_COMMITED)
1144
- return [await this.claim(signer, abortSignal, onBeforeClaimTxSent, secret)];
1145
- let txCount = 0;
1146
- const txs = await this.txsCommitAndClaim(skipChecks, secret);
1147
- const result = await this.wrapper._chain.sendAndConfirm(signer, txs, true, abortSignal, undefined, (txId) => {
1148
- txCount++;
1149
- if (onBeforeCommitTxSent != null && txCount === 1)
1150
- onBeforeCommitTxSent(txId);
1151
- if (onBeforeClaimTxSent != null && txCount === txs.length)
1152
- onBeforeClaimTxSent(txId);
1153
- return Promise.resolve();
1154
- });
1155
- this._commitTxId = result[0] ?? this._commitTxId;
1156
- this._claimTxId = result[result.length - 1] ?? this._claimTxId;
1157
- if (this._state !== FromBTCLNSwapState.CLAIM_CLAIMED) {
1158
- await this._saveAndEmit(FromBTCLNSwapState.CLAIM_CLAIMED);
1159
- }
1160
- return result;
1161
- }
1162
- //////////////////////////////
1163
- //// LNURL
1164
- /**
1165
- * Whether this swap uses an LNURL-withdraw link
1166
- */
1167
- isLNURL() {
1168
- return this.lnurl != null;
1169
- }
1170
- /**
1171
- * Gets the used LNURL or `null` if this is not an LNURL-withdraw swap
1172
- */
1173
- getLNURL() {
1174
- return this.lnurl ?? null;
1175
- }
1176
- /**
1177
- * Pay the generated lightning network invoice with an LNURL-withdraw link, this
1178
- * is useful when you want to display a lightning payment QR code and also want to
1179
- * allow payments using LNURL-withdraw NFC cards.
1180
- *
1181
- * Note that the swap needs to be created **without** an LNURL to begin with for this function
1182
- * to work. If this swap is already using an LNURL-withdraw link, this function throws.
1183
- */
1184
- async settleWithLNURLWithdraw(lnurl) {
1185
- if (this._state !== FromBTCLNSwapState.PR_CREATED &&
1186
- (this._state !== FromBTCLNSwapState.QUOTE_SOFT_EXPIRED || this.signatureData != null))
1187
- throw new Error("Must be in PR_CREATED state!");
1188
- if (this.lnurl != null)
1189
- throw new Error("Cannot settle LNURL-withdraw swap with different LNURL");
1190
- let lnurlParams;
1191
- if (typeof (lnurl) === "string") {
1192
- const parsedLNURL = await LNURL_1.LNURL.getLNURL(lnurl);
1193
- if (parsedLNURL == null || parsedLNURL.tag !== "withdrawRequest")
1194
- throw new UserError_1.UserError("Invalid LNURL-withdraw to settle the swap");
1195
- lnurlParams = parsedLNURL;
1196
- }
1197
- else {
1198
- lnurlParams = lnurl.params;
1199
- }
1200
- if (this.pr == null || !this.pr.toLowerCase().startsWith("ln"))
1201
- throw new Error("Input lightning network invoice not available, the swap was probably recovered!");
1202
- LNURL_1.LNURL.useLNURLWithdraw(lnurlParams, this.pr).catch(e => this.lnurlFailSignal.abort(e));
1203
- this.lnurl = lnurlParams.url;
1204
- this.lnurlCallback = lnurlParams.callback;
1205
- this.lnurlK1 = lnurlParams.k1;
1206
- this.prPosted = true;
1207
- await this._saveAndEmit();
1208
- }
1209
- //////////////////////////////
1210
- //// Storage
1211
- /**
1212
- * @inheritDoc
1213
- */
1214
- serialize() {
1215
- return {
1216
- ...super.serialize(),
1217
- pr: this.pr,
1218
- secret: this.secret,
1219
- lnurl: this.lnurl,
1220
- lnurlK1: this.lnurlK1,
1221
- lnurlCallback: this.lnurlCallback,
1222
- prPosted: this.prPosted,
1223
- initialSwapData: this.initialSwapData.serialize(),
1224
- usesClaimHashAsId: this.usesClaimHashAsId
1225
- };
1226
- }
1227
- //////////////////////////////
1228
- //// Swap ticks & sync
1229
- /**
1230
- * Checks the swap's state on-chain and compares it to its internal state, updates/changes it according to on-chain
1231
- * data
1232
- *
1233
- * @private
1234
- */
1235
- async syncStateFromChain(quoteDefinitelyExpired, commitStatus) {
1236
- if (this._state === FromBTCLNSwapState.PR_PAID ||
1237
- (this._state === FromBTCLNSwapState.QUOTE_SOFT_EXPIRED && this.signatureData != null) ||
1238
- this._state === FromBTCLNSwapState.CLAIM_COMMITED ||
1239
- this._state === FromBTCLNSwapState.EXPIRED) {
1240
- //Check for expiry before the getCommitStatus to prevent race conditions
1241
- let quoteExpired = false;
1242
- if (this._state === FromBTCLNSwapState.PR_PAID || (this._state === FromBTCLNSwapState.QUOTE_SOFT_EXPIRED && this.signatureData != null)) {
1243
- quoteExpired = quoteDefinitelyExpired ?? await this._verifyQuoteDefinitelyExpired();
1244
- }
1245
- //Check if it's already successfully paid
1246
- commitStatus ??= await this._contract.getCommitStatus(this._getInitiator(), this._data);
1247
- if (commitStatus != null && await this._forciblySetOnchainState(commitStatus))
1248
- return true;
1249
- //Set the state on expiry here
1250
- if (this._state === FromBTCLNSwapState.PR_PAID || (this._state === FromBTCLNSwapState.QUOTE_SOFT_EXPIRED && this.signatureData != null)) {
1251
- if (quoteExpired) {
1252
- this._state = FromBTCLNSwapState.QUOTE_EXPIRED;
1253
- return true;
1254
- }
1255
- }
1256
- }
1257
- return false;
1258
- }
1259
- /**
1260
- * @inheritDoc
1261
- * @internal
1262
- */
1263
- _shouldFetchExpiryStatus() {
1264
- return this._state === FromBTCLNSwapState.PR_PAID || (this._state === FromBTCLNSwapState.QUOTE_SOFT_EXPIRED && this.signatureData != null);
1265
- }
1266
- /**
1267
- * @inheritDoc
1268
- * @internal
1269
- */
1270
- _shouldFetchOnchainState() {
1271
- return this._state === FromBTCLNSwapState.PR_PAID || (this._state === FromBTCLNSwapState.QUOTE_SOFT_EXPIRED && this.signatureData != null) ||
1272
- this._state === FromBTCLNSwapState.CLAIM_COMMITED || this._state === FromBTCLNSwapState.EXPIRED;
1273
- }
1274
- /**
1275
- * Whether an intermediary (LP) should be contacted to get the state of this swap.
1276
- *
1277
- * @internal
1278
- */
1279
- _shouldCheckIntermediary() {
1280
- return this._state === FromBTCLNSwapState.PR_CREATED || (this._state === FromBTCLNSwapState.QUOTE_SOFT_EXPIRED && this.signatureData == null);
1281
- }
1282
- /**
1283
- * @inheritDoc
1284
- * @internal
1285
- */
1286
- async _sync(save, quoteDefinitelyExpired, commitStatus, skipLpCheck) {
1287
- let changed = false;
1288
- if (this._state === FromBTCLNSwapState.PR_CREATED || (this._state === FromBTCLNSwapState.QUOTE_SOFT_EXPIRED && this.signatureData == null)) {
1289
- if (this._state != FromBTCLNSwapState.QUOTE_SOFT_EXPIRED && this.getTimeoutTime() < Date.now()) {
1290
- this._state = FromBTCLNSwapState.QUOTE_SOFT_EXPIRED;
1291
- changed ||= true;
1292
- }
1293
- if (!skipLpCheck)
1294
- try {
1295
- const result = await this._checkIntermediaryPaymentReceived(false);
1296
- if (result !== null)
1297
- changed ||= true;
1298
- }
1299
- catch (e) {
1300
- this.logger.error("_sync(): Failed to synchronize swap, error: ", e);
1301
- }
1302
- if (this._state === FromBTCLNSwapState.PR_CREATED || (this._state === FromBTCLNSwapState.QUOTE_SOFT_EXPIRED && this.signatureData == null)) {
1303
- if (await this._verifyQuoteDefinitelyExpired()) {
1304
- this._state = FromBTCLNSwapState.QUOTE_EXPIRED;
1305
- changed ||= true;
1306
- }
1307
- }
1308
- }
1309
- if (await this.syncStateFromChain(quoteDefinitelyExpired, commitStatus))
1310
- changed = true;
1311
- if (this._state === FromBTCLNSwapState.CLAIM_COMMITED) {
1312
- const expired = await this._contract.isExpired(this._getInitiator(), this._data);
1313
- if (expired) {
1314
- this._state = FromBTCLNSwapState.EXPIRED;
1315
- changed = true;
1316
- }
1317
- }
1318
- if (save && changed)
1319
- await this._saveAndEmit();
1320
- return changed;
1321
- }
1322
- /**
1323
- * @inheritDoc
1324
- * @internal
1325
- */
1326
- async _forciblySetOnchainState(commitStatus) {
1327
- switch (commitStatus.type) {
1328
- case base_1.SwapCommitStateType.PAID:
1329
- if (this._commitTxId == null && commitStatus.getInitTxId != null)
1330
- this._commitTxId = await commitStatus.getInitTxId();
1331
- if (this._claimTxId == null)
1332
- this._claimTxId = await commitStatus.getClaimTxId();
1333
- if (this.secret == null || this.pr == null)
1334
- this._setSwapSecret(await commitStatus.getClaimResult());
1335
- this._state = FromBTCLNSwapState.CLAIM_CLAIMED;
1336
- return true;
1337
- case base_1.SwapCommitStateType.NOT_COMMITED:
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) {
1344
- this._refundTxId = await commitStatus.getRefundTxId();
1345
- changed = true;
1346
- }
1347
- if (this._refundTxId != null) {
1348
- this._state = FromBTCLNSwapState.FAILED;
1349
- changed = true;
1350
- }
1351
- return changed;
1352
- case base_1.SwapCommitStateType.EXPIRED:
1353
- if (this._commitTxId == null && commitStatus.getInitTxId != null)
1354
- this._commitTxId = await commitStatus.getInitTxId();
1355
- if (this._refundTxId == null && commitStatus.getRefundTxId)
1356
- this._refundTxId = await commitStatus.getRefundTxId();
1357
- this._state = this._refundTxId == null ? FromBTCLNSwapState.QUOTE_EXPIRED : FromBTCLNSwapState.FAILED;
1358
- return true;
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
- }
1365
- if (this._state !== FromBTCLNSwapState.CLAIM_COMMITED && this._state !== FromBTCLNSwapState.EXPIRED) {
1366
- this._state = FromBTCLNSwapState.CLAIM_COMMITED;
1367
- save = true;
1368
- }
1369
- return save;
1370
- }
1371
- return false;
1372
- }
1373
- /**
1374
- * @inheritDoc
1375
- * @internal
1376
- */
1377
- async _tick(save) {
1378
- switch (this._state) {
1379
- case FromBTCLNSwapState.PR_CREATED:
1380
- if (this.getTimeoutTime() < Date.now()) {
1381
- this._state = FromBTCLNSwapState.QUOTE_SOFT_EXPIRED;
1382
- if (save)
1383
- await this._saveAndEmit();
1384
- return true;
1385
- }
1386
- break;
1387
- case FromBTCLNSwapState.PR_PAID:
1388
- if (this.expiry < Date.now()) {
1389
- this._state = FromBTCLNSwapState.QUOTE_SOFT_EXPIRED;
1390
- if (save)
1391
- await this._saveAndEmit();
1392
- return true;
1393
- }
1394
- break;
1395
- case FromBTCLNSwapState.CLAIM_COMMITED:
1396
- const expired = await this._contract.isExpired(this._getInitiator(), this._data);
1397
- if (expired) {
1398
- this._state = FromBTCLNSwapState.EXPIRED;
1399
- if (save)
1400
- await this._saveAndEmit();
1401
- return true;
1402
- }
1403
- break;
1404
- }
1405
- return false;
1406
- }
1407
- /**
1408
- * Forcibly sets the swap secret pre-image from on-chain data
1409
- *
1410
- * @internal
1411
- */
1412
- _setSwapSecret(secret) {
1413
- this.secret = secret;
1414
- if (this.pr == null) {
1415
- this.pr = buffer_1.Buffer.from((0, sha2_1.sha256)(buffer_1.Buffer.from(secret, "hex"))).toString("hex");
1416
- }
1417
- }
1418
- }
1419
- exports.FromBTCLNSwap = FromBTCLNSwap;
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.FromBTCLNSwap = exports.isFromBTCLNSwapInit = exports.FromBTCLNSwapState = void 0;
4
+ const bolt11_1 = require("@atomiqlabs/bolt11");
5
+ const IFromBTCSelfInitSwap_1 = require("../IFromBTCSelfInitSwap");
6
+ const SwapType_1 = require("../../../../enums/SwapType");
7
+ const base_1 = require("@atomiqlabs/base");
8
+ const buffer_1 = require("buffer");
9
+ const LNURL_1 = require("../../../../lnurl/LNURL");
10
+ const UserError_1 = require("../../../../errors/UserError");
11
+ const IntermediaryAPI_1 = require("../../../../intermediaries/apis/IntermediaryAPI");
12
+ const IntermediaryError_1 = require("../../../../errors/IntermediaryError");
13
+ const Utils_1 = require("../../../../utils/Utils");
14
+ const IEscrowSelfInitSwap_1 = require("../../IEscrowSelfInitSwap");
15
+ const TokenAmount_1 = require("../../../../types/TokenAmount");
16
+ const Token_1 = require("../../../../types/Token");
17
+ const Logger_1 = require("../../../../utils/Logger");
18
+ const TimeoutUtils_1 = require("../../../../utils/TimeoutUtils");
19
+ const LNURLWithdraw_1 = require("../../../../types/lnurl/LNURLWithdraw");
20
+ const sha2_1 = require("@noble/hashes/sha2");
21
+ /**
22
+ * State enum for legacy Lightning -> Smart chain swaps
23
+ * @category Swaps/Legacy/Lightning → Smart chain
24
+ */
25
+ var FromBTCLNSwapState;
26
+ (function (FromBTCLNSwapState) {
27
+ /**
28
+ * Swap has failed as the user didn't settle the HTLC on the destination before expiration
29
+ */
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
+ */
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
+ */
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
+ */
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
+ */
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
+ */
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
+ */
63
+ FromBTCLNSwapState[FromBTCLNSwapState["CLAIM_COMMITED"] = 2] = "CLAIM_COMMITED";
64
+ /**
65
+ * Swap successfully settled and funds received on the destination chain
66
+ */
67
+ FromBTCLNSwapState[FromBTCLNSwapState["CLAIM_CLAIMED"] = 3] = "CLAIM_CLAIMED";
68
+ })(FromBTCLNSwapState = exports.FromBTCLNSwapState || (exports.FromBTCLNSwapState = {}));
69
+ const FromBTCLNSwapStateDescription = {
70
+ [FromBTCLNSwapState.FAILED]: "Swap has failed as the user didn't settle the HTLC on the destination before expiration",
71
+ [FromBTCLNSwapState.QUOTE_EXPIRED]: "Swap has expired for good and there is no way how it can be executed anymore",
72
+ [FromBTCLNSwapState.QUOTE_SOFT_EXPIRED]: "Swap is expired, though there is still a chance that it will be processed",
73
+ [FromBTCLNSwapState.EXPIRED]: "Swap HTLC on the destination chain has expired, it is not safe anymore to settle (claim) the swap on the destination smart chain.",
74
+ [FromBTCLNSwapState.PR_CREATED]: "Swap quote was created, pay the bolt11 lightning network invoice to initiate the swap, then use the wait till the lightning network payment is received by the intermediary (LP)",
75
+ [FromBTCLNSwapState.PR_PAID]: "Lightning network payment has been received by the intermediary (LP), the user can now settle the swap on the destination smart chain side.",
76
+ [FromBTCLNSwapState.CLAIM_COMMITED]: "Swap escrow HTLC has been created on the destination chain. Continue by claiming it.",
77
+ [FromBTCLNSwapState.CLAIM_CLAIMED]: "Swap successfully settled and funds received on the destination chain"
78
+ };
79
+ function isFromBTCLNSwapInit(obj) {
80
+ return (obj.pr == null || typeof obj.pr === "string") &&
81
+ (obj.secret == null || typeof obj.secret === "string") &&
82
+ (obj.lnurl == null || typeof (obj.lnurl) === "string") &&
83
+ (obj.lnurlK1 == null || typeof (obj.lnurlK1) === "string") &&
84
+ (obj.lnurlCallback == null || typeof (obj.lnurlCallback) === "string") &&
85
+ (0, IEscrowSelfInitSwap_1.isIEscrowSelfInitSwapInit)(obj);
86
+ }
87
+ exports.isFromBTCLNSwapInit = isFromBTCLNSwapInit;
88
+ /**
89
+ * Legacy escrow (HTLC) based swap for Bitcoin Lightning -> Smart chains, requires manual settlement
90
+ * of the swap on the destination network once the lightning network payment is received by the LP.
91
+ *
92
+ * @category Swaps/Legacy/Lightning → Smart chain
93
+ */
94
+ class FromBTCLNSwap extends IFromBTCSelfInitSwap_1.IFromBTCSelfInitSwap {
95
+ /**
96
+ * Sets the LNURL data for the swap
97
+ *
98
+ * @internal
99
+ */
100
+ _setLNURLData(lnurl, lnurlK1, lnurlCallback) {
101
+ this.lnurl = lnurl;
102
+ this.lnurlK1 = lnurlK1;
103
+ this.lnurlCallback = lnurlCallback;
104
+ }
105
+ constructor(wrapper, initOrObject) {
106
+ if (isFromBTCLNSwapInit(initOrObject) && initOrObject.url != null)
107
+ initOrObject.url += "/frombtcln";
108
+ super(wrapper, initOrObject);
109
+ this.TYPE = SwapType_1.SwapType.FROM_BTCLN;
110
+ /**
111
+ * @internal
112
+ */
113
+ this.swapStateName = (state) => FromBTCLNSwapState[state];
114
+ /**
115
+ * @internal
116
+ */
117
+ this.swapStateDescription = FromBTCLNSwapStateDescription;
118
+ /**
119
+ * @internal
120
+ */
121
+ this.inputToken = Token_1.BitcoinTokens.BTCLN;
122
+ this.lnurlFailSignal = new AbortController();
123
+ this.prPosted = false;
124
+ if (isFromBTCLNSwapInit(initOrObject)) {
125
+ this._state = FromBTCLNSwapState.PR_CREATED;
126
+ this.pr = initOrObject.pr;
127
+ this.secret = initOrObject.secret;
128
+ this.initialSwapData = initOrObject.initialSwapData;
129
+ this.lnurl = initOrObject.lnurl;
130
+ this.lnurlK1 = initOrObject.lnurlK1;
131
+ this.lnurlCallback = initOrObject.lnurlCallback;
132
+ this.usesClaimHashAsId = true;
133
+ }
134
+ else {
135
+ this.pr = initOrObject.pr;
136
+ this.secret = initOrObject.secret;
137
+ if (initOrObject.initialSwapData == null) {
138
+ this.initialSwapData = this._data;
139
+ }
140
+ else {
141
+ this.initialSwapData = base_1.SwapData.deserialize(initOrObject.initialSwapData);
142
+ }
143
+ this.lnurl = initOrObject.lnurl;
144
+ this.lnurlK1 = initOrObject.lnurlK1;
145
+ this.lnurlCallback = initOrObject.lnurlCallback;
146
+ this.prPosted = initOrObject.prPosted;
147
+ if (this._state === FromBTCLNSwapState.PR_CREATED && this._data != null) {
148
+ this.initialSwapData = this._data;
149
+ delete this._data;
150
+ }
151
+ this.usesClaimHashAsId = initOrObject.usesClaimHashAsId ?? false;
152
+ }
153
+ this.tryRecomputeSwapPrice();
154
+ this.logger = (0, Logger_1.getLogger)("FromBTCLN(" + this.getIdentifierHashString() + "): ");
155
+ }
156
+ /**
157
+ * @inheritDoc
158
+ * @internal
159
+ */
160
+ getSwapData() {
161
+ return this._data ?? this.initialSwapData;
162
+ }
163
+ /**
164
+ * @inheritDoc
165
+ * @internal
166
+ */
167
+ upgradeVersion() {
168
+ if (this.version == null) {
169
+ switch (this._state) {
170
+ case -2:
171
+ this._state = FromBTCLNSwapState.QUOTE_EXPIRED;
172
+ break;
173
+ case -1:
174
+ this._state = FromBTCLNSwapState.FAILED;
175
+ break;
176
+ case 0:
177
+ this._state = FromBTCLNSwapState.PR_CREATED;
178
+ break;
179
+ case 1:
180
+ this._state = FromBTCLNSwapState.PR_PAID;
181
+ break;
182
+ case 2:
183
+ this._state = FromBTCLNSwapState.CLAIM_COMMITED;
184
+ break;
185
+ case 3:
186
+ this._state = FromBTCLNSwapState.CLAIM_CLAIMED;
187
+ break;
188
+ }
189
+ this.version = 1;
190
+ }
191
+ }
192
+ //////////////////////////////
193
+ //// Getters & utils
194
+ /**
195
+ * @inheritDoc
196
+ * @internal
197
+ */
198
+ getIdentifierHash() {
199
+ const idBuffer = this.usesClaimHashAsId
200
+ ? buffer_1.Buffer.from(this.getClaimHash(), "hex")
201
+ : this.getPaymentHash();
202
+ if (this._randomNonce == null)
203
+ return idBuffer;
204
+ return buffer_1.Buffer.concat([idBuffer, buffer_1.Buffer.from(this._randomNonce, "hex")]);
205
+ }
206
+ /**
207
+ * Returns the payment hash of the swap and lightning network invoice, or `null` if not known (i.e. if
208
+ * the swap was recovered from on-chain data, the payment hash might not be known)
209
+ *
210
+ * @internal
211
+ */
212
+ getPaymentHash() {
213
+ if (this.pr == null)
214
+ return null;
215
+ if (this.pr.toLowerCase().startsWith("ln")) {
216
+ const parsed = (0, bolt11_1.decode)(this.pr);
217
+ if (parsed.tagsObject.payment_hash == null)
218
+ throw new Error("Swap invoice has no payment hash field!");
219
+ return buffer_1.Buffer.from(parsed.tagsObject.payment_hash, "hex");
220
+ }
221
+ return buffer_1.Buffer.from(this.pr, "hex");
222
+ }
223
+ /**
224
+ * @inheritDoc
225
+ * @internal
226
+ */
227
+ canCommit(skipQuoteExpiryChecks) {
228
+ return this._state === FromBTCLNSwapState.PR_PAID || (!!skipQuoteExpiryChecks && this._state === FromBTCLNSwapState.QUOTE_SOFT_EXPIRED);
229
+ }
230
+ /**
231
+ * @inheritDoc
232
+ */
233
+ getInputAddress() {
234
+ return this.lnurl ?? this.pr ?? null;
235
+ }
236
+ /**
237
+ * @inheritDoc
238
+ */
239
+ getInputTxId() {
240
+ const paymentHash = this.getPaymentHash();
241
+ if (paymentHash == null)
242
+ return null;
243
+ return paymentHash.toString("hex");
244
+ }
245
+ /**
246
+ * Returns the lightning network BOLT11 invoice that needs to be paid as an input to the swap.
247
+ *
248
+ * In case the swap is recovered from on-chain data, the address returned might be just a payment hash,
249
+ * as it is impossible to retrieve the actual lightning network invoice paid purely from on-chain
250
+ * data.
251
+ */
252
+ getAddress() {
253
+ return this.pr ?? "";
254
+ }
255
+ /**
256
+ * A hyperlink representation of the address + amount that the user needs to sends on the source chain.
257
+ * This is suitable to be displayed in a form of QR code.
258
+ *
259
+ * @remarks
260
+ * In case the swap is recovered from on-chain data, the address returned might be just a payment hash,
261
+ * as it is impossible to retrieve the actual lightning network invoice paid purely from on-chain
262
+ * data.
263
+ */
264
+ getHyperlink() {
265
+ return this.pr == null ? "" : "lightning:" + this.pr.toUpperCase();
266
+ }
267
+ /**
268
+ * Returns the timeout time (in UNIX milliseconds) when the swap will definitelly be considered as expired
269
+ * if the LP doesn't make it expired sooner
270
+ */
271
+ getDefinitiveExpiryTime() {
272
+ if (this.pr == null || !this.pr.toLowerCase().startsWith("ln"))
273
+ return 0;
274
+ const decoded = (0, bolt11_1.decode)(this.pr);
275
+ if (decoded.timeExpireDate == null)
276
+ throw new Error("Swap invoice doesn't contain expiry date field!");
277
+ const finalCltvExpiryDelta = decoded.tagsObject.min_final_cltv_expiry ?? 144;
278
+ const finalCltvExpiryDelay = finalCltvExpiryDelta * this.wrapper._options.bitcoinBlocktime * this.wrapper._options.safetyFactor;
279
+ return (decoded.timeExpireDate + finalCltvExpiryDelay) * 1000;
280
+ }
281
+ /**
282
+ * Returns timeout time (in UNIX milliseconds) when the swap htlc will expire
283
+ */
284
+ getHtlcTimeoutTime() {
285
+ if (this._data == null)
286
+ return null;
287
+ return Number(this.wrapper._getHtlcTimeout(this._data)) * 1000;
288
+ }
289
+ /**
290
+ * Returns timeout time (in UNIX milliseconds) when the LN invoice will expire
291
+ */
292
+ getTimeoutTime() {
293
+ if (this.pr == null || !this.pr.toLowerCase().startsWith("ln"))
294
+ return 0;
295
+ const decoded = (0, bolt11_1.decode)(this.pr);
296
+ if (decoded.timeExpireDate == null)
297
+ throw new Error("Swap invoice doesn't contain expiry date field!");
298
+ return (decoded.timeExpireDate * 1000);
299
+ }
300
+ /**
301
+ * @inheritDoc
302
+ */
303
+ isFinished() {
304
+ return this._state === FromBTCLNSwapState.CLAIM_CLAIMED || this._state === FromBTCLNSwapState.QUOTE_EXPIRED || this._state === FromBTCLNSwapState.FAILED;
305
+ }
306
+ /**
307
+ * @inheritDoc
308
+ */
309
+ isClaimable() {
310
+ return this._state === FromBTCLNSwapState.CLAIM_COMMITED;
311
+ }
312
+ /**
313
+ * @inheritDoc
314
+ */
315
+ isSuccessful() {
316
+ return this._state === FromBTCLNSwapState.CLAIM_CLAIMED;
317
+ }
318
+ /**
319
+ * @inheritDoc
320
+ */
321
+ isFailed() {
322
+ return this._state === FromBTCLNSwapState.FAILED || this._state === FromBTCLNSwapState.EXPIRED;
323
+ }
324
+ /**
325
+ * @inheritDoc
326
+ */
327
+ isInProgress() {
328
+ return (this._state === FromBTCLNSwapState.PR_CREATED && this.initiated) ||
329
+ (this._state === FromBTCLNSwapState.QUOTE_SOFT_EXPIRED && this.initiated) ||
330
+ this._state === FromBTCLNSwapState.PR_PAID ||
331
+ this._state === FromBTCLNSwapState.CLAIM_COMMITED;
332
+ }
333
+ /**
334
+ * @inheritDoc
335
+ */
336
+ isQuoteExpired() {
337
+ return this._state === FromBTCLNSwapState.QUOTE_EXPIRED;
338
+ }
339
+ /**
340
+ * @inheritDoc
341
+ */
342
+ isQuoteSoftExpired() {
343
+ return this._state === FromBTCLNSwapState.QUOTE_EXPIRED || this._state === FromBTCLNSwapState.QUOTE_SOFT_EXPIRED;
344
+ }
345
+ /**
346
+ * @inheritDoc
347
+ * @internal
348
+ */
349
+ _verifyQuoteDefinitelyExpired() {
350
+ if (this._state === FromBTCLNSwapState.PR_CREATED || (this._state === FromBTCLNSwapState.QUOTE_SOFT_EXPIRED && this.signatureData == null)) {
351
+ return Promise.resolve(this.getDefinitiveExpiryTime() < Date.now());
352
+ }
353
+ return super._verifyQuoteDefinitelyExpired();
354
+ }
355
+ /**
356
+ * @inheritDoc
357
+ * @internal
358
+ */
359
+ _verifyQuoteValid() {
360
+ if (this._state === FromBTCLNSwapState.PR_CREATED ||
361
+ (this._state === FromBTCLNSwapState.QUOTE_SOFT_EXPIRED && this.signatureData == null)) {
362
+ return Promise.resolve(this.getTimeoutTime() > Date.now());
363
+ }
364
+ return super._verifyQuoteValid();
365
+ }
366
+ //////////////////////////////
367
+ //// Amounts & fees
368
+ /**
369
+ * @inheritDoc
370
+ */
371
+ getInputToken() {
372
+ return Token_1.BitcoinTokens.BTCLN;
373
+ }
374
+ /**
375
+ * @inheritDoc
376
+ */
377
+ getInput() {
378
+ if (this.pr == null || !this.pr.toLowerCase().startsWith("ln"))
379
+ return (0, TokenAmount_1.toTokenAmount)(null, this.inputToken, this.wrapper._prices, this.pricingInfo);
380
+ const parsed = (0, bolt11_1.decode)(this.pr);
381
+ if (parsed.millisatoshis == null)
382
+ throw new Error("Swap invoice doesn't contain msat amount field!");
383
+ const amount = (BigInt(parsed.millisatoshis) + 999n) / 1000n;
384
+ return (0, TokenAmount_1.toTokenAmount)(amount, this.inputToken, this.wrapper._prices, this.pricingInfo);
385
+ }
386
+ /**
387
+ * @inheritDoc
388
+ */
389
+ getSmartChainNetworkFee() {
390
+ return this.getCommitAndClaimNetworkFee();
391
+ }
392
+ /**
393
+ * @inheritDoc
394
+ */
395
+ async hasEnoughForTxFees() {
396
+ const [balance, feeRate] = await Promise.all([
397
+ this._contract.getBalance(this._getInitiator(), this.wrapper._chain.getNativeCurrencyAddress(), false),
398
+ this.feeRate != null ? Promise.resolve(this.feeRate) : this._contract.getInitFeeRate(this.getSwapData().getOfferer(), this.getSwapData().getClaimer(), this.getSwapData().getToken(), this.getSwapData().getClaimHash())
399
+ ]);
400
+ const commitFee = await this._contract.getCommitFee(this._getInitiator(), this.getSwapData(), feeRate);
401
+ const claimFee = await this._contract.getClaimFee(this._getInitiator(), this.getSwapData(), feeRate);
402
+ const totalFee = commitFee + claimFee + this.getSwapData().getTotalDeposit();
403
+ return {
404
+ enoughBalance: balance >= totalFee,
405
+ balance: (0, TokenAmount_1.toTokenAmount)(balance, this.wrapper._getNativeToken(), this.wrapper._prices, this.pricingInfo),
406
+ required: (0, TokenAmount_1.toTokenAmount)(totalFee, this.wrapper._getNativeToken(), this.wrapper._prices, this.pricingInfo)
407
+ };
408
+ }
409
+ isValidSecretPreimage(secret) {
410
+ const paymentHash = buffer_1.Buffer.from((0, sha2_1.sha256)(buffer_1.Buffer.from(secret, "hex")));
411
+ const claimHash = this._contract.getHashForHtlc(paymentHash).toString("hex");
412
+ return this.getSwapData().getClaimHash() === claimHash;
413
+ }
414
+ /**
415
+ * Sets the secret preimage for the swap, in case it is not known already
416
+ *
417
+ * @param secret Secret preimage that matches the expected payment hash
418
+ *
419
+ * @throws {Error} If an invalid secret preimage is provided
420
+ */
421
+ setSecretPreimage(secret) {
422
+ if (!this.isValidSecretPreimage(secret))
423
+ throw new Error("Invalid secret preimage provided, hash doesn't match!");
424
+ this.secret = secret;
425
+ }
426
+ /**
427
+ * Returns whether the secret preimage for this swap is known
428
+ */
429
+ hasSecretPreimage() {
430
+ return this.secret != null;
431
+ }
432
+ //////////////////////////////
433
+ //// Execution
434
+ /**
435
+ * Executes the swap with the provided bitcoin lightning network wallet or LNURL
436
+ *
437
+ * @param dstSigner Signer on the destination network, needs to have the same address as the one specified when
438
+ * quote was created, this is required for legacy swaps because the destination wallet needs to actively claim
439
+ * the swap funds on the destination (this also means you need native token to cover gas costs)
440
+ * @param walletOrLnurlWithdraw Bitcoin lightning wallet to use to pay the lightning network invoice, or an LNURL-withdraw
441
+ * link, wallet is not required and the LN invoice can be paid externally as well (just pass null or undefined here)
442
+ * @param callbacks Callbacks to track the progress of the swap
443
+ * @param options Optional options for the swap like feeRate, AbortSignal, and timeouts/intervals
444
+ * @param options.secret A swap secret to use for the claim transaction, generally only needed if the swap
445
+ * was recovered from on-chain data, or the pre-image was generated outside the SDK
446
+ */
447
+ async execute(dstSigner, walletOrLnurlWithdraw, callbacks, options) {
448
+ if (this._state === FromBTCLNSwapState.FAILED)
449
+ throw new Error("Swap failed!");
450
+ if (this._state === FromBTCLNSwapState.EXPIRED)
451
+ throw new Error("Swap HTLC expired!");
452
+ if (this._state === FromBTCLNSwapState.QUOTE_EXPIRED || this._state === FromBTCLNSwapState.QUOTE_SOFT_EXPIRED)
453
+ throw new Error("Swap quote expired!");
454
+ if (this._state === FromBTCLNSwapState.CLAIM_CLAIMED)
455
+ throw new Error("Swap already settled!");
456
+ let abortSignal = options?.abortSignal;
457
+ if (this._state === FromBTCLNSwapState.PR_CREATED) {
458
+ if (walletOrLnurlWithdraw != null && this.lnurl == null) {
459
+ if (this.pr == null || !this.pr.toLowerCase().startsWith("ln"))
460
+ throw new Error("Input lightning network invoice not available, the swap was probably recovered!");
461
+ if (typeof (walletOrLnurlWithdraw) === "string" || (0, LNURLWithdraw_1.isLNURLWithdraw)(walletOrLnurlWithdraw)) {
462
+ await this.settleWithLNURLWithdraw(walletOrLnurlWithdraw);
463
+ }
464
+ else {
465
+ const paymentPromise = walletOrLnurlWithdraw.payInvoice(this.pr);
466
+ const abortController = new AbortController();
467
+ paymentPromise.catch(e => abortController.abort(e));
468
+ if (options?.abortSignal != null)
469
+ options.abortSignal.addEventListener("abort", () => abortController.abort(options?.abortSignal?.reason));
470
+ abortSignal = abortController.signal;
471
+ }
472
+ }
473
+ const paymentSuccess = await this.waitForPayment(callbacks?.onSourceTransactionReceived, options?.lightningTxCheckIntervalSeconds, abortSignal);
474
+ if (!paymentSuccess)
475
+ throw new Error("Failed to receive lightning network payment");
476
+ }
477
+ if (this._state === FromBTCLNSwapState.PR_PAID || this._state === FromBTCLNSwapState.CLAIM_COMMITED) {
478
+ if (this.canCommitAndClaimInOneShot()) {
479
+ await this.commitAndClaim(dstSigner, options?.abortSignal, undefined, callbacks?.onDestinationCommitSent, callbacks?.onDestinationClaimSent, options?.secret);
480
+ }
481
+ else {
482
+ if (this._state === FromBTCLNSwapState.PR_PAID) {
483
+ await this.commit(dstSigner, options?.abortSignal, undefined, callbacks?.onDestinationCommitSent);
484
+ if (options?.delayBetweenCommitAndClaimSeconds != null)
485
+ await (0, TimeoutUtils_1.timeoutPromise)(options.delayBetweenCommitAndClaimSeconds * 1000, options?.abortSignal);
486
+ }
487
+ if (this._state === FromBTCLNSwapState.CLAIM_COMMITED) {
488
+ await this.claim(dstSigner, options?.abortSignal, callbacks?.onDestinationClaimSent, options?.secret);
489
+ }
490
+ }
491
+ }
492
+ // @ts-ignore
493
+ if (this._state === FromBTCLNSwapState.CLAIM_CLAIMED) {
494
+ if (callbacks?.onSwapSettled != null)
495
+ callbacks.onSwapSettled(this.getOutputTxId());
496
+ }
497
+ return true;
498
+ }
499
+ /**
500
+ * @internal
501
+ */
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);
534
+ }
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;
554
+ }
555
+ return {
556
+ steps: [
557
+ {
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
566
+ },
567
+ {
568
+ type: "Settlement",
569
+ side: "destination",
570
+ chain: this.chainIdentifier,
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;
633
+ }
634
+ if (this._state === FromBTCLNSwapState.CLAIM_COMMITED) {
635
+ const txIds = await this.wrapper._chain.sendSignedAndConfirm(parsedTxs, true, abortSignal, false);
636
+ await this.waitTillClaimed(undefined, abortSignal);
637
+ return txIds;
638
+ }
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
+ };
660
+ }
661
+ /**
662
+ * @inheritDoc
663
+ *
664
+ * @param options
665
+ * @param options.skipChecks Skip checks like making sure init signature is still valid and swap
666
+ * wasn't commited yet (this is handled on swap creation, if you commit right after quoting, you
667
+ * can use `skipChecks=true`)
668
+ * @param options.secret A swap secret to use for the claim transaction, generally only needed if the swap
669
+ * was recovered from on-chain data, or the pre-image was generated outside the SDK
670
+ */
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;
692
+ }
693
+ //////////////////////////////
694
+ //// Payment
695
+ /**
696
+ * Checks whether the LP received the LN payment and we can continue by committing & claiming the HTLC on-chain
697
+ *
698
+ * @param save If the new swap state should be saved
699
+ *
700
+ * @internal
701
+ */
702
+ async _checkIntermediaryPaymentReceived(save = true) {
703
+ if (this._state === FromBTCLNSwapState.PR_PAID ||
704
+ this._state === FromBTCLNSwapState.CLAIM_COMMITED ||
705
+ this._state === FromBTCLNSwapState.CLAIM_CLAIMED ||
706
+ this._state === FromBTCLNSwapState.FAILED ||
707
+ this._state === FromBTCLNSwapState.EXPIRED)
708
+ return true;
709
+ if (this._state === FromBTCLNSwapState.QUOTE_EXPIRED || (this._state === FromBTCLNSwapState.QUOTE_SOFT_EXPIRED && this.signatureData != null))
710
+ return false;
711
+ if (this.url == null)
712
+ return false;
713
+ const paymentHash = this.getPaymentHash();
714
+ if (paymentHash == null)
715
+ throw new Error("Failed to check LP payment received, payment hash not known (probably recovered swap?)");
716
+ const resp = await this.wrapper._lpApi.getPaymentAuthorization(this.url, paymentHash.toString("hex"));
717
+ switch (resp.code) {
718
+ case IntermediaryAPI_1.PaymentAuthorizationResponseCodes.AUTH_DATA:
719
+ const data = new (this.wrapper._swapDataDeserializer(this._contractVersion))(resp.data.data);
720
+ try {
721
+ await this.checkIntermediaryReturnedAuthData(this._getInitiator(), data, resp.data);
722
+ this.expiry = await this._contract.getInitAuthorizationExpiry(data, resp.data);
723
+ this._state = FromBTCLNSwapState.PR_PAID;
724
+ this._data = data;
725
+ this.signatureData = {
726
+ prefix: resp.data.prefix,
727
+ timeout: resp.data.timeout,
728
+ signature: resp.data.signature
729
+ };
730
+ this.initiated = true;
731
+ if (save)
732
+ await this._saveAndEmit();
733
+ return true;
734
+ }
735
+ catch (e) { }
736
+ return null;
737
+ case IntermediaryAPI_1.PaymentAuthorizationResponseCodes.EXPIRED:
738
+ this._state = FromBTCLNSwapState.QUOTE_EXPIRED;
739
+ this.initiated = true;
740
+ if (save)
741
+ await this._saveAndEmit();
742
+ return false;
743
+ default:
744
+ return null;
745
+ }
746
+ }
747
+ /**
748
+ * Checks the data returned by the intermediary in the payment auth request
749
+ *
750
+ * @param signer Smart chain signer's address initiating the swap
751
+ * @param data Parsed swap data as returned by the intermediary
752
+ * @param signature Signature data as returned by the intermediary
753
+ *
754
+ * @throws {IntermediaryError} If the returned are not valid
755
+ * @throws {SignatureVerificationError} If the returned signature is not valid
756
+ * @throws {Error} If the swap is already committed on-chain
757
+ *
758
+ * @internal
759
+ */
760
+ async checkIntermediaryReturnedAuthData(signer, data, signature) {
761
+ data.setClaimer(signer);
762
+ if (data.getType() !== base_1.ChainSwapType.HTLC)
763
+ throw new IntermediaryError_1.IntermediaryError("Invalid swap type");
764
+ if (!data.isOfferer(this.getSwapData().getOfferer()))
765
+ throw new IntermediaryError_1.IntermediaryError("Invalid offerer used");
766
+ if (!data.isClaimer(this._getInitiator()))
767
+ throw new IntermediaryError_1.IntermediaryError("Invalid claimer used");
768
+ if (!data.isToken(this.getSwapData().getToken()))
769
+ throw new IntermediaryError_1.IntermediaryError("Invalid token used");
770
+ if (data.getSecurityDeposit() > this.getSwapData().getSecurityDeposit())
771
+ throw new IntermediaryError_1.IntermediaryError("Invalid security deposit!");
772
+ if (data.getClaimerBounty() !== 0n)
773
+ throw new IntermediaryError_1.IntermediaryError("Invalid claimer bounty!");
774
+ if (data.getAmount() < this.getSwapData().getAmount())
775
+ throw new IntermediaryError_1.IntermediaryError("Invalid amount received!");
776
+ if (data.getClaimHash() !== this.getSwapData().getClaimHash())
777
+ throw new IntermediaryError_1.IntermediaryError("Invalid payment hash used!");
778
+ if (!data.isDepositToken(this.getSwapData().getDepositToken()))
779
+ throw new IntermediaryError_1.IntermediaryError("Invalid deposit token used!");
780
+ if (data.hasSuccessAction())
781
+ throw new IntermediaryError_1.IntermediaryError("Invalid has success action");
782
+ await Promise.all([
783
+ this._contract.isValidInitAuthorization(this._getInitiator(), data, signature, this.feeRate),
784
+ this._contract.getCommitStatus(data.getClaimer(), data)
785
+ .then(status => {
786
+ if (status?.type !== base_1.SwapCommitStateType.NOT_COMMITED)
787
+ throw new Error("Swap already committed on-chain!");
788
+ })
789
+ ]);
790
+ }
791
+ /**
792
+ * Waits till a lightning network payment is received by the intermediary and client
793
+ * can continue by initiating (committing) & settling (claiming) the HTLC by calling
794
+ * either the {@link commitAndClaim} function (if the underlying chain allows commit
795
+ * and claim in a single transaction - check with {@link canCommitAndClaimInOneShot}).
796
+ * Or call {@link commit} and then {@link claim} separately.
797
+ *
798
+ * If this swap is using an LNURL-withdraw link as input, it automatically posts the
799
+ * generated invoice to the LNURL service to pay it.
800
+ *
801
+ * @param onPaymentReceived Callback as for when the LP reports having received the ln payment
802
+ * @param abortSignal Abort signal to stop waiting for payment
803
+ * @param checkIntervalSeconds How often to poll the intermediary for answer (default 5 seconds)
804
+ */
805
+ async waitForPayment(onPaymentReceived, checkIntervalSeconds, abortSignal) {
806
+ checkIntervalSeconds ??= 5;
807
+ if (this._state !== FromBTCLNSwapState.PR_CREATED &&
808
+ (this._state !== FromBTCLNSwapState.QUOTE_SOFT_EXPIRED || this.signatureData != null))
809
+ throw new Error("Must be in PR_CREATED state!");
810
+ if (this.url == null)
811
+ throw new Error("LP URL not known, cannot await the payment!");
812
+ const abortController = new AbortController();
813
+ if (abortSignal != null)
814
+ abortSignal.addEventListener("abort", () => abortController.abort(abortSignal.reason));
815
+ let save = false;
816
+ if (this.lnurl != null && this.lnurlK1 != null && this.lnurlCallback != null && !this.prPosted) {
817
+ if (this.pr == null || !this.pr.toLowerCase().startsWith("ln"))
818
+ throw new Error("Input lightning network invoice not available, the swap was probably recovered!");
819
+ LNURL_1.LNURL.postInvoiceToLNURLWithdraw({ k1: this.lnurlK1, callback: this.lnurlCallback }, this.pr).catch(e => {
820
+ this.lnurlFailSignal.abort(e);
821
+ });
822
+ this.prPosted = true;
823
+ save ||= true;
824
+ }
825
+ if (!this.initiated) {
826
+ this.initiated = true;
827
+ save ||= true;
828
+ }
829
+ if (save)
830
+ await this._saveAndEmit();
831
+ let lnurlFailListener = () => abortController.abort(this.lnurlFailSignal.signal.reason);
832
+ this.lnurlFailSignal.signal.addEventListener("abort", lnurlFailListener);
833
+ this.lnurlFailSignal.signal.throwIfAborted();
834
+ const paymentHash = this.getPaymentHash();
835
+ if (paymentHash == null)
836
+ throw new Error("Swap payment hash not available, the swap was probably recovered!");
837
+ let resp = { code: IntermediaryAPI_1.PaymentAuthorizationResponseCodes.PENDING, msg: "" };
838
+ while (!abortController.signal.aborted && resp.code === IntermediaryAPI_1.PaymentAuthorizationResponseCodes.PENDING) {
839
+ resp = await this.wrapper._lpApi.getPaymentAuthorization(this.url, paymentHash.toString("hex"));
840
+ if (resp.code === IntermediaryAPI_1.PaymentAuthorizationResponseCodes.PENDING)
841
+ await (0, TimeoutUtils_1.timeoutPromise)(checkIntervalSeconds * 1000, abortController.signal);
842
+ }
843
+ this.lnurlFailSignal.signal.removeEventListener("abort", lnurlFailListener);
844
+ abortController.signal.throwIfAborted();
845
+ if (resp.code === IntermediaryAPI_1.PaymentAuthorizationResponseCodes.AUTH_DATA) {
846
+ const sigData = resp.data;
847
+ const swapData = new (this.wrapper._swapDataDeserializer(this._contractVersion))(resp.data.data);
848
+ await this.checkIntermediaryReturnedAuthData(this._getInitiator(), swapData, sigData);
849
+ this.expiry = await this._contract.getInitAuthorizationExpiry(swapData, sigData);
850
+ if (onPaymentReceived != null)
851
+ onPaymentReceived(this.getInputTxId());
852
+ if (this._state === FromBTCLNSwapState.PR_CREATED || this._state === FromBTCLNSwapState.QUOTE_SOFT_EXPIRED) {
853
+ this._data = swapData;
854
+ this.signatureData = {
855
+ prefix: sigData.prefix,
856
+ timeout: sigData.timeout,
857
+ signature: sigData.signature
858
+ };
859
+ await this._saveAndEmit(FromBTCLNSwapState.PR_PAID);
860
+ }
861
+ return true;
862
+ }
863
+ if (this._state === FromBTCLNSwapState.PR_CREATED || this._state === FromBTCLNSwapState.QUOTE_SOFT_EXPIRED) {
864
+ if (resp.code === IntermediaryAPI_1.PaymentAuthorizationResponseCodes.EXPIRED) {
865
+ await this._saveAndEmit(FromBTCLNSwapState.QUOTE_EXPIRED);
866
+ }
867
+ return false;
868
+ }
869
+ throw new IntermediaryError_1.IntermediaryError("Invalid response from the LP");
870
+ }
871
+ //////////////////////////////
872
+ //// Commit
873
+ /**
874
+ * @inheritDoc
875
+ *
876
+ * @throws {Error} If invalid signer is provided that doesn't match the swap data
877
+ */
878
+ async commit(_signer, abortSignal, skipChecks, onBeforeTxSent) {
879
+ const signer = (0, base_1.isAbstractSigner)(_signer) ? _signer : await this.wrapper._chain.wrapSigner(_signer);
880
+ this.checkSigner(signer);
881
+ let txCount = 0;
882
+ const txs = await this.txsCommit(skipChecks);
883
+ const result = await this.wrapper._chain.sendAndConfirm(signer, txs, true, abortSignal, undefined, (txId) => {
884
+ txCount++;
885
+ if (onBeforeTxSent != null && txCount === txs.length)
886
+ onBeforeTxSent(txId);
887
+ return Promise.resolve();
888
+ });
889
+ this._commitTxId = result[result.length - 1];
890
+ if (this._state === FromBTCLNSwapState.PR_PAID || this._state === FromBTCLNSwapState.QUOTE_SOFT_EXPIRED || this._state === FromBTCLNSwapState.QUOTE_EXPIRED) {
891
+ await this._saveAndEmit(FromBTCLNSwapState.CLAIM_COMMITED);
892
+ }
893
+ return this._commitTxId;
894
+ }
895
+ /**
896
+ * @inheritDoc
897
+ */
898
+ async waitTillCommited(abortSignal) {
899
+ if (this._state === FromBTCLNSwapState.CLAIM_COMMITED || this._state === FromBTCLNSwapState.CLAIM_CLAIMED)
900
+ return Promise.resolve();
901
+ if (this._state !== FromBTCLNSwapState.PR_PAID && (this._state !== FromBTCLNSwapState.QUOTE_SOFT_EXPIRED && this.signatureData != null))
902
+ throw new Error("Invalid state");
903
+ const abortController = (0, Utils_1.extendAbortController)(abortSignal);
904
+ const result = await Promise.race([
905
+ this.watchdogWaitTillCommited(undefined, abortController.signal),
906
+ this.waitTillState(FromBTCLNSwapState.CLAIM_COMMITED, "gte", abortController.signal).then(() => 0)
907
+ ]);
908
+ abortController.abort();
909
+ if (result === 0) {
910
+ this.logger.debug("waitTillCommited(): Resolved from state changed");
911
+ }
912
+ else if (result != null) {
913
+ this.logger.debug("waitTillCommited(): Resolved from watchdog - commited");
914
+ }
915
+ if (result === null) {
916
+ this.logger.debug("waitTillCommited(): Resolved from watchdog - signature expired");
917
+ if (this._state === FromBTCLNSwapState.PR_PAID ||
918
+ this._state === FromBTCLNSwapState.QUOTE_SOFT_EXPIRED) {
919
+ await this._saveAndEmit(FromBTCLNSwapState.QUOTE_EXPIRED);
920
+ }
921
+ return;
922
+ }
923
+ if (this._state === FromBTCLNSwapState.PR_PAID ||
924
+ this._state === FromBTCLNSwapState.QUOTE_SOFT_EXPIRED) {
925
+ if (typeof (result) === "object" && result.getInitTxId != null && this._commitTxId == null)
926
+ this._commitTxId = await result.getInitTxId();
927
+ await this._saveAndEmit(FromBTCLNSwapState.CLAIM_COMMITED);
928
+ }
929
+ }
930
+ //////////////////////////////
931
+ //// Claim
932
+ /**
933
+ * Unsafe txs claim getter without state checking!
934
+ *
935
+ * @param _signer
936
+ * @param secret A swap secret to use for the claim transaction, generally only needed if the swap
937
+ * was recovered from on-chain data, or the pre-image was generated outside the SDK
938
+ *
939
+ * @internal
940
+ */
941
+ async _txsClaim(_signer, secret) {
942
+ let address = undefined;
943
+ if (_signer != null) {
944
+ if (typeof (_signer) === "string") {
945
+ address = _signer;
946
+ }
947
+ else if ((0, base_1.isAbstractSigner)(_signer)) {
948
+ address = _signer.getAddress();
949
+ }
950
+ else {
951
+ address = (await this.wrapper._chain.wrapSigner(_signer)).getAddress();
952
+ }
953
+ }
954
+ if (this._data == null)
955
+ throw new Error("Unknown data, wrong state?");
956
+ const useSecret = secret ?? this.secret;
957
+ if (useSecret == null)
958
+ throw new Error("Swap secret pre-image not known and not provided, please provide the swap secret pre-image as an argument");
959
+ if (!this.isValidSecretPreimage(useSecret))
960
+ throw new Error("Invalid swap secret pre-image provided!");
961
+ return this._contract.txsClaimWithSecret(address ?? this._getInitiator(), this._data, useSecret, true, true);
962
+ }
963
+ /**
964
+ * @inheritDoc
965
+ *
966
+ * @param _signer Optional signer address to use for claiming the swap, can also be different from the initializer
967
+ * @param secret A swap secret to use for the claim transaction, generally only needed if the swap
968
+ * was recovered from on-chain data, or the pre-image was generated outside the SDK
969
+ *
970
+ * @throws {Error} If in invalid state (must be {@link FromBTCLNSwapState.CLAIM_COMMITED})
971
+ */
972
+ async txsClaim(_signer, secret) {
973
+ if (this._state !== FromBTCLNSwapState.CLAIM_COMMITED)
974
+ throw new Error("Must be in CLAIM_COMMITED state!");
975
+ return this._txsClaim(_signer, secret);
976
+ }
977
+ /**
978
+ * @inheritDoc
979
+ *
980
+ * @param _signer
981
+ * @param abortSignal
982
+ * @param onBeforeTxSent
983
+ * @param secret A swap secret to use for the claim transaction, generally only needed if the swap
984
+ * was recovered from on-chain data, or the pre-image was generated outside the SDK
985
+ */
986
+ async claim(_signer, abortSignal, onBeforeTxSent, secret) {
987
+ const signer = (0, base_1.isAbstractSigner)(_signer) ? _signer : await this.wrapper._chain.wrapSigner(_signer);
988
+ let txCount = 0;
989
+ const result = await this.wrapper._chain.sendAndConfirm(signer, await this.txsClaim(_signer, secret), true, abortSignal, undefined, (txId) => {
990
+ txCount++;
991
+ if (onBeforeTxSent != null && txCount === 1)
992
+ onBeforeTxSent(txId);
993
+ return Promise.resolve();
994
+ });
995
+ this._claimTxId = result[0];
996
+ if (this._state === FromBTCLNSwapState.CLAIM_COMMITED || this._state === FromBTCLNSwapState.EXPIRED || this._state === FromBTCLNSwapState.FAILED) {
997
+ await this._saveAndEmit(FromBTCLNSwapState.CLAIM_CLAIMED);
998
+ }
999
+ return result[0];
1000
+ }
1001
+ /**
1002
+ * @inheritDoc
1003
+ *
1004
+ * @throws {Error} If swap is in invalid state (must be {@link FromBTCLNSwapState.CLAIM_COMMITED})
1005
+ * @throws {Error} If the LP refunded sooner than we were able to claim
1006
+ */
1007
+ async waitTillClaimed(maxWaitTimeSeconds, abortSignal) {
1008
+ if (this._state === FromBTCLNSwapState.CLAIM_CLAIMED)
1009
+ return Promise.resolve(true);
1010
+ if (this._state !== FromBTCLNSwapState.CLAIM_COMMITED)
1011
+ throw new Error("Invalid state (not CLAIM_COMMITED)");
1012
+ const abortController = new AbortController();
1013
+ if (abortSignal != null)
1014
+ abortSignal.addEventListener("abort", () => abortController.abort(abortSignal.reason));
1015
+ let timedOut = false;
1016
+ if (maxWaitTimeSeconds != null) {
1017
+ const timeout = setTimeout(() => {
1018
+ timedOut = true;
1019
+ abortController.abort();
1020
+ }, maxWaitTimeSeconds * 1000);
1021
+ abortController.signal.addEventListener("abort", () => clearTimeout(timeout));
1022
+ }
1023
+ let res;
1024
+ try {
1025
+ res = await Promise.race([
1026
+ this.watchdogWaitTillResult(undefined, abortController.signal),
1027
+ this.waitTillState(FromBTCLNSwapState.CLAIM_CLAIMED, "eq", abortController.signal).then(() => 0),
1028
+ this.waitTillState(FromBTCLNSwapState.EXPIRED, "eq", abortController.signal).then(() => 1),
1029
+ ]);
1030
+ abortController.abort();
1031
+ }
1032
+ catch (e) {
1033
+ abortController.abort();
1034
+ if (timedOut)
1035
+ return false;
1036
+ throw e;
1037
+ }
1038
+ if (res === 0) {
1039
+ this.logger.debug("waitTillClaimed(): Resolved from state change (CLAIM_CLAIMED)");
1040
+ return true;
1041
+ }
1042
+ if (res === 1) {
1043
+ this.logger.debug("waitTillClaimed(): Resolved from state change (EXPIRED)");
1044
+ throw new Error("Swap expired during claiming");
1045
+ }
1046
+ this.logger.debug("waitTillClaimed(): Resolved from watchdog");
1047
+ if (res?.type === base_1.SwapCommitStateType.PAID) {
1048
+ if (this._state !== FromBTCLNSwapState.CLAIM_CLAIMED) {
1049
+ this._claimTxId = await res.getClaimTxId();
1050
+ await this._saveAndEmit(FromBTCLNSwapState.CLAIM_CLAIMED);
1051
+ }
1052
+ }
1053
+ if (res?.type === base_1.SwapCommitStateType.NOT_COMMITED || res?.type === base_1.SwapCommitStateType.EXPIRED) {
1054
+ if (this._state !== FromBTCLNSwapState.CLAIM_CLAIMED &&
1055
+ this._state !== FromBTCLNSwapState.FAILED) {
1056
+ if (res.getRefundTxId != null)
1057
+ this._refundTxId = await res.getRefundTxId();
1058
+ await this._saveAndEmit(FromBTCLNSwapState.FAILED);
1059
+ }
1060
+ throw new Error("Swap expired while waiting for claim!");
1061
+ }
1062
+ return true;
1063
+ }
1064
+ //////////////////////////////
1065
+ //// Commit & claim
1066
+ /**
1067
+ * Estimated transaction fee for commit & claim transactions combined, required
1068
+ * to settle the swap on the smart chain destination side.
1069
+ */
1070
+ async getCommitAndClaimNetworkFee() {
1071
+ const swapContract = this._contract;
1072
+ const feeRate = this.feeRate ?? await swapContract.getInitFeeRate(this.getSwapData().getOfferer(), this.getSwapData().getClaimer(), this.getSwapData().getToken(), this.getSwapData().getClaimHash());
1073
+ const commitFee = await (swapContract.getRawCommitFee != null ?
1074
+ swapContract.getRawCommitFee(this._getInitiator(), this.getSwapData(), feeRate) :
1075
+ swapContract.getCommitFee(this._getInitiator(), this.getSwapData(), feeRate));
1076
+ const claimFee = await (swapContract.getRawClaimFee != null ?
1077
+ swapContract.getRawClaimFee(this._getInitiator(), this.getSwapData(), feeRate) :
1078
+ swapContract.getClaimFee(this._getInitiator(), this.getSwapData(), feeRate));
1079
+ return (0, TokenAmount_1.toTokenAmount)(commitFee + claimFee, this.wrapper._getNativeToken(), this.wrapper._prices);
1080
+ }
1081
+ /**
1082
+ * Returns whether the underlying chain supports calling commit and claim in a single call,
1083
+ * such that you can use the {@link commitAndClaim} function. If not you have to manually
1084
+ * call {@link commit} first and then {@link claim}.
1085
+ */
1086
+ canCommitAndClaimInOneShot() {
1087
+ return this._contract.initAndClaimWithSecret != null;
1088
+ }
1089
+ /**
1090
+ * Returns transactions for both commit & claim operation together, such that they can be signed all at once by
1091
+ * the wallet. **WARNING**: transactions must be sent sequentially, such that the claim (2nd) transaction is only
1092
+ * sent after the commit (1st) transaction confirms. Failure to do so can reveal the HTLC pre-image too soon,
1093
+ * opening a possibility for the LP to steal funds!
1094
+ *
1095
+ * @param skipChecks Skip checks like making sure init signature is still valid and swap wasn't commited yet
1096
+ * (this is handled when swap is created (quoted), if you commit right after quoting, you can use skipChecks=true)
1097
+ * @param secret A swap secret to use for the claim transaction, generally only needed if the swap
1098
+ * was recovered from on-chain data, or the pre-image was generated outside the SDK
1099
+ *
1100
+ * @throws {Error} If in invalid state (must be PR_PAID or CLAIM_COMMITED)
1101
+ */
1102
+ async txsCommitAndClaim(skipChecks, secret) {
1103
+ if (this._state === FromBTCLNSwapState.CLAIM_COMMITED)
1104
+ return await this.txsClaim(undefined, secret);
1105
+ if (this._state !== FromBTCLNSwapState.PR_PAID &&
1106
+ (this._state !== FromBTCLNSwapState.QUOTE_SOFT_EXPIRED || this.signatureData == null))
1107
+ throw new Error("Must be in PR_PAID state!");
1108
+ if (this._data == null)
1109
+ throw new Error("Unknown data, wrong state?");
1110
+ const useSecret = secret ?? this.secret;
1111
+ if (useSecret == null)
1112
+ throw new Error("Swap secret pre-image not known and not provided, please provide the swap secret pre-image as second argument");
1113
+ if (!this.isValidSecretPreimage(useSecret))
1114
+ throw new Error("Invalid swap secret pre-image provided!");
1115
+ const initTxs = await this.txsCommit(skipChecks);
1116
+ const claimTxs = await this._contract.txsClaimWithSecret(this._getInitiator(), this._data, useSecret, true, true);
1117
+ return initTxs.concat(claimTxs);
1118
+ }
1119
+ /**
1120
+ * Commits and claims the swap, in a way that the transactions can be signed together by the provided signer and
1121
+ * then automatically sent sequentially by the SDK. To check if the underlying chain supports this flow check
1122
+ * the {@link canCommitAndClaimInOneShot} function.
1123
+ *
1124
+ * @param _signer Signer to sign the transactions with, must be the same as used in the initialization
1125
+ * @param abortSignal Abort signal to stop waiting for the transaction confirmation and abort
1126
+ * @param skipChecks Skip checks like making sure init signature is still valid and swap wasn't commited yet
1127
+ * (this is handled when swap is created (quoted), if you commit right after quoting, you can use skipChecks=true)
1128
+ * @param onBeforeCommitTxSent Optional callback called before the initialization (commit) transaction is
1129
+ * broadcasted
1130
+ * @param onBeforeClaimTxSent Optional callback called before the settlement (claim) transaction is
1131
+ * broadcasted
1132
+ * @param secret A swap secret to use for the claim transaction, generally only needed if the swap
1133
+ * was recovered from on-chain data, or the pre-image was generated outside the SDK
1134
+ *
1135
+ * @throws {Error} If in invalid state (must be PR_PAID or CLAIM_COMMITED)
1136
+ * @throws {Error} If invalid signer is provided that doesn't match the swap data
1137
+ */
1138
+ async commitAndClaim(_signer, abortSignal, skipChecks, onBeforeCommitTxSent, onBeforeClaimTxSent, secret) {
1139
+ const signer = (0, base_1.isAbstractSigner)(_signer) ? _signer : await this.wrapper._chain.wrapSigner(_signer);
1140
+ if (!this.canCommitAndClaimInOneShot())
1141
+ throw new Error("Cannot commitAndClaim in single action, please run commit and claim separately!");
1142
+ this.checkSigner(signer);
1143
+ if (this._state === FromBTCLNSwapState.CLAIM_COMMITED)
1144
+ return [await this.claim(signer, abortSignal, onBeforeClaimTxSent, secret)];
1145
+ let txCount = 0;
1146
+ const txs = await this.txsCommitAndClaim(skipChecks, secret);
1147
+ const result = await this.wrapper._chain.sendAndConfirm(signer, txs, true, abortSignal, undefined, (txId) => {
1148
+ txCount++;
1149
+ if (onBeforeCommitTxSent != null && txCount === 1)
1150
+ onBeforeCommitTxSent(txId);
1151
+ if (onBeforeClaimTxSent != null && txCount === txs.length)
1152
+ onBeforeClaimTxSent(txId);
1153
+ return Promise.resolve();
1154
+ });
1155
+ this._commitTxId = result[0] ?? this._commitTxId;
1156
+ this._claimTxId = result[result.length - 1] ?? this._claimTxId;
1157
+ if (this._state !== FromBTCLNSwapState.CLAIM_CLAIMED) {
1158
+ await this._saveAndEmit(FromBTCLNSwapState.CLAIM_CLAIMED);
1159
+ }
1160
+ return result;
1161
+ }
1162
+ //////////////////////////////
1163
+ //// LNURL
1164
+ /**
1165
+ * Whether this swap uses an LNURL-withdraw link
1166
+ */
1167
+ isLNURL() {
1168
+ return this.lnurl != null;
1169
+ }
1170
+ /**
1171
+ * Gets the used LNURL or `null` if this is not an LNURL-withdraw swap
1172
+ */
1173
+ getLNURL() {
1174
+ return this.lnurl ?? null;
1175
+ }
1176
+ /**
1177
+ * Pay the generated lightning network invoice with an LNURL-withdraw link, this
1178
+ * is useful when you want to display a lightning payment QR code and also want to
1179
+ * allow payments using LNURL-withdraw NFC cards.
1180
+ *
1181
+ * Note that the swap needs to be created **without** an LNURL to begin with for this function
1182
+ * to work. If this swap is already using an LNURL-withdraw link, this function throws.
1183
+ */
1184
+ async settleWithLNURLWithdraw(lnurl) {
1185
+ if (this._state !== FromBTCLNSwapState.PR_CREATED &&
1186
+ (this._state !== FromBTCLNSwapState.QUOTE_SOFT_EXPIRED || this.signatureData != null))
1187
+ throw new Error("Must be in PR_CREATED state!");
1188
+ if (this.lnurl != null)
1189
+ throw new Error("Cannot settle LNURL-withdraw swap with different LNURL");
1190
+ let lnurlParams;
1191
+ if (typeof (lnurl) === "string") {
1192
+ const parsedLNURL = await LNURL_1.LNURL.getLNURL(lnurl);
1193
+ if (parsedLNURL == null || parsedLNURL.tag !== "withdrawRequest")
1194
+ throw new UserError_1.UserError("Invalid LNURL-withdraw to settle the swap");
1195
+ lnurlParams = parsedLNURL;
1196
+ }
1197
+ else {
1198
+ lnurlParams = lnurl.params;
1199
+ }
1200
+ if (this.pr == null || !this.pr.toLowerCase().startsWith("ln"))
1201
+ throw new Error("Input lightning network invoice not available, the swap was probably recovered!");
1202
+ LNURL_1.LNURL.useLNURLWithdraw(lnurlParams, this.pr).catch(e => this.lnurlFailSignal.abort(e));
1203
+ this.lnurl = lnurlParams.url;
1204
+ this.lnurlCallback = lnurlParams.callback;
1205
+ this.lnurlK1 = lnurlParams.k1;
1206
+ this.prPosted = true;
1207
+ await this._saveAndEmit();
1208
+ }
1209
+ //////////////////////////////
1210
+ //// Storage
1211
+ /**
1212
+ * @inheritDoc
1213
+ */
1214
+ serialize() {
1215
+ return {
1216
+ ...super.serialize(),
1217
+ pr: this.pr,
1218
+ secret: this.secret,
1219
+ lnurl: this.lnurl,
1220
+ lnurlK1: this.lnurlK1,
1221
+ lnurlCallback: this.lnurlCallback,
1222
+ prPosted: this.prPosted,
1223
+ initialSwapData: this.initialSwapData.serialize(),
1224
+ usesClaimHashAsId: this.usesClaimHashAsId
1225
+ };
1226
+ }
1227
+ //////////////////////////////
1228
+ //// Swap ticks & sync
1229
+ /**
1230
+ * Checks the swap's state on-chain and compares it to its internal state, updates/changes it according to on-chain
1231
+ * data
1232
+ *
1233
+ * @private
1234
+ */
1235
+ async syncStateFromChain(quoteDefinitelyExpired, commitStatus) {
1236
+ if (this._state === FromBTCLNSwapState.PR_PAID ||
1237
+ (this._state === FromBTCLNSwapState.QUOTE_SOFT_EXPIRED && this.signatureData != null) ||
1238
+ this._state === FromBTCLNSwapState.CLAIM_COMMITED ||
1239
+ this._state === FromBTCLNSwapState.EXPIRED) {
1240
+ //Check for expiry before the getCommitStatus to prevent race conditions
1241
+ let quoteExpired = false;
1242
+ if (this._state === FromBTCLNSwapState.PR_PAID || (this._state === FromBTCLNSwapState.QUOTE_SOFT_EXPIRED && this.signatureData != null)) {
1243
+ quoteExpired = quoteDefinitelyExpired ?? await this._verifyQuoteDefinitelyExpired();
1244
+ }
1245
+ //Check if it's already successfully paid
1246
+ commitStatus ??= await this._contract.getCommitStatus(this._getInitiator(), this._data);
1247
+ if (commitStatus != null && await this._forciblySetOnchainState(commitStatus))
1248
+ return true;
1249
+ //Set the state on expiry here
1250
+ if (this._state === FromBTCLNSwapState.PR_PAID || (this._state === FromBTCLNSwapState.QUOTE_SOFT_EXPIRED && this.signatureData != null)) {
1251
+ if (quoteExpired) {
1252
+ this._state = FromBTCLNSwapState.QUOTE_EXPIRED;
1253
+ return true;
1254
+ }
1255
+ }
1256
+ }
1257
+ return false;
1258
+ }
1259
+ /**
1260
+ * @inheritDoc
1261
+ * @internal
1262
+ */
1263
+ _shouldFetchExpiryStatus() {
1264
+ return this._state === FromBTCLNSwapState.PR_PAID || (this._state === FromBTCLNSwapState.QUOTE_SOFT_EXPIRED && this.signatureData != null);
1265
+ }
1266
+ /**
1267
+ * @inheritDoc
1268
+ * @internal
1269
+ */
1270
+ _shouldFetchOnchainState() {
1271
+ return this._state === FromBTCLNSwapState.PR_PAID || (this._state === FromBTCLNSwapState.QUOTE_SOFT_EXPIRED && this.signatureData != null) ||
1272
+ this._state === FromBTCLNSwapState.CLAIM_COMMITED || this._state === FromBTCLNSwapState.EXPIRED;
1273
+ }
1274
+ /**
1275
+ * Whether an intermediary (LP) should be contacted to get the state of this swap.
1276
+ *
1277
+ * @internal
1278
+ */
1279
+ _shouldCheckIntermediary() {
1280
+ return this._state === FromBTCLNSwapState.PR_CREATED || (this._state === FromBTCLNSwapState.QUOTE_SOFT_EXPIRED && this.signatureData == null);
1281
+ }
1282
+ /**
1283
+ * @inheritDoc
1284
+ * @internal
1285
+ */
1286
+ async _sync(save, quoteDefinitelyExpired, commitStatus, skipLpCheck) {
1287
+ let changed = false;
1288
+ if (this._state === FromBTCLNSwapState.PR_CREATED || (this._state === FromBTCLNSwapState.QUOTE_SOFT_EXPIRED && this.signatureData == null)) {
1289
+ if (this._state != FromBTCLNSwapState.QUOTE_SOFT_EXPIRED && this.getTimeoutTime() < Date.now()) {
1290
+ this._state = FromBTCLNSwapState.QUOTE_SOFT_EXPIRED;
1291
+ changed ||= true;
1292
+ }
1293
+ if (!skipLpCheck)
1294
+ try {
1295
+ const result = await this._checkIntermediaryPaymentReceived(false);
1296
+ if (result !== null)
1297
+ changed ||= true;
1298
+ }
1299
+ catch (e) {
1300
+ this.logger.error("_sync(): Failed to synchronize swap, error: ", e);
1301
+ }
1302
+ if (this._state === FromBTCLNSwapState.PR_CREATED || (this._state === FromBTCLNSwapState.QUOTE_SOFT_EXPIRED && this.signatureData == null)) {
1303
+ if (await this._verifyQuoteDefinitelyExpired()) {
1304
+ this._state = FromBTCLNSwapState.QUOTE_EXPIRED;
1305
+ changed ||= true;
1306
+ }
1307
+ }
1308
+ }
1309
+ if (await this.syncStateFromChain(quoteDefinitelyExpired, commitStatus))
1310
+ changed = true;
1311
+ if (this._state === FromBTCLNSwapState.CLAIM_COMMITED) {
1312
+ const expired = await this._contract.isExpired(this._getInitiator(), this._data);
1313
+ if (expired) {
1314
+ this._state = FromBTCLNSwapState.EXPIRED;
1315
+ changed = true;
1316
+ }
1317
+ }
1318
+ if (save && changed)
1319
+ await this._saveAndEmit();
1320
+ return changed;
1321
+ }
1322
+ /**
1323
+ * @inheritDoc
1324
+ * @internal
1325
+ */
1326
+ async _forciblySetOnchainState(commitStatus) {
1327
+ switch (commitStatus.type) {
1328
+ case base_1.SwapCommitStateType.PAID:
1329
+ if (this._commitTxId == null && commitStatus.getInitTxId != null)
1330
+ this._commitTxId = await commitStatus.getInitTxId();
1331
+ if (this._claimTxId == null)
1332
+ this._claimTxId = await commitStatus.getClaimTxId();
1333
+ if (this.secret == null || this.pr == null)
1334
+ this._setSwapSecret(await commitStatus.getClaimResult());
1335
+ this._state = FromBTCLNSwapState.CLAIM_CLAIMED;
1336
+ return true;
1337
+ case base_1.SwapCommitStateType.NOT_COMMITED:
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) {
1344
+ this._refundTxId = await commitStatus.getRefundTxId();
1345
+ changed = true;
1346
+ }
1347
+ if (this._refundTxId != null) {
1348
+ this._state = FromBTCLNSwapState.FAILED;
1349
+ changed = true;
1350
+ }
1351
+ return changed;
1352
+ case base_1.SwapCommitStateType.EXPIRED:
1353
+ if (this._commitTxId == null && commitStatus.getInitTxId != null)
1354
+ this._commitTxId = await commitStatus.getInitTxId();
1355
+ if (this._refundTxId == null && commitStatus.getRefundTxId)
1356
+ this._refundTxId = await commitStatus.getRefundTxId();
1357
+ this._state = this._refundTxId == null ? FromBTCLNSwapState.QUOTE_EXPIRED : FromBTCLNSwapState.FAILED;
1358
+ return true;
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
+ }
1365
+ if (this._state !== FromBTCLNSwapState.CLAIM_COMMITED && this._state !== FromBTCLNSwapState.EXPIRED) {
1366
+ this._state = FromBTCLNSwapState.CLAIM_COMMITED;
1367
+ save = true;
1368
+ }
1369
+ return save;
1370
+ }
1371
+ return false;
1372
+ }
1373
+ /**
1374
+ * @inheritDoc
1375
+ * @internal
1376
+ */
1377
+ async _tick(save) {
1378
+ switch (this._state) {
1379
+ case FromBTCLNSwapState.PR_CREATED:
1380
+ if (this.getTimeoutTime() < Date.now()) {
1381
+ this._state = FromBTCLNSwapState.QUOTE_SOFT_EXPIRED;
1382
+ if (save)
1383
+ await this._saveAndEmit();
1384
+ return true;
1385
+ }
1386
+ break;
1387
+ case FromBTCLNSwapState.PR_PAID:
1388
+ if (this.expiry < Date.now()) {
1389
+ this._state = FromBTCLNSwapState.QUOTE_SOFT_EXPIRED;
1390
+ if (save)
1391
+ await this._saveAndEmit();
1392
+ return true;
1393
+ }
1394
+ break;
1395
+ case FromBTCLNSwapState.CLAIM_COMMITED:
1396
+ const expired = await this._contract.isExpired(this._getInitiator(), this._data);
1397
+ if (expired) {
1398
+ this._state = FromBTCLNSwapState.EXPIRED;
1399
+ if (save)
1400
+ await this._saveAndEmit();
1401
+ return true;
1402
+ }
1403
+ break;
1404
+ }
1405
+ return false;
1406
+ }
1407
+ /**
1408
+ * Forcibly sets the swap secret pre-image from on-chain data
1409
+ *
1410
+ * @internal
1411
+ */
1412
+ _setSwapSecret(secret) {
1413
+ this.secret = secret;
1414
+ if (this.pr == null) {
1415
+ this.pr = buffer_1.Buffer.from((0, sha2_1.sha256)(buffer_1.Buffer.from(secret, "hex"))).toString("hex");
1416
+ }
1417
+ }
1418
+ }
1419
+ exports.FromBTCLNSwap = FromBTCLNSwap;