@atomiqlabs/sdk 8.9.1 → 8.9.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (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 +765 -770
  120. package/dist/swapper/Swapper.js +1749 -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 +2557 -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,1687 +1,1687 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.SpvFromBTCSwap = exports.isSpvFromBTCSwapInit = exports.SpvFromBTCSwapState = void 0;
4
- const ISwap_1 = require("../ISwap");
5
- const base_1 = require("@atomiqlabs/base");
6
- const SwapType_1 = require("../../enums/SwapType");
7
- const Utils_1 = require("../../utils/Utils");
8
- const BitcoinUtils_1 = require("../../utils/BitcoinUtils");
9
- const btc_signer_1 = require("@scure/btc-signer");
10
- const buffer_1 = require("buffer");
11
- const IBitcoinWallet_1 = require("../../bitcoin/wallet/IBitcoinWallet");
12
- const FeeType_1 = require("../../enums/FeeType");
13
- const PercentagePPM_1 = require("../../types/fees/PercentagePPM");
14
- const TokenAmount_1 = require("../../types/TokenAmount");
15
- const Token_1 = require("../../types/Token");
16
- const Logger_1 = require("../../utils/Logger");
17
- const TimeoutUtils_1 = require("../../utils/TimeoutUtils");
18
- const PriceInfoType_1 = require("../../types/PriceInfoType");
19
- const BitcoinWalletUtils_1 = require("../../utils/BitcoinWalletUtils");
20
- /**
21
- * State enum for SPV vault (UTXO-controlled vault) based swaps
22
- * @category Swaps/Bitcoin → Smart chain
23
- */
24
- var SpvFromBTCSwapState;
25
- (function (SpvFromBTCSwapState) {
26
- /**
27
- * Catastrophic failure has occurred when processing the swap on the smart chain side,
28
- * this implies a bug in the smart contract code or the user and intermediary deliberately
29
- * creating a bitcoin transaction with invalid format unparsable by the smart contract.
30
- */
31
- SpvFromBTCSwapState[SpvFromBTCSwapState["CLOSED"] = -5] = "CLOSED";
32
- /**
33
- * Some of the bitcoin swap transaction inputs were double-spent, this means the swap
34
- * has failed and no BTC was sent
35
- */
36
- SpvFromBTCSwapState[SpvFromBTCSwapState["FAILED"] = -4] = "FAILED";
37
- /**
38
- * The intermediary (LP) declined to co-sign the submitted PSBT, hence the swap failed
39
- */
40
- SpvFromBTCSwapState[SpvFromBTCSwapState["DECLINED"] = -3] = "DECLINED";
41
- /**
42
- * Swap has expired for good and there is no way how it can be executed anymore
43
- */
44
- SpvFromBTCSwapState[SpvFromBTCSwapState["QUOTE_EXPIRED"] = -2] = "QUOTE_EXPIRED";
45
- /**
46
- * A swap is almost expired, and it should be presented to the user as expired, though
47
- * there is still a chance that it will be processed
48
- */
49
- SpvFromBTCSwapState[SpvFromBTCSwapState["QUOTE_SOFT_EXPIRED"] = -1] = "QUOTE_SOFT_EXPIRED";
50
- /**
51
- * Swap was created, use the {@link SpvFromBTCSwap.getFundedPsbt} or {@link SpvFromBTCSwap.getPsbt} functions
52
- * to get the bitcoin swap PSBT that should be signed by the user's wallet and then submitted via the
53
- * {@link SpvFromBTCSwap.submitPsbt} function.
54
- */
55
- SpvFromBTCSwapState[SpvFromBTCSwapState["CREATED"] = 0] = "CREATED";
56
- /**
57
- * Swap bitcoin PSBT was submitted by the client to the SDK
58
- */
59
- SpvFromBTCSwapState[SpvFromBTCSwapState["SIGNED"] = 1] = "SIGNED";
60
- /**
61
- * Swap bitcoin PSBT sent to the intermediary (LP), waiting for the intermediary co-sign
62
- * it and broadcast. You can use the {@link SpvFromBTCSwap.waitTillClaimedOrFronted}
63
- * function to wait till the intermediary broadcasts the transaction and the transaction
64
- * confirms.
65
- */
66
- SpvFromBTCSwapState[SpvFromBTCSwapState["POSTED"] = 2] = "POSTED";
67
- /**
68
- * Intermediary (LP) has co-signed and broadcasted the bitcoin transaction. You can use the
69
- * {@link SpvFromBTCSwap.waitTillClaimedOrFronted} function to wait till the transaction
70
- * confirms.
71
- */
72
- SpvFromBTCSwapState[SpvFromBTCSwapState["BROADCASTED"] = 3] = "BROADCASTED";
73
- /**
74
- * Settlement on the destination smart chain was fronted and funds were already received
75
- * by the user, even before the final settlement.
76
- */
77
- SpvFromBTCSwapState[SpvFromBTCSwapState["FRONTED"] = 4] = "FRONTED";
78
- /**
79
- * Bitcoin transaction confirmed with necessary amount of confirmations, wait for automatic
80
- * settlement by the watchtower with the {@link waitTillClaimedOrFronted} function, or settle manually
81
- * using the {@link FromBTCSwap.claim} or {@link FromBTCSwap.txsClaim} function.
82
- */
83
- SpvFromBTCSwapState[SpvFromBTCSwapState["BTC_TX_CONFIRMED"] = 5] = "BTC_TX_CONFIRMED";
84
- /**
85
- * Swap settled on the smart chain and funds received
86
- */
87
- SpvFromBTCSwapState[SpvFromBTCSwapState["CLAIMED"] = 6] = "CLAIMED";
88
- })(SpvFromBTCSwapState = exports.SpvFromBTCSwapState || (exports.SpvFromBTCSwapState = {}));
89
- const SpvFromBTCSwapStateDescription = {
90
- [SpvFromBTCSwapState.CLOSED]: "Catastrophic failure has occurred when processing the swap on the smart chain side, this implies a bug in the smart contract code or the user and intermediary deliberately creating a bitcoin transaction with invalid format unparsable by the smart contract.",
91
- [SpvFromBTCSwapState.FAILED]: "Some of the bitcoin swap transaction inputs were double-spent, this means the swap has failed and no BTC was sent",
92
- [SpvFromBTCSwapState.DECLINED]: "The intermediary (LP) declined to co-sign the submitted PSBT, hence the swap failed",
93
- [SpvFromBTCSwapState.QUOTE_EXPIRED]: "Swap has expired for good and there is no way how it can be executed anymore",
94
- [SpvFromBTCSwapState.QUOTE_SOFT_EXPIRED]: "A swap is almost expired, and it should be presented to the user as expired, though there is still a chance that it will be processed",
95
- [SpvFromBTCSwapState.CREATED]: "Swap was created, get the bitcoin swap PSBT that should be signed by the user's wallet and then submit it back to the SDK.",
96
- [SpvFromBTCSwapState.SIGNED]: "Swap bitcoin PSBT was submitted by the client to the SDK",
97
- [SpvFromBTCSwapState.POSTED]: "Swap bitcoin PSBT sent to the intermediary (LP), waiting for the intermediary co-sign it and broadcast.",
98
- [SpvFromBTCSwapState.BROADCASTED]: "Intermediary (LP) has co-signed and broadcasted the bitcoin transaction.",
99
- [SpvFromBTCSwapState.FRONTED]: "Settlement on the destination smart chain was fronted and funds were already received by the user, even before the final settlement.",
100
- [SpvFromBTCSwapState.BTC_TX_CONFIRMED]: "Bitcoin transaction confirmed with necessary amount of confirmations, wait for automatic settlement by the watchtower or settle manually.",
101
- [SpvFromBTCSwapState.CLAIMED]: "Swap settled on the smart chain and funds received"
102
- };
103
- function isSpvFromBTCSwapInit(obj) {
104
- return typeof obj === "object" &&
105
- typeof (obj.quoteId) === "string" &&
106
- typeof (obj.recipient) === "string" &&
107
- typeof (obj.vaultOwner) === "string" &&
108
- typeof (obj.vaultId) === "bigint" &&
109
- typeof (obj.vaultRequiredConfirmations) === "number" &&
110
- Array.isArray(obj.vaultTokenMultipliers) && obj.vaultTokenMultipliers.reduce((prev, curr) => prev && typeof (curr) === "bigint", true) &&
111
- typeof (obj.vaultBtcAddress) === "string" &&
112
- typeof (obj.vaultUtxo) === "string" &&
113
- typeof (obj.vaultUtxoValue) === "bigint" &&
114
- typeof (obj.btcDestinationAddress) === "string" &&
115
- typeof (obj.btcAmount) === "bigint" &&
116
- typeof (obj.btcAmountSwap) === "bigint" &&
117
- typeof (obj.btcAmountGas) === "bigint" &&
118
- typeof (obj.minimumBtcFeeRate) === "number" &&
119
- typeof (obj.outputTotalSwap) === "bigint" &&
120
- typeof (obj.outputSwapToken) === "string" &&
121
- typeof (obj.outputTotalGas) === "bigint" &&
122
- typeof (obj.outputGasToken) === "string" &&
123
- typeof (obj.gasSwapFeeBtc) === "bigint" &&
124
- typeof (obj.gasSwapFee) === "bigint" &&
125
- typeof (obj.callerFeeShare) === "bigint" &&
126
- typeof (obj.frontingFeeShare) === "bigint" &&
127
- typeof (obj.executionFeeShare) === "bigint" &&
128
- typeof (obj.genesisSmartChainBlockHeight) === "number" &&
129
- (obj.gasPricingInfo == null || (0, PriceInfoType_1.isPriceInfoType)(obj.gasPricingInfo)) &&
130
- (0, ISwap_1.isISwapInit)(obj);
131
- }
132
- exports.isSpvFromBTCSwapInit = isSpvFromBTCSwapInit;
133
- /**
134
- * New spv vault (UTXO-controlled vault) based swaps for Bitcoin -> Smart chain swaps not requiring
135
- * any initiation on the destination chain, and with the added possibility for the user to receive
136
- * a native token on the destination chain as part of the swap (a "gas drop" feature).
137
- *
138
- * @category Swaps/Bitcoin → Smart chain
139
- */
140
- class SpvFromBTCSwap extends ISwap_1.ISwap {
141
- constructor(wrapper, initOrObject) {
142
- if (isSpvFromBTCSwapInit(initOrObject) && initOrObject.url != null)
143
- initOrObject.url += "/frombtc_spv";
144
- super(wrapper, initOrObject);
145
- this.currentVersion = 2;
146
- this.TYPE = SwapType_1.SwapType.SPV_VAULT_FROM_BTC;
147
- /**
148
- * @internal
149
- */
150
- this.swapStateDescription = SpvFromBTCSwapStateDescription;
151
- /**
152
- * @internal
153
- */
154
- this.swapStateName = (state) => SpvFromBTCSwapState[state];
155
- if (isSpvFromBTCSwapInit(initOrObject)) {
156
- this._state = SpvFromBTCSwapState.CREATED;
157
- this.quoteId = initOrObject.quoteId;
158
- this.recipient = initOrObject.recipient;
159
- this.vaultOwner = initOrObject.vaultOwner;
160
- this.vaultId = initOrObject.vaultId;
161
- this.vaultRequiredConfirmations = initOrObject.vaultRequiredConfirmations;
162
- this.vaultTokenMultipliers = initOrObject.vaultTokenMultipliers;
163
- this.vaultBtcAddress = initOrObject.vaultBtcAddress;
164
- this.vaultUtxo = initOrObject.vaultUtxo;
165
- this.vaultUtxoValue = initOrObject.vaultUtxoValue;
166
- this.btcDestinationAddress = initOrObject.btcDestinationAddress;
167
- this.btcAmount = initOrObject.btcAmount;
168
- this.btcAmountSwap = initOrObject.btcAmountSwap;
169
- this.btcAmountGas = initOrObject.btcAmountGas;
170
- this.minimumBtcFeeRate = initOrObject.minimumBtcFeeRate;
171
- this.outputTotalSwap = initOrObject.outputTotalSwap;
172
- this.outputSwapToken = initOrObject.outputSwapToken;
173
- this.outputTotalGas = initOrObject.outputTotalGas;
174
- this.outputGasToken = initOrObject.outputGasToken;
175
- this.gasSwapFeeBtc = initOrObject.gasSwapFeeBtc;
176
- this.gasSwapFee = initOrObject.gasSwapFee;
177
- this.callerFeeShare = initOrObject.callerFeeShare;
178
- this.frontingFeeShare = initOrObject.frontingFeeShare;
179
- this.executionFeeShare = initOrObject.executionFeeShare;
180
- this._genesisSmartChainBlockHeight = initOrObject.genesisSmartChainBlockHeight;
181
- this.gasPricingInfo = initOrObject.gasPricingInfo;
182
- const vaultAddressType = (0, BitcoinUtils_1.toCoinselectAddressType)((0, BitcoinUtils_1.toOutputScript)(this.wrapper._options.bitcoinNetwork, this.vaultBtcAddress));
183
- if (vaultAddressType !== "p2tr" && vaultAddressType !== "p2wpkh" && vaultAddressType !== "p2wsh")
184
- throw new Error("Vault address type must be of witness type: p2tr, p2wpkh, p2wsh");
185
- }
186
- else {
187
- this.quoteId = initOrObject.quoteId;
188
- this.recipient = initOrObject.recipient;
189
- this.vaultOwner = initOrObject.vaultOwner;
190
- this.vaultId = BigInt(initOrObject.vaultId);
191
- this.vaultRequiredConfirmations = initOrObject.vaultRequiredConfirmations;
192
- this.vaultTokenMultipliers = initOrObject.vaultTokenMultipliers.map((val) => BigInt(val));
193
- this.vaultBtcAddress = initOrObject.vaultBtcAddress;
194
- this.vaultUtxo = initOrObject.vaultUtxo;
195
- this.vaultUtxoValue = BigInt(initOrObject.vaultUtxoValue);
196
- this.btcDestinationAddress = initOrObject.btcDestinationAddress;
197
- this.btcAmount = BigInt(initOrObject.btcAmount);
198
- this.btcAmountSwap = BigInt(initOrObject.btcAmountSwap);
199
- this.btcAmountGas = BigInt(initOrObject.btcAmountGas);
200
- this.minimumBtcFeeRate = initOrObject.minimumBtcFeeRate;
201
- this.outputTotalSwap = BigInt(initOrObject.outputTotalSwap);
202
- this.outputSwapToken = initOrObject.outputSwapToken;
203
- this.outputTotalGas = BigInt(initOrObject.outputTotalGas);
204
- this.outputGasToken = initOrObject.outputGasToken;
205
- this.gasSwapFeeBtc = BigInt(initOrObject.gasSwapFeeBtc);
206
- this.gasSwapFee = BigInt(initOrObject.gasSwapFee);
207
- this.callerFeeShare = BigInt(initOrObject.callerFeeShare);
208
- this.frontingFeeShare = BigInt(initOrObject.frontingFeeShare);
209
- this.executionFeeShare = BigInt(initOrObject.executionFeeShare);
210
- this._genesisSmartChainBlockHeight = initOrObject.genesisSmartChainBlockHeight;
211
- this._senderAddress = initOrObject.senderAddress;
212
- this._claimTxId = initOrObject.claimTxId;
213
- this._frontTxId = initOrObject.frontTxId;
214
- this.gasPricingInfo = (0, PriceInfoType_1.deserializePriceInfoType)(initOrObject.gasPricingInfo);
215
- this.btcTxConfirmedAt = initOrObject.btcTxConfirmedAt;
216
- this.posted = initOrObject.posted;
217
- if (initOrObject.data != null)
218
- this._data = new (this.wrapper._spvWithdrawalDataDeserializer(this._contractVersion))(initOrObject.data);
219
- }
220
- this.tryCalculateSwapFee();
221
- this.logger = (0, Logger_1.getLogger)("SPVFromBTC(" + this.getId() + "): ");
222
- this._contract = wrapper._contract(this._contractVersion);
223
- }
224
- /**
225
- * @inheritDoc
226
- * @internal
227
- */
228
- upgradeVersion() {
229
- if (this.version === 1) {
230
- this.posted = this.initiated && this._data != null;
231
- this.version = 2;
232
- }
233
- }
234
- /**
235
- * @inheritDoc
236
- * @internal
237
- */
238
- tryCalculateSwapFee() {
239
- if (this.swapFeeBtc == null && this.swapFee != null) {
240
- this.swapFeeBtc = this.swapFee * this.btcAmountSwap / this.getOutputWithoutFee().rawAmount;
241
- }
242
- if (this.pricingInfo != null && this.pricingInfo.swapPriceUSatPerToken == null) {
243
- const priceUsdPerBtc = this.pricingInfo.realPriceUsdPerBitcoin;
244
- this.pricingInfo = this.wrapper._prices.recomputePriceInfoReceive(this.chainIdentifier, this.btcAmountSwap, this.pricingInfo.satsBaseFee, this.pricingInfo.feePPM, this.getOutputWithoutFee().rawAmount, this.outputSwapToken);
245
- this.pricingInfo.realPriceUsdPerBitcoin = priceUsdPerBtc;
246
- }
247
- }
248
- //////////////////////////////
249
- //// Pricing
250
- /**
251
- * @inheritDoc
252
- */
253
- async refreshPriceData() {
254
- if (this.pricingInfo == null)
255
- return;
256
- const usdPricePerBtc = this.pricingInfo.realPriceUsdPerBitcoin;
257
- this.pricingInfo = await this.wrapper._prices.isValidAmountReceive(this.chainIdentifier, this.btcAmountSwap, this.pricingInfo.satsBaseFee, this.pricingInfo.feePPM, this.getOutputWithoutFee().rawAmount, this.outputSwapToken, undefined, undefined, this.swapFeeBtc);
258
- this.pricingInfo.realPriceUsdPerBitcoin = usdPricePerBtc;
259
- }
260
- //////////////////////////////
261
- //// Getters & utils
262
- /**
263
- * @inheritDoc
264
- * @internal
265
- */
266
- _getInitiator() {
267
- return this.recipient;
268
- }
269
- /**
270
- * @inheritDoc
271
- * @internal
272
- */
273
- _getEscrowHash() {
274
- return this._data?.btcTx?.txid ?? null;
275
- }
276
- /**
277
- * @inheritDoc
278
- */
279
- getId() {
280
- return this.quoteId + this._randomNonce;
281
- }
282
- /**
283
- * @inheritDoc
284
- */
285
- getQuoteExpiry() {
286
- return this.expiry - 20 * 1000;
287
- }
288
- /**
289
- * @inheritDoc
290
- * @internal
291
- */
292
- _verifyQuoteDefinitelyExpired() {
293
- return Promise.resolve(this.expiry < Date.now());
294
- }
295
- /**
296
- * @inheritDoc
297
- * @internal
298
- */
299
- _verifyQuoteValid() {
300
- return Promise.resolve(this.expiry > Date.now() && (this._state === SpvFromBTCSwapState.CREATED || this._state === SpvFromBTCSwapState.QUOTE_SOFT_EXPIRED));
301
- }
302
- /**
303
- * @inheritDoc
304
- */
305
- getOutputAddress() {
306
- return this.recipient;
307
- }
308
- /**
309
- * @inheritDoc
310
- */
311
- getOutputTxId() {
312
- return this._frontTxId ?? this._claimTxId ?? null;
313
- }
314
- /**
315
- * @inheritDoc
316
- */
317
- getInputAddress() {
318
- return this._senderAddress ?? null;
319
- }
320
- /**
321
- * @inheritDoc
322
- */
323
- getInputTxId() {
324
- return this._data?.btcTx?.txid ?? null;
325
- }
326
- /**
327
- * @inheritDoc
328
- */
329
- requiresAction() {
330
- return this._state === SpvFromBTCSwapState.BTC_TX_CONFIRMED;
331
- }
332
- /**
333
- * @inheritDoc
334
- */
335
- isFinished() {
336
- return this.isSuccessful() || this.isFailed() || this.isQuoteExpired();
337
- }
338
- /**
339
- * @inheritDoc
340
- */
341
- isClaimable() {
342
- return this._state === SpvFromBTCSwapState.BTC_TX_CONFIRMED;
343
- }
344
- /**
345
- * @inheritDoc
346
- */
347
- isSuccessful() {
348
- return this._state === SpvFromBTCSwapState.FRONTED || this._state === SpvFromBTCSwapState.CLAIMED;
349
- }
350
- /**
351
- * @inheritDoc
352
- */
353
- isFailed() {
354
- return this._state === SpvFromBTCSwapState.FAILED || this._state === SpvFromBTCSwapState.DECLINED || this._state === SpvFromBTCSwapState.CLOSED;
355
- }
356
- /**
357
- * @inheritDoc
358
- */
359
- isInProgress() {
360
- return this._state === SpvFromBTCSwapState.POSTED ||
361
- this._state === SpvFromBTCSwapState.BROADCASTED ||
362
- this._state === SpvFromBTCSwapState.BTC_TX_CONFIRMED;
363
- }
364
- /**
365
- * @inheritDoc
366
- */
367
- isQuoteExpired() {
368
- return this._state === SpvFromBTCSwapState.QUOTE_EXPIRED;
369
- }
370
- /**
371
- * @inheritDoc
372
- */
373
- isQuoteSoftExpired() {
374
- return this._state === SpvFromBTCSwapState.QUOTE_EXPIRED || this._state === SpvFromBTCSwapState.QUOTE_SOFT_EXPIRED;
375
- }
376
- /**
377
- * Returns the data about used spv vault (UTXO-controlled vault) to perform the swap
378
- */
379
- getSpvVaultData() {
380
- return {
381
- owner: this.vaultOwner,
382
- vaultId: this.vaultId,
383
- utxo: this.vaultUtxo
384
- };
385
- }
386
- //////////////////////////////
387
- //// Amounts & fees
388
- /**
389
- * Returns the input BTC amount in sats without any fees
390
- *
391
- * @internal
392
- */
393
- getInputSwapAmountWithoutFee() {
394
- return (this.btcAmountSwap - this.swapFeeBtc) * 100000n / (100000n + this.callerFeeShare + this.frontingFeeShare + this.executionFeeShare);
395
- }
396
- /**
397
- * Returns the input gas BTC amount in sats without any fees
398
- *
399
- * @internal
400
- */
401
- getInputGasAmountWithoutFee() {
402
- return (this.btcAmountGas - this.gasSwapFeeBtc) * 100000n / (100000n + this.callerFeeShare + this.frontingFeeShare);
403
- }
404
- /**
405
- * Returns to total input BTC amount in sats without any fees (this is BTC amount for the swap + BTC amount
406
- * for the gas drop).
407
- *
408
- * @internal
409
- */
410
- getInputAmountWithoutFee() {
411
- return this.getInputSwapAmountWithoutFee() + this.getInputGasAmountWithoutFee();
412
- }
413
- /**
414
- * Returns the swap output amount without any fees, this value is therefore always higher than
415
- * the actual received output.
416
- *
417
- * @internal
418
- */
419
- getOutputWithoutFee() {
420
- return (0, TokenAmount_1.toTokenAmount)((this.outputTotalSwap * (100000n + this.callerFeeShare + this.frontingFeeShare + this.executionFeeShare) / 100000n) + (this.swapFee ?? 0n), this.wrapper._tokens[this.outputSwapToken], this.wrapper._prices, this.pricingInfo);
421
- }
422
- /**
423
- * Returns the swap fee charged by the intermediary (LP) on this swap
424
- *
425
- * @internal
426
- */
427
- getSwapFee() {
428
- if (this.pricingInfo == null)
429
- throw new Error("No pricing info known, cannot estimate fee!");
430
- const outputToken = this.wrapper._tokens[this.outputSwapToken];
431
- const gasSwapFeeInOutputToken = this.gasSwapFeeBtc
432
- * (10n ** BigInt(outputToken.decimals))
433
- * 1000000n
434
- / this.pricingInfo.swapPriceUSatPerToken;
435
- const feeWithoutBaseFee = this.swapFeeBtc - this.pricingInfo.satsBaseFee;
436
- const swapFeePPM = feeWithoutBaseFee * 1000000n / (this.btcAmount - this.swapFeeBtc - this.gasSwapFeeBtc);
437
- const amountInSrcToken = (0, TokenAmount_1.toTokenAmount)(this.swapFeeBtc + this.gasSwapFeeBtc, Token_1.BitcoinTokens.BTC, this.wrapper._prices, this.pricingInfo);
438
- return {
439
- amountInSrcToken,
440
- amountInDstToken: (0, TokenAmount_1.toTokenAmount)(this.swapFee + gasSwapFeeInOutputToken, outputToken, this.wrapper._prices, this.pricingInfo),
441
- currentUsdValue: amountInSrcToken.currentUsdValue,
442
- usdValue: amountInSrcToken.usdValue,
443
- pastUsdValue: amountInSrcToken.pastUsdValue,
444
- composition: {
445
- base: (0, TokenAmount_1.toTokenAmount)(this.pricingInfo.satsBaseFee, Token_1.BitcoinTokens.BTC, this.wrapper._prices, this.pricingInfo),
446
- percentage: (0, PercentagePPM_1.ppmToPercentage)(swapFeePPM)
447
- }
448
- };
449
- }
450
- /**
451
- * Returns the fee to be paid to watchtowers on the destination chain to automatically
452
- * process and settle this swap without requiring any user interaction
453
- *
454
- * @internal
455
- */
456
- getWatchtowerFee() {
457
- if (this.pricingInfo == null)
458
- throw new Error("No pricing info known, cannot estimate fee!");
459
- const totalFeeShare = this.callerFeeShare + this.frontingFeeShare;
460
- const outputToken = this.wrapper._tokens[this.outputSwapToken];
461
- const watchtowerFeeInOutputToken = this.getInputGasAmountWithoutFee() * totalFeeShare
462
- * (10n ** BigInt(outputToken.decimals))
463
- * 1000000n
464
- / this.pricingInfo.swapPriceUSatPerToken
465
- / 100000n;
466
- const feeBtc = this.getInputAmountWithoutFee() * (totalFeeShare + this.executionFeeShare) / 100000n;
467
- const amountInSrcToken = (0, TokenAmount_1.toTokenAmount)(feeBtc, Token_1.BitcoinTokens.BTC, this.wrapper._prices, this.pricingInfo);
468
- return {
469
- amountInSrcToken,
470
- amountInDstToken: (0, TokenAmount_1.toTokenAmount)((this.outputTotalSwap * (totalFeeShare + this.executionFeeShare) / 100000n) + watchtowerFeeInOutputToken, outputToken, this.wrapper._prices, this.pricingInfo),
471
- currentUsdValue: amountInSrcToken.currentUsdValue,
472
- usdValue: amountInSrcToken.usdValue,
473
- pastUsdValue: amountInSrcToken.pastUsdValue
474
- };
475
- }
476
- /**
477
- * @inheritDoc
478
- */
479
- getFee() {
480
- const swapFee = this.getSwapFee();
481
- const watchtowerFee = this.getWatchtowerFee();
482
- const amountInSrcToken = (0, TokenAmount_1.toTokenAmount)(swapFee.amountInSrcToken.rawAmount + watchtowerFee.amountInSrcToken.rawAmount, Token_1.BitcoinTokens.BTC, this.wrapper._prices, this.pricingInfo);
483
- return {
484
- amountInSrcToken,
485
- amountInDstToken: (0, TokenAmount_1.toTokenAmount)(swapFee.amountInDstToken.rawAmount + watchtowerFee.amountInDstToken.rawAmount, this.wrapper._tokens[this.outputSwapToken], this.wrapper._prices, this.pricingInfo),
486
- currentUsdValue: amountInSrcToken.currentUsdValue,
487
- usdValue: amountInSrcToken.usdValue,
488
- pastUsdValue: amountInSrcToken.pastUsdValue
489
- };
490
- }
491
- /**
492
- * @inheritDoc
493
- */
494
- getFeeBreakdown() {
495
- return [
496
- {
497
- type: FeeType_1.FeeType.SWAP,
498
- fee: this.getSwapFee()
499
- },
500
- {
501
- type: FeeType_1.FeeType.NETWORK_OUTPUT,
502
- fee: this.getWatchtowerFee()
503
- }
504
- ];
505
- }
506
- /**
507
- * @inheritDoc
508
- */
509
- getOutputToken() {
510
- return this.wrapper._tokens[this.outputSwapToken];
511
- }
512
- /**
513
- * @inheritDoc
514
- */
515
- getOutput() {
516
- return (0, TokenAmount_1.toTokenAmount)(this.outputTotalSwap, this.wrapper._tokens[this.outputSwapToken], this.wrapper._prices, this.pricingInfo);
517
- }
518
- /**
519
- * @inheritDoc
520
- */
521
- getGasDropOutput() {
522
- return (0, TokenAmount_1.toTokenAmount)(this.outputTotalGas, this.wrapper._tokens[this.outputGasToken], this.wrapper._prices, this.gasPricingInfo);
523
- }
524
- /**
525
- * @inheritDoc
526
- */
527
- getInputWithoutFee() {
528
- return (0, TokenAmount_1.toTokenAmount)(this.getInputAmountWithoutFee(), Token_1.BitcoinTokens.BTC, this.wrapper._prices, this.pricingInfo);
529
- }
530
- /**
531
- * @inheritDoc
532
- */
533
- getInputToken() {
534
- return Token_1.BitcoinTokens.BTC;
535
- }
536
- /**
537
- * @inheritDoc
538
- */
539
- getInput() {
540
- return (0, TokenAmount_1.toTokenAmount)(this.btcAmount, Token_1.BitcoinTokens.BTC, this.wrapper._prices, this.pricingInfo);
541
- }
542
- //////////////////////////////
543
- //// Bitcoin tx
544
- /**
545
- * @inheritDoc
546
- */
547
- getRequiredConfirmationsCount() {
548
- return this.vaultRequiredConfirmations;
549
- }
550
- /**
551
- * Returns raw transaction details that can be used to manually create a swap PSBT. It is better to use
552
- * the {@link getPsbt} or {@link getFundedPsbt} function retrieve an already prepared PSBT.
553
- */
554
- async getTransactionDetails() {
555
- const [txId, voutStr] = this.vaultUtxo.split(":");
556
- const vaultScript = (0, BitcoinUtils_1.toOutputScript)(this.wrapper._options.bitcoinNetwork, this.vaultBtcAddress);
557
- const out2script = (0, BitcoinUtils_1.toOutputScript)(this.wrapper._options.bitcoinNetwork, this.btcDestinationAddress);
558
- const opReturnData = this._contract.toOpReturnData(this.recipient, [
559
- this.outputTotalSwap / this.vaultTokenMultipliers[0],
560
- this.outputTotalGas / this.vaultTokenMultipliers[1]
561
- ]);
562
- const out1script = buffer_1.Buffer.concat([
563
- opReturnData.length > 75 ? buffer_1.Buffer.from([0x6a, 0x4c, opReturnData.length]) : buffer_1.Buffer.from([0x6a, opReturnData.length]),
564
- opReturnData
565
- ]);
566
- if (this.callerFeeShare < 0n || this.callerFeeShare > 0xfffffn)
567
- throw new Error("Caller fee out of bounds!");
568
- if (this.frontingFeeShare < 0n || this.frontingFeeShare > 0xfffffn)
569
- throw new Error("Fronting fee out of bounds!");
570
- if (this.executionFeeShare < 0n || this.executionFeeShare > 0xfffffn)
571
- throw new Error("Execution fee out of bounds!");
572
- const nSequence0 = 0x80000000n | (this.callerFeeShare & 0xfffffn) | (this.frontingFeeShare & 1047552n) << 10n;
573
- const nSequence1 = 0x80000000n | (this.executionFeeShare & 0xfffffn) | (this.frontingFeeShare & 1023n) << 20n;
574
- return {
575
- in0txid: txId,
576
- in0vout: parseInt(voutStr),
577
- in0sequence: Number(nSequence0),
578
- vaultAmount: this.vaultUtxoValue,
579
- vaultScript,
580
- in1sequence: Number(nSequence1),
581
- out1script,
582
- out2amount: this.btcAmount,
583
- out2script,
584
- locktime: 500000000 + Math.floor(Math.random() * 1000000000) //Use this as a random salt to make the btc txId unique!
585
- };
586
- }
587
- /**
588
- * Returns the raw PSBT (not funded), the wallet should fund the PSBT (add its inputs) and importantly **set the nSequence field of the
589
- * 2nd input** (input 1 - indexing from 0) to the value returned in `in1sequence`, sign the PSBT and then pass
590
- * it back to the swap with {@link submitPsbt} function. The transaction should use at least the returned `feeRate`
591
- * sats/vB as the transaction fee.
592
- */
593
- async getPsbt() {
594
- const res = await this.getTransactionDetails();
595
- const psbt = new btc_signer_1.Transaction({
596
- allowUnknownOutputs: true,
597
- allowLegacyWitnessUtxo: true,
598
- lockTime: res.locktime
599
- });
600
- psbt.addInput({
601
- txid: res.in0txid,
602
- index: res.in0vout,
603
- witnessUtxo: {
604
- amount: res.vaultAmount,
605
- script: res.vaultScript
606
- },
607
- sequence: res.in0sequence
608
- });
609
- psbt.addOutput({
610
- amount: res.vaultAmount,
611
- script: res.vaultScript
612
- });
613
- psbt.addOutput({
614
- amount: 0n,
615
- script: res.out1script
616
- });
617
- psbt.addOutput({
618
- amount: res.out2amount,
619
- script: res.out2script
620
- });
621
- const serializedPsbt = buffer_1.Buffer.from(psbt.toPSBT());
622
- return {
623
- psbt,
624
- psbtHex: serializedPsbt.toString("hex"),
625
- psbtBase64: serializedPsbt.toString("base64"),
626
- in1sequence: res.in1sequence,
627
- feeRate: this.minimumBtcFeeRate
628
- };
629
- }
630
- /**
631
- * Returns the PSBT that is already funded with wallet's UTXOs (runs a coin-selection algorithm to choose UTXOs to use),
632
- * also returns inputs indices that need to be signed by the wallet before submitting the PSBT back to the SDK with
633
- * {@link submitPsbt}
634
- *
635
- * @remarks
636
- * Note that when passing the `feeRate` argument, the fee must be at least {@link minimumBtcFeeRate} sats/vB.
637
- *
638
- * @param _bitcoinWallet Sender's bitcoin wallet
639
- * @param feeRate Optional fee rate in sats/vB for the transaction
640
- * @param additionalOutputs additional outputs to add to the PSBT - can be used to collect fees from users
641
- * @param utxos Pre-fetched list of UTXOs to spend from
642
- * @param spendFully Instructs the wallet to spend all the passed UTXOs in the transaction without creating any
643
- * change output, if the `feeRate` is passed, it will also enforce that the feeRate in sats/vB for the resulting
644
- * transaction is not more than 50% and 10 sats/vB larger (considering also the CPFP adjustments)
645
- */
646
- async getFundedPsbt(_bitcoinWallet, feeRate, additionalOutputs, utxos, spendFully) {
647
- const bitcoinWallet = (0, BitcoinWalletUtils_1.toBitcoinWallet)(_bitcoinWallet, this.wrapper._btcRpc, this.wrapper._options.bitcoinNetwork);
648
- if (feeRate != null) {
649
- if (feeRate < this.minimumBtcFeeRate)
650
- throw new Error("Bitcoin tx fee needs to be at least " + this.minimumBtcFeeRate + " sats/vB");
651
- }
652
- else {
653
- feeRate = Math.max(this.minimumBtcFeeRate, await bitcoinWallet.getFeeRate());
654
- }
655
- let { psbt, in1sequence } = await this.getPsbt();
656
- if (additionalOutputs != null)
657
- additionalOutputs.forEach(output => {
658
- psbt.addOutput({
659
- amount: output.amount,
660
- script: output.outputScript ?? (0, BitcoinUtils_1.toOutputScript)(this.wrapper._options.bitcoinNetwork, output.address)
661
- });
662
- });
663
- psbt = await bitcoinWallet.fundPsbt(psbt, feeRate, utxos, spendFully);
664
- psbt.updateInput(1, { sequence: in1sequence });
665
- //Sign every input except the first one
666
- const signInputs = [];
667
- for (let i = 1; i < psbt.inputsLength; i++) {
668
- signInputs.push(i);
669
- }
670
- const serializedPsbt = buffer_1.Buffer.from(psbt.toPSBT());
671
- return {
672
- psbt,
673
- psbtHex: serializedPsbt.toString("hex"),
674
- psbtBase64: serializedPsbt.toString("base64"),
675
- signInputs,
676
- feeRate
677
- };
678
- }
679
- /**
680
- * @inheritDoc
681
- */
682
- async submitPsbt(_psbt) {
683
- const psbt = (0, BitcoinUtils_1.parsePsbtTransaction)(_psbt);
684
- //Ensure not expired
685
- if (this.expiry < Date.now()) {
686
- throw new Error("Quote expired!");
687
- }
688
- //Ensure valid state
689
- if (this._state !== SpvFromBTCSwapState.QUOTE_SOFT_EXPIRED && this._state !== SpvFromBTCSwapState.CREATED) {
690
- throw new Error("Invalid swap state!");
691
- }
692
- if (this.url == null)
693
- throw new Error("LP URL not known, cannot submit PSBT!");
694
- //Ensure all inputs except the 1st are finalized
695
- for (let i = 1; i < psbt.inputsLength; i++) {
696
- if ((0, btc_signer_1.getInputType)(psbt.getInput(i)).txType === "legacy")
697
- throw new Error("Legacy (non-segwit) inputs are not allowed in the transaction!");
698
- psbt.finalizeIdx(i);
699
- }
700
- const btcTx = await this.wrapper._btcRpc.parseTransaction(buffer_1.Buffer.from(psbt.toBytes(true)).toString("hex"));
701
- const data = await this._contract.getWithdrawalData(btcTx);
702
- this.logger.debug("submitPsbt(): parsed withdrawal data: ", data);
703
- //Verify correct withdrawal data
704
- if (!data.isRecipient(this.recipient) ||
705
- data.rawAmounts[0] * this.vaultTokenMultipliers[0] !== this.outputTotalSwap ||
706
- (data.rawAmounts[1] ?? 0n) * this.vaultTokenMultipliers[1] !== this.outputTotalGas ||
707
- data.callerFeeRate !== this.callerFeeShare ||
708
- data.frontingFeeRate !== this.frontingFeeShare ||
709
- data.executionFeeRate !== this.executionFeeShare ||
710
- data.getSpentVaultUtxo() !== this.vaultUtxo ||
711
- BigInt(data.getNewVaultBtcAmount()) !== this.vaultUtxoValue ||
712
- !data.getNewVaultScript().equals((0, BitcoinUtils_1.toOutputScript)(this.wrapper._options.bitcoinNetwork, this.vaultBtcAddress)) ||
713
- data.getExecutionData() != null) {
714
- throw new Error("Invalid withdrawal tx data submitted!");
715
- }
716
- //Verify correct LP output
717
- const lpOutput = psbt.getOutput(2);
718
- if (lpOutput.script == null ||
719
- lpOutput.amount !== this.btcAmount ||
720
- !(0, BitcoinUtils_1.toOutputScript)(this.wrapper._options.bitcoinNetwork, this.btcDestinationAddress).equals(buffer_1.Buffer.from(lpOutput.script))) {
721
- throw new Error("Invalid LP bitcoin output in transaction!");
722
- }
723
- //Verify vault utxo not spent yet
724
- if (await this.wrapper._btcRpc.isSpent(this.vaultUtxo)) {
725
- throw new Error("Vault UTXO already spent, please create new swap!");
726
- }
727
- //Verify tx is parsable by the contract
728
- try {
729
- await this._contract.checkWithdrawalTx(data);
730
- }
731
- catch (e) {
732
- throw new Error("Transaction not parsable by the contract: " + (e.message ?? e.toString()));
733
- }
734
- //Ensure still not expired
735
- if (this.expiry < Date.now()) {
736
- throw new Error("Quote expired!");
737
- }
738
- this._data = data;
739
- this.initiated = true;
740
- this.posted = true;
741
- await this._saveAndEmit(SpvFromBTCSwapState.SIGNED);
742
- try {
743
- await this.wrapper._lpApi.initSpvFromBTC(this.chainIdentifier, this.url, {
744
- quoteId: this.quoteId,
745
- psbtHex: buffer_1.Buffer.from(psbt.toPSBT(0)).toString("hex")
746
- });
747
- await this._saveAndEmit(SpvFromBTCSwapState.POSTED);
748
- }
749
- catch (e) {
750
- await this._saveAndEmit(SpvFromBTCSwapState.DECLINED);
751
- throw e;
752
- }
753
- return this._data.getTxId();
754
- }
755
- /**
756
- * @inheritDoc
757
- */
758
- async estimateBitcoinFee(_bitcoinWallet, feeRate) {
759
- const bitcoinWallet = (0, BitcoinWalletUtils_1.toBitcoinWallet)(_bitcoinWallet, this.wrapper._btcRpc, this.wrapper._options.bitcoinNetwork);
760
- const txFee = await bitcoinWallet.getFundedPsbtFee((await this.getPsbt()).psbt, feeRate);
761
- if (txFee == null)
762
- return null;
763
- return (0, TokenAmount_1.toTokenAmount)(BigInt(txFee), Token_1.BitcoinTokens.BTC, this.wrapper._prices, this.pricingInfo);
764
- }
765
- /**
766
- * @inheritDoc
767
- */
768
- async sendBitcoinTransaction(wallet, feeRate, utxos, spendFully) {
769
- const { psbt, psbtBase64, psbtHex, signInputs } = await this.getFundedPsbt(wallet, feeRate, undefined, utxos, spendFully);
770
- let signedPsbt;
771
- if ((0, IBitcoinWallet_1.isIBitcoinWallet)(wallet)) {
772
- signedPsbt = await wallet.signPsbt(psbt, signInputs);
773
- }
774
- else {
775
- signedPsbt = await wallet.signPsbt({
776
- psbt, psbtHex, psbtBase64
777
- }, signInputs);
778
- }
779
- return await this.submitPsbt(signedPsbt);
780
- }
781
- /**
782
- * Executes the swap with the provided bitcoin wallet
783
- *
784
- * @param wallet Bitcoin wallet to use to sign the bitcoin transaction
785
- * @param callbacks Callbacks to track the progress of the swap
786
- * @param options Optional options for the swap like feeRate, AbortSignal, and timeouts/intervals
787
- *
788
- * @returns {boolean} Whether a swap was settled automatically by swap watchtowers or requires manual claim by the
789
- * user, in case `false` is returned the user should call the {@link claim} function to settle the swap on the
790
- * destination manually
791
- */
792
- async execute(wallet, callbacks, options) {
793
- if (this._state === SpvFromBTCSwapState.CLOSED)
794
- throw new Error("Swap encountered a catastrophic failure!");
795
- if (this._state === SpvFromBTCSwapState.FAILED)
796
- throw new Error("Swap failed!");
797
- if (this._state === SpvFromBTCSwapState.DECLINED)
798
- throw new Error("Swap execution already declined by the LP!");
799
- if (this._state === SpvFromBTCSwapState.QUOTE_EXPIRED)
800
- throw new Error("Swap quote expired!");
801
- if (this._state === SpvFromBTCSwapState.CLAIMED || this._state === SpvFromBTCSwapState.FRONTED)
802
- throw new Error("Swap already settled or fronted!");
803
- if (this._state === SpvFromBTCSwapState.CREATED) {
804
- const txId = await this.sendBitcoinTransaction(wallet, options?.feeRate, options?.utxos, options?.spendFully);
805
- if (callbacks?.onSourceTransactionSent != null)
806
- callbacks.onSourceTransactionSent(txId);
807
- }
808
- if (this._state === SpvFromBTCSwapState.POSTED || this._state === SpvFromBTCSwapState.BROADCASTED) {
809
- const txId = await this.waitForBitcoinTransaction(callbacks?.onSourceTransactionConfirmationStatus, options?.btcTxCheckIntervalSeconds, options?.abortSignal);
810
- if (callbacks?.onSourceTransactionConfirmed != null)
811
- callbacks.onSourceTransactionConfirmed(txId);
812
- }
813
- // @ts-ignore
814
- if (this._state === SpvFromBTCSwapState.CLAIMED || this._state === SpvFromBTCSwapState.FRONTED)
815
- return true;
816
- if (this._state === SpvFromBTCSwapState.BTC_TX_CONFIRMED) {
817
- const success = await this.waitTillClaimedOrFronted(options?.maxWaitTillAutomaticSettlementSeconds ?? 60, options?.abortSignal);
818
- if (success && callbacks?.onSwapSettled != null)
819
- callbacks.onSwapSettled(this.getOutputTxId());
820
- return success;
821
- }
822
- throw new Error("Unexpected state reached!");
823
- }
824
- /**
825
- * @internal
826
- */
827
- async _getExecutionStatus(options) {
828
- const state = this._state;
829
- const now = Date.now();
830
- let confirmations;
831
- let bitcoinPaymentStatus = "inactive";
832
- let destinationSettlementStatus = "inactive";
833
- let buildCurrentAction = async () => undefined;
834
- switch (state) {
835
- case SpvFromBTCSwapState.QUOTE_EXPIRED:
836
- case SpvFromBTCSwapState.DECLINED:
837
- case SpvFromBTCSwapState.FAILED:
838
- bitcoinPaymentStatus = "expired";
839
- break;
840
- case SpvFromBTCSwapState.CREATED: {
841
- const quoteValid = await this._verifyQuoteValid();
842
- bitcoinPaymentStatus = quoteValid ? "awaiting" : "soft_expired";
843
- if (quoteValid) {
844
- buildCurrentAction = this._buildDepositPsbtAction.bind(this);
845
- }
846
- break;
847
- }
848
- case SpvFromBTCSwapState.QUOTE_SOFT_EXPIRED:
849
- case SpvFromBTCSwapState.SIGNED:
850
- case SpvFromBTCSwapState.POSTED:
851
- case SpvFromBTCSwapState.BROADCASTED:
852
- case SpvFromBTCSwapState.FRONTED: {
853
- const bitcoinPayment = await this.getBitcoinPayment();
854
- let bitcoinConfirmationDelay = -1;
855
- let knownBitcoinPaymentStatus;
856
- if (bitcoinPayment != null) {
857
- if (bitcoinPayment.confirmations >= bitcoinPayment.targetConfirmations) {
858
- knownBitcoinPaymentStatus = "confirmed";
859
- }
860
- else {
861
- const result = await this.wrapper._btcRpc.getConfirmationDelay(bitcoinPayment.btcTx, bitcoinPayment.targetConfirmations);
862
- confirmations = {
863
- current: bitcoinPayment.confirmations,
864
- target: bitcoinPayment.targetConfirmations,
865
- etaSeconds: result ?? -1
866
- };
867
- knownBitcoinPaymentStatus = "received";
868
- bitcoinConfirmationDelay = result ?? -1;
869
- }
870
- }
871
- if (state === SpvFromBTCSwapState.QUOTE_SOFT_EXPIRED)
872
- bitcoinPaymentStatus = knownBitcoinPaymentStatus ?? "soft_expired";
873
- if (state === SpvFromBTCSwapState.POSTED || state === SpvFromBTCSwapState.SIGNED)
874
- bitcoinPaymentStatus = knownBitcoinPaymentStatus ?? "awaiting";
875
- if (state === SpvFromBTCSwapState.BROADCASTED)
876
- bitcoinPaymentStatus = knownBitcoinPaymentStatus ?? "received";
877
- destinationSettlementStatus = "inactive";
878
- if (state === SpvFromBTCSwapState.FRONTED) {
879
- bitcoinPaymentStatus = knownBitcoinPaymentStatus ?? "received";
880
- destinationSettlementStatus = "settled";
881
- }
882
- if (state === SpvFromBTCSwapState.SIGNED ||
883
- state === SpvFromBTCSwapState.POSTED ||
884
- state === SpvFromBTCSwapState.BROADCASTED) {
885
- buildCurrentAction = this._buildWaitBitcoinConfirmationsAction.bind(this, bitcoinConfirmationDelay);
886
- }
887
- break;
888
- }
889
- case SpvFromBTCSwapState.BTC_TX_CONFIRMED:
890
- bitcoinPaymentStatus = "confirmed";
891
- if (this.btcTxConfirmedAt == null ||
892
- options?.maxWaitTillAutomaticSettlementSeconds === 0 ||
893
- (now - this.btcTxConfirmedAt) > (options?.maxWaitTillAutomaticSettlementSeconds ?? 60) * 1000) {
894
- destinationSettlementStatus = "awaiting_manual";
895
- buildCurrentAction = this._buildClaimSmartChainTxAction.bind(this);
896
- }
897
- else {
898
- destinationSettlementStatus = "awaiting_automatic";
899
- buildCurrentAction = this._buildWaitSettlementAction.bind(this, options?.maxWaitTillAutomaticSettlementSeconds);
900
- }
901
- break;
902
- case SpvFromBTCSwapState.CLAIMED:
903
- bitcoinPaymentStatus = "confirmed";
904
- destinationSettlementStatus = "settled";
905
- break;
906
- case SpvFromBTCSwapState.CLOSED:
907
- bitcoinPaymentStatus = "confirmed";
908
- destinationSettlementStatus = "expired";
909
- break;
910
- }
911
- if (bitcoinPaymentStatus === "confirmed") {
912
- confirmations = {
913
- current: this.getRequiredConfirmationsCount(),
914
- target: this.getRequiredConfirmationsCount(),
915
- etaSeconds: 0
916
- };
917
- }
918
- return {
919
- steps: [
920
- {
921
- type: "Payment",
922
- side: "source",
923
- chain: "BITCOIN",
924
- title: "Bitcoin payment",
925
- description: "Sign and submit the Bitcoin swap PSBT, then wait for the bitcoin transaction to confirm",
926
- status: bitcoinPaymentStatus,
927
- confirmations,
928
- initTxId: this._data?.btcTx?.txid,
929
- settleTxId: bitcoinPaymentStatus === "confirmed" ? this._data?.btcTx?.txid : undefined
930
- },
931
- {
932
- type: "Settlement",
933
- side: "destination",
934
- chain: this.chainIdentifier,
935
- title: "Destination settlement",
936
- description: `Wait for automatic settlement on the ${this.chainIdentifier} side, or settle manually if it takes too long`,
937
- status: destinationSettlementStatus,
938
- initTxId: this._frontTxId ?? this._claimTxId,
939
- settleTxId: this._frontTxId ?? this._claimTxId
940
- }
941
- ],
942
- buildCurrentAction,
943
- state
944
- };
945
- }
946
- /**
947
- * @inheritDoc
948
- * @internal
949
- */
950
- async _submitExecutionTransactions(txs, abortSignal, requiredStates, idempotent) {
951
- if (txs.length === 0)
952
- throw new Error("Need to submit at least 1 transaction in the array, submitted empty array of transactions!");
953
- // Handle idempotent calls
954
- if (idempotent) {
955
- let idempotencyTriggered = false;
956
- const txIds = [];
957
- for (let tx of txs) {
958
- let parsedTx;
959
- if (typeof (tx) === "string") {
960
- try {
961
- parsedTx = await this.wrapper._chain.deserializeSignedTx(tx);
962
- }
963
- catch (e) { }
964
- try {
965
- parsedTx = (0, BitcoinUtils_1.parsePsbtTransaction)(tx);
966
- }
967
- catch (e) { }
968
- }
969
- else {
970
- parsedTx = tx;
971
- }
972
- if (parsedTx == null) {
973
- this.logger.debug("_submitExecutionTransactions(): Failed to parse provided execution transaction: ", tx);
974
- continue;
975
- }
976
- if (parsedTx instanceof btc_signer_1.Transaction) {
977
- // Bitcoin tx
978
- const btcTx = await this.wrapper._btcRpc.parseTransaction(buffer_1.Buffer.from(parsedTx.toBytes(true)).toString("hex"));
979
- if (btcTx.txid === this._data?.getTxId()) {
980
- if (this._state !== SpvFromBTCSwapState.SIGNED && this._state !== SpvFromBTCSwapState.DECLINED)
981
- idempotencyTriggered = true;
982
- }
983
- txIds.push(btcTx.txid);
984
- }
985
- else {
986
- // SC tx
987
- if (this.wrapper._chain.getTxId != null) {
988
- const txId = await this.wrapper._chain.getTxId(parsedTx);
989
- if (this._claimTxId === txId)
990
- idempotencyTriggered = true;
991
- txIds.push(txId);
992
- }
993
- }
994
- }
995
- if (idempotencyTriggered)
996
- return txIds;
997
- }
998
- if (requiredStates != null && !requiredStates.includes(this._state))
999
- throw new Error("Swap state has changed before transactions were submitted!");
1000
- if (this._state === SpvFromBTCSwapState.CREATED || this._state === SpvFromBTCSwapState.QUOTE_SOFT_EXPIRED) {
1001
- let psbt;
1002
- if (txs.length !== 1)
1003
- throw new Error("Need to submit exactly 1 signed PSBT!");
1004
- if (typeof (txs[0]) !== "string" && !(txs[0] instanceof btc_signer_1.Transaction))
1005
- throw new Error("Must submit a valid PSBT as hex/base64 string or `@scure/btc-signer` Transaction object!");
1006
- psbt = txs[0];
1007
- return [await this.submitPsbt(psbt)];
1008
- }
1009
- if (this._state === SpvFromBTCSwapState.BTC_TX_CONFIRMED) {
1010
- const parsedTxs = [];
1011
- for (let tx of txs) {
1012
- parsedTxs.push(typeof (tx) === "string" ? await this.wrapper._chain.deserializeSignedTx(tx) : tx);
1013
- }
1014
- const txIds = await this.wrapper._chain.sendSignedAndConfirm(parsedTxs, true, abortSignal, false);
1015
- await this.waitTillClaimed(undefined, abortSignal);
1016
- return txIds;
1017
- }
1018
- throw new Error("Invalid swap state for transaction submission!");
1019
- }
1020
- /**
1021
- * @internal
1022
- */
1023
- async _buildDepositPsbtAction(actionOptions) {
1024
- return {
1025
- type: "SignPSBT",
1026
- name: "Deposit on Bitcoin",
1027
- description: "Send funds to the bitcoin swap address",
1028
- chain: "BITCOIN",
1029
- txs: [
1030
- actionOptions?.bitcoinWallet == null
1031
- ? { ...await this.getPsbt(), type: "RAW_PSBT" }
1032
- : { ...await this.getFundedPsbt(actionOptions.bitcoinWallet, actionOptions?.bitcoinFeeRate), type: "FUNDED_PSBT" }
1033
- ],
1034
- submitPsbt: async (signedPsbt, idempotent) => {
1035
- return this._submitExecutionTransactions(Array.isArray(signedPsbt) ? signedPsbt : [signedPsbt], undefined, [SpvFromBTCSwapState.CREATED, SpvFromBTCSwapState.QUOTE_SOFT_EXPIRED], idempotent);
1036
- }
1037
- };
1038
- }
1039
- /**
1040
- * @internal
1041
- */
1042
- async _buildWaitBitcoinConfirmationsAction(confirmationDelay) {
1043
- return {
1044
- type: "Wait",
1045
- name: "Bitcoin confirmations",
1046
- description: "Wait for bitcoin transaction to confirm",
1047
- pollTimeSeconds: 10,
1048
- expectedTimeSeconds: confirmationDelay === -1 ? -1 : Math.floor(confirmationDelay / 1000),
1049
- wait: async (maxWaitTimeSeconds, pollIntervalSeconds, abortSignal, btcConfirmationsCallback) => {
1050
- const abortController = (0, Utils_1.extendAbortController)(abortSignal, maxWaitTimeSeconds, "Timed out waiting for bitcoin transaction");
1051
- await this.waitForBitcoinTransaction(btcConfirmationsCallback, pollIntervalSeconds, abortController.signal);
1052
- }
1053
- };
1054
- }
1055
- /**
1056
- * @internal
1057
- */
1058
- async _buildWaitSettlementAction(maxWaitTillAutomaticSettlementSeconds) {
1059
- return {
1060
- type: "Wait",
1061
- name: "Automatic settlement",
1062
- description: "Wait for bitcoin transaction to confirm",
1063
- pollTimeSeconds: 5,
1064
- expectedTimeSeconds: 10,
1065
- wait: async (maxWaitTimeSeconds, pollIntervalSeconds, abortSignal) => {
1066
- await this.waitTillClaimedOrFronted(maxWaitTimeSeconds ?? maxWaitTillAutomaticSettlementSeconds ?? 60, abortSignal, pollIntervalSeconds);
1067
- }
1068
- };
1069
- }
1070
- /**
1071
- * @internal
1072
- */
1073
- async _buildClaimSmartChainTxAction(actionOptions) {
1074
- const signerAddress = await this.wrapper._getSignerAddress(actionOptions?.manualSettlementSmartChainSigner);
1075
- return {
1076
- type: "SignSmartChainTransaction",
1077
- name: "Settle manually",
1078
- description: "Manually settle the swap on the destination smart chain",
1079
- chain: this.chainIdentifier,
1080
- txs: await this.prepareTransactions(this.txsClaim(actionOptions?.manualSettlementSmartChainSigner)),
1081
- submitTransactions: async (txs, abortSignal, idempotent) => {
1082
- return this._submitExecutionTransactions(txs, abortSignal, [SpvFromBTCSwapState.BTC_TX_CONFIRMED], idempotent);
1083
- },
1084
- requiredSigner: signerAddress ?? this._getInitiator()
1085
- };
1086
- }
1087
- /**
1088
- * @inheritDoc
1089
- *
1090
- * @param options.bitcoinFeeRate Optional fee rate to use for the created Bitcoin transaction
1091
- * @param options.bitcoinWallet Optional bitcoin wallet address specification to return a funded PSBT,
1092
- * if not provided a raw PSBT is returned instead which necessitates the implementor to manually add
1093
- * inputs to the bitcoin transaction and **set the nSequence field of the 2nd input** (input 1 -
1094
- * indexing from 0) to the value returned in `in1sequence`
1095
- * @param options.manualSettlementSmartChainSigner Optional smart chain signer to create a manual claim (settlement) transaction
1096
- * @param options.maxWaitTillAutomaticSettlementSeconds Maximum time to wait for an automatic settlement after
1097
- * the bitcoin transaction is confirmed (defaults to 60 seconds)
1098
- */
1099
- async getExecutionAction(options) {
1100
- const executionStatus = await this._getExecutionStatus(options);
1101
- return executionStatus.buildCurrentAction(options);
1102
- }
1103
- /**
1104
- * @inheritDoc
1105
- */
1106
- async getExecutionStatus(options) {
1107
- const executionStatus = await this._getExecutionStatus(options);
1108
- return {
1109
- steps: executionStatus.steps,
1110
- currentAction: options?.skipBuildingAction ? undefined : await executionStatus.buildCurrentAction(options),
1111
- stateInfo: this._getStateInfo(executionStatus.state)
1112
- };
1113
- }
1114
- /**
1115
- * @inheritDoc
1116
- */
1117
- async getExecutionSteps(options) {
1118
- return (await this._getExecutionStatus(options)).steps;
1119
- }
1120
- //////////////////////////////
1121
- //// Bitcoin tx listener
1122
- /**
1123
- * Checks whether a bitcoin payment was already made, returns the payment or null when no payment has been made.
1124
- * @internal
1125
- */
1126
- async getBitcoinPayment() {
1127
- if (this._data?.btcTx?.txid == null)
1128
- return null;
1129
- const result = await this.wrapper._btcRpc.getTransaction(this._data?.btcTx?.txid);
1130
- if (result == null)
1131
- return null;
1132
- return {
1133
- txId: result.txid,
1134
- confirmations: result.confirmations ?? 0,
1135
- targetConfirmations: this.vaultRequiredConfirmations,
1136
- btcTx: result,
1137
- inputAddresses: result.inputAddresses
1138
- };
1139
- }
1140
- /**
1141
- * @inheritDoc
1142
- *
1143
- * @throws {Error} if in invalid state (must be {@link SpvFromBTCSwapState.POSTED} or
1144
- * {@link SpvFromBTCSwapState.BROADCASTED} states)
1145
- */
1146
- async waitForBitcoinTransaction(updateCallback, checkIntervalSeconds, abortSignal) {
1147
- if (this._state !== SpvFromBTCSwapState.POSTED &&
1148
- this._state !== SpvFromBTCSwapState.BROADCASTED &&
1149
- !(this._state === SpvFromBTCSwapState.QUOTE_SOFT_EXPIRED && this.posted))
1150
- throw new Error("Must be in POSTED or BROADCASTED state!");
1151
- if (this._data == null)
1152
- throw new Error("Expected swap to have withdrawal data filled!");
1153
- const result = await this.wrapper._btcRpc.waitForTransaction(this._data.btcTx.txid, this.vaultRequiredConfirmations, (btcTx, txEtaMs) => {
1154
- if (updateCallback != null)
1155
- updateCallback(btcTx?.txid, btcTx?.confirmations, this.vaultRequiredConfirmations, txEtaMs);
1156
- if (btcTx == null)
1157
- return;
1158
- let save = false;
1159
- if (btcTx.inputAddresses != null && this._senderAddress == null) {
1160
- this._senderAddress = btcTx.inputAddresses[1];
1161
- save = true;
1162
- }
1163
- if (this._state === SpvFromBTCSwapState.POSTED || this._state == SpvFromBTCSwapState.QUOTE_SOFT_EXPIRED) {
1164
- this._state = SpvFromBTCSwapState.BROADCASTED;
1165
- save = true;
1166
- }
1167
- if (save)
1168
- this._saveAndEmit();
1169
- }, abortSignal, checkIntervalSeconds);
1170
- if (abortSignal != null)
1171
- abortSignal.throwIfAborted();
1172
- let save = false;
1173
- if (result.inputAddresses != null && this._senderAddress == null) {
1174
- this._senderAddress = result.inputAddresses[1];
1175
- save = true;
1176
- }
1177
- if (this._state !== SpvFromBTCSwapState.FRONTED &&
1178
- this._state !== SpvFromBTCSwapState.CLAIMED) {
1179
- this.btcTxConfirmedAt ??= Date.now();
1180
- this._state = SpvFromBTCSwapState.BTC_TX_CONFIRMED;
1181
- save = true;
1182
- }
1183
- if (save)
1184
- await this._saveAndEmit();
1185
- return result.txid;
1186
- }
1187
- //////////////////////////////
1188
- //// Claim
1189
- /**
1190
- * Returns transactions for settling (claiming) the swap if the swap requires manual settlement, you can check so
1191
- * with isClaimable. After sending the transaction manually be sure to call the waitTillClaimed function to wait
1192
- * till the claim transaction is observed, processed by the SDK and state of the swap properly updated.
1193
- *
1194
- * @remarks
1195
- * Might also return transactions necessary to sync the bitcoin light client.
1196
- *
1197
- * @param _signer Address of the signer to create the claim transactions for, can also be different to the recipient
1198
- *
1199
- * @throws {Error} If the swap is in invalid state (must be {@link SpvFromBTCSwapState.BTC_TX_CONFIRMED})
1200
- */
1201
- async txsClaim(_signer) {
1202
- let address = undefined;
1203
- if (_signer != null) {
1204
- if (typeof (_signer) === "string") {
1205
- address = _signer;
1206
- }
1207
- else if ((0, base_1.isAbstractSigner)(_signer)) {
1208
- address = _signer.getAddress();
1209
- }
1210
- else {
1211
- address = (await this.wrapper._chain.wrapSigner(_signer)).getAddress();
1212
- }
1213
- }
1214
- if (!this.isClaimable())
1215
- throw new Error("Must be in BTC_TX_CONFIRMED state!");
1216
- if (this._data == null)
1217
- throw new Error("Expected swap to have withdrawal data filled!");
1218
- const vaultData = await this._contract.getVaultData(this.vaultOwner, this.vaultId);
1219
- if (vaultData == null)
1220
- throw new Error(`Vault data for ${this.vaultOwner}:${this.vaultId.toString(10)} not found (already closed???)!`);
1221
- const btcTx = await this.wrapper._btcRpc.getTransaction(this._data.btcTx.txid);
1222
- if (btcTx == null)
1223
- throw new Error(`Bitcoin transaction ${this._data.btcTx.txid} not found!`);
1224
- const txs = [btcTx];
1225
- //Trace back from current tx to the vaultData-specified UTXO
1226
- const vaultUtxo = vaultData.getUtxo();
1227
- while (txs[0].ins[0].txid + ":" + txs[0].ins[0].vout !== vaultUtxo) {
1228
- const btcTx = await this.wrapper._btcRpc.getTransaction(txs[0].ins[0].txid);
1229
- if (btcTx == null)
1230
- throw new Error(`Prior withdrawal bitcoin transaction ${this._data.btcTx.txid} not found!`);
1231
- txs.unshift(btcTx);
1232
- }
1233
- //Parse transactions to withdrawal data
1234
- const withdrawalData = [];
1235
- for (let tx of txs) {
1236
- withdrawalData.push(await this._contract.getWithdrawalData(tx));
1237
- }
1238
- return await this._contract.txsClaim(address ?? this._getInitiator(), vaultData, withdrawalData.map(tx => { return { tx }; }), this.wrapper._synchronizer(this._contractVersion), true);
1239
- }
1240
- /**
1241
- * Settles the swap by claiming the funds on the destination chain if the swap requires manual settlement, you can
1242
- * check so with isClaimable.
1243
- *
1244
- * @remarks
1245
- * Might also sync the bitcoin light client during the process.
1246
- *
1247
- * @param _signer Signer to use for signing the settlement transactions, can also be different to the recipient
1248
- * @param abortSignal Abort signal
1249
- * @param onBeforeTxSent Optional callback triggered before the claim transaction is broadcasted
1250
- *
1251
- * @throws {Error} If the swap is in invalid state (must be {@link SpvFromBTCSwapState.BTC_TX_CONFIRMED})
1252
- */
1253
- async claim(_signer, abortSignal, onBeforeTxSent) {
1254
- const signer = (0, base_1.isAbstractSigner)(_signer) ? _signer : await this.wrapper._chain.wrapSigner(_signer);
1255
- let txIds;
1256
- try {
1257
- let txCount = 0;
1258
- const txs = await this.txsClaim(signer);
1259
- txIds = await this.wrapper._chain.sendAndConfirm(signer, txs, true, abortSignal, undefined, (txId) => {
1260
- txCount++;
1261
- if (onBeforeTxSent != null && txCount === txs.length)
1262
- onBeforeTxSent(txId);
1263
- return Promise.resolve();
1264
- });
1265
- }
1266
- catch (e) {
1267
- if (this._data == null)
1268
- throw e;
1269
- this.logger.info("claim(): Failed to claim ourselves, checking swap claim state...");
1270
- if (this._state === SpvFromBTCSwapState.CLAIMED) {
1271
- this.logger.info("claim(): Transaction state is CLAIMED, swap was successfully claimed by the watchtower");
1272
- return this._claimTxId;
1273
- }
1274
- const withdrawalState = await this._contract.getWithdrawalState(this._data, this._genesisSmartChainBlockHeight);
1275
- if (withdrawalState != null && withdrawalState.type === base_1.SpvWithdrawalStateType.CLAIMED) {
1276
- this.logger.info("claim(): Transaction status is CLAIMED, swap was successfully claimed by the watchtower");
1277
- this._claimTxId = withdrawalState.txId;
1278
- await this._saveAndEmit(SpvFromBTCSwapState.CLAIMED);
1279
- return withdrawalState.txId;
1280
- }
1281
- throw e;
1282
- }
1283
- this._claimTxId = txIds[0];
1284
- if (this._state === SpvFromBTCSwapState.POSTED || this._state === SpvFromBTCSwapState.BROADCASTED ||
1285
- this._state === SpvFromBTCSwapState.BTC_TX_CONFIRMED || this._state === SpvFromBTCSwapState.FAILED ||
1286
- this._state === SpvFromBTCSwapState.FRONTED) {
1287
- await this._saveAndEmit(SpvFromBTCSwapState.CLAIMED);
1288
- }
1289
- return txIds[0];
1290
- }
1291
- /**
1292
- * Periodically checks the chain to see whether the swap was finished (claimed or refunded)
1293
- *
1294
- * @param interval How often to check (in seconds), default to 5s
1295
- * @param abortSignal
1296
- * @internal
1297
- */
1298
- async watchdogWaitTillResult(interval = 5, abortSignal) {
1299
- if (this._data == null)
1300
- throw new Error("Cannot await the result before the btc transaction is sent!");
1301
- let status = { type: base_1.SpvWithdrawalStateType.NOT_FOUND };
1302
- while (status.type === base_1.SpvWithdrawalStateType.NOT_FOUND) {
1303
- await (0, TimeoutUtils_1.timeoutPromise)(interval * 1000, abortSignal);
1304
- try {
1305
- //Be smart about checking withdrawal state
1306
- if (await this._shouldCheckWithdrawalState()) {
1307
- status = await this._contract.getWithdrawalState(this._data, this._genesisSmartChainBlockHeight) ?? { type: base_1.SpvWithdrawalStateType.NOT_FOUND };
1308
- }
1309
- }
1310
- catch (e) {
1311
- this.logger.error("watchdogWaitTillResult(): Error when fetching commit status: ", e);
1312
- }
1313
- }
1314
- if (abortSignal != null)
1315
- abortSignal.throwIfAborted();
1316
- return status;
1317
- }
1318
- /**
1319
- * Waits till the swap is successfully settled (claimed), should be called after sending the claim (settlement)
1320
- * transactions manually to wait till the SDK processes the settlement and updates the swap state accordingly.
1321
- *
1322
- * @remarks
1323
- * This is an alias for the {@link waitTillClaimedOrFronted} function and will also resolve if the swap has
1324
- * been fronted (not necessarily claimed)
1325
- *
1326
- * @param maxWaitTimeSeconds – Maximum time in seconds to wait for the swap to be settled
1327
- * @param abortSignal – AbortSignal
1328
- *
1329
- * @returns Whether the swap was claimed in time or not
1330
- */
1331
- waitTillClaimed(maxWaitTimeSeconds, abortSignal) {
1332
- return this.waitTillClaimedOrFronted(maxWaitTimeSeconds, abortSignal);
1333
- }
1334
- /**
1335
- * Waits till the swap is successfully fronted or settled on the destination chain
1336
- *
1337
- * @param maxWaitTimeSeconds Maximum time in seconds to wait for the swap to be settled (by default
1338
- * it waits indefinitely)
1339
- * @param abortSignal Abort signal
1340
- * @param pollIntervalSeconds How often to poll via the watchdog
1341
- *
1342
- * @returns {boolean} whether the swap was claimed or fronted automatically or not, if the swap was not claimed
1343
- * the user can claim manually through the {@link claim} function
1344
- */
1345
- async waitTillClaimedOrFronted(maxWaitTimeSeconds, abortSignal, pollIntervalSeconds) {
1346
- if (this._state === SpvFromBTCSwapState.CLAIMED || this._state === SpvFromBTCSwapState.FRONTED)
1347
- return Promise.resolve(true);
1348
- const abortController = (0, Utils_1.extendAbortController)(abortSignal);
1349
- let timedOut = false;
1350
- if (maxWaitTimeSeconds != null) {
1351
- const timeout = setTimeout(() => {
1352
- timedOut = true;
1353
- abortController.abort();
1354
- }, maxWaitTimeSeconds * 1000);
1355
- abortController.signal.addEventListener("abort", () => clearTimeout(timeout));
1356
- }
1357
- let res;
1358
- try {
1359
- res = await Promise.race([
1360
- this.watchdogWaitTillResult(pollIntervalSeconds, abortController.signal),
1361
- this.waitTillState(SpvFromBTCSwapState.CLAIMED, "eq", abortController.signal).then(() => 0),
1362
- this.waitTillState(SpvFromBTCSwapState.FRONTED, "eq", abortController.signal).then(() => 1),
1363
- this.waitTillState(SpvFromBTCSwapState.FAILED, "eq", abortController.signal).then(() => 2),
1364
- ]);
1365
- abortController.abort();
1366
- }
1367
- catch (e) {
1368
- abortController.abort();
1369
- if (timedOut)
1370
- return false;
1371
- throw e;
1372
- }
1373
- if (typeof (res) === "number") {
1374
- if (res === 0) {
1375
- this.logger.debug("waitTillClaimedOrFronted(): Resolved from state change (CLAIMED)");
1376
- return true;
1377
- }
1378
- if (res === 1) {
1379
- this.logger.debug("waitTillClaimedOrFronted(): Resolved from state change (FRONTED)");
1380
- return true;
1381
- }
1382
- if (res === 2) {
1383
- this.logger.debug("waitTillClaimedOrFronted(): Resolved from state change (FAILED)");
1384
- throw new Error("Swap failed while waiting for claim or front");
1385
- }
1386
- throw new Error("Invalid numeric response, this should never happen!");
1387
- }
1388
- this.logger.debug("waitTillClaimedOrFronted(): Resolved from watchdog");
1389
- if (res.type === base_1.SpvWithdrawalStateType.FRONTED) {
1390
- if (this._state !== SpvFromBTCSwapState.FRONTED ||
1391
- this._state !== SpvFromBTCSwapState.CLAIMED) {
1392
- this._frontTxId = res.txId;
1393
- await this._saveAndEmit(SpvFromBTCSwapState.FRONTED);
1394
- }
1395
- }
1396
- if (res.type === base_1.SpvWithdrawalStateType.CLAIMED) {
1397
- if (this._state !== SpvFromBTCSwapState.CLAIMED) {
1398
- this._claimTxId = res.txId;
1399
- await this._saveAndEmit(SpvFromBTCSwapState.CLAIMED);
1400
- }
1401
- }
1402
- if (res.type === base_1.SpvWithdrawalStateType.CLOSED) {
1403
- if (this._state !== SpvFromBTCSwapState.CLOSED)
1404
- await this._saveAndEmit(SpvFromBTCSwapState.CLOSED);
1405
- throw new Error("Swap failed with catastrophic error!");
1406
- }
1407
- return true;
1408
- }
1409
- /**
1410
- * Waits till the bitcoin transaction confirms and swap settled on the destination chain
1411
- *
1412
- * @param updateCallback Callback called when txId is found, and also called with subsequent confirmations
1413
- * @param checkIntervalSeconds How often to check the bitcoin transaction (5 seconds by default)
1414
- * @param abortSignal Abort signal
1415
- *
1416
- * @throws {Error} if in invalid state (must be {@link SpvFromBTCSwapState.POSTED} or
1417
- * {@link SpvFromBTCSwapState.BROADCASTED} states)
1418
- */
1419
- async waitTillExecuted(updateCallback, checkIntervalSeconds, abortSignal) {
1420
- await this.waitForBitcoinTransaction(updateCallback, checkIntervalSeconds, abortSignal);
1421
- await this.waitTillClaimedOrFronted(undefined, abortSignal);
1422
- }
1423
- //////////////////////////////
1424
- //// Storage
1425
- /**
1426
- * @inheritDoc
1427
- */
1428
- serialize() {
1429
- return {
1430
- ...super.serialize(),
1431
- quoteId: this.quoteId,
1432
- recipient: this.recipient,
1433
- vaultOwner: this.vaultOwner,
1434
- vaultId: this.vaultId.toString(10),
1435
- vaultRequiredConfirmations: this.vaultRequiredConfirmations,
1436
- vaultTokenMultipliers: this.vaultTokenMultipliers.map(val => val.toString(10)),
1437
- vaultBtcAddress: this.vaultBtcAddress,
1438
- vaultUtxo: this.vaultUtxo,
1439
- vaultUtxoValue: this.vaultUtxoValue.toString(10),
1440
- btcDestinationAddress: this.btcDestinationAddress,
1441
- btcAmount: this.btcAmount.toString(10),
1442
- btcAmountSwap: this.btcAmountSwap.toString(10),
1443
- btcAmountGas: this.btcAmountGas.toString(10),
1444
- minimumBtcFeeRate: this.minimumBtcFeeRate,
1445
- outputTotalSwap: this.outputTotalSwap.toString(10),
1446
- outputSwapToken: this.outputSwapToken,
1447
- outputTotalGas: this.outputTotalGas.toString(10),
1448
- outputGasToken: this.outputGasToken,
1449
- gasSwapFeeBtc: this.gasSwapFeeBtc.toString(10),
1450
- gasSwapFee: this.gasSwapFee.toString(10),
1451
- callerFeeShare: this.callerFeeShare.toString(10),
1452
- frontingFeeShare: this.frontingFeeShare.toString(10),
1453
- executionFeeShare: this.executionFeeShare.toString(10),
1454
- genesisSmartChainBlockHeight: this._genesisSmartChainBlockHeight,
1455
- gasPricingInfo: (0, PriceInfoType_1.serializePriceInfoType)(this.gasPricingInfo),
1456
- posted: this.posted,
1457
- senderAddress: this._senderAddress,
1458
- claimTxId: this._claimTxId,
1459
- frontTxId: this._frontTxId,
1460
- data: this._data?.serialize(),
1461
- btcTxConfirmedAt: this.btcTxConfirmedAt
1462
- };
1463
- }
1464
- //////////////////////////////
1465
- //// Swap ticks & sync
1466
- /**
1467
- * Used to set the txId of the bitcoin payment from the on-chain events listener
1468
- *
1469
- * @param txId
1470
- * @internal
1471
- */
1472
- async _setBitcoinTxId(txId) {
1473
- if (this._data == null)
1474
- return;
1475
- if (txId != this._data.btcTx.txid)
1476
- return;
1477
- if (this._senderAddress != null)
1478
- return;
1479
- const btcTx = await this.wrapper._btcRpc.getTransaction(txId);
1480
- if (btcTx == null || btcTx.inputAddresses == null)
1481
- return;
1482
- this._senderAddress = btcTx.inputAddresses[1];
1483
- }
1484
- /**
1485
- * @internal
1486
- */
1487
- async _syncStateFromBitcoin(save) {
1488
- if (this._data?.btcTx == null)
1489
- return false;
1490
- //Check if bitcoin payment was confirmed
1491
- this.btcTxLastChecked = Date.now();
1492
- const res = await this.getBitcoinPayment();
1493
- if (res == null) {
1494
- //Check inputs double-spent
1495
- for (let input of this._data.btcTx.ins) {
1496
- if (await this.wrapper._btcRpc.isSpent(input.txid + ":" + input.vout, true)) {
1497
- if (this._state === SpvFromBTCSwapState.SIGNED ||
1498
- this._state === SpvFromBTCSwapState.POSTED ||
1499
- this._state === SpvFromBTCSwapState.QUOTE_SOFT_EXPIRED ||
1500
- this._state === SpvFromBTCSwapState.DECLINED) {
1501
- //One of the inputs was double-spent
1502
- this._state = SpvFromBTCSwapState.QUOTE_EXPIRED;
1503
- }
1504
- else {
1505
- //One of the inputs was double-spent
1506
- this._state = SpvFromBTCSwapState.FAILED;
1507
- }
1508
- if (save)
1509
- await this._saveAndEmit();
1510
- return true;
1511
- }
1512
- }
1513
- }
1514
- else {
1515
- let needsSave = false;
1516
- if (res.inputAddresses != null && this._senderAddress == null) {
1517
- this._senderAddress = res.inputAddresses[1];
1518
- needsSave = true;
1519
- }
1520
- if (res.confirmations >= this.vaultRequiredConfirmations) {
1521
- if (this._state !== SpvFromBTCSwapState.BTC_TX_CONFIRMED &&
1522
- this._state !== SpvFromBTCSwapState.FRONTED &&
1523
- this._state !== SpvFromBTCSwapState.CLAIMED) {
1524
- this.btcTxConfirmedAt ??= Date.now();
1525
- this._state = SpvFromBTCSwapState.BTC_TX_CONFIRMED;
1526
- needsSave = true;
1527
- }
1528
- }
1529
- else if (this._state === SpvFromBTCSwapState.QUOTE_SOFT_EXPIRED ||
1530
- this._state === SpvFromBTCSwapState.POSTED ||
1531
- this._state === SpvFromBTCSwapState.SIGNED ||
1532
- this._state === SpvFromBTCSwapState.DECLINED) {
1533
- this._state = SpvFromBTCSwapState.BROADCASTED;
1534
- needsSave = true;
1535
- }
1536
- if (needsSave && save)
1537
- await this._saveAndEmit();
1538
- return needsSave;
1539
- }
1540
- return false;
1541
- }
1542
- /**
1543
- * Checks the swap's state on-chain and compares it to its internal state, updates/changes it according to on-chain
1544
- * data
1545
- */
1546
- async syncStateFromChain() {
1547
- let changed = false;
1548
- if (this._state === SpvFromBTCSwapState.SIGNED ||
1549
- this._state === SpvFromBTCSwapState.POSTED ||
1550
- this._state === SpvFromBTCSwapState.BROADCASTED ||
1551
- this._state === SpvFromBTCSwapState.QUOTE_SOFT_EXPIRED ||
1552
- this._state === SpvFromBTCSwapState.DECLINED ||
1553
- this._state === SpvFromBTCSwapState.BTC_TX_CONFIRMED) {
1554
- //Check BTC transaction
1555
- if (await this._syncStateFromBitcoin(false))
1556
- changed ||= true;
1557
- }
1558
- if (this._state === SpvFromBTCSwapState.BROADCASTED || this._state === SpvFromBTCSwapState.BTC_TX_CONFIRMED) {
1559
- if (await this._shouldCheckWithdrawalState()) {
1560
- const status = await this._contract.getWithdrawalState(this._data, this._genesisSmartChainBlockHeight);
1561
- this.logger.debug("syncStateFromChain(): status of " + this._data.btcTx.txid, status);
1562
- switch (status?.type) {
1563
- case base_1.SpvWithdrawalStateType.FRONTED:
1564
- this._frontTxId = status.txId;
1565
- this._state = SpvFromBTCSwapState.FRONTED;
1566
- changed ||= true;
1567
- break;
1568
- case base_1.SpvWithdrawalStateType.CLAIMED:
1569
- this._claimTxId = status.txId;
1570
- this._state = SpvFromBTCSwapState.CLAIMED;
1571
- changed ||= true;
1572
- break;
1573
- case base_1.SpvWithdrawalStateType.CLOSED:
1574
- this._state = SpvFromBTCSwapState.CLOSED;
1575
- changed ||= true;
1576
- break;
1577
- }
1578
- }
1579
- }
1580
- if (this._state === SpvFromBTCSwapState.CREATED ||
1581
- this._state === SpvFromBTCSwapState.SIGNED ||
1582
- this._state === SpvFromBTCSwapState.POSTED) {
1583
- if (this.expiry < Date.now()) {
1584
- if (this._state === SpvFromBTCSwapState.CREATED) {
1585
- this._state = SpvFromBTCSwapState.QUOTE_EXPIRED;
1586
- }
1587
- else {
1588
- this._state = SpvFromBTCSwapState.QUOTE_SOFT_EXPIRED;
1589
- }
1590
- changed ||= true;
1591
- }
1592
- }
1593
- return changed;
1594
- }
1595
- /**
1596
- * @inheritDoc
1597
- * @internal
1598
- */
1599
- async _sync(save) {
1600
- const changed = await this.syncStateFromChain();
1601
- if (changed && save)
1602
- await this._saveAndEmit();
1603
- return changed;
1604
- }
1605
- /**
1606
- * @inheritDoc
1607
- * @internal
1608
- */
1609
- async _tick(save) {
1610
- if (this._state === SpvFromBTCSwapState.CREATED ||
1611
- this._state === SpvFromBTCSwapState.SIGNED) {
1612
- if (this.getQuoteExpiry() < Date.now()) {
1613
- this._state = SpvFromBTCSwapState.QUOTE_SOFT_EXPIRED;
1614
- if (save)
1615
- await this._saveAndEmit();
1616
- return true;
1617
- }
1618
- }
1619
- if (this._state === SpvFromBTCSwapState.QUOTE_SOFT_EXPIRED && !this.posted) {
1620
- if (this.expiry < Date.now()) {
1621
- this._state = SpvFromBTCSwapState.QUOTE_EXPIRED;
1622
- if (save)
1623
- await this._saveAndEmit();
1624
- return true;
1625
- }
1626
- }
1627
- if (this.btcTxLastChecked == null || Date.now() - this.btcTxLastChecked > 120000) {
1628
- if (this._state === SpvFromBTCSwapState.POSTED ||
1629
- this._state === SpvFromBTCSwapState.BROADCASTED) {
1630
- try {
1631
- //Check if bitcoin payment was confirmed
1632
- return await this._syncStateFromBitcoin(save);
1633
- }
1634
- catch (e) {
1635
- this.logger.error("tickSwap(" + this.getId() + "): ", e);
1636
- }
1637
- }
1638
- }
1639
- return false;
1640
- }
1641
- /**
1642
- * Checks whether an on-chain withdrawal state should be fetched for this specific swap
1643
- *
1644
- * @internal
1645
- */
1646
- async _shouldCheckWithdrawalState(frontingAddress, vaultDataUtxo) {
1647
- if (frontingAddress === undefined)
1648
- frontingAddress = await this._contract.getFronterAddress(this.vaultOwner, this.vaultId, this._data);
1649
- if (vaultDataUtxo === undefined)
1650
- vaultDataUtxo = await this._contract.getVaultLatestUtxo(this.vaultOwner, this.vaultId);
1651
- if (frontingAddress != null)
1652
- return true; //In case the swap is fronted there will for sure be a fronted event
1653
- if (vaultDataUtxo == null)
1654
- return true; //Vault UTXO is null (the vault closed)
1655
- const [txId, _] = vaultDataUtxo.split(":");
1656
- //Don't check both txns if their txId is equal
1657
- if (this._data.btcTx.txid === txId)
1658
- return true;
1659
- const [btcTx, latestVaultTx] = await Promise.all([
1660
- this.wrapper._btcRpc.getTransaction(this._data.btcTx.txid),
1661
- this.wrapper._btcRpc.getTransaction(txId)
1662
- ]);
1663
- if (latestVaultTx == null || latestVaultTx.blockheight == null) {
1664
- //Something must've gone horribly wrong, the latest vault utxo tx of the vault either
1665
- // cannot be found on bitcoin network or is not even confirmed yet
1666
- this.logger.debug(`_shouldCheckWithdrawalState(): Latest vault utxo not found or not confirmed on bitcoin ${txId}`);
1667
- return false;
1668
- }
1669
- if (btcTx != null) {
1670
- const btcTxHeight = btcTx.blockheight;
1671
- const latestVaultTxHeight = latestVaultTx.blockheight;
1672
- //We also need to cover the case where bitcoin tx isn't confirmed yet (hence btxTxHeight==null)
1673
- if (btcTxHeight == null || latestVaultTxHeight < btcTxHeight) {
1674
- //Definitely not claimed!
1675
- this.logger.debug(`_shouldCheckWithdrawalState(): Skipped checking withdrawal state, latestVaultTxHeight: ${latestVaultTx.blockheight}, btcTxHeight: ${btcTxHeight} and not fronted!`);
1676
- return false;
1677
- }
1678
- }
1679
- else {
1680
- //Definitely not claimed because the transaction was probably double-spent (or evicted from mempool)
1681
- this.logger.debug(`_shouldCheckWithdrawalState(): Skipped checking withdrawal state, btc tx probably replaced or evicted: ${this._data.btcTx.txid} and not fronted`);
1682
- return false;
1683
- }
1684
- return true;
1685
- }
1686
- }
1687
- exports.SpvFromBTCSwap = SpvFromBTCSwap;
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.SpvFromBTCSwap = exports.isSpvFromBTCSwapInit = exports.SpvFromBTCSwapState = void 0;
4
+ const ISwap_1 = require("../ISwap");
5
+ const base_1 = require("@atomiqlabs/base");
6
+ const SwapType_1 = require("../../enums/SwapType");
7
+ const Utils_1 = require("../../utils/Utils");
8
+ const BitcoinUtils_1 = require("../../utils/BitcoinUtils");
9
+ const btc_signer_1 = require("@scure/btc-signer");
10
+ const buffer_1 = require("buffer");
11
+ const IBitcoinWallet_1 = require("../../bitcoin/wallet/IBitcoinWallet");
12
+ const FeeType_1 = require("../../enums/FeeType");
13
+ const PercentagePPM_1 = require("../../types/fees/PercentagePPM");
14
+ const TokenAmount_1 = require("../../types/TokenAmount");
15
+ const Token_1 = require("../../types/Token");
16
+ const Logger_1 = require("../../utils/Logger");
17
+ const TimeoutUtils_1 = require("../../utils/TimeoutUtils");
18
+ const PriceInfoType_1 = require("../../types/PriceInfoType");
19
+ const BitcoinWalletUtils_1 = require("../../utils/BitcoinWalletUtils");
20
+ /**
21
+ * State enum for SPV vault (UTXO-controlled vault) based swaps
22
+ * @category Swaps/Bitcoin → Smart chain
23
+ */
24
+ var SpvFromBTCSwapState;
25
+ (function (SpvFromBTCSwapState) {
26
+ /**
27
+ * Catastrophic failure has occurred when processing the swap on the smart chain side,
28
+ * this implies a bug in the smart contract code or the user and intermediary deliberately
29
+ * creating a bitcoin transaction with invalid format unparsable by the smart contract.
30
+ */
31
+ SpvFromBTCSwapState[SpvFromBTCSwapState["CLOSED"] = -5] = "CLOSED";
32
+ /**
33
+ * Some of the bitcoin swap transaction inputs were double-spent, this means the swap
34
+ * has failed and no BTC was sent
35
+ */
36
+ SpvFromBTCSwapState[SpvFromBTCSwapState["FAILED"] = -4] = "FAILED";
37
+ /**
38
+ * The intermediary (LP) declined to co-sign the submitted PSBT, hence the swap failed
39
+ */
40
+ SpvFromBTCSwapState[SpvFromBTCSwapState["DECLINED"] = -3] = "DECLINED";
41
+ /**
42
+ * Swap has expired for good and there is no way how it can be executed anymore
43
+ */
44
+ SpvFromBTCSwapState[SpvFromBTCSwapState["QUOTE_EXPIRED"] = -2] = "QUOTE_EXPIRED";
45
+ /**
46
+ * A swap is almost expired, and it should be presented to the user as expired, though
47
+ * there is still a chance that it will be processed
48
+ */
49
+ SpvFromBTCSwapState[SpvFromBTCSwapState["QUOTE_SOFT_EXPIRED"] = -1] = "QUOTE_SOFT_EXPIRED";
50
+ /**
51
+ * Swap was created, use the {@link SpvFromBTCSwap.getFundedPsbt} or {@link SpvFromBTCSwap.getPsbt} functions
52
+ * to get the bitcoin swap PSBT that should be signed by the user's wallet and then submitted via the
53
+ * {@link SpvFromBTCSwap.submitPsbt} function.
54
+ */
55
+ SpvFromBTCSwapState[SpvFromBTCSwapState["CREATED"] = 0] = "CREATED";
56
+ /**
57
+ * Swap bitcoin PSBT was submitted by the client to the SDK
58
+ */
59
+ SpvFromBTCSwapState[SpvFromBTCSwapState["SIGNED"] = 1] = "SIGNED";
60
+ /**
61
+ * Swap bitcoin PSBT sent to the intermediary (LP), waiting for the intermediary co-sign
62
+ * it and broadcast. You can use the {@link SpvFromBTCSwap.waitTillClaimedOrFronted}
63
+ * function to wait till the intermediary broadcasts the transaction and the transaction
64
+ * confirms.
65
+ */
66
+ SpvFromBTCSwapState[SpvFromBTCSwapState["POSTED"] = 2] = "POSTED";
67
+ /**
68
+ * Intermediary (LP) has co-signed and broadcasted the bitcoin transaction. You can use the
69
+ * {@link SpvFromBTCSwap.waitTillClaimedOrFronted} function to wait till the transaction
70
+ * confirms.
71
+ */
72
+ SpvFromBTCSwapState[SpvFromBTCSwapState["BROADCASTED"] = 3] = "BROADCASTED";
73
+ /**
74
+ * Settlement on the destination smart chain was fronted and funds were already received
75
+ * by the user, even before the final settlement.
76
+ */
77
+ SpvFromBTCSwapState[SpvFromBTCSwapState["FRONTED"] = 4] = "FRONTED";
78
+ /**
79
+ * Bitcoin transaction confirmed with necessary amount of confirmations, wait for automatic
80
+ * settlement by the watchtower with the {@link waitTillClaimedOrFronted} function, or settle manually
81
+ * using the {@link FromBTCSwap.claim} or {@link FromBTCSwap.txsClaim} function.
82
+ */
83
+ SpvFromBTCSwapState[SpvFromBTCSwapState["BTC_TX_CONFIRMED"] = 5] = "BTC_TX_CONFIRMED";
84
+ /**
85
+ * Swap settled on the smart chain and funds received
86
+ */
87
+ SpvFromBTCSwapState[SpvFromBTCSwapState["CLAIMED"] = 6] = "CLAIMED";
88
+ })(SpvFromBTCSwapState = exports.SpvFromBTCSwapState || (exports.SpvFromBTCSwapState = {}));
89
+ const SpvFromBTCSwapStateDescription = {
90
+ [SpvFromBTCSwapState.CLOSED]: "Catastrophic failure has occurred when processing the swap on the smart chain side, this implies a bug in the smart contract code or the user and intermediary deliberately creating a bitcoin transaction with invalid format unparsable by the smart contract.",
91
+ [SpvFromBTCSwapState.FAILED]: "Some of the bitcoin swap transaction inputs were double-spent, this means the swap has failed and no BTC was sent",
92
+ [SpvFromBTCSwapState.DECLINED]: "The intermediary (LP) declined to co-sign the submitted PSBT, hence the swap failed",
93
+ [SpvFromBTCSwapState.QUOTE_EXPIRED]: "Swap has expired for good and there is no way how it can be executed anymore",
94
+ [SpvFromBTCSwapState.QUOTE_SOFT_EXPIRED]: "A swap is almost expired, and it should be presented to the user as expired, though there is still a chance that it will be processed",
95
+ [SpvFromBTCSwapState.CREATED]: "Swap was created, get the bitcoin swap PSBT that should be signed by the user's wallet and then submit it back to the SDK.",
96
+ [SpvFromBTCSwapState.SIGNED]: "Swap bitcoin PSBT was submitted by the client to the SDK",
97
+ [SpvFromBTCSwapState.POSTED]: "Swap bitcoin PSBT sent to the intermediary (LP), waiting for the intermediary co-sign it and broadcast.",
98
+ [SpvFromBTCSwapState.BROADCASTED]: "Intermediary (LP) has co-signed and broadcasted the bitcoin transaction.",
99
+ [SpvFromBTCSwapState.FRONTED]: "Settlement on the destination smart chain was fronted and funds were already received by the user, even before the final settlement.",
100
+ [SpvFromBTCSwapState.BTC_TX_CONFIRMED]: "Bitcoin transaction confirmed with necessary amount of confirmations, wait for automatic settlement by the watchtower or settle manually.",
101
+ [SpvFromBTCSwapState.CLAIMED]: "Swap settled on the smart chain and funds received"
102
+ };
103
+ function isSpvFromBTCSwapInit(obj) {
104
+ return typeof obj === "object" &&
105
+ typeof (obj.quoteId) === "string" &&
106
+ typeof (obj.recipient) === "string" &&
107
+ typeof (obj.vaultOwner) === "string" &&
108
+ typeof (obj.vaultId) === "bigint" &&
109
+ typeof (obj.vaultRequiredConfirmations) === "number" &&
110
+ Array.isArray(obj.vaultTokenMultipliers) && obj.vaultTokenMultipliers.reduce((prev, curr) => prev && typeof (curr) === "bigint", true) &&
111
+ typeof (obj.vaultBtcAddress) === "string" &&
112
+ typeof (obj.vaultUtxo) === "string" &&
113
+ typeof (obj.vaultUtxoValue) === "bigint" &&
114
+ typeof (obj.btcDestinationAddress) === "string" &&
115
+ typeof (obj.btcAmount) === "bigint" &&
116
+ typeof (obj.btcAmountSwap) === "bigint" &&
117
+ typeof (obj.btcAmountGas) === "bigint" &&
118
+ typeof (obj.minimumBtcFeeRate) === "number" &&
119
+ typeof (obj.outputTotalSwap) === "bigint" &&
120
+ typeof (obj.outputSwapToken) === "string" &&
121
+ typeof (obj.outputTotalGas) === "bigint" &&
122
+ typeof (obj.outputGasToken) === "string" &&
123
+ typeof (obj.gasSwapFeeBtc) === "bigint" &&
124
+ typeof (obj.gasSwapFee) === "bigint" &&
125
+ typeof (obj.callerFeeShare) === "bigint" &&
126
+ typeof (obj.frontingFeeShare) === "bigint" &&
127
+ typeof (obj.executionFeeShare) === "bigint" &&
128
+ typeof (obj.genesisSmartChainBlockHeight) === "number" &&
129
+ (obj.gasPricingInfo == null || (0, PriceInfoType_1.isPriceInfoType)(obj.gasPricingInfo)) &&
130
+ (0, ISwap_1.isISwapInit)(obj);
131
+ }
132
+ exports.isSpvFromBTCSwapInit = isSpvFromBTCSwapInit;
133
+ /**
134
+ * New spv vault (UTXO-controlled vault) based swaps for Bitcoin -> Smart chain swaps not requiring
135
+ * any initiation on the destination chain, and with the added possibility for the user to receive
136
+ * a native token on the destination chain as part of the swap (a "gas drop" feature).
137
+ *
138
+ * @category Swaps/Bitcoin → Smart chain
139
+ */
140
+ class SpvFromBTCSwap extends ISwap_1.ISwap {
141
+ constructor(wrapper, initOrObject) {
142
+ if (isSpvFromBTCSwapInit(initOrObject) && initOrObject.url != null)
143
+ initOrObject.url += "/frombtc_spv";
144
+ super(wrapper, initOrObject);
145
+ this.currentVersion = 2;
146
+ this.TYPE = SwapType_1.SwapType.SPV_VAULT_FROM_BTC;
147
+ /**
148
+ * @internal
149
+ */
150
+ this.swapStateDescription = SpvFromBTCSwapStateDescription;
151
+ /**
152
+ * @internal
153
+ */
154
+ this.swapStateName = (state) => SpvFromBTCSwapState[state];
155
+ if (isSpvFromBTCSwapInit(initOrObject)) {
156
+ this._state = SpvFromBTCSwapState.CREATED;
157
+ this.quoteId = initOrObject.quoteId;
158
+ this.recipient = initOrObject.recipient;
159
+ this.vaultOwner = initOrObject.vaultOwner;
160
+ this.vaultId = initOrObject.vaultId;
161
+ this.vaultRequiredConfirmations = initOrObject.vaultRequiredConfirmations;
162
+ this.vaultTokenMultipliers = initOrObject.vaultTokenMultipliers;
163
+ this.vaultBtcAddress = initOrObject.vaultBtcAddress;
164
+ this.vaultUtxo = initOrObject.vaultUtxo;
165
+ this.vaultUtxoValue = initOrObject.vaultUtxoValue;
166
+ this.btcDestinationAddress = initOrObject.btcDestinationAddress;
167
+ this.btcAmount = initOrObject.btcAmount;
168
+ this.btcAmountSwap = initOrObject.btcAmountSwap;
169
+ this.btcAmountGas = initOrObject.btcAmountGas;
170
+ this.minimumBtcFeeRate = initOrObject.minimumBtcFeeRate;
171
+ this.outputTotalSwap = initOrObject.outputTotalSwap;
172
+ this.outputSwapToken = initOrObject.outputSwapToken;
173
+ this.outputTotalGas = initOrObject.outputTotalGas;
174
+ this.outputGasToken = initOrObject.outputGasToken;
175
+ this.gasSwapFeeBtc = initOrObject.gasSwapFeeBtc;
176
+ this.gasSwapFee = initOrObject.gasSwapFee;
177
+ this.callerFeeShare = initOrObject.callerFeeShare;
178
+ this.frontingFeeShare = initOrObject.frontingFeeShare;
179
+ this.executionFeeShare = initOrObject.executionFeeShare;
180
+ this._genesisSmartChainBlockHeight = initOrObject.genesisSmartChainBlockHeight;
181
+ this.gasPricingInfo = initOrObject.gasPricingInfo;
182
+ const vaultAddressType = (0, BitcoinUtils_1.toCoinselectAddressType)((0, BitcoinUtils_1.toOutputScript)(this.wrapper._options.bitcoinNetwork, this.vaultBtcAddress));
183
+ if (vaultAddressType !== "p2tr" && vaultAddressType !== "p2wpkh" && vaultAddressType !== "p2wsh")
184
+ throw new Error("Vault address type must be of witness type: p2tr, p2wpkh, p2wsh");
185
+ }
186
+ else {
187
+ this.quoteId = initOrObject.quoteId;
188
+ this.recipient = initOrObject.recipient;
189
+ this.vaultOwner = initOrObject.vaultOwner;
190
+ this.vaultId = BigInt(initOrObject.vaultId);
191
+ this.vaultRequiredConfirmations = initOrObject.vaultRequiredConfirmations;
192
+ this.vaultTokenMultipliers = initOrObject.vaultTokenMultipliers.map((val) => BigInt(val));
193
+ this.vaultBtcAddress = initOrObject.vaultBtcAddress;
194
+ this.vaultUtxo = initOrObject.vaultUtxo;
195
+ this.vaultUtxoValue = BigInt(initOrObject.vaultUtxoValue);
196
+ this.btcDestinationAddress = initOrObject.btcDestinationAddress;
197
+ this.btcAmount = BigInt(initOrObject.btcAmount);
198
+ this.btcAmountSwap = BigInt(initOrObject.btcAmountSwap);
199
+ this.btcAmountGas = BigInt(initOrObject.btcAmountGas);
200
+ this.minimumBtcFeeRate = initOrObject.minimumBtcFeeRate;
201
+ this.outputTotalSwap = BigInt(initOrObject.outputTotalSwap);
202
+ this.outputSwapToken = initOrObject.outputSwapToken;
203
+ this.outputTotalGas = BigInt(initOrObject.outputTotalGas);
204
+ this.outputGasToken = initOrObject.outputGasToken;
205
+ this.gasSwapFeeBtc = BigInt(initOrObject.gasSwapFeeBtc);
206
+ this.gasSwapFee = BigInt(initOrObject.gasSwapFee);
207
+ this.callerFeeShare = BigInt(initOrObject.callerFeeShare);
208
+ this.frontingFeeShare = BigInt(initOrObject.frontingFeeShare);
209
+ this.executionFeeShare = BigInt(initOrObject.executionFeeShare);
210
+ this._genesisSmartChainBlockHeight = initOrObject.genesisSmartChainBlockHeight;
211
+ this._senderAddress = initOrObject.senderAddress;
212
+ this._claimTxId = initOrObject.claimTxId;
213
+ this._frontTxId = initOrObject.frontTxId;
214
+ this.gasPricingInfo = (0, PriceInfoType_1.deserializePriceInfoType)(initOrObject.gasPricingInfo);
215
+ this.btcTxConfirmedAt = initOrObject.btcTxConfirmedAt;
216
+ this.posted = initOrObject.posted;
217
+ if (initOrObject.data != null)
218
+ this._data = new (this.wrapper._spvWithdrawalDataDeserializer(this._contractVersion))(initOrObject.data);
219
+ }
220
+ this.tryCalculateSwapFee();
221
+ this.logger = (0, Logger_1.getLogger)("SPVFromBTC(" + this.getId() + "): ");
222
+ this._contract = wrapper._contract(this._contractVersion);
223
+ }
224
+ /**
225
+ * @inheritDoc
226
+ * @internal
227
+ */
228
+ upgradeVersion() {
229
+ if (this.version === 1) {
230
+ this.posted = this.initiated && this._data != null;
231
+ this.version = 2;
232
+ }
233
+ }
234
+ /**
235
+ * @inheritDoc
236
+ * @internal
237
+ */
238
+ tryCalculateSwapFee() {
239
+ if (this.swapFeeBtc == null && this.swapFee != null) {
240
+ this.swapFeeBtc = this.swapFee * this.btcAmountSwap / this.getOutputWithoutFee().rawAmount;
241
+ }
242
+ if (this.pricingInfo != null && this.pricingInfo.swapPriceUSatPerToken == null) {
243
+ const priceUsdPerBtc = this.pricingInfo.realPriceUsdPerBitcoin;
244
+ this.pricingInfo = this.wrapper._prices.recomputePriceInfoReceive(this.chainIdentifier, this.btcAmountSwap, this.pricingInfo.satsBaseFee, this.pricingInfo.feePPM, this.getOutputWithoutFee().rawAmount, this.outputSwapToken);
245
+ this.pricingInfo.realPriceUsdPerBitcoin = priceUsdPerBtc;
246
+ }
247
+ }
248
+ //////////////////////////////
249
+ //// Pricing
250
+ /**
251
+ * @inheritDoc
252
+ */
253
+ async refreshPriceData() {
254
+ if (this.pricingInfo == null)
255
+ return;
256
+ const usdPricePerBtc = this.pricingInfo.realPriceUsdPerBitcoin;
257
+ this.pricingInfo = await this.wrapper._prices.isValidAmountReceive(this.chainIdentifier, this.btcAmountSwap, this.pricingInfo.satsBaseFee, this.pricingInfo.feePPM, this.getOutputWithoutFee().rawAmount, this.outputSwapToken, undefined, undefined, this.swapFeeBtc);
258
+ this.pricingInfo.realPriceUsdPerBitcoin = usdPricePerBtc;
259
+ }
260
+ //////////////////////////////
261
+ //// Getters & utils
262
+ /**
263
+ * @inheritDoc
264
+ * @internal
265
+ */
266
+ _getInitiator() {
267
+ return this.recipient;
268
+ }
269
+ /**
270
+ * @inheritDoc
271
+ * @internal
272
+ */
273
+ _getEscrowHash() {
274
+ return this._data?.btcTx?.txid ?? null;
275
+ }
276
+ /**
277
+ * @inheritDoc
278
+ */
279
+ getId() {
280
+ return this.quoteId + this._randomNonce;
281
+ }
282
+ /**
283
+ * @inheritDoc
284
+ */
285
+ getQuoteExpiry() {
286
+ return this.expiry - 20 * 1000;
287
+ }
288
+ /**
289
+ * @inheritDoc
290
+ * @internal
291
+ */
292
+ _verifyQuoteDefinitelyExpired() {
293
+ return Promise.resolve(this.expiry < Date.now());
294
+ }
295
+ /**
296
+ * @inheritDoc
297
+ * @internal
298
+ */
299
+ _verifyQuoteValid() {
300
+ return Promise.resolve(this.expiry > Date.now() && (this._state === SpvFromBTCSwapState.CREATED || this._state === SpvFromBTCSwapState.QUOTE_SOFT_EXPIRED));
301
+ }
302
+ /**
303
+ * @inheritDoc
304
+ */
305
+ getOutputAddress() {
306
+ return this.recipient;
307
+ }
308
+ /**
309
+ * @inheritDoc
310
+ */
311
+ getOutputTxId() {
312
+ return this._frontTxId ?? this._claimTxId ?? null;
313
+ }
314
+ /**
315
+ * @inheritDoc
316
+ */
317
+ getInputAddress() {
318
+ return this._senderAddress ?? null;
319
+ }
320
+ /**
321
+ * @inheritDoc
322
+ */
323
+ getInputTxId() {
324
+ return this._data?.btcTx?.txid ?? null;
325
+ }
326
+ /**
327
+ * @inheritDoc
328
+ */
329
+ requiresAction() {
330
+ return this._state === SpvFromBTCSwapState.BTC_TX_CONFIRMED;
331
+ }
332
+ /**
333
+ * @inheritDoc
334
+ */
335
+ isFinished() {
336
+ return this.isSuccessful() || this.isFailed() || this.isQuoteExpired();
337
+ }
338
+ /**
339
+ * @inheritDoc
340
+ */
341
+ isClaimable() {
342
+ return this._state === SpvFromBTCSwapState.BTC_TX_CONFIRMED;
343
+ }
344
+ /**
345
+ * @inheritDoc
346
+ */
347
+ isSuccessful() {
348
+ return this._state === SpvFromBTCSwapState.FRONTED || this._state === SpvFromBTCSwapState.CLAIMED;
349
+ }
350
+ /**
351
+ * @inheritDoc
352
+ */
353
+ isFailed() {
354
+ return this._state === SpvFromBTCSwapState.FAILED || this._state === SpvFromBTCSwapState.DECLINED || this._state === SpvFromBTCSwapState.CLOSED;
355
+ }
356
+ /**
357
+ * @inheritDoc
358
+ */
359
+ isInProgress() {
360
+ return this._state === SpvFromBTCSwapState.POSTED ||
361
+ this._state === SpvFromBTCSwapState.BROADCASTED ||
362
+ this._state === SpvFromBTCSwapState.BTC_TX_CONFIRMED;
363
+ }
364
+ /**
365
+ * @inheritDoc
366
+ */
367
+ isQuoteExpired() {
368
+ return this._state === SpvFromBTCSwapState.QUOTE_EXPIRED;
369
+ }
370
+ /**
371
+ * @inheritDoc
372
+ */
373
+ isQuoteSoftExpired() {
374
+ return this._state === SpvFromBTCSwapState.QUOTE_EXPIRED || this._state === SpvFromBTCSwapState.QUOTE_SOFT_EXPIRED;
375
+ }
376
+ /**
377
+ * Returns the data about used spv vault (UTXO-controlled vault) to perform the swap
378
+ */
379
+ getSpvVaultData() {
380
+ return {
381
+ owner: this.vaultOwner,
382
+ vaultId: this.vaultId,
383
+ utxo: this.vaultUtxo
384
+ };
385
+ }
386
+ //////////////////////////////
387
+ //// Amounts & fees
388
+ /**
389
+ * Returns the input BTC amount in sats without any fees
390
+ *
391
+ * @internal
392
+ */
393
+ getInputSwapAmountWithoutFee() {
394
+ return (this.btcAmountSwap - this.swapFeeBtc) * 100000n / (100000n + this.callerFeeShare + this.frontingFeeShare + this.executionFeeShare);
395
+ }
396
+ /**
397
+ * Returns the input gas BTC amount in sats without any fees
398
+ *
399
+ * @internal
400
+ */
401
+ getInputGasAmountWithoutFee() {
402
+ return (this.btcAmountGas - this.gasSwapFeeBtc) * 100000n / (100000n + this.callerFeeShare + this.frontingFeeShare);
403
+ }
404
+ /**
405
+ * Returns to total input BTC amount in sats without any fees (this is BTC amount for the swap + BTC amount
406
+ * for the gas drop).
407
+ *
408
+ * @internal
409
+ */
410
+ getInputAmountWithoutFee() {
411
+ return this.getInputSwapAmountWithoutFee() + this.getInputGasAmountWithoutFee();
412
+ }
413
+ /**
414
+ * Returns the swap output amount without any fees, this value is therefore always higher than
415
+ * the actual received output.
416
+ *
417
+ * @internal
418
+ */
419
+ getOutputWithoutFee() {
420
+ return (0, TokenAmount_1.toTokenAmount)((this.outputTotalSwap * (100000n + this.callerFeeShare + this.frontingFeeShare + this.executionFeeShare) / 100000n) + (this.swapFee ?? 0n), this.wrapper._tokens[this.outputSwapToken], this.wrapper._prices, this.pricingInfo);
421
+ }
422
+ /**
423
+ * Returns the swap fee charged by the intermediary (LP) on this swap
424
+ *
425
+ * @internal
426
+ */
427
+ getSwapFee() {
428
+ if (this.pricingInfo == null)
429
+ throw new Error("No pricing info known, cannot estimate fee!");
430
+ const outputToken = this.wrapper._tokens[this.outputSwapToken];
431
+ const gasSwapFeeInOutputToken = this.gasSwapFeeBtc
432
+ * (10n ** BigInt(outputToken.decimals))
433
+ * 1000000n
434
+ / this.pricingInfo.swapPriceUSatPerToken;
435
+ const feeWithoutBaseFee = this.swapFeeBtc - this.pricingInfo.satsBaseFee;
436
+ const swapFeePPM = feeWithoutBaseFee * 1000000n / (this.btcAmount - this.swapFeeBtc - this.gasSwapFeeBtc);
437
+ const amountInSrcToken = (0, TokenAmount_1.toTokenAmount)(this.swapFeeBtc + this.gasSwapFeeBtc, Token_1.BitcoinTokens.BTC, this.wrapper._prices, this.pricingInfo);
438
+ return {
439
+ amountInSrcToken,
440
+ amountInDstToken: (0, TokenAmount_1.toTokenAmount)(this.swapFee + gasSwapFeeInOutputToken, outputToken, this.wrapper._prices, this.pricingInfo),
441
+ currentUsdValue: amountInSrcToken.currentUsdValue,
442
+ usdValue: amountInSrcToken.usdValue,
443
+ pastUsdValue: amountInSrcToken.pastUsdValue,
444
+ composition: {
445
+ base: (0, TokenAmount_1.toTokenAmount)(this.pricingInfo.satsBaseFee, Token_1.BitcoinTokens.BTC, this.wrapper._prices, this.pricingInfo),
446
+ percentage: (0, PercentagePPM_1.ppmToPercentage)(swapFeePPM)
447
+ }
448
+ };
449
+ }
450
+ /**
451
+ * Returns the fee to be paid to watchtowers on the destination chain to automatically
452
+ * process and settle this swap without requiring any user interaction
453
+ *
454
+ * @internal
455
+ */
456
+ getWatchtowerFee() {
457
+ if (this.pricingInfo == null)
458
+ throw new Error("No pricing info known, cannot estimate fee!");
459
+ const totalFeeShare = this.callerFeeShare + this.frontingFeeShare;
460
+ const outputToken = this.wrapper._tokens[this.outputSwapToken];
461
+ const watchtowerFeeInOutputToken = this.getInputGasAmountWithoutFee() * totalFeeShare
462
+ * (10n ** BigInt(outputToken.decimals))
463
+ * 1000000n
464
+ / this.pricingInfo.swapPriceUSatPerToken
465
+ / 100000n;
466
+ const feeBtc = this.getInputAmountWithoutFee() * (totalFeeShare + this.executionFeeShare) / 100000n;
467
+ const amountInSrcToken = (0, TokenAmount_1.toTokenAmount)(feeBtc, Token_1.BitcoinTokens.BTC, this.wrapper._prices, this.pricingInfo);
468
+ return {
469
+ amountInSrcToken,
470
+ amountInDstToken: (0, TokenAmount_1.toTokenAmount)((this.outputTotalSwap * (totalFeeShare + this.executionFeeShare) / 100000n) + watchtowerFeeInOutputToken, outputToken, this.wrapper._prices, this.pricingInfo),
471
+ currentUsdValue: amountInSrcToken.currentUsdValue,
472
+ usdValue: amountInSrcToken.usdValue,
473
+ pastUsdValue: amountInSrcToken.pastUsdValue
474
+ };
475
+ }
476
+ /**
477
+ * @inheritDoc
478
+ */
479
+ getFee() {
480
+ const swapFee = this.getSwapFee();
481
+ const watchtowerFee = this.getWatchtowerFee();
482
+ const amountInSrcToken = (0, TokenAmount_1.toTokenAmount)(swapFee.amountInSrcToken.rawAmount + watchtowerFee.amountInSrcToken.rawAmount, Token_1.BitcoinTokens.BTC, this.wrapper._prices, this.pricingInfo);
483
+ return {
484
+ amountInSrcToken,
485
+ amountInDstToken: (0, TokenAmount_1.toTokenAmount)(swapFee.amountInDstToken.rawAmount + watchtowerFee.amountInDstToken.rawAmount, this.wrapper._tokens[this.outputSwapToken], this.wrapper._prices, this.pricingInfo),
486
+ currentUsdValue: amountInSrcToken.currentUsdValue,
487
+ usdValue: amountInSrcToken.usdValue,
488
+ pastUsdValue: amountInSrcToken.pastUsdValue
489
+ };
490
+ }
491
+ /**
492
+ * @inheritDoc
493
+ */
494
+ getFeeBreakdown() {
495
+ return [
496
+ {
497
+ type: FeeType_1.FeeType.SWAP,
498
+ fee: this.getSwapFee()
499
+ },
500
+ {
501
+ type: FeeType_1.FeeType.NETWORK_OUTPUT,
502
+ fee: this.getWatchtowerFee()
503
+ }
504
+ ];
505
+ }
506
+ /**
507
+ * @inheritDoc
508
+ */
509
+ getOutputToken() {
510
+ return this.wrapper._tokens[this.outputSwapToken];
511
+ }
512
+ /**
513
+ * @inheritDoc
514
+ */
515
+ getOutput() {
516
+ return (0, TokenAmount_1.toTokenAmount)(this.outputTotalSwap, this.wrapper._tokens[this.outputSwapToken], this.wrapper._prices, this.pricingInfo);
517
+ }
518
+ /**
519
+ * @inheritDoc
520
+ */
521
+ getGasDropOutput() {
522
+ return (0, TokenAmount_1.toTokenAmount)(this.outputTotalGas, this.wrapper._tokens[this.outputGasToken], this.wrapper._prices, this.gasPricingInfo);
523
+ }
524
+ /**
525
+ * @inheritDoc
526
+ */
527
+ getInputWithoutFee() {
528
+ return (0, TokenAmount_1.toTokenAmount)(this.getInputAmountWithoutFee(), Token_1.BitcoinTokens.BTC, this.wrapper._prices, this.pricingInfo);
529
+ }
530
+ /**
531
+ * @inheritDoc
532
+ */
533
+ getInputToken() {
534
+ return Token_1.BitcoinTokens.BTC;
535
+ }
536
+ /**
537
+ * @inheritDoc
538
+ */
539
+ getInput() {
540
+ return (0, TokenAmount_1.toTokenAmount)(this.btcAmount, Token_1.BitcoinTokens.BTC, this.wrapper._prices, this.pricingInfo);
541
+ }
542
+ //////////////////////////////
543
+ //// Bitcoin tx
544
+ /**
545
+ * @inheritDoc
546
+ */
547
+ getRequiredConfirmationsCount() {
548
+ return this.vaultRequiredConfirmations;
549
+ }
550
+ /**
551
+ * Returns raw transaction details that can be used to manually create a swap PSBT. It is better to use
552
+ * the {@link getPsbt} or {@link getFundedPsbt} function retrieve an already prepared PSBT.
553
+ */
554
+ async getTransactionDetails() {
555
+ const [txId, voutStr] = this.vaultUtxo.split(":");
556
+ const vaultScript = (0, BitcoinUtils_1.toOutputScript)(this.wrapper._options.bitcoinNetwork, this.vaultBtcAddress);
557
+ const out2script = (0, BitcoinUtils_1.toOutputScript)(this.wrapper._options.bitcoinNetwork, this.btcDestinationAddress);
558
+ const opReturnData = this._contract.toOpReturnData(this.recipient, [
559
+ this.outputTotalSwap / this.vaultTokenMultipliers[0],
560
+ this.outputTotalGas / this.vaultTokenMultipliers[1]
561
+ ]);
562
+ const out1script = buffer_1.Buffer.concat([
563
+ opReturnData.length > 75 ? buffer_1.Buffer.from([0x6a, 0x4c, opReturnData.length]) : buffer_1.Buffer.from([0x6a, opReturnData.length]),
564
+ opReturnData
565
+ ]);
566
+ if (this.callerFeeShare < 0n || this.callerFeeShare > 0xfffffn)
567
+ throw new Error("Caller fee out of bounds!");
568
+ if (this.frontingFeeShare < 0n || this.frontingFeeShare > 0xfffffn)
569
+ throw new Error("Fronting fee out of bounds!");
570
+ if (this.executionFeeShare < 0n || this.executionFeeShare > 0xfffffn)
571
+ throw new Error("Execution fee out of bounds!");
572
+ const nSequence0 = 0x80000000n | (this.callerFeeShare & 0xfffffn) | (this.frontingFeeShare & 1047552n) << 10n;
573
+ const nSequence1 = 0x80000000n | (this.executionFeeShare & 0xfffffn) | (this.frontingFeeShare & 1023n) << 20n;
574
+ return {
575
+ in0txid: txId,
576
+ in0vout: parseInt(voutStr),
577
+ in0sequence: Number(nSequence0),
578
+ vaultAmount: this.vaultUtxoValue,
579
+ vaultScript,
580
+ in1sequence: Number(nSequence1),
581
+ out1script,
582
+ out2amount: this.btcAmount,
583
+ out2script,
584
+ locktime: 500000000 + Math.floor(Math.random() * 1000000000) //Use this as a random salt to make the btc txId unique!
585
+ };
586
+ }
587
+ /**
588
+ * Returns the raw PSBT (not funded), the wallet should fund the PSBT (add its inputs) and importantly **set the nSequence field of the
589
+ * 2nd input** (input 1 - indexing from 0) to the value returned in `in1sequence`, sign the PSBT and then pass
590
+ * it back to the swap with {@link submitPsbt} function. The transaction should use at least the returned `feeRate`
591
+ * sats/vB as the transaction fee.
592
+ */
593
+ async getPsbt() {
594
+ const res = await this.getTransactionDetails();
595
+ const psbt = new btc_signer_1.Transaction({
596
+ allowUnknownOutputs: true,
597
+ allowLegacyWitnessUtxo: true,
598
+ lockTime: res.locktime
599
+ });
600
+ psbt.addInput({
601
+ txid: res.in0txid,
602
+ index: res.in0vout,
603
+ witnessUtxo: {
604
+ amount: res.vaultAmount,
605
+ script: res.vaultScript
606
+ },
607
+ sequence: res.in0sequence
608
+ });
609
+ psbt.addOutput({
610
+ amount: res.vaultAmount,
611
+ script: res.vaultScript
612
+ });
613
+ psbt.addOutput({
614
+ amount: 0n,
615
+ script: res.out1script
616
+ });
617
+ psbt.addOutput({
618
+ amount: res.out2amount,
619
+ script: res.out2script
620
+ });
621
+ const serializedPsbt = buffer_1.Buffer.from(psbt.toPSBT());
622
+ return {
623
+ psbt,
624
+ psbtHex: serializedPsbt.toString("hex"),
625
+ psbtBase64: serializedPsbt.toString("base64"),
626
+ in1sequence: res.in1sequence,
627
+ feeRate: this.minimumBtcFeeRate
628
+ };
629
+ }
630
+ /**
631
+ * Returns the PSBT that is already funded with wallet's UTXOs (runs a coin-selection algorithm to choose UTXOs to use),
632
+ * also returns inputs indices that need to be signed by the wallet before submitting the PSBT back to the SDK with
633
+ * {@link submitPsbt}
634
+ *
635
+ * @remarks
636
+ * Note that when passing the `feeRate` argument, the fee must be at least {@link minimumBtcFeeRate} sats/vB.
637
+ *
638
+ * @param _bitcoinWallet Sender's bitcoin wallet
639
+ * @param feeRate Optional fee rate in sats/vB for the transaction
640
+ * @param additionalOutputs additional outputs to add to the PSBT - can be used to collect fees from users
641
+ * @param utxos Pre-fetched list of UTXOs to spend from
642
+ * @param spendFully Instructs the wallet to spend all the passed UTXOs in the transaction without creating any
643
+ * change output, if the `feeRate` is passed, it will also enforce that the feeRate in sats/vB for the resulting
644
+ * transaction is not more than 50% and 10 sats/vB larger (considering also the CPFP adjustments)
645
+ */
646
+ async getFundedPsbt(_bitcoinWallet, feeRate, additionalOutputs, utxos, spendFully) {
647
+ const bitcoinWallet = (0, BitcoinWalletUtils_1.toBitcoinWallet)(_bitcoinWallet, this.wrapper._btcRpc, this.wrapper._options.bitcoinNetwork);
648
+ if (feeRate != null) {
649
+ if (feeRate < this.minimumBtcFeeRate)
650
+ throw new Error("Bitcoin tx fee needs to be at least " + this.minimumBtcFeeRate + " sats/vB");
651
+ }
652
+ else {
653
+ feeRate = Math.max(this.minimumBtcFeeRate, await bitcoinWallet.getFeeRate());
654
+ }
655
+ let { psbt, in1sequence } = await this.getPsbt();
656
+ if (additionalOutputs != null)
657
+ additionalOutputs.forEach(output => {
658
+ psbt.addOutput({
659
+ amount: output.amount,
660
+ script: output.outputScript ?? (0, BitcoinUtils_1.toOutputScript)(this.wrapper._options.bitcoinNetwork, output.address)
661
+ });
662
+ });
663
+ psbt = await bitcoinWallet.fundPsbt(psbt, feeRate, utxos, spendFully);
664
+ psbt.updateInput(1, { sequence: in1sequence });
665
+ //Sign every input except the first one
666
+ const signInputs = [];
667
+ for (let i = 1; i < psbt.inputsLength; i++) {
668
+ signInputs.push(i);
669
+ }
670
+ const serializedPsbt = buffer_1.Buffer.from(psbt.toPSBT());
671
+ return {
672
+ psbt,
673
+ psbtHex: serializedPsbt.toString("hex"),
674
+ psbtBase64: serializedPsbt.toString("base64"),
675
+ signInputs,
676
+ feeRate
677
+ };
678
+ }
679
+ /**
680
+ * @inheritDoc
681
+ */
682
+ async submitPsbt(_psbt) {
683
+ const psbt = (0, BitcoinUtils_1.parsePsbtTransaction)(_psbt);
684
+ //Ensure not expired
685
+ if (this.expiry < Date.now()) {
686
+ throw new Error("Quote expired!");
687
+ }
688
+ //Ensure valid state
689
+ if (this._state !== SpvFromBTCSwapState.QUOTE_SOFT_EXPIRED && this._state !== SpvFromBTCSwapState.CREATED) {
690
+ throw new Error("Invalid swap state!");
691
+ }
692
+ if (this.url == null)
693
+ throw new Error("LP URL not known, cannot submit PSBT!");
694
+ //Ensure all inputs except the 1st are finalized
695
+ for (let i = 1; i < psbt.inputsLength; i++) {
696
+ if ((0, btc_signer_1.getInputType)(psbt.getInput(i)).txType === "legacy")
697
+ throw new Error("Legacy (non-segwit) inputs are not allowed in the transaction!");
698
+ psbt.finalizeIdx(i);
699
+ }
700
+ const btcTx = await this.wrapper._btcRpc.parseTransaction(buffer_1.Buffer.from(psbt.toBytes(true)).toString("hex"));
701
+ const data = await this._contract.getWithdrawalData(btcTx);
702
+ this.logger.debug("submitPsbt(): parsed withdrawal data: ", data);
703
+ //Verify correct withdrawal data
704
+ if (!data.isRecipient(this.recipient) ||
705
+ data.rawAmounts[0] * this.vaultTokenMultipliers[0] !== this.outputTotalSwap ||
706
+ (data.rawAmounts[1] ?? 0n) * this.vaultTokenMultipliers[1] !== this.outputTotalGas ||
707
+ data.callerFeeRate !== this.callerFeeShare ||
708
+ data.frontingFeeRate !== this.frontingFeeShare ||
709
+ data.executionFeeRate !== this.executionFeeShare ||
710
+ data.getSpentVaultUtxo() !== this.vaultUtxo ||
711
+ BigInt(data.getNewVaultBtcAmount()) !== this.vaultUtxoValue ||
712
+ !data.getNewVaultScript().equals((0, BitcoinUtils_1.toOutputScript)(this.wrapper._options.bitcoinNetwork, this.vaultBtcAddress)) ||
713
+ data.getExecutionData() != null) {
714
+ throw new Error("Invalid withdrawal tx data submitted!");
715
+ }
716
+ //Verify correct LP output
717
+ const lpOutput = psbt.getOutput(2);
718
+ if (lpOutput.script == null ||
719
+ lpOutput.amount !== this.btcAmount ||
720
+ !(0, BitcoinUtils_1.toOutputScript)(this.wrapper._options.bitcoinNetwork, this.btcDestinationAddress).equals(buffer_1.Buffer.from(lpOutput.script))) {
721
+ throw new Error("Invalid LP bitcoin output in transaction!");
722
+ }
723
+ //Verify vault utxo not spent yet
724
+ if (await this.wrapper._btcRpc.isSpent(this.vaultUtxo)) {
725
+ throw new Error("Vault UTXO already spent, please create new swap!");
726
+ }
727
+ //Verify tx is parsable by the contract
728
+ try {
729
+ await this._contract.checkWithdrawalTx(data);
730
+ }
731
+ catch (e) {
732
+ throw new Error("Transaction not parsable by the contract: " + (e.message ?? e.toString()));
733
+ }
734
+ //Ensure still not expired
735
+ if (this.expiry < Date.now()) {
736
+ throw new Error("Quote expired!");
737
+ }
738
+ this._data = data;
739
+ this.initiated = true;
740
+ this.posted = true;
741
+ await this._saveAndEmit(SpvFromBTCSwapState.SIGNED);
742
+ try {
743
+ await this.wrapper._lpApi.initSpvFromBTC(this.chainIdentifier, this.url, {
744
+ quoteId: this.quoteId,
745
+ psbtHex: buffer_1.Buffer.from(psbt.toPSBT(0)).toString("hex")
746
+ });
747
+ await this._saveAndEmit(SpvFromBTCSwapState.POSTED);
748
+ }
749
+ catch (e) {
750
+ await this._saveAndEmit(SpvFromBTCSwapState.DECLINED);
751
+ throw e;
752
+ }
753
+ return this._data.getTxId();
754
+ }
755
+ /**
756
+ * @inheritDoc
757
+ */
758
+ async estimateBitcoinFee(_bitcoinWallet, feeRate) {
759
+ const bitcoinWallet = (0, BitcoinWalletUtils_1.toBitcoinWallet)(_bitcoinWallet, this.wrapper._btcRpc, this.wrapper._options.bitcoinNetwork);
760
+ const txFee = await bitcoinWallet.getFundedPsbtFee((await this.getPsbt()).psbt, feeRate);
761
+ if (txFee == null)
762
+ return null;
763
+ return (0, TokenAmount_1.toTokenAmount)(BigInt(txFee), Token_1.BitcoinTokens.BTC, this.wrapper._prices, this.pricingInfo);
764
+ }
765
+ /**
766
+ * @inheritDoc
767
+ */
768
+ async sendBitcoinTransaction(wallet, feeRate, utxos, spendFully) {
769
+ const { psbt, psbtBase64, psbtHex, signInputs } = await this.getFundedPsbt(wallet, feeRate, undefined, utxos, spendFully);
770
+ let signedPsbt;
771
+ if ((0, IBitcoinWallet_1.isIBitcoinWallet)(wallet)) {
772
+ signedPsbt = await wallet.signPsbt(psbt, signInputs);
773
+ }
774
+ else {
775
+ signedPsbt = await wallet.signPsbt({
776
+ psbt, psbtHex, psbtBase64
777
+ }, signInputs);
778
+ }
779
+ return await this.submitPsbt(signedPsbt);
780
+ }
781
+ /**
782
+ * Executes the swap with the provided bitcoin wallet
783
+ *
784
+ * @param wallet Bitcoin wallet to use to sign the bitcoin transaction
785
+ * @param callbacks Callbacks to track the progress of the swap
786
+ * @param options Optional options for the swap like feeRate, AbortSignal, and timeouts/intervals
787
+ *
788
+ * @returns {boolean} Whether a swap was settled automatically by swap watchtowers or requires manual claim by the
789
+ * user, in case `false` is returned the user should call the {@link claim} function to settle the swap on the
790
+ * destination manually
791
+ */
792
+ async execute(wallet, callbacks, options) {
793
+ if (this._state === SpvFromBTCSwapState.CLOSED)
794
+ throw new Error("Swap encountered a catastrophic failure!");
795
+ if (this._state === SpvFromBTCSwapState.FAILED)
796
+ throw new Error("Swap failed!");
797
+ if (this._state === SpvFromBTCSwapState.DECLINED)
798
+ throw new Error("Swap execution already declined by the LP!");
799
+ if (this._state === SpvFromBTCSwapState.QUOTE_EXPIRED)
800
+ throw new Error("Swap quote expired!");
801
+ if (this._state === SpvFromBTCSwapState.CLAIMED || this._state === SpvFromBTCSwapState.FRONTED)
802
+ throw new Error("Swap already settled or fronted!");
803
+ if (this._state === SpvFromBTCSwapState.CREATED) {
804
+ const txId = await this.sendBitcoinTransaction(wallet, options?.feeRate, options?.utxos, options?.spendFully);
805
+ if (callbacks?.onSourceTransactionSent != null)
806
+ callbacks.onSourceTransactionSent(txId);
807
+ }
808
+ if (this._state === SpvFromBTCSwapState.POSTED || this._state === SpvFromBTCSwapState.BROADCASTED) {
809
+ const txId = await this.waitForBitcoinTransaction(callbacks?.onSourceTransactionConfirmationStatus, options?.btcTxCheckIntervalSeconds, options?.abortSignal);
810
+ if (callbacks?.onSourceTransactionConfirmed != null)
811
+ callbacks.onSourceTransactionConfirmed(txId);
812
+ }
813
+ // @ts-ignore
814
+ if (this._state === SpvFromBTCSwapState.CLAIMED || this._state === SpvFromBTCSwapState.FRONTED)
815
+ return true;
816
+ if (this._state === SpvFromBTCSwapState.BTC_TX_CONFIRMED) {
817
+ const success = await this.waitTillClaimedOrFronted(options?.maxWaitTillAutomaticSettlementSeconds ?? 60, options?.abortSignal);
818
+ if (success && callbacks?.onSwapSettled != null)
819
+ callbacks.onSwapSettled(this.getOutputTxId());
820
+ return success;
821
+ }
822
+ throw new Error("Unexpected state reached!");
823
+ }
824
+ /**
825
+ * @internal
826
+ */
827
+ async _getExecutionStatus(options) {
828
+ const state = this._state;
829
+ const now = Date.now();
830
+ let confirmations;
831
+ let bitcoinPaymentStatus = "inactive";
832
+ let destinationSettlementStatus = "inactive";
833
+ let buildCurrentAction = async () => undefined;
834
+ switch (state) {
835
+ case SpvFromBTCSwapState.QUOTE_EXPIRED:
836
+ case SpvFromBTCSwapState.DECLINED:
837
+ case SpvFromBTCSwapState.FAILED:
838
+ bitcoinPaymentStatus = "expired";
839
+ break;
840
+ case SpvFromBTCSwapState.CREATED: {
841
+ const quoteValid = await this._verifyQuoteValid();
842
+ bitcoinPaymentStatus = quoteValid ? "awaiting" : "soft_expired";
843
+ if (quoteValid) {
844
+ buildCurrentAction = this._buildDepositPsbtAction.bind(this);
845
+ }
846
+ break;
847
+ }
848
+ case SpvFromBTCSwapState.QUOTE_SOFT_EXPIRED:
849
+ case SpvFromBTCSwapState.SIGNED:
850
+ case SpvFromBTCSwapState.POSTED:
851
+ case SpvFromBTCSwapState.BROADCASTED:
852
+ case SpvFromBTCSwapState.FRONTED: {
853
+ const bitcoinPayment = await this.getBitcoinPayment();
854
+ let bitcoinConfirmationDelay = -1;
855
+ let knownBitcoinPaymentStatus;
856
+ if (bitcoinPayment != null) {
857
+ if (bitcoinPayment.confirmations >= bitcoinPayment.targetConfirmations) {
858
+ knownBitcoinPaymentStatus = "confirmed";
859
+ }
860
+ else {
861
+ const result = await this.wrapper._btcRpc.getConfirmationDelay(bitcoinPayment.btcTx, bitcoinPayment.targetConfirmations);
862
+ confirmations = {
863
+ current: bitcoinPayment.confirmations,
864
+ target: bitcoinPayment.targetConfirmations,
865
+ etaSeconds: result ?? -1
866
+ };
867
+ knownBitcoinPaymentStatus = "received";
868
+ bitcoinConfirmationDelay = result ?? -1;
869
+ }
870
+ }
871
+ if (state === SpvFromBTCSwapState.QUOTE_SOFT_EXPIRED)
872
+ bitcoinPaymentStatus = knownBitcoinPaymentStatus ?? "soft_expired";
873
+ if (state === SpvFromBTCSwapState.POSTED || state === SpvFromBTCSwapState.SIGNED)
874
+ bitcoinPaymentStatus = knownBitcoinPaymentStatus ?? "awaiting";
875
+ if (state === SpvFromBTCSwapState.BROADCASTED)
876
+ bitcoinPaymentStatus = knownBitcoinPaymentStatus ?? "received";
877
+ destinationSettlementStatus = "inactive";
878
+ if (state === SpvFromBTCSwapState.FRONTED) {
879
+ bitcoinPaymentStatus = knownBitcoinPaymentStatus ?? "received";
880
+ destinationSettlementStatus = "settled";
881
+ }
882
+ if (state === SpvFromBTCSwapState.SIGNED ||
883
+ state === SpvFromBTCSwapState.POSTED ||
884
+ state === SpvFromBTCSwapState.BROADCASTED) {
885
+ buildCurrentAction = this._buildWaitBitcoinConfirmationsAction.bind(this, bitcoinConfirmationDelay);
886
+ }
887
+ break;
888
+ }
889
+ case SpvFromBTCSwapState.BTC_TX_CONFIRMED:
890
+ bitcoinPaymentStatus = "confirmed";
891
+ if (this.btcTxConfirmedAt == null ||
892
+ options?.maxWaitTillAutomaticSettlementSeconds === 0 ||
893
+ (now - this.btcTxConfirmedAt) > (options?.maxWaitTillAutomaticSettlementSeconds ?? 60) * 1000) {
894
+ destinationSettlementStatus = "awaiting_manual";
895
+ buildCurrentAction = this._buildClaimSmartChainTxAction.bind(this);
896
+ }
897
+ else {
898
+ destinationSettlementStatus = "awaiting_automatic";
899
+ buildCurrentAction = this._buildWaitSettlementAction.bind(this, options?.maxWaitTillAutomaticSettlementSeconds);
900
+ }
901
+ break;
902
+ case SpvFromBTCSwapState.CLAIMED:
903
+ bitcoinPaymentStatus = "confirmed";
904
+ destinationSettlementStatus = "settled";
905
+ break;
906
+ case SpvFromBTCSwapState.CLOSED:
907
+ bitcoinPaymentStatus = "confirmed";
908
+ destinationSettlementStatus = "expired";
909
+ break;
910
+ }
911
+ if (bitcoinPaymentStatus === "confirmed") {
912
+ confirmations = {
913
+ current: this.getRequiredConfirmationsCount(),
914
+ target: this.getRequiredConfirmationsCount(),
915
+ etaSeconds: 0
916
+ };
917
+ }
918
+ return {
919
+ steps: [
920
+ {
921
+ type: "Payment",
922
+ side: "source",
923
+ chain: "BITCOIN",
924
+ title: "Bitcoin payment",
925
+ description: "Sign and submit the Bitcoin swap PSBT, then wait for the bitcoin transaction to confirm",
926
+ status: bitcoinPaymentStatus,
927
+ confirmations,
928
+ initTxId: this._data?.btcTx?.txid,
929
+ settleTxId: bitcoinPaymentStatus === "confirmed" ? this._data?.btcTx?.txid : undefined
930
+ },
931
+ {
932
+ type: "Settlement",
933
+ side: "destination",
934
+ chain: this.chainIdentifier,
935
+ title: "Destination settlement",
936
+ description: `Wait for automatic settlement on the ${this.chainIdentifier} side, or settle manually if it takes too long`,
937
+ status: destinationSettlementStatus,
938
+ initTxId: this._frontTxId ?? this._claimTxId,
939
+ settleTxId: this._frontTxId ?? this._claimTxId
940
+ }
941
+ ],
942
+ buildCurrentAction,
943
+ state
944
+ };
945
+ }
946
+ /**
947
+ * @inheritDoc
948
+ * @internal
949
+ */
950
+ async _submitExecutionTransactions(txs, abortSignal, requiredStates, idempotent) {
951
+ if (txs.length === 0)
952
+ throw new Error("Need to submit at least 1 transaction in the array, submitted empty array of transactions!");
953
+ // Handle idempotent calls
954
+ if (idempotent) {
955
+ let idempotencyTriggered = false;
956
+ const txIds = [];
957
+ for (let tx of txs) {
958
+ let parsedTx;
959
+ if (typeof (tx) === "string") {
960
+ try {
961
+ parsedTx = await this.wrapper._chain.deserializeSignedTx(tx);
962
+ }
963
+ catch (e) { }
964
+ try {
965
+ parsedTx = (0, BitcoinUtils_1.parsePsbtTransaction)(tx);
966
+ }
967
+ catch (e) { }
968
+ }
969
+ else {
970
+ parsedTx = tx;
971
+ }
972
+ if (parsedTx == null) {
973
+ this.logger.debug("_submitExecutionTransactions(): Failed to parse provided execution transaction: ", tx);
974
+ continue;
975
+ }
976
+ if (parsedTx instanceof btc_signer_1.Transaction) {
977
+ // Bitcoin tx
978
+ const btcTx = await this.wrapper._btcRpc.parseTransaction(buffer_1.Buffer.from(parsedTx.toBytes(true)).toString("hex"));
979
+ if (btcTx.txid === this._data?.getTxId()) {
980
+ if (this._state !== SpvFromBTCSwapState.SIGNED && this._state !== SpvFromBTCSwapState.DECLINED)
981
+ idempotencyTriggered = true;
982
+ }
983
+ txIds.push(btcTx.txid);
984
+ }
985
+ else {
986
+ // SC tx
987
+ if (this.wrapper._chain.getTxId != null) {
988
+ const txId = await this.wrapper._chain.getTxId(parsedTx);
989
+ if (this._claimTxId === txId)
990
+ idempotencyTriggered = true;
991
+ txIds.push(txId);
992
+ }
993
+ }
994
+ }
995
+ if (idempotencyTriggered)
996
+ return txIds;
997
+ }
998
+ if (requiredStates != null && !requiredStates.includes(this._state))
999
+ throw new Error("Swap state has changed before transactions were submitted!");
1000
+ if (this._state === SpvFromBTCSwapState.CREATED || this._state === SpvFromBTCSwapState.QUOTE_SOFT_EXPIRED) {
1001
+ let psbt;
1002
+ if (txs.length !== 1)
1003
+ throw new Error("Need to submit exactly 1 signed PSBT!");
1004
+ if (typeof (txs[0]) !== "string" && !(txs[0] instanceof btc_signer_1.Transaction))
1005
+ throw new Error("Must submit a valid PSBT as hex/base64 string or `@scure/btc-signer` Transaction object!");
1006
+ psbt = txs[0];
1007
+ return [await this.submitPsbt(psbt)];
1008
+ }
1009
+ if (this._state === SpvFromBTCSwapState.BTC_TX_CONFIRMED) {
1010
+ const parsedTxs = [];
1011
+ for (let tx of txs) {
1012
+ parsedTxs.push(typeof (tx) === "string" ? await this.wrapper._chain.deserializeSignedTx(tx) : tx);
1013
+ }
1014
+ const txIds = await this.wrapper._chain.sendSignedAndConfirm(parsedTxs, true, abortSignal, false);
1015
+ await this.waitTillClaimed(undefined, abortSignal);
1016
+ return txIds;
1017
+ }
1018
+ throw new Error("Invalid swap state for transaction submission!");
1019
+ }
1020
+ /**
1021
+ * @internal
1022
+ */
1023
+ async _buildDepositPsbtAction(actionOptions) {
1024
+ return {
1025
+ type: "SignPSBT",
1026
+ name: "Deposit on Bitcoin",
1027
+ description: "Send funds to the bitcoin swap address",
1028
+ chain: "BITCOIN",
1029
+ txs: [
1030
+ actionOptions?.bitcoinWallet == null
1031
+ ? { ...await this.getPsbt(), type: "RAW_PSBT" }
1032
+ : { ...await this.getFundedPsbt(actionOptions.bitcoinWallet, actionOptions?.bitcoinFeeRate), type: "FUNDED_PSBT" }
1033
+ ],
1034
+ submitPsbt: async (signedPsbt, idempotent) => {
1035
+ return this._submitExecutionTransactions(Array.isArray(signedPsbt) ? signedPsbt : [signedPsbt], undefined, [SpvFromBTCSwapState.CREATED, SpvFromBTCSwapState.QUOTE_SOFT_EXPIRED], idempotent);
1036
+ }
1037
+ };
1038
+ }
1039
+ /**
1040
+ * @internal
1041
+ */
1042
+ async _buildWaitBitcoinConfirmationsAction(confirmationDelay) {
1043
+ return {
1044
+ type: "Wait",
1045
+ name: "Bitcoin confirmations",
1046
+ description: "Wait for bitcoin transaction to confirm",
1047
+ pollTimeSeconds: 10,
1048
+ expectedTimeSeconds: confirmationDelay === -1 ? -1 : Math.floor(confirmationDelay / 1000),
1049
+ wait: async (maxWaitTimeSeconds, pollIntervalSeconds, abortSignal, btcConfirmationsCallback) => {
1050
+ const abortController = (0, Utils_1.extendAbortController)(abortSignal, maxWaitTimeSeconds, "Timed out waiting for bitcoin transaction");
1051
+ await this.waitForBitcoinTransaction(btcConfirmationsCallback, pollIntervalSeconds, abortController.signal);
1052
+ }
1053
+ };
1054
+ }
1055
+ /**
1056
+ * @internal
1057
+ */
1058
+ async _buildWaitSettlementAction(maxWaitTillAutomaticSettlementSeconds) {
1059
+ return {
1060
+ type: "Wait",
1061
+ name: "Automatic settlement",
1062
+ description: "Wait for bitcoin transaction to confirm",
1063
+ pollTimeSeconds: 5,
1064
+ expectedTimeSeconds: 10,
1065
+ wait: async (maxWaitTimeSeconds, pollIntervalSeconds, abortSignal) => {
1066
+ await this.waitTillClaimedOrFronted(maxWaitTimeSeconds ?? maxWaitTillAutomaticSettlementSeconds ?? 60, abortSignal, pollIntervalSeconds);
1067
+ }
1068
+ };
1069
+ }
1070
+ /**
1071
+ * @internal
1072
+ */
1073
+ async _buildClaimSmartChainTxAction(actionOptions) {
1074
+ const signerAddress = await this.wrapper._getSignerAddress(actionOptions?.manualSettlementSmartChainSigner);
1075
+ return {
1076
+ type: "SignSmartChainTransaction",
1077
+ name: "Settle manually",
1078
+ description: "Manually settle the swap on the destination smart chain",
1079
+ chain: this.chainIdentifier,
1080
+ txs: await this.prepareTransactions(this.txsClaim(actionOptions?.manualSettlementSmartChainSigner)),
1081
+ submitTransactions: async (txs, abortSignal, idempotent) => {
1082
+ return this._submitExecutionTransactions(txs, abortSignal, [SpvFromBTCSwapState.BTC_TX_CONFIRMED], idempotent);
1083
+ },
1084
+ requiredSigner: signerAddress ?? this._getInitiator()
1085
+ };
1086
+ }
1087
+ /**
1088
+ * @inheritDoc
1089
+ *
1090
+ * @param options.bitcoinFeeRate Optional fee rate to use for the created Bitcoin transaction
1091
+ * @param options.bitcoinWallet Optional bitcoin wallet address specification to return a funded PSBT,
1092
+ * if not provided a raw PSBT is returned instead which necessitates the implementor to manually add
1093
+ * inputs to the bitcoin transaction and **set the nSequence field of the 2nd input** (input 1 -
1094
+ * indexing from 0) to the value returned in `in1sequence`
1095
+ * @param options.manualSettlementSmartChainSigner Optional smart chain signer to create a manual claim (settlement) transaction
1096
+ * @param options.maxWaitTillAutomaticSettlementSeconds Maximum time to wait for an automatic settlement after
1097
+ * the bitcoin transaction is confirmed (defaults to 60 seconds)
1098
+ */
1099
+ async getExecutionAction(options) {
1100
+ const executionStatus = await this._getExecutionStatus(options);
1101
+ return executionStatus.buildCurrentAction(options);
1102
+ }
1103
+ /**
1104
+ * @inheritDoc
1105
+ */
1106
+ async getExecutionStatus(options) {
1107
+ const executionStatus = await this._getExecutionStatus(options);
1108
+ return {
1109
+ steps: executionStatus.steps,
1110
+ currentAction: options?.skipBuildingAction ? undefined : await executionStatus.buildCurrentAction(options),
1111
+ stateInfo: this._getStateInfo(executionStatus.state)
1112
+ };
1113
+ }
1114
+ /**
1115
+ * @inheritDoc
1116
+ */
1117
+ async getExecutionSteps(options) {
1118
+ return (await this._getExecutionStatus(options)).steps;
1119
+ }
1120
+ //////////////////////////////
1121
+ //// Bitcoin tx listener
1122
+ /**
1123
+ * Checks whether a bitcoin payment was already made, returns the payment or null when no payment has been made.
1124
+ * @internal
1125
+ */
1126
+ async getBitcoinPayment() {
1127
+ if (this._data?.btcTx?.txid == null)
1128
+ return null;
1129
+ const result = await this.wrapper._btcRpc.getTransaction(this._data?.btcTx?.txid);
1130
+ if (result == null)
1131
+ return null;
1132
+ return {
1133
+ txId: result.txid,
1134
+ confirmations: result.confirmations ?? 0,
1135
+ targetConfirmations: this.vaultRequiredConfirmations,
1136
+ btcTx: result,
1137
+ inputAddresses: result.inputAddresses
1138
+ };
1139
+ }
1140
+ /**
1141
+ * @inheritDoc
1142
+ *
1143
+ * @throws {Error} if in invalid state (must be {@link SpvFromBTCSwapState.POSTED} or
1144
+ * {@link SpvFromBTCSwapState.BROADCASTED} states)
1145
+ */
1146
+ async waitForBitcoinTransaction(updateCallback, checkIntervalSeconds, abortSignal) {
1147
+ if (this._state !== SpvFromBTCSwapState.POSTED &&
1148
+ this._state !== SpvFromBTCSwapState.BROADCASTED &&
1149
+ !(this._state === SpvFromBTCSwapState.QUOTE_SOFT_EXPIRED && this.posted))
1150
+ throw new Error("Must be in POSTED or BROADCASTED state!");
1151
+ if (this._data == null)
1152
+ throw new Error("Expected swap to have withdrawal data filled!");
1153
+ const result = await this.wrapper._btcRpc.waitForTransaction(this._data.btcTx.txid, this.vaultRequiredConfirmations, (btcTx, txEtaMs) => {
1154
+ if (updateCallback != null)
1155
+ updateCallback(btcTx?.txid, btcTx?.confirmations, this.vaultRequiredConfirmations, txEtaMs);
1156
+ if (btcTx == null)
1157
+ return;
1158
+ let save = false;
1159
+ if (btcTx.inputAddresses != null && this._senderAddress == null) {
1160
+ this._senderAddress = btcTx.inputAddresses[1];
1161
+ save = true;
1162
+ }
1163
+ if (this._state === SpvFromBTCSwapState.POSTED || this._state == SpvFromBTCSwapState.QUOTE_SOFT_EXPIRED) {
1164
+ this._state = SpvFromBTCSwapState.BROADCASTED;
1165
+ save = true;
1166
+ }
1167
+ if (save)
1168
+ this._saveAndEmit();
1169
+ }, abortSignal, checkIntervalSeconds);
1170
+ if (abortSignal != null)
1171
+ abortSignal.throwIfAborted();
1172
+ let save = false;
1173
+ if (result.inputAddresses != null && this._senderAddress == null) {
1174
+ this._senderAddress = result.inputAddresses[1];
1175
+ save = true;
1176
+ }
1177
+ if (this._state !== SpvFromBTCSwapState.FRONTED &&
1178
+ this._state !== SpvFromBTCSwapState.CLAIMED) {
1179
+ this.btcTxConfirmedAt ??= Date.now();
1180
+ this._state = SpvFromBTCSwapState.BTC_TX_CONFIRMED;
1181
+ save = true;
1182
+ }
1183
+ if (save)
1184
+ await this._saveAndEmit();
1185
+ return result.txid;
1186
+ }
1187
+ //////////////////////////////
1188
+ //// Claim
1189
+ /**
1190
+ * Returns transactions for settling (claiming) the swap if the swap requires manual settlement, you can check so
1191
+ * with isClaimable. After sending the transaction manually be sure to call the waitTillClaimed function to wait
1192
+ * till the claim transaction is observed, processed by the SDK and state of the swap properly updated.
1193
+ *
1194
+ * @remarks
1195
+ * Might also return transactions necessary to sync the bitcoin light client.
1196
+ *
1197
+ * @param _signer Address of the signer to create the claim transactions for, can also be different to the recipient
1198
+ *
1199
+ * @throws {Error} If the swap is in invalid state (must be {@link SpvFromBTCSwapState.BTC_TX_CONFIRMED})
1200
+ */
1201
+ async txsClaim(_signer) {
1202
+ let address = undefined;
1203
+ if (_signer != null) {
1204
+ if (typeof (_signer) === "string") {
1205
+ address = _signer;
1206
+ }
1207
+ else if ((0, base_1.isAbstractSigner)(_signer)) {
1208
+ address = _signer.getAddress();
1209
+ }
1210
+ else {
1211
+ address = (await this.wrapper._chain.wrapSigner(_signer)).getAddress();
1212
+ }
1213
+ }
1214
+ if (!this.isClaimable())
1215
+ throw new Error("Must be in BTC_TX_CONFIRMED state!");
1216
+ if (this._data == null)
1217
+ throw new Error("Expected swap to have withdrawal data filled!");
1218
+ const vaultData = await this._contract.getVaultData(this.vaultOwner, this.vaultId);
1219
+ if (vaultData == null)
1220
+ throw new Error(`Vault data for ${this.vaultOwner}:${this.vaultId.toString(10)} not found (already closed???)!`);
1221
+ const btcTx = await this.wrapper._btcRpc.getTransaction(this._data.btcTx.txid);
1222
+ if (btcTx == null)
1223
+ throw new Error(`Bitcoin transaction ${this._data.btcTx.txid} not found!`);
1224
+ const txs = [btcTx];
1225
+ //Trace back from current tx to the vaultData-specified UTXO
1226
+ const vaultUtxo = vaultData.getUtxo();
1227
+ while (txs[0].ins[0].txid + ":" + txs[0].ins[0].vout !== vaultUtxo) {
1228
+ const btcTx = await this.wrapper._btcRpc.getTransaction(txs[0].ins[0].txid);
1229
+ if (btcTx == null)
1230
+ throw new Error(`Prior withdrawal bitcoin transaction ${this._data.btcTx.txid} not found!`);
1231
+ txs.unshift(btcTx);
1232
+ }
1233
+ //Parse transactions to withdrawal data
1234
+ const withdrawalData = [];
1235
+ for (let tx of txs) {
1236
+ withdrawalData.push(await this._contract.getWithdrawalData(tx));
1237
+ }
1238
+ return await this._contract.txsClaim(address ?? this._getInitiator(), vaultData, withdrawalData.map(tx => { return { tx }; }), this.wrapper._synchronizer(this._contractVersion), true);
1239
+ }
1240
+ /**
1241
+ * Settles the swap by claiming the funds on the destination chain if the swap requires manual settlement, you can
1242
+ * check so with isClaimable.
1243
+ *
1244
+ * @remarks
1245
+ * Might also sync the bitcoin light client during the process.
1246
+ *
1247
+ * @param _signer Signer to use for signing the settlement transactions, can also be different to the recipient
1248
+ * @param abortSignal Abort signal
1249
+ * @param onBeforeTxSent Optional callback triggered before the claim transaction is broadcasted
1250
+ *
1251
+ * @throws {Error} If the swap is in invalid state (must be {@link SpvFromBTCSwapState.BTC_TX_CONFIRMED})
1252
+ */
1253
+ async claim(_signer, abortSignal, onBeforeTxSent) {
1254
+ const signer = (0, base_1.isAbstractSigner)(_signer) ? _signer : await this.wrapper._chain.wrapSigner(_signer);
1255
+ let txIds;
1256
+ try {
1257
+ let txCount = 0;
1258
+ const txs = await this.txsClaim(signer);
1259
+ txIds = await this.wrapper._chain.sendAndConfirm(signer, txs, true, abortSignal, undefined, (txId) => {
1260
+ txCount++;
1261
+ if (onBeforeTxSent != null && txCount === txs.length)
1262
+ onBeforeTxSent(txId);
1263
+ return Promise.resolve();
1264
+ });
1265
+ }
1266
+ catch (e) {
1267
+ if (this._data == null)
1268
+ throw e;
1269
+ this.logger.info("claim(): Failed to claim ourselves, checking swap claim state...");
1270
+ if (this._state === SpvFromBTCSwapState.CLAIMED) {
1271
+ this.logger.info("claim(): Transaction state is CLAIMED, swap was successfully claimed by the watchtower");
1272
+ return this._claimTxId;
1273
+ }
1274
+ const withdrawalState = await this._contract.getWithdrawalState(this._data, this._genesisSmartChainBlockHeight);
1275
+ if (withdrawalState != null && withdrawalState.type === base_1.SpvWithdrawalStateType.CLAIMED) {
1276
+ this.logger.info("claim(): Transaction status is CLAIMED, swap was successfully claimed by the watchtower");
1277
+ this._claimTxId = withdrawalState.txId;
1278
+ await this._saveAndEmit(SpvFromBTCSwapState.CLAIMED);
1279
+ return withdrawalState.txId;
1280
+ }
1281
+ throw e;
1282
+ }
1283
+ this._claimTxId = txIds[0];
1284
+ if (this._state === SpvFromBTCSwapState.POSTED || this._state === SpvFromBTCSwapState.BROADCASTED ||
1285
+ this._state === SpvFromBTCSwapState.BTC_TX_CONFIRMED || this._state === SpvFromBTCSwapState.FAILED ||
1286
+ this._state === SpvFromBTCSwapState.FRONTED) {
1287
+ await this._saveAndEmit(SpvFromBTCSwapState.CLAIMED);
1288
+ }
1289
+ return txIds[0];
1290
+ }
1291
+ /**
1292
+ * Periodically checks the chain to see whether the swap was finished (claimed or refunded)
1293
+ *
1294
+ * @param interval How often to check (in seconds), default to 5s
1295
+ * @param abortSignal
1296
+ * @internal
1297
+ */
1298
+ async watchdogWaitTillResult(interval = 5, abortSignal) {
1299
+ if (this._data == null)
1300
+ throw new Error("Cannot await the result before the btc transaction is sent!");
1301
+ let status = { type: base_1.SpvWithdrawalStateType.NOT_FOUND };
1302
+ while (status.type === base_1.SpvWithdrawalStateType.NOT_FOUND) {
1303
+ await (0, TimeoutUtils_1.timeoutPromise)(interval * 1000, abortSignal);
1304
+ try {
1305
+ //Be smart about checking withdrawal state
1306
+ if (await this._shouldCheckWithdrawalState()) {
1307
+ status = await this._contract.getWithdrawalState(this._data, this._genesisSmartChainBlockHeight) ?? { type: base_1.SpvWithdrawalStateType.NOT_FOUND };
1308
+ }
1309
+ }
1310
+ catch (e) {
1311
+ this.logger.error("watchdogWaitTillResult(): Error when fetching commit status: ", e);
1312
+ }
1313
+ }
1314
+ if (abortSignal != null)
1315
+ abortSignal.throwIfAborted();
1316
+ return status;
1317
+ }
1318
+ /**
1319
+ * Waits till the swap is successfully settled (claimed), should be called after sending the claim (settlement)
1320
+ * transactions manually to wait till the SDK processes the settlement and updates the swap state accordingly.
1321
+ *
1322
+ * @remarks
1323
+ * This is an alias for the {@link waitTillClaimedOrFronted} function and will also resolve if the swap has
1324
+ * been fronted (not necessarily claimed)
1325
+ *
1326
+ * @param maxWaitTimeSeconds – Maximum time in seconds to wait for the swap to be settled
1327
+ * @param abortSignal – AbortSignal
1328
+ *
1329
+ * @returns Whether the swap was claimed in time or not
1330
+ */
1331
+ waitTillClaimed(maxWaitTimeSeconds, abortSignal) {
1332
+ return this.waitTillClaimedOrFronted(maxWaitTimeSeconds, abortSignal);
1333
+ }
1334
+ /**
1335
+ * Waits till the swap is successfully fronted or settled on the destination chain
1336
+ *
1337
+ * @param maxWaitTimeSeconds Maximum time in seconds to wait for the swap to be settled (by default
1338
+ * it waits indefinitely)
1339
+ * @param abortSignal Abort signal
1340
+ * @param pollIntervalSeconds How often to poll via the watchdog
1341
+ *
1342
+ * @returns {boolean} whether the swap was claimed or fronted automatically or not, if the swap was not claimed
1343
+ * the user can claim manually through the {@link claim} function
1344
+ */
1345
+ async waitTillClaimedOrFronted(maxWaitTimeSeconds, abortSignal, pollIntervalSeconds) {
1346
+ if (this._state === SpvFromBTCSwapState.CLAIMED || this._state === SpvFromBTCSwapState.FRONTED)
1347
+ return Promise.resolve(true);
1348
+ const abortController = (0, Utils_1.extendAbortController)(abortSignal);
1349
+ let timedOut = false;
1350
+ if (maxWaitTimeSeconds != null) {
1351
+ const timeout = setTimeout(() => {
1352
+ timedOut = true;
1353
+ abortController.abort();
1354
+ }, maxWaitTimeSeconds * 1000);
1355
+ abortController.signal.addEventListener("abort", () => clearTimeout(timeout));
1356
+ }
1357
+ let res;
1358
+ try {
1359
+ res = await Promise.race([
1360
+ this.watchdogWaitTillResult(pollIntervalSeconds, abortController.signal),
1361
+ this.waitTillState(SpvFromBTCSwapState.CLAIMED, "eq", abortController.signal).then(() => 0),
1362
+ this.waitTillState(SpvFromBTCSwapState.FRONTED, "eq", abortController.signal).then(() => 1),
1363
+ this.waitTillState(SpvFromBTCSwapState.FAILED, "eq", abortController.signal).then(() => 2),
1364
+ ]);
1365
+ abortController.abort();
1366
+ }
1367
+ catch (e) {
1368
+ abortController.abort();
1369
+ if (timedOut)
1370
+ return false;
1371
+ throw e;
1372
+ }
1373
+ if (typeof (res) === "number") {
1374
+ if (res === 0) {
1375
+ this.logger.debug("waitTillClaimedOrFronted(): Resolved from state change (CLAIMED)");
1376
+ return true;
1377
+ }
1378
+ if (res === 1) {
1379
+ this.logger.debug("waitTillClaimedOrFronted(): Resolved from state change (FRONTED)");
1380
+ return true;
1381
+ }
1382
+ if (res === 2) {
1383
+ this.logger.debug("waitTillClaimedOrFronted(): Resolved from state change (FAILED)");
1384
+ throw new Error("Swap failed while waiting for claim or front");
1385
+ }
1386
+ throw new Error("Invalid numeric response, this should never happen!");
1387
+ }
1388
+ this.logger.debug("waitTillClaimedOrFronted(): Resolved from watchdog");
1389
+ if (res.type === base_1.SpvWithdrawalStateType.FRONTED) {
1390
+ if (this._state !== SpvFromBTCSwapState.FRONTED ||
1391
+ this._state !== SpvFromBTCSwapState.CLAIMED) {
1392
+ this._frontTxId = res.txId;
1393
+ await this._saveAndEmit(SpvFromBTCSwapState.FRONTED);
1394
+ }
1395
+ }
1396
+ if (res.type === base_1.SpvWithdrawalStateType.CLAIMED) {
1397
+ if (this._state !== SpvFromBTCSwapState.CLAIMED) {
1398
+ this._claimTxId = res.txId;
1399
+ await this._saveAndEmit(SpvFromBTCSwapState.CLAIMED);
1400
+ }
1401
+ }
1402
+ if (res.type === base_1.SpvWithdrawalStateType.CLOSED) {
1403
+ if (this._state !== SpvFromBTCSwapState.CLOSED)
1404
+ await this._saveAndEmit(SpvFromBTCSwapState.CLOSED);
1405
+ throw new Error("Swap failed with catastrophic error!");
1406
+ }
1407
+ return true;
1408
+ }
1409
+ /**
1410
+ * Waits till the bitcoin transaction confirms and swap settled on the destination chain
1411
+ *
1412
+ * @param updateCallback Callback called when txId is found, and also called with subsequent confirmations
1413
+ * @param checkIntervalSeconds How often to check the bitcoin transaction (5 seconds by default)
1414
+ * @param abortSignal Abort signal
1415
+ *
1416
+ * @throws {Error} if in invalid state (must be {@link SpvFromBTCSwapState.POSTED} or
1417
+ * {@link SpvFromBTCSwapState.BROADCASTED} states)
1418
+ */
1419
+ async waitTillExecuted(updateCallback, checkIntervalSeconds, abortSignal) {
1420
+ await this.waitForBitcoinTransaction(updateCallback, checkIntervalSeconds, abortSignal);
1421
+ await this.waitTillClaimedOrFronted(undefined, abortSignal);
1422
+ }
1423
+ //////////////////////////////
1424
+ //// Storage
1425
+ /**
1426
+ * @inheritDoc
1427
+ */
1428
+ serialize() {
1429
+ return {
1430
+ ...super.serialize(),
1431
+ quoteId: this.quoteId,
1432
+ recipient: this.recipient,
1433
+ vaultOwner: this.vaultOwner,
1434
+ vaultId: this.vaultId.toString(10),
1435
+ vaultRequiredConfirmations: this.vaultRequiredConfirmations,
1436
+ vaultTokenMultipliers: this.vaultTokenMultipliers.map(val => val.toString(10)),
1437
+ vaultBtcAddress: this.vaultBtcAddress,
1438
+ vaultUtxo: this.vaultUtxo,
1439
+ vaultUtxoValue: this.vaultUtxoValue.toString(10),
1440
+ btcDestinationAddress: this.btcDestinationAddress,
1441
+ btcAmount: this.btcAmount.toString(10),
1442
+ btcAmountSwap: this.btcAmountSwap.toString(10),
1443
+ btcAmountGas: this.btcAmountGas.toString(10),
1444
+ minimumBtcFeeRate: this.minimumBtcFeeRate,
1445
+ outputTotalSwap: this.outputTotalSwap.toString(10),
1446
+ outputSwapToken: this.outputSwapToken,
1447
+ outputTotalGas: this.outputTotalGas.toString(10),
1448
+ outputGasToken: this.outputGasToken,
1449
+ gasSwapFeeBtc: this.gasSwapFeeBtc.toString(10),
1450
+ gasSwapFee: this.gasSwapFee.toString(10),
1451
+ callerFeeShare: this.callerFeeShare.toString(10),
1452
+ frontingFeeShare: this.frontingFeeShare.toString(10),
1453
+ executionFeeShare: this.executionFeeShare.toString(10),
1454
+ genesisSmartChainBlockHeight: this._genesisSmartChainBlockHeight,
1455
+ gasPricingInfo: (0, PriceInfoType_1.serializePriceInfoType)(this.gasPricingInfo),
1456
+ posted: this.posted,
1457
+ senderAddress: this._senderAddress,
1458
+ claimTxId: this._claimTxId,
1459
+ frontTxId: this._frontTxId,
1460
+ data: this._data?.serialize(),
1461
+ btcTxConfirmedAt: this.btcTxConfirmedAt
1462
+ };
1463
+ }
1464
+ //////////////////////////////
1465
+ //// Swap ticks & sync
1466
+ /**
1467
+ * Used to set the txId of the bitcoin payment from the on-chain events listener
1468
+ *
1469
+ * @param txId
1470
+ * @internal
1471
+ */
1472
+ async _setBitcoinTxId(txId) {
1473
+ if (this._data == null)
1474
+ return;
1475
+ if (txId != this._data.btcTx.txid)
1476
+ return;
1477
+ if (this._senderAddress != null)
1478
+ return;
1479
+ const btcTx = await this.wrapper._btcRpc.getTransaction(txId);
1480
+ if (btcTx == null || btcTx.inputAddresses == null)
1481
+ return;
1482
+ this._senderAddress = btcTx.inputAddresses[1];
1483
+ }
1484
+ /**
1485
+ * @internal
1486
+ */
1487
+ async _syncStateFromBitcoin(save) {
1488
+ if (this._data?.btcTx == null)
1489
+ return false;
1490
+ //Check if bitcoin payment was confirmed
1491
+ this.btcTxLastChecked = Date.now();
1492
+ const res = await this.getBitcoinPayment();
1493
+ if (res == null) {
1494
+ //Check inputs double-spent
1495
+ for (let input of this._data.btcTx.ins) {
1496
+ if (await this.wrapper._btcRpc.isSpent(input.txid + ":" + input.vout, true)) {
1497
+ if (this._state === SpvFromBTCSwapState.SIGNED ||
1498
+ this._state === SpvFromBTCSwapState.POSTED ||
1499
+ this._state === SpvFromBTCSwapState.QUOTE_SOFT_EXPIRED ||
1500
+ this._state === SpvFromBTCSwapState.DECLINED) {
1501
+ //One of the inputs was double-spent
1502
+ this._state = SpvFromBTCSwapState.QUOTE_EXPIRED;
1503
+ }
1504
+ else {
1505
+ //One of the inputs was double-spent
1506
+ this._state = SpvFromBTCSwapState.FAILED;
1507
+ }
1508
+ if (save)
1509
+ await this._saveAndEmit();
1510
+ return true;
1511
+ }
1512
+ }
1513
+ }
1514
+ else {
1515
+ let needsSave = false;
1516
+ if (res.inputAddresses != null && this._senderAddress == null) {
1517
+ this._senderAddress = res.inputAddresses[1];
1518
+ needsSave = true;
1519
+ }
1520
+ if (res.confirmations >= this.vaultRequiredConfirmations) {
1521
+ if (this._state !== SpvFromBTCSwapState.BTC_TX_CONFIRMED &&
1522
+ this._state !== SpvFromBTCSwapState.FRONTED &&
1523
+ this._state !== SpvFromBTCSwapState.CLAIMED) {
1524
+ this.btcTxConfirmedAt ??= Date.now();
1525
+ this._state = SpvFromBTCSwapState.BTC_TX_CONFIRMED;
1526
+ needsSave = true;
1527
+ }
1528
+ }
1529
+ else if (this._state === SpvFromBTCSwapState.QUOTE_SOFT_EXPIRED ||
1530
+ this._state === SpvFromBTCSwapState.POSTED ||
1531
+ this._state === SpvFromBTCSwapState.SIGNED ||
1532
+ this._state === SpvFromBTCSwapState.DECLINED) {
1533
+ this._state = SpvFromBTCSwapState.BROADCASTED;
1534
+ needsSave = true;
1535
+ }
1536
+ if (needsSave && save)
1537
+ await this._saveAndEmit();
1538
+ return needsSave;
1539
+ }
1540
+ return false;
1541
+ }
1542
+ /**
1543
+ * Checks the swap's state on-chain and compares it to its internal state, updates/changes it according to on-chain
1544
+ * data
1545
+ */
1546
+ async syncStateFromChain() {
1547
+ let changed = false;
1548
+ if (this._state === SpvFromBTCSwapState.SIGNED ||
1549
+ this._state === SpvFromBTCSwapState.POSTED ||
1550
+ this._state === SpvFromBTCSwapState.BROADCASTED ||
1551
+ this._state === SpvFromBTCSwapState.QUOTE_SOFT_EXPIRED ||
1552
+ this._state === SpvFromBTCSwapState.DECLINED ||
1553
+ this._state === SpvFromBTCSwapState.BTC_TX_CONFIRMED) {
1554
+ //Check BTC transaction
1555
+ if (await this._syncStateFromBitcoin(false))
1556
+ changed ||= true;
1557
+ }
1558
+ if (this._state === SpvFromBTCSwapState.BROADCASTED || this._state === SpvFromBTCSwapState.BTC_TX_CONFIRMED) {
1559
+ if (await this._shouldCheckWithdrawalState()) {
1560
+ const status = await this._contract.getWithdrawalState(this._data, this._genesisSmartChainBlockHeight);
1561
+ this.logger.debug("syncStateFromChain(): status of " + this._data.btcTx.txid, status);
1562
+ switch (status?.type) {
1563
+ case base_1.SpvWithdrawalStateType.FRONTED:
1564
+ this._frontTxId = status.txId;
1565
+ this._state = SpvFromBTCSwapState.FRONTED;
1566
+ changed ||= true;
1567
+ break;
1568
+ case base_1.SpvWithdrawalStateType.CLAIMED:
1569
+ this._claimTxId = status.txId;
1570
+ this._state = SpvFromBTCSwapState.CLAIMED;
1571
+ changed ||= true;
1572
+ break;
1573
+ case base_1.SpvWithdrawalStateType.CLOSED:
1574
+ this._state = SpvFromBTCSwapState.CLOSED;
1575
+ changed ||= true;
1576
+ break;
1577
+ }
1578
+ }
1579
+ }
1580
+ if (this._state === SpvFromBTCSwapState.CREATED ||
1581
+ this._state === SpvFromBTCSwapState.SIGNED ||
1582
+ this._state === SpvFromBTCSwapState.POSTED) {
1583
+ if (this.expiry < Date.now()) {
1584
+ if (this._state === SpvFromBTCSwapState.CREATED) {
1585
+ this._state = SpvFromBTCSwapState.QUOTE_EXPIRED;
1586
+ }
1587
+ else {
1588
+ this._state = SpvFromBTCSwapState.QUOTE_SOFT_EXPIRED;
1589
+ }
1590
+ changed ||= true;
1591
+ }
1592
+ }
1593
+ return changed;
1594
+ }
1595
+ /**
1596
+ * @inheritDoc
1597
+ * @internal
1598
+ */
1599
+ async _sync(save) {
1600
+ const changed = await this.syncStateFromChain();
1601
+ if (changed && save)
1602
+ await this._saveAndEmit();
1603
+ return changed;
1604
+ }
1605
+ /**
1606
+ * @inheritDoc
1607
+ * @internal
1608
+ */
1609
+ async _tick(save) {
1610
+ if (this._state === SpvFromBTCSwapState.CREATED ||
1611
+ this._state === SpvFromBTCSwapState.SIGNED) {
1612
+ if (this.getQuoteExpiry() < Date.now()) {
1613
+ this._state = SpvFromBTCSwapState.QUOTE_SOFT_EXPIRED;
1614
+ if (save)
1615
+ await this._saveAndEmit();
1616
+ return true;
1617
+ }
1618
+ }
1619
+ if (this._state === SpvFromBTCSwapState.QUOTE_SOFT_EXPIRED && !this.posted) {
1620
+ if (this.expiry < Date.now()) {
1621
+ this._state = SpvFromBTCSwapState.QUOTE_EXPIRED;
1622
+ if (save)
1623
+ await this._saveAndEmit();
1624
+ return true;
1625
+ }
1626
+ }
1627
+ if (this.btcTxLastChecked == null || Date.now() - this.btcTxLastChecked > 120000) {
1628
+ if (this._state === SpvFromBTCSwapState.POSTED ||
1629
+ this._state === SpvFromBTCSwapState.BROADCASTED) {
1630
+ try {
1631
+ //Check if bitcoin payment was confirmed
1632
+ return await this._syncStateFromBitcoin(save);
1633
+ }
1634
+ catch (e) {
1635
+ this.logger.error("tickSwap(" + this.getId() + "): ", e);
1636
+ }
1637
+ }
1638
+ }
1639
+ return false;
1640
+ }
1641
+ /**
1642
+ * Checks whether an on-chain withdrawal state should be fetched for this specific swap
1643
+ *
1644
+ * @internal
1645
+ */
1646
+ async _shouldCheckWithdrawalState(frontingAddress, vaultDataUtxo) {
1647
+ if (frontingAddress === undefined)
1648
+ frontingAddress = await this._contract.getFronterAddress(this.vaultOwner, this.vaultId, this._data);
1649
+ if (vaultDataUtxo === undefined)
1650
+ vaultDataUtxo = await this._contract.getVaultLatestUtxo(this.vaultOwner, this.vaultId);
1651
+ if (frontingAddress != null)
1652
+ return true; //In case the swap is fronted there will for sure be a fronted event
1653
+ if (vaultDataUtxo == null)
1654
+ return true; //Vault UTXO is null (the vault closed)
1655
+ const [txId, _] = vaultDataUtxo.split(":");
1656
+ //Don't check both txns if their txId is equal
1657
+ if (this._data.btcTx.txid === txId)
1658
+ return true;
1659
+ const [btcTx, latestVaultTx] = await Promise.all([
1660
+ this.wrapper._btcRpc.getTransaction(this._data.btcTx.txid),
1661
+ this.wrapper._btcRpc.getTransaction(txId)
1662
+ ]);
1663
+ if (latestVaultTx == null || latestVaultTx.blockheight == null) {
1664
+ //Something must've gone horribly wrong, the latest vault utxo tx of the vault either
1665
+ // cannot be found on bitcoin network or is not even confirmed yet
1666
+ this.logger.debug(`_shouldCheckWithdrawalState(): Latest vault utxo not found or not confirmed on bitcoin ${txId}`);
1667
+ return false;
1668
+ }
1669
+ if (btcTx != null) {
1670
+ const btcTxHeight = btcTx.blockheight;
1671
+ const latestVaultTxHeight = latestVaultTx.blockheight;
1672
+ //We also need to cover the case where bitcoin tx isn't confirmed yet (hence btxTxHeight==null)
1673
+ if (btcTxHeight == null || latestVaultTxHeight < btcTxHeight) {
1674
+ //Definitely not claimed!
1675
+ this.logger.debug(`_shouldCheckWithdrawalState(): Skipped checking withdrawal state, latestVaultTxHeight: ${latestVaultTx.blockheight}, btcTxHeight: ${btcTxHeight} and not fronted!`);
1676
+ return false;
1677
+ }
1678
+ }
1679
+ else {
1680
+ //Definitely not claimed because the transaction was probably double-spent (or evicted from mempool)
1681
+ this.logger.debug(`_shouldCheckWithdrawalState(): Skipped checking withdrawal state, btc tx probably replaced or evicted: ${this._data.btcTx.txid} and not fronted`);
1682
+ return false;
1683
+ }
1684
+ return true;
1685
+ }
1686
+ }
1687
+ exports.SpvFromBTCSwap = SpvFromBTCSwap;