@atomiqlabs/sdk 8.6.4 → 8.6.6

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 (239) hide show
  1. package/dist/SmartChainAssets.d.ts +181 -181
  2. package/dist/SmartChainAssets.js +181 -181
  3. package/dist/bitcoin/coinselect2/accumulative.d.ts +6 -6
  4. package/dist/bitcoin/coinselect2/accumulative.js +51 -52
  5. package/dist/bitcoin/coinselect2/blackjack.d.ts +6 -6
  6. package/dist/bitcoin/coinselect2/blackjack.js +37 -38
  7. package/dist/bitcoin/coinselect2/index.d.ts +17 -19
  8. package/dist/bitcoin/coinselect2/index.js +69 -69
  9. package/dist/bitcoin/coinselect2/utils.d.ts +75 -77
  10. package/dist/bitcoin/coinselect2/utils.js +123 -123
  11. package/dist/bitcoin/wallet/BitcoinWallet.d.ts +128 -130
  12. package/dist/bitcoin/wallet/BitcoinWallet.js +322 -322
  13. package/dist/bitcoin/wallet/IBitcoinWallet.d.ts +78 -78
  14. package/dist/bitcoin/wallet/IBitcoinWallet.js +20 -21
  15. package/dist/bitcoin/wallet/SingleAddressBitcoinWallet.d.ts +99 -101
  16. package/dist/bitcoin/wallet/SingleAddressBitcoinWallet.js +176 -176
  17. package/dist/enums/FeeType.d.ts +15 -15
  18. package/dist/enums/FeeType.js +19 -19
  19. package/dist/enums/SwapAmountType.d.ts +15 -15
  20. package/dist/enums/SwapAmountType.js +19 -19
  21. package/dist/enums/SwapDirection.d.ts +15 -15
  22. package/dist/enums/SwapDirection.js +19 -19
  23. package/dist/enums/SwapSide.d.ts +15 -15
  24. package/dist/enums/SwapSide.js +19 -19
  25. package/dist/enums/SwapType.d.ts +75 -75
  26. package/dist/enums/SwapType.js +79 -79
  27. package/dist/errors/IntermediaryError.d.ts +13 -13
  28. package/dist/errors/IntermediaryError.js +27 -27
  29. package/dist/errors/RequestError.d.ts +32 -32
  30. package/dist/errors/RequestError.js +54 -54
  31. package/dist/errors/UserError.d.ts +8 -8
  32. package/dist/errors/UserError.js +16 -16
  33. package/dist/events/UnifiedSwapEventListener.d.ts +23 -23
  34. package/dist/events/UnifiedSwapEventListener.js +130 -130
  35. package/dist/http/HttpUtils.d.ts +27 -27
  36. package/dist/http/HttpUtils.js +90 -91
  37. package/dist/http/paramcoders/IParamReader.d.ts +8 -8
  38. package/dist/http/paramcoders/IParamReader.js +2 -2
  39. package/dist/http/paramcoders/ParamDecoder.d.ts +42 -44
  40. package/dist/http/paramcoders/ParamDecoder.js +137 -137
  41. package/dist/http/paramcoders/ParamEncoder.d.ts +18 -20
  42. package/dist/http/paramcoders/ParamEncoder.js +36 -36
  43. package/dist/http/paramcoders/SchemaVerifier.d.ts +26 -26
  44. package/dist/http/paramcoders/SchemaVerifier.js +145 -145
  45. package/dist/http/paramcoders/client/ResponseParamDecoder.d.ts +11 -11
  46. package/dist/http/paramcoders/client/ResponseParamDecoder.js +57 -57
  47. package/dist/http/paramcoders/client/StreamParamEncoder.d.ts +11 -13
  48. package/dist/http/paramcoders/client/StreamParamEncoder.js +26 -26
  49. package/dist/http/paramcoders/client/StreamingFetchPromise.d.ts +16 -16
  50. package/dist/http/paramcoders/client/StreamingFetchPromise.js +173 -174
  51. package/dist/index.d.ts +85 -85
  52. package/dist/index.js +158 -158
  53. package/dist/intermediaries/Intermediary.d.ts +157 -157
  54. package/dist/intermediaries/Intermediary.js +142 -142
  55. package/dist/intermediaries/IntermediaryDiscovery.d.ts +198 -199
  56. package/dist/intermediaries/IntermediaryDiscovery.js +406 -406
  57. package/dist/intermediaries/apis/IntermediaryAPI.d.ts +437 -438
  58. package/dist/intermediaries/apis/IntermediaryAPI.js +603 -602
  59. package/dist/intermediaries/apis/TrustedIntermediaryAPI.d.ts +155 -155
  60. package/dist/intermediaries/apis/TrustedIntermediaryAPI.js +137 -137
  61. package/dist/lnurl/LNURL.d.ts +102 -102
  62. package/dist/lnurl/LNURL.js +321 -321
  63. package/dist/prices/RedundantSwapPrice.d.ts +110 -110
  64. package/dist/prices/RedundantSwapPrice.js +222 -222
  65. package/dist/prices/SingleSwapPrice.d.ts +34 -34
  66. package/dist/prices/SingleSwapPrice.js +44 -44
  67. package/dist/prices/SwapPriceWithChain.d.ts +107 -107
  68. package/dist/prices/SwapPriceWithChain.js +128 -128
  69. package/dist/prices/abstract/ICachedSwapPrice.d.ts +28 -28
  70. package/dist/prices/abstract/ICachedSwapPrice.js +62 -62
  71. package/dist/prices/abstract/IPriceProvider.d.ts +81 -81
  72. package/dist/prices/abstract/IPriceProvider.js +74 -74
  73. package/dist/prices/abstract/ISwapPrice.d.ts +168 -166
  74. package/dist/prices/abstract/ISwapPrice.js +279 -267
  75. package/dist/prices/providers/BinancePriceProvider.d.ts +23 -23
  76. package/dist/prices/providers/BinancePriceProvider.js +30 -30
  77. package/dist/prices/providers/CoinGeckoPriceProvider.d.ts +23 -23
  78. package/dist/prices/providers/CoinGeckoPriceProvider.js +29 -29
  79. package/dist/prices/providers/CoinPaprikaPriceProvider.d.ts +25 -25
  80. package/dist/prices/providers/CoinPaprikaPriceProvider.js +29 -29
  81. package/dist/prices/providers/CustomPriceProvider.d.ts +24 -24
  82. package/dist/prices/providers/CustomPriceProvider.js +35 -35
  83. package/dist/prices/providers/KrakenPriceProvider.d.ts +38 -38
  84. package/dist/prices/providers/KrakenPriceProvider.js +45 -45
  85. package/dist/prices/providers/OKXPriceProvider.d.ts +34 -34
  86. package/dist/prices/providers/OKXPriceProvider.js +29 -29
  87. package/dist/prices/providers/abstract/ExchangePriceProvider.d.ts +17 -17
  88. package/dist/prices/providers/abstract/ExchangePriceProvider.js +21 -21
  89. package/dist/prices/providers/abstract/HttpPriceProvider.d.ts +7 -7
  90. package/dist/prices/providers/abstract/HttpPriceProvider.js +12 -12
  91. package/dist/storage/IUnifiedStorage.d.ts +85 -85
  92. package/dist/storage/IUnifiedStorage.js +2 -2
  93. package/dist/storage/UnifiedSwapStorage.d.ts +114 -114
  94. package/dist/storage/UnifiedSwapStorage.js +116 -116
  95. package/dist/storage-browser/IndexedDBUnifiedStorage.d.ts +63 -63
  96. package/dist/storage-browser/IndexedDBUnifiedStorage.js +298 -298
  97. package/dist/storage-browser/LocalStorageManager.d.ts +49 -49
  98. package/dist/storage-browser/LocalStorageManager.js +93 -93
  99. package/dist/swapper/Swapper.d.ts +686 -687
  100. package/dist/swapper/Swapper.js +1603 -1603
  101. package/dist/swapper/SwapperFactory.d.ts +135 -135
  102. package/dist/swapper/SwapperFactory.js +162 -162
  103. package/dist/swapper/SwapperUtils.d.ts +200 -200
  104. package/dist/swapper/SwapperUtils.js +467 -467
  105. package/dist/swapper/SwapperWithChain.d.ts +404 -404
  106. package/dist/swapper/SwapperWithChain.js +469 -469
  107. package/dist/swapper/SwapperWithSigner.d.ts +322 -322
  108. package/dist/swapper/SwapperWithSigner.js +318 -318
  109. package/dist/swaps/IAddressSwap.d.ts +22 -22
  110. package/dist/swaps/IAddressSwap.js +13 -14
  111. package/dist/swaps/IBTCWalletSwap.d.ts +73 -73
  112. package/dist/swaps/IBTCWalletSwap.js +17 -18
  113. package/dist/swaps/IClaimableSwap.d.ts +49 -49
  114. package/dist/swaps/IClaimableSwap.js +14 -15
  115. package/dist/swaps/IClaimableSwapWrapper.d.ts +15 -15
  116. package/dist/swaps/IClaimableSwapWrapper.js +2 -2
  117. package/dist/swaps/IRefundableSwap.d.ts +43 -43
  118. package/dist/swaps/IRefundableSwap.js +13 -14
  119. package/dist/swaps/ISwap.d.ts +386 -387
  120. package/dist/swaps/ISwap.js +346 -341
  121. package/dist/swaps/ISwapWithGasDrop.d.ts +21 -21
  122. package/dist/swaps/ISwapWithGasDrop.js +11 -12
  123. package/dist/swaps/ISwapWrapper.d.ts +283 -284
  124. package/dist/swaps/ISwapWrapper.js +353 -353
  125. package/dist/swaps/escrow_swaps/IEscrowSelfInitSwap.d.ts +98 -98
  126. package/dist/swaps/escrow_swaps/IEscrowSelfInitSwap.js +126 -126
  127. package/dist/swaps/escrow_swaps/IEscrowSwap.d.ts +133 -135
  128. package/dist/swaps/escrow_swaps/IEscrowSwap.js +169 -169
  129. package/dist/swaps/escrow_swaps/IEscrowSwapWrapper.d.ts +114 -115
  130. package/dist/swaps/escrow_swaps/IEscrowSwapWrapper.js +134 -134
  131. package/dist/swaps/escrow_swaps/frombtc/IFromBTCLNWrapper.d.ts +98 -101
  132. package/dist/swaps/escrow_swaps/frombtc/IFromBTCLNWrapper.js +130 -130
  133. package/dist/swaps/escrow_swaps/frombtc/IFromBTCSelfInitSwap.d.ts +162 -162
  134. package/dist/swaps/escrow_swaps/frombtc/IFromBTCSelfInitSwap.js +190 -190
  135. package/dist/swaps/escrow_swaps/frombtc/IFromBTCWrapper.d.ts +58 -58
  136. package/dist/swaps/escrow_swaps/frombtc/IFromBTCWrapper.js +78 -78
  137. package/dist/swaps/escrow_swaps/frombtc/ln/FromBTCLNSwap.d.ts +529 -531
  138. package/dist/swaps/escrow_swaps/frombtc/ln/FromBTCLNSwap.js +1285 -1285
  139. package/dist/swaps/escrow_swaps/frombtc/ln/FromBTCLNWrapper.d.ts +181 -184
  140. package/dist/swaps/escrow_swaps/frombtc/ln/FromBTCLNWrapper.js +418 -417
  141. package/dist/swaps/escrow_swaps/frombtc/ln_auto/FromBTCLNAutoSwap.d.ts +581 -583
  142. package/dist/swaps/escrow_swaps/frombtc/ln_auto/FromBTCLNAutoSwap.js +1371 -1371
  143. package/dist/swaps/escrow_swaps/frombtc/ln_auto/FromBTCLNAutoWrapper.d.ts +225 -228
  144. package/dist/swaps/escrow_swaps/frombtc/ln_auto/FromBTCLNAutoWrapper.js +506 -506
  145. package/dist/swaps/escrow_swaps/frombtc/onchain/FromBTCSwap.d.ts +458 -458
  146. package/dist/swaps/escrow_swaps/frombtc/onchain/FromBTCSwap.js +1126 -1126
  147. package/dist/swaps/escrow_swaps/frombtc/onchain/FromBTCWrapper.d.ts +190 -191
  148. package/dist/swaps/escrow_swaps/frombtc/onchain/FromBTCWrapper.js +378 -377
  149. package/dist/swaps/escrow_swaps/tobtc/IToBTCSwap.d.ts +403 -403
  150. package/dist/swaps/escrow_swaps/tobtc/IToBTCSwap.js +924 -924
  151. package/dist/swaps/escrow_swaps/tobtc/IToBTCWrapper.d.ts +62 -62
  152. package/dist/swaps/escrow_swaps/tobtc/IToBTCWrapper.js +112 -112
  153. package/dist/swaps/escrow_swaps/tobtc/ln/ToBTCLNSwap.d.ts +125 -127
  154. package/dist/swaps/escrow_swaps/tobtc/ln/ToBTCLNSwap.js +256 -256
  155. package/dist/swaps/escrow_swaps/tobtc/ln/ToBTCLNWrapper.d.ts +241 -242
  156. package/dist/swaps/escrow_swaps/tobtc/ln/ToBTCLNWrapper.js +520 -520
  157. package/dist/swaps/escrow_swaps/tobtc/onchain/ToBTCSwap.d.ts +73 -73
  158. package/dist/swaps/escrow_swaps/tobtc/onchain/ToBTCSwap.js +155 -155
  159. package/dist/swaps/escrow_swaps/tobtc/onchain/ToBTCWrapper.d.ts +127 -128
  160. package/dist/swaps/escrow_swaps/tobtc/onchain/ToBTCWrapper.js +278 -278
  161. package/dist/swaps/spv_swaps/SpvFromBTCSwap.d.ts +630 -630
  162. package/dist/swaps/spv_swaps/SpvFromBTCSwap.js +1443 -1443
  163. package/dist/swaps/spv_swaps/SpvFromBTCWrapper.d.ts +213 -207
  164. package/dist/swaps/spv_swaps/SpvFromBTCWrapper.js +756 -755
  165. package/dist/swaps/trusted/ln/LnForGasSwap.d.ts +261 -261
  166. package/dist/swaps/trusted/ln/LnForGasSwap.js +511 -511
  167. package/dist/swaps/trusted/ln/LnForGasWrapper.d.ts +40 -40
  168. package/dist/swaps/trusted/ln/LnForGasWrapper.js +82 -82
  169. package/dist/swaps/trusted/onchain/OnchainForGasSwap.d.ts +342 -342
  170. package/dist/swaps/trusted/onchain/OnchainForGasSwap.js +715 -715
  171. package/dist/swaps/trusted/onchain/OnchainForGasWrapper.d.ts +68 -69
  172. package/dist/swaps/trusted/onchain/OnchainForGasWrapper.js +92 -92
  173. package/dist/types/AmountData.d.ts +10 -10
  174. package/dist/types/AmountData.js +2 -2
  175. package/dist/types/CustomPriceFunction.d.ts +11 -11
  176. package/dist/types/CustomPriceFunction.js +2 -2
  177. package/dist/types/PriceInfoType.d.ts +28 -28
  178. package/dist/types/PriceInfoType.js +56 -57
  179. package/dist/types/SwapExecutionAction.d.ts +88 -88
  180. package/dist/types/SwapExecutionAction.js +2 -2
  181. package/dist/types/SwapStateInfo.d.ts +5 -5
  182. package/dist/types/SwapStateInfo.js +2 -2
  183. package/dist/types/SwapWithSigner.d.ts +17 -17
  184. package/dist/types/SwapWithSigner.js +42 -43
  185. package/dist/types/Token.d.ts +99 -99
  186. package/dist/types/Token.js +76 -76
  187. package/dist/types/TokenAmount.d.ts +69 -69
  188. package/dist/types/TokenAmount.js +59 -60
  189. package/dist/types/fees/Fee.d.ts +50 -50
  190. package/dist/types/fees/Fee.js +2 -2
  191. package/dist/types/fees/FeeBreakdown.d.ts +11 -11
  192. package/dist/types/fees/FeeBreakdown.js +2 -2
  193. package/dist/types/fees/PercentagePPM.d.ts +17 -17
  194. package/dist/types/fees/PercentagePPM.js +17 -18
  195. package/dist/types/lnurl/LNURLPay.d.ts +61 -61
  196. package/dist/types/lnurl/LNURLPay.js +30 -31
  197. package/dist/types/lnurl/LNURLWithdraw.d.ts +48 -48
  198. package/dist/types/lnurl/LNURLWithdraw.js +26 -27
  199. package/dist/types/wallets/LightningInvoiceCreateService.d.ts +24 -24
  200. package/dist/types/wallets/LightningInvoiceCreateService.js +14 -15
  201. package/dist/types/wallets/MinimalBitcoinWalletInterface.d.ts +23 -23
  202. package/dist/types/wallets/MinimalBitcoinWalletInterface.js +2 -2
  203. package/dist/types/wallets/MinimalLightningNetworkWalletInterface.d.ts +9 -9
  204. package/dist/types/wallets/MinimalLightningNetworkWalletInterface.js +2 -2
  205. package/dist/utils/AutomaticClockDriftCorrection.d.ts +1 -1
  206. package/dist/utils/AutomaticClockDriftCorrection.js +69 -70
  207. package/dist/utils/BitcoinUtils.d.ts +12 -14
  208. package/dist/utils/BitcoinUtils.js +101 -102
  209. package/dist/utils/BitcoinWalletUtils.d.ts +7 -7
  210. package/dist/utils/BitcoinWalletUtils.js +13 -14
  211. package/dist/utils/Logger.d.ts +7 -7
  212. package/dist/utils/Logger.js +11 -12
  213. package/dist/utils/RetryUtils.d.ts +22 -22
  214. package/dist/utils/RetryUtils.js +66 -67
  215. package/dist/utils/SwapUtils.d.ts +88 -88
  216. package/dist/utils/SwapUtils.js +72 -72
  217. package/dist/utils/TimeoutUtils.d.ts +17 -17
  218. package/dist/utils/TimeoutUtils.js +54 -55
  219. package/dist/utils/TokenUtils.d.ts +19 -19
  220. package/dist/utils/TokenUtils.js +36 -37
  221. package/dist/utils/TypeUtils.d.ts +7 -7
  222. package/dist/utils/TypeUtils.js +2 -2
  223. package/dist/utils/Utils.d.ts +56 -58
  224. package/dist/utils/Utils.js +193 -194
  225. package/package.json +1 -1
  226. package/src/intermediaries/apis/IntermediaryAPI.ts +4 -2
  227. package/src/prices/abstract/ISwapPrice.ts +19 -6
  228. package/src/swaps/ISwap.ts +17 -6
  229. package/src/swaps/ISwapWrapper.ts +4 -3
  230. package/src/swaps/escrow_swaps/frombtc/ln/FromBTCLNWrapper.ts +4 -2
  231. package/src/swaps/escrow_swaps/frombtc/ln_auto/FromBTCLNAutoSwap.ts +4 -1
  232. package/src/swaps/escrow_swaps/frombtc/ln_auto/FromBTCLNAutoWrapper.ts +2 -2
  233. package/src/swaps/escrow_swaps/frombtc/onchain/FromBTCWrapper.ts +4 -2
  234. package/src/swaps/escrow_swaps/tobtc/ln/ToBTCLNWrapper.ts +6 -6
  235. package/src/swaps/escrow_swaps/tobtc/onchain/ToBTCWrapper.ts +5 -5
  236. package/src/swaps/spv_swaps/SpvFromBTCSwap.ts +4 -1
  237. package/src/swaps/spv_swaps/SpvFromBTCWrapper.ts +10 -2
  238. package/src/swaps/trusted/ln/LnForGasWrapper.ts +1 -1
  239. package/src/swaps/trusted/onchain/OnchainForGasWrapper.ts +1 -1
@@ -1,1443 +1,1443 @@
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 IntermediaryAPI_1 = require("../../intermediaries/apis/IntermediaryAPI");
13
- const FeeType_1 = require("../../enums/FeeType");
14
- const PercentagePPM_1 = require("../../types/fees/PercentagePPM");
15
- const TokenAmount_1 = require("../../types/TokenAmount");
16
- const Token_1 = require("../../types/Token");
17
- const Logger_1 = require("../../utils/Logger");
18
- const TimeoutUtils_1 = require("../../utils/TimeoutUtils");
19
- const PriceInfoType_1 = require("../../types/PriceInfoType");
20
- const BitcoinWalletUtils_1 = require("../../utils/BitcoinWalletUtils");
21
- /**
22
- * State enum for SPV vault (UTXO-controlled vault) based swaps
23
- * @category Swaps/Bitcoin Smart chain
24
- */
25
- var SpvFromBTCSwapState;
26
- (function (SpvFromBTCSwapState) {
27
- /**
28
- * Catastrophic failure has occurred when processing the swap on the smart chain side,
29
- * this implies a bug in the smart contract code or the user and intermediary deliberately
30
- * creating a bitcoin transaction with invalid format unparsable by the smart contract.
31
- */
32
- SpvFromBTCSwapState[SpvFromBTCSwapState["CLOSED"] = -5] = "CLOSED";
33
- /**
34
- * Some of the bitcoin swap transaction inputs were double-spent, this means the swap
35
- * has failed and no BTC was sent
36
- */
37
- SpvFromBTCSwapState[SpvFromBTCSwapState["FAILED"] = -4] = "FAILED";
38
- /**
39
- * The intermediary (LP) declined to co-sign the submitted PSBT, hence the swap failed
40
- */
41
- SpvFromBTCSwapState[SpvFromBTCSwapState["DECLINED"] = -3] = "DECLINED";
42
- /**
43
- * Swap has expired for good and there is no way how it can be executed anymore
44
- */
45
- SpvFromBTCSwapState[SpvFromBTCSwapState["QUOTE_EXPIRED"] = -2] = "QUOTE_EXPIRED";
46
- /**
47
- * A swap is almost expired, and it should be presented to the user as expired, though
48
- * there is still a chance that it will be processed
49
- */
50
- SpvFromBTCSwapState[SpvFromBTCSwapState["QUOTE_SOFT_EXPIRED"] = -1] = "QUOTE_SOFT_EXPIRED";
51
- /**
52
- * Swap was created, use the {@link SpvFromBTCSwap.getFundedPsbt} or {@link SpvFromBTCSwap.getPsbt} functions
53
- * to get the bitcoin swap PSBT that should be signed by the user's wallet and then submitted via the
54
- * {@link SpvFromBTCSwap.submitPsbt} function.
55
- */
56
- SpvFromBTCSwapState[SpvFromBTCSwapState["CREATED"] = 0] = "CREATED";
57
- /**
58
- * Swap bitcoin PSBT was submitted by the client to the SDK
59
- */
60
- SpvFromBTCSwapState[SpvFromBTCSwapState["SIGNED"] = 1] = "SIGNED";
61
- /**
62
- * Swap bitcoin PSBT sent to the intermediary (LP), waiting for the intermediary co-sign
63
- * it and broadcast. You can use the {@link SpvFromBTCSwap.waitTillClaimedOrFronted}
64
- * function to wait till the intermediary broadcasts the transaction and the transaction
65
- * confirms.
66
- */
67
- SpvFromBTCSwapState[SpvFromBTCSwapState["POSTED"] = 2] = "POSTED";
68
- /**
69
- * Intermediary (LP) has co-signed and broadcasted the bitcoin transaction. You can use the
70
- * {@link SpvFromBTCSwap.waitTillClaimedOrFronted} function to wait till the transaction
71
- * confirms.
72
- */
73
- SpvFromBTCSwapState[SpvFromBTCSwapState["BROADCASTED"] = 3] = "BROADCASTED";
74
- /**
75
- * Settlement on the destination smart chain was fronted and funds were already received
76
- * by the user, even before the final settlement.
77
- */
78
- SpvFromBTCSwapState[SpvFromBTCSwapState["FRONTED"] = 4] = "FRONTED";
79
- /**
80
- * Bitcoin transaction confirmed with necessary amount of confirmations, wait for automatic
81
- * settlement by the watchtower with the {@link waitTillClaimedOrFronted} function, or settle manually
82
- * using the {@link FromBTCSwap.claim} or {@link FromBTCSwap.txsClaim} function.
83
- */
84
- SpvFromBTCSwapState[SpvFromBTCSwapState["BTC_TX_CONFIRMED"] = 5] = "BTC_TX_CONFIRMED";
85
- /**
86
- * Swap settled on the smart chain and funds received
87
- */
88
- SpvFromBTCSwapState[SpvFromBTCSwapState["CLAIMED"] = 6] = "CLAIMED";
89
- })(SpvFromBTCSwapState = exports.SpvFromBTCSwapState || (exports.SpvFromBTCSwapState = {}));
90
- const SpvFromBTCSwapStateDescription = {
91
- [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.",
92
- [SpvFromBTCSwapState.FAILED]: "Some of the bitcoin swap transaction inputs were double-spent, this means the swap has failed and no BTC was sent",
93
- [SpvFromBTCSwapState.DECLINED]: "The intermediary (LP) declined to co-sign the submitted PSBT, hence the swap failed",
94
- [SpvFromBTCSwapState.QUOTE_EXPIRED]: "Swap has expired for good and there is no way how it can be executed anymore",
95
- [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",
96
- [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.",
97
- [SpvFromBTCSwapState.SIGNED]: "Swap bitcoin PSBT was submitted by the client to the SDK",
98
- [SpvFromBTCSwapState.POSTED]: "Swap bitcoin PSBT sent to the intermediary (LP), waiting for the intermediary co-sign it and broadcast.",
99
- [SpvFromBTCSwapState.BROADCASTED]: "Intermediary (LP) has co-signed and broadcasted the bitcoin transaction.",
100
- [SpvFromBTCSwapState.FRONTED]: "Settlement on the destination smart chain was fronted and funds were already received by the user, even before the final settlement.",
101
- [SpvFromBTCSwapState.BTC_TX_CONFIRMED]: "Bitcoin transaction confirmed with necessary amount of confirmations, wait for automatic settlement by the watchtower or settle manually.",
102
- [SpvFromBTCSwapState.CLAIMED]: "Swap settled on the smart chain and funds received"
103
- };
104
- function isSpvFromBTCSwapInit(obj) {
105
- return typeof obj === "object" &&
106
- typeof (obj.quoteId) === "string" &&
107
- typeof (obj.recipient) === "string" &&
108
- typeof (obj.vaultOwner) === "string" &&
109
- typeof (obj.vaultId) === "bigint" &&
110
- typeof (obj.vaultRequiredConfirmations) === "number" &&
111
- Array.isArray(obj.vaultTokenMultipliers) && obj.vaultTokenMultipliers.reduce((prev, curr) => prev && typeof (curr) === "bigint", true) &&
112
- typeof (obj.vaultBtcAddress) === "string" &&
113
- typeof (obj.vaultUtxo) === "string" &&
114
- typeof (obj.vaultUtxoValue) === "bigint" &&
115
- typeof (obj.btcDestinationAddress) === "string" &&
116
- typeof (obj.btcAmount) === "bigint" &&
117
- typeof (obj.btcAmountSwap) === "bigint" &&
118
- typeof (obj.btcAmountGas) === "bigint" &&
119
- typeof (obj.minimumBtcFeeRate) === "number" &&
120
- typeof (obj.outputTotalSwap) === "bigint" &&
121
- typeof (obj.outputSwapToken) === "string" &&
122
- typeof (obj.outputTotalGas) === "bigint" &&
123
- typeof (obj.outputGasToken) === "string" &&
124
- typeof (obj.gasSwapFeeBtc) === "bigint" &&
125
- typeof (obj.gasSwapFee) === "bigint" &&
126
- typeof (obj.callerFeeShare) === "bigint" &&
127
- typeof (obj.frontingFeeShare) === "bigint" &&
128
- typeof (obj.executionFeeShare) === "bigint" &&
129
- typeof (obj.genesisSmartChainBlockHeight) === "number" &&
130
- (obj.gasPricingInfo == null || (0, PriceInfoType_1.isPriceInfoType)(obj.gasPricingInfo)) &&
131
- (0, ISwap_1.isISwapInit)(obj);
132
- }
133
- exports.isSpvFromBTCSwapInit = isSpvFromBTCSwapInit;
134
- /**
135
- * New spv vault (UTXO-controlled vault) based swaps for Bitcoin -> Smart chain swaps not requiring
136
- * any initiation on the destination chain, and with the added possibility for the user to receive
137
- * a native token on the destination chain as part of the swap (a "gas drop" feature).
138
- *
139
- * @category Swaps/Bitcoin → Smart chain
140
- */
141
- class SpvFromBTCSwap extends ISwap_1.ISwap {
142
- constructor(wrapper, initOrObject) {
143
- if (isSpvFromBTCSwapInit(initOrObject) && initOrObject.url != null)
144
- initOrObject.url += "/frombtc_spv";
145
- super(wrapper, initOrObject);
146
- this.currentVersion = 2;
147
- this.TYPE = SwapType_1.SwapType.SPV_VAULT_FROM_BTC;
148
- /**
149
- * @internal
150
- */
151
- this.swapStateDescription = SpvFromBTCSwapStateDescription;
152
- /**
153
- * @internal
154
- */
155
- this.swapStateName = (state) => SpvFromBTCSwapState[state];
156
- if (isSpvFromBTCSwapInit(initOrObject)) {
157
- this._state = SpvFromBTCSwapState.CREATED;
158
- this.quoteId = initOrObject.quoteId;
159
- this.recipient = initOrObject.recipient;
160
- this.vaultOwner = initOrObject.vaultOwner;
161
- this.vaultId = initOrObject.vaultId;
162
- this.vaultRequiredConfirmations = initOrObject.vaultRequiredConfirmations;
163
- this.vaultTokenMultipliers = initOrObject.vaultTokenMultipliers;
164
- this.vaultBtcAddress = initOrObject.vaultBtcAddress;
165
- this.vaultUtxo = initOrObject.vaultUtxo;
166
- this.vaultUtxoValue = initOrObject.vaultUtxoValue;
167
- this.btcDestinationAddress = initOrObject.btcDestinationAddress;
168
- this.btcAmount = initOrObject.btcAmount;
169
- this.btcAmountSwap = initOrObject.btcAmountSwap;
170
- this.btcAmountGas = initOrObject.btcAmountGas;
171
- this.minimumBtcFeeRate = initOrObject.minimumBtcFeeRate;
172
- this.outputTotalSwap = initOrObject.outputTotalSwap;
173
- this.outputSwapToken = initOrObject.outputSwapToken;
174
- this.outputTotalGas = initOrObject.outputTotalGas;
175
- this.outputGasToken = initOrObject.outputGasToken;
176
- this.gasSwapFeeBtc = initOrObject.gasSwapFeeBtc;
177
- this.gasSwapFee = initOrObject.gasSwapFee;
178
- this.callerFeeShare = initOrObject.callerFeeShare;
179
- this.frontingFeeShare = initOrObject.frontingFeeShare;
180
- this.executionFeeShare = initOrObject.executionFeeShare;
181
- this._genesisSmartChainBlockHeight = initOrObject.genesisSmartChainBlockHeight;
182
- this.gasPricingInfo = initOrObject.gasPricingInfo;
183
- const vaultAddressType = (0, BitcoinUtils_1.toCoinselectAddressType)((0, BitcoinUtils_1.toOutputScript)(this.wrapper._options.bitcoinNetwork, this.vaultBtcAddress));
184
- if (vaultAddressType !== "p2tr" && vaultAddressType !== "p2wpkh" && vaultAddressType !== "p2wsh")
185
- throw new Error("Vault address type must be of witness type: p2tr, p2wpkh, p2wsh");
186
- }
187
- else {
188
- this.quoteId = initOrObject.quoteId;
189
- this.recipient = initOrObject.recipient;
190
- this.vaultOwner = initOrObject.vaultOwner;
191
- this.vaultId = BigInt(initOrObject.vaultId);
192
- this.vaultRequiredConfirmations = initOrObject.vaultRequiredConfirmations;
193
- this.vaultTokenMultipliers = initOrObject.vaultTokenMultipliers.map((val) => BigInt(val));
194
- this.vaultBtcAddress = initOrObject.vaultBtcAddress;
195
- this.vaultUtxo = initOrObject.vaultUtxo;
196
- this.vaultUtxoValue = BigInt(initOrObject.vaultUtxoValue);
197
- this.btcDestinationAddress = initOrObject.btcDestinationAddress;
198
- this.btcAmount = BigInt(initOrObject.btcAmount);
199
- this.btcAmountSwap = BigInt(initOrObject.btcAmountSwap);
200
- this.btcAmountGas = BigInt(initOrObject.btcAmountGas);
201
- this.minimumBtcFeeRate = initOrObject.minimumBtcFeeRate;
202
- this.outputTotalSwap = BigInt(initOrObject.outputTotalSwap);
203
- this.outputSwapToken = initOrObject.outputSwapToken;
204
- this.outputTotalGas = BigInt(initOrObject.outputTotalGas);
205
- this.outputGasToken = initOrObject.outputGasToken;
206
- this.gasSwapFeeBtc = BigInt(initOrObject.gasSwapFeeBtc);
207
- this.gasSwapFee = BigInt(initOrObject.gasSwapFee);
208
- this.callerFeeShare = BigInt(initOrObject.callerFeeShare);
209
- this.frontingFeeShare = BigInt(initOrObject.frontingFeeShare);
210
- this.executionFeeShare = BigInt(initOrObject.executionFeeShare);
211
- this._genesisSmartChainBlockHeight = initOrObject.genesisSmartChainBlockHeight;
212
- this._senderAddress = initOrObject.senderAddress;
213
- this._claimTxId = initOrObject.claimTxId;
214
- this._frontTxId = initOrObject.frontTxId;
215
- this.gasPricingInfo = (0, PriceInfoType_1.deserializePriceInfoType)(initOrObject.gasPricingInfo);
216
- this.btcTxConfirmedAt = initOrObject.btcTxConfirmedAt;
217
- this.posted = initOrObject.posted;
218
- if (initOrObject.data != null)
219
- this._data = new this.wrapper._spvWithdrawalDataDeserializer(initOrObject.data);
220
- }
221
- this.tryCalculateSwapFee();
222
- this.logger = (0, Logger_1.getLogger)("SPVFromBTC(" + this.getId() + "): ");
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);
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._state === SpvFromBTCSwapState.CLAIMED || this._state === SpvFromBTCSwapState.QUOTE_EXPIRED || this._state === SpvFromBTCSwapState.FAILED;
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.wrapper._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.
591
- */
592
- async getPsbt() {
593
- const res = await this.getTransactionDetails();
594
- const psbt = new btc_signer_1.Transaction({
595
- allowUnknownOutputs: true,
596
- allowLegacyWitnessUtxo: true,
597
- lockTime: res.locktime
598
- });
599
- psbt.addInput({
600
- txid: res.in0txid,
601
- index: res.in0vout,
602
- witnessUtxo: {
603
- amount: res.vaultAmount,
604
- script: res.vaultScript
605
- },
606
- sequence: res.in0sequence
607
- });
608
- psbt.addOutput({
609
- amount: res.vaultAmount,
610
- script: res.vaultScript
611
- });
612
- psbt.addOutput({
613
- amount: 0n,
614
- script: res.out1script
615
- });
616
- psbt.addOutput({
617
- amount: res.out2amount,
618
- script: res.out2script
619
- });
620
- const serializedPsbt = buffer_1.Buffer.from(psbt.toPSBT());
621
- return {
622
- psbt,
623
- psbtHex: serializedPsbt.toString("hex"),
624
- psbtBase64: serializedPsbt.toString("base64"),
625
- in1sequence: res.in1sequence
626
- };
627
- }
628
- /**
629
- * Returns the PSBT that is already funded with wallet's UTXOs (runs a coin-selection algorithm to choose UTXOs to use),
630
- * also returns inputs indices that need to be signed by the wallet before submitting the PSBT back to the SDK with
631
- * {@link submitPsbt}
632
- *
633
- * @remarks
634
- * Note that when passing the `feeRate` argument, the fee must be at least {@link minimumBtcFeeRate} sats/vB.
635
- *
636
- * @param _bitcoinWallet Sender's bitcoin wallet
637
- * @param feeRate Optional fee rate in sats/vB for the transaction
638
- * @param additionalOutputs additional outputs to add to the PSBT - can be used to collect fees from users
639
- */
640
- async getFundedPsbt(_bitcoinWallet, feeRate, additionalOutputs) {
641
- const bitcoinWallet = (0, BitcoinWalletUtils_1.toBitcoinWallet)(_bitcoinWallet, this.wrapper._btcRpc, this.wrapper._options.bitcoinNetwork);
642
- if (feeRate != null) {
643
- if (feeRate < this.minimumBtcFeeRate)
644
- throw new Error("Bitcoin tx fee needs to be at least " + this.minimumBtcFeeRate + " sats/vB");
645
- }
646
- else {
647
- feeRate = Math.max(this.minimumBtcFeeRate, await bitcoinWallet.getFeeRate());
648
- }
649
- let { psbt, in1sequence } = await this.getPsbt();
650
- if (additionalOutputs != null)
651
- additionalOutputs.forEach(output => {
652
- psbt.addOutput({
653
- amount: output.amount,
654
- script: output.outputScript ?? (0, BitcoinUtils_1.toOutputScript)(this.wrapper._options.bitcoinNetwork, output.address)
655
- });
656
- });
657
- psbt = await bitcoinWallet.fundPsbt(psbt, feeRate);
658
- psbt.updateInput(1, { sequence: in1sequence });
659
- //Sign every input except the first one
660
- const signInputs = [];
661
- for (let i = 1; i < psbt.inputsLength; i++) {
662
- signInputs.push(i);
663
- }
664
- const serializedPsbt = buffer_1.Buffer.from(psbt.toPSBT());
665
- return {
666
- psbt,
667
- psbtHex: serializedPsbt.toString("hex"),
668
- psbtBase64: serializedPsbt.toString("base64"),
669
- signInputs
670
- };
671
- }
672
- /**
673
- * @inheritDoc
674
- */
675
- async submitPsbt(_psbt) {
676
- const psbt = (0, BitcoinUtils_1.parsePsbtTransaction)(_psbt);
677
- //Ensure not expired
678
- if (this.expiry < Date.now()) {
679
- throw new Error("Quote expired!");
680
- }
681
- //Ensure valid state
682
- if (this._state !== SpvFromBTCSwapState.QUOTE_SOFT_EXPIRED && this._state !== SpvFromBTCSwapState.CREATED) {
683
- throw new Error("Invalid swap state!");
684
- }
685
- if (this.url == null)
686
- throw new Error("LP URL not known, cannot submit PSBT!");
687
- //Ensure all inputs except the 1st are finalized
688
- for (let i = 1; i < psbt.inputsLength; i++) {
689
- if ((0, btc_signer_1.getInputType)(psbt.getInput(i)).txType === "legacy")
690
- throw new Error("Legacy (non-segwit) inputs are not allowed in the transaction!");
691
- psbt.finalizeIdx(i);
692
- }
693
- const btcTx = await this.wrapper._btcRpc.parseTransaction(buffer_1.Buffer.from(psbt.toBytes(true)).toString("hex"));
694
- const data = await this.wrapper._contract.getWithdrawalData(btcTx);
695
- this.logger.debug("submitPsbt(): parsed withdrawal data: ", data);
696
- //Verify correct withdrawal data
697
- if (!data.isRecipient(this.recipient) ||
698
- data.rawAmounts[0] * this.vaultTokenMultipliers[0] !== this.outputTotalSwap ||
699
- (data.rawAmounts[1] ?? 0n) * this.vaultTokenMultipliers[1] !== this.outputTotalGas ||
700
- data.callerFeeRate !== this.callerFeeShare ||
701
- data.frontingFeeRate !== this.frontingFeeShare ||
702
- data.executionFeeRate !== this.executionFeeShare ||
703
- data.getSpentVaultUtxo() !== this.vaultUtxo ||
704
- BigInt(data.getNewVaultBtcAmount()) !== this.vaultUtxoValue ||
705
- !data.getNewVaultScript().equals((0, BitcoinUtils_1.toOutputScript)(this.wrapper._options.bitcoinNetwork, this.vaultBtcAddress)) ||
706
- data.getExecutionData() != null) {
707
- throw new Error("Invalid withdrawal tx data submitted!");
708
- }
709
- //Verify correct LP output
710
- const lpOutput = psbt.getOutput(2);
711
- if (lpOutput.script == null ||
712
- lpOutput.amount !== this.btcAmount ||
713
- !(0, BitcoinUtils_1.toOutputScript)(this.wrapper._options.bitcoinNetwork, this.btcDestinationAddress).equals(buffer_1.Buffer.from(lpOutput.script))) {
714
- throw new Error("Invalid LP bitcoin output in transaction!");
715
- }
716
- //Verify vault utxo not spent yet
717
- if (await this.wrapper._btcRpc.isSpent(this.vaultUtxo)) {
718
- throw new Error("Vault UTXO already spent, please create new swap!");
719
- }
720
- //Verify tx is parsable by the contract
721
- try {
722
- await this.wrapper._contract.checkWithdrawalTx(data);
723
- }
724
- catch (e) {
725
- throw new Error("Transaction not parsable by the contract: " + (e.message ?? e.toString()));
726
- }
727
- //Ensure still not expired
728
- if (this.expiry < Date.now()) {
729
- throw new Error("Quote expired!");
730
- }
731
- this._data = data;
732
- this.initiated = true;
733
- this.posted = true;
734
- await this._saveAndEmit(SpvFromBTCSwapState.SIGNED);
735
- try {
736
- await IntermediaryAPI_1.IntermediaryAPI.initSpvFromBTC(this.chainIdentifier, this.url, {
737
- quoteId: this.quoteId,
738
- psbtHex: buffer_1.Buffer.from(psbt.toPSBT(0)).toString("hex")
739
- });
740
- await this._saveAndEmit(SpvFromBTCSwapState.POSTED);
741
- }
742
- catch (e) {
743
- await this._saveAndEmit(SpvFromBTCSwapState.DECLINED);
744
- throw e;
745
- }
746
- return this._data.getTxId();
747
- }
748
- /**
749
- * @inheritDoc
750
- */
751
- async estimateBitcoinFee(_bitcoinWallet, feeRate) {
752
- const bitcoinWallet = (0, BitcoinWalletUtils_1.toBitcoinWallet)(_bitcoinWallet, this.wrapper._btcRpc, this.wrapper._options.bitcoinNetwork);
753
- const txFee = await bitcoinWallet.getFundedPsbtFee((await this.getPsbt()).psbt, feeRate);
754
- if (txFee == null)
755
- return null;
756
- return (0, TokenAmount_1.toTokenAmount)(BigInt(txFee), Token_1.BitcoinTokens.BTC, this.wrapper._prices, this.pricingInfo);
757
- }
758
- /**
759
- * @inheritDoc
760
- */
761
- async sendBitcoinTransaction(wallet, feeRate) {
762
- const { psbt, psbtBase64, psbtHex, signInputs } = await this.getFundedPsbt(wallet, feeRate);
763
- let signedPsbt;
764
- if ((0, IBitcoinWallet_1.isIBitcoinWallet)(wallet)) {
765
- signedPsbt = await wallet.signPsbt(psbt, signInputs);
766
- }
767
- else {
768
- signedPsbt = await wallet.signPsbt({
769
- psbt, psbtHex, psbtBase64
770
- }, signInputs);
771
- }
772
- return await this.submitPsbt(signedPsbt);
773
- }
774
- /**
775
- * Executes the swap with the provided bitcoin wallet
776
- *
777
- * @param wallet Bitcoin wallet to use to sign the bitcoin transaction
778
- * @param callbacks Callbacks to track the progress of the swap
779
- * @param options Optional options for the swap like feeRate, AbortSignal, and timeouts/intervals
780
- *
781
- * @returns {boolean} Whether a swap was settled automatically by swap watchtowers or requires manual claim by the
782
- * user, in case `false` is returned the user should call the {@link claim} function to settle the swap on the
783
- * destination manually
784
- */
785
- async execute(wallet, callbacks, options) {
786
- if (this._state === SpvFromBTCSwapState.CLOSED)
787
- throw new Error("Swap encountered a catastrophic failure!");
788
- if (this._state === SpvFromBTCSwapState.FAILED)
789
- throw new Error("Swap failed!");
790
- if (this._state === SpvFromBTCSwapState.DECLINED)
791
- throw new Error("Swap execution already declined by the LP!");
792
- if (this._state === SpvFromBTCSwapState.QUOTE_EXPIRED)
793
- throw new Error("Swap quote expired!");
794
- if (this._state === SpvFromBTCSwapState.CLAIMED || this._state === SpvFromBTCSwapState.FRONTED)
795
- throw new Error("Swap already settled or fronted!");
796
- if (this._state === SpvFromBTCSwapState.CREATED) {
797
- const txId = await this.sendBitcoinTransaction(wallet, options?.feeRate);
798
- if (callbacks?.onSourceTransactionSent != null)
799
- callbacks.onSourceTransactionSent(txId);
800
- }
801
- if (this._state === SpvFromBTCSwapState.POSTED || this._state === SpvFromBTCSwapState.BROADCASTED) {
802
- const txId = await this.waitForBitcoinTransaction(callbacks?.onSourceTransactionConfirmationStatus, options?.btcTxCheckIntervalSeconds, options?.abortSignal);
803
- if (callbacks?.onSourceTransactionConfirmed != null)
804
- callbacks.onSourceTransactionConfirmed(txId);
805
- }
806
- // @ts-ignore
807
- if (this._state === SpvFromBTCSwapState.CLAIMED || this._state === SpvFromBTCSwapState.FRONTED)
808
- return true;
809
- if (this._state === SpvFromBTCSwapState.BTC_TX_CONFIRMED) {
810
- const success = await this.waitTillClaimedOrFronted(options?.maxWaitTillAutomaticSettlementSeconds ?? 60, options?.abortSignal);
811
- if (success && callbacks?.onSwapSettled != null)
812
- callbacks.onSwapSettled(this.getOutputTxId());
813
- return success;
814
- }
815
- throw new Error("Unexpected state reached!");
816
- }
817
- /**
818
- * @inheritDoc
819
- *
820
- * @param options.bitcoinFeeRate Optional fee rate to use for the created Bitcoin transaction
821
- * @param options.bitcoinWallet Optional bitcoin wallet address specification to return a funded PSBT,
822
- * if not provided a raw PSBT is returned instead which necessitates the implementor to manually add
823
- * inputs to the bitcoin transaction and **set the nSequence field of the 2nd input** (input 1 -
824
- * indexing from 0) to the value returned in `in1sequence`
825
- */
826
- async txsExecute(options) {
827
- if (this._state === SpvFromBTCSwapState.CREATED) {
828
- if (!await this._verifyQuoteValid())
829
- throw new Error("Quote already expired or close to expiry!");
830
- return [
831
- {
832
- name: "Payment",
833
- description: "Send funds to the bitcoin swap address",
834
- chain: "BITCOIN",
835
- txs: [
836
- options?.bitcoinWallet == null
837
- ? { ...await this.getPsbt(), type: "RAW_PSBT" }
838
- : { ...await this.getFundedPsbt(options.bitcoinWallet, options?.bitcoinFeeRate), type: "FUNDED_PSBT" }
839
- ]
840
- }
841
- ];
842
- }
843
- throw new Error("Invalid swap state to obtain execution txns, required CREATED");
844
- }
845
- /**
846
- * @inheritDoc
847
- *
848
- * @param options.bitcoinFeeRate Optional fee rate to use for the created Bitcoin transaction
849
- * @param options.bitcoinWallet Optional bitcoin wallet address specification to return a funded PSBT,
850
- * if not provided a raw PSBT is returned instead which necessitates the implementor to manually add
851
- * inputs to the bitcoin transaction and **set the nSequence field of the 2nd input** (input 1 -
852
- * indexing from 0) to the value returned in `in1sequence`
853
- * @param options.manualSettlementSmartChainSigner Optional smart chain signer to create a manual claim (settlement) transaction
854
- * @param options.maxWaitTillAutomaticSettlementSeconds Maximum time to wait for an automatic settlement after
855
- * the bitcoin transaction is confirmed (defaults to 60 seconds)
856
- */
857
- async getCurrentActions(options) {
858
- if (this._state === SpvFromBTCSwapState.CREATED) {
859
- try {
860
- return await this.txsExecute(options);
861
- }
862
- catch (e) { }
863
- }
864
- if (this._state === SpvFromBTCSwapState.BTC_TX_CONFIRMED) {
865
- if (this.btcTxConfirmedAt == null ||
866
- options?.maxWaitTillAutomaticSettlementSeconds === 0 ||
867
- (Date.now() - this.btcTxConfirmedAt) > (options?.maxWaitTillAutomaticSettlementSeconds ?? 60) * 1000) {
868
- return [{
869
- name: "Claim",
870
- description: "Manually settle (claim) the swap on the destination smart chain",
871
- chain: this.chainIdentifier,
872
- txs: await this.txsClaim(options?.manualSettlementSmartChainSigner)
873
- }];
874
- }
875
- }
876
- return [];
877
- }
878
- //////////////////////////////
879
- //// Bitcoin tx listener
880
- /**
881
- * Checks whether a bitcoin payment was already made, returns the payment or null when no payment has been made.
882
- * @internal
883
- */
884
- async getBitcoinPayment() {
885
- if (this._data?.btcTx?.txid == null)
886
- return null;
887
- const result = await this.wrapper._btcRpc.getTransaction(this._data?.btcTx?.txid);
888
- if (result == null)
889
- return null;
890
- return {
891
- txId: result.txid,
892
- confirmations: result.confirmations ?? 0,
893
- targetConfirmations: this.vaultRequiredConfirmations,
894
- inputAddresses: result.inputAddresses
895
- };
896
- }
897
- /**
898
- * @inheritDoc
899
- *
900
- * @throws {Error} if in invalid state (must be {@link SpvFromBTCSwapState.POSTED} or
901
- * {@link SpvFromBTCSwapState.BROADCASTED} states)
902
- */
903
- async waitForBitcoinTransaction(updateCallback, checkIntervalSeconds, abortSignal) {
904
- if (this._state !== SpvFromBTCSwapState.POSTED &&
905
- this._state !== SpvFromBTCSwapState.BROADCASTED &&
906
- !(this._state === SpvFromBTCSwapState.QUOTE_SOFT_EXPIRED && this.posted))
907
- throw new Error("Must be in POSTED or BROADCASTED state!");
908
- if (this._data == null)
909
- throw new Error("Expected swap to have withdrawal data filled!");
910
- const result = await this.wrapper._btcRpc.waitForTransaction(this._data.btcTx.txid, this.vaultRequiredConfirmations, (btcTx, txEtaMs) => {
911
- if (updateCallback != null)
912
- updateCallback(btcTx?.txid, btcTx?.confirmations, this.vaultRequiredConfirmations, txEtaMs);
913
- if (btcTx == null)
914
- return;
915
- let save = false;
916
- if (btcTx.inputAddresses != null && this._senderAddress == null) {
917
- this._senderAddress = btcTx.inputAddresses[1];
918
- save = true;
919
- }
920
- if (this._state === SpvFromBTCSwapState.POSTED || this._state == SpvFromBTCSwapState.QUOTE_SOFT_EXPIRED) {
921
- this._state = SpvFromBTCSwapState.BROADCASTED;
922
- save = true;
923
- }
924
- if (save)
925
- this._saveAndEmit();
926
- }, abortSignal, checkIntervalSeconds);
927
- if (abortSignal != null)
928
- abortSignal.throwIfAborted();
929
- let save = false;
930
- if (result.inputAddresses != null && this._senderAddress == null) {
931
- this._senderAddress = result.inputAddresses[1];
932
- save = true;
933
- }
934
- if (this._state !== SpvFromBTCSwapState.FRONTED &&
935
- this._state !== SpvFromBTCSwapState.CLAIMED) {
936
- this.btcTxConfirmedAt ??= Date.now();
937
- this._state = SpvFromBTCSwapState.BTC_TX_CONFIRMED;
938
- save = true;
939
- }
940
- if (save)
941
- await this._saveAndEmit();
942
- return result.txid;
943
- }
944
- //////////////////////////////
945
- //// Claim
946
- /**
947
- * Returns transactions for settling (claiming) the swap if the swap requires manual settlement, you can check so
948
- * with isClaimable. After sending the transaction manually be sure to call the waitTillClaimed function to wait
949
- * till the claim transaction is observed, processed by the SDK and state of the swap properly updated.
950
- *
951
- * @remarks
952
- * Might also return transactions necessary to sync the bitcoin light client.
953
- *
954
- * @param _signer Address of the signer to create the claim transactions for, can also be different to the recipient
955
- *
956
- * @throws {Error} If the swap is in invalid state (must be {@link SpvFromBTCSwapState.BTC_TX_CONFIRMED})
957
- */
958
- async txsClaim(_signer) {
959
- let address = undefined;
960
- if (_signer != null) {
961
- if (typeof (_signer) === "string") {
962
- address = _signer;
963
- }
964
- else if ((0, base_1.isAbstractSigner)(_signer)) {
965
- address = _signer.getAddress();
966
- }
967
- else {
968
- address = (await this.wrapper._chain.wrapSigner(_signer)).getAddress();
969
- }
970
- }
971
- if (!this.isClaimable())
972
- throw new Error("Must be in BTC_TX_CONFIRMED state!");
973
- if (this._data == null)
974
- throw new Error("Expected swap to have withdrawal data filled!");
975
- const vaultData = await this.wrapper._contract.getVaultData(this.vaultOwner, this.vaultId);
976
- if (vaultData == null)
977
- throw new Error(`Vault data for ${this.vaultOwner}:${this.vaultId.toString(10)} not found (already closed???)!`);
978
- const btcTx = await this.wrapper._btcRpc.getTransaction(this._data.btcTx.txid);
979
- if (btcTx == null)
980
- throw new Error(`Bitcoin transaction ${this._data.btcTx.txid} not found!`);
981
- const txs = [btcTx];
982
- //Trace back from current tx to the vaultData-specified UTXO
983
- const vaultUtxo = vaultData.getUtxo();
984
- while (txs[0].ins[0].txid + ":" + txs[0].ins[0].vout !== vaultUtxo) {
985
- const btcTx = await this.wrapper._btcRpc.getTransaction(txs[0].ins[0].txid);
986
- if (btcTx == null)
987
- throw new Error(`Prior withdrawal bitcoin transaction ${this._data.btcTx.txid} not found!`);
988
- txs.unshift(btcTx);
989
- }
990
- //Parse transactions to withdrawal data
991
- const withdrawalData = [];
992
- for (let tx of txs) {
993
- withdrawalData.push(await this.wrapper._contract.getWithdrawalData(tx));
994
- }
995
- return await this.wrapper._contract.txsClaim(address ?? this._getInitiator(), vaultData, withdrawalData.map(tx => { return { tx }; }), this.wrapper._synchronizer, true);
996
- }
997
- /**
998
- * Settles the swap by claiming the funds on the destination chain if the swap requires manual settlement, you can
999
- * check so with isClaimable.
1000
- *
1001
- * @remarks
1002
- * Might also sync the bitcoin light client during the process.
1003
- *
1004
- * @param _signer Signer to use for signing the settlement transactions, can also be different to the recipient
1005
- * @param abortSignal Abort signal
1006
- * @param onBeforeTxSent Optional callback triggered before the claim transaction is broadcasted
1007
- *
1008
- * @throws {Error} If the swap is in invalid state (must be {@link SpvFromBTCSwapState.BTC_TX_CONFIRMED})
1009
- */
1010
- async claim(_signer, abortSignal, onBeforeTxSent) {
1011
- const signer = (0, base_1.isAbstractSigner)(_signer) ? _signer : await this.wrapper._chain.wrapSigner(_signer);
1012
- let txIds;
1013
- try {
1014
- let txCount = 0;
1015
- const txs = await this.txsClaim(signer);
1016
- txIds = await this.wrapper._chain.sendAndConfirm(signer, txs, true, abortSignal, undefined, (txId) => {
1017
- txCount++;
1018
- if (onBeforeTxSent != null && txCount === txs.length)
1019
- onBeforeTxSent(txId);
1020
- return Promise.resolve();
1021
- });
1022
- }
1023
- catch (e) {
1024
- if (this._data == null)
1025
- throw e;
1026
- this.logger.info("claim(): Failed to claim ourselves, checking swap claim state...");
1027
- if (this._state === SpvFromBTCSwapState.CLAIMED) {
1028
- this.logger.info("claim(): Transaction state is CLAIMED, swap was successfully claimed by the watchtower");
1029
- return this._claimTxId;
1030
- }
1031
- const withdrawalState = await this.wrapper._contract.getWithdrawalState(this._data, this._genesisSmartChainBlockHeight);
1032
- if (withdrawalState != null && withdrawalState.type === base_1.SpvWithdrawalStateType.CLAIMED) {
1033
- this.logger.info("claim(): Transaction status is CLAIMED, swap was successfully claimed by the watchtower");
1034
- this._claimTxId = withdrawalState.txId;
1035
- await this._saveAndEmit(SpvFromBTCSwapState.CLAIMED);
1036
- return withdrawalState.txId;
1037
- }
1038
- throw e;
1039
- }
1040
- this._claimTxId = txIds[0];
1041
- if (this._state === SpvFromBTCSwapState.POSTED || this._state === SpvFromBTCSwapState.BROADCASTED ||
1042
- this._state === SpvFromBTCSwapState.BTC_TX_CONFIRMED || this._state === SpvFromBTCSwapState.FAILED ||
1043
- this._state === SpvFromBTCSwapState.FRONTED) {
1044
- await this._saveAndEmit(SpvFromBTCSwapState.CLAIMED);
1045
- }
1046
- return txIds[0];
1047
- }
1048
- /**
1049
- * Periodically checks the chain to see whether the swap was finished (claimed or refunded)
1050
- *
1051
- * @param abortSignal
1052
- * @param interval How often to check (in seconds), default to 5s
1053
- * @internal
1054
- */
1055
- async watchdogWaitTillResult(abortSignal, interval = 5) {
1056
- if (this._data == null)
1057
- throw new Error("Cannot await the result before the btc transaction is sent!");
1058
- let status = { type: base_1.SpvWithdrawalStateType.NOT_FOUND };
1059
- while (status.type === base_1.SpvWithdrawalStateType.NOT_FOUND) {
1060
- await (0, TimeoutUtils_1.timeoutPromise)(interval * 1000, abortSignal);
1061
- try {
1062
- //Be smart about checking withdrawal state
1063
- if (await this._shouldCheckWithdrawalState()) {
1064
- status = await this.wrapper._contract.getWithdrawalState(this._data, this._genesisSmartChainBlockHeight) ?? { type: base_1.SpvWithdrawalStateType.NOT_FOUND };
1065
- }
1066
- }
1067
- catch (e) {
1068
- this.logger.error("watchdogWaitTillResult(): Error when fetching commit status: ", e);
1069
- }
1070
- }
1071
- if (abortSignal != null)
1072
- abortSignal.throwIfAborted();
1073
- return status;
1074
- }
1075
- /**
1076
- * Waits till the swap is successfully settled (claimed), should be called after sending the claim (settlement)
1077
- * transactions manually to wait till the SDK processes the settlement and updates the swap state accordingly.
1078
- *
1079
- * @remarks
1080
- * This is an alias for the {@link waitTillClaimedOrFronted} function and will also resolve if the swap has
1081
- * been fronted (not necessarily claimed)
1082
- *
1083
- * @param maxWaitTimeSeconds – Maximum time in seconds to wait for the swap to be settled
1084
- * @param abortSignal – AbortSignal
1085
- *
1086
- * @returns Whether the swap was claimed in time or not
1087
- */
1088
- waitTillClaimed(maxWaitTimeSeconds, abortSignal) {
1089
- return this.waitTillClaimedOrFronted(maxWaitTimeSeconds, abortSignal);
1090
- }
1091
- /**
1092
- * Waits till the swap is successfully fronted or settled on the destination chain
1093
- *
1094
- * @param maxWaitTimeSeconds Maximum time in seconds to wait for the swap to be settled (by default
1095
- * it waits indefinitely)
1096
- * @param abortSignal Abort signal
1097
- *
1098
- * @returns {boolean} whether the swap was claimed or fronted automatically or not, if the swap was not claimed
1099
- * the user can claim manually through the {@link claim} function
1100
- */
1101
- async waitTillClaimedOrFronted(maxWaitTimeSeconds, abortSignal) {
1102
- if (this._state === SpvFromBTCSwapState.CLAIMED || this._state === SpvFromBTCSwapState.FRONTED)
1103
- return Promise.resolve(true);
1104
- const abortController = (0, Utils_1.extendAbortController)(abortSignal);
1105
- let timedOut = false;
1106
- if (maxWaitTimeSeconds != null) {
1107
- const timeout = setTimeout(() => {
1108
- timedOut = true;
1109
- abortController.abort();
1110
- }, maxWaitTimeSeconds * 1000);
1111
- abortController.signal.addEventListener("abort", () => clearTimeout(timeout));
1112
- }
1113
- let res;
1114
- try {
1115
- res = await Promise.race([
1116
- this.watchdogWaitTillResult(abortController.signal),
1117
- this.waitTillState(SpvFromBTCSwapState.CLAIMED, "eq", abortController.signal).then(() => 0),
1118
- this.waitTillState(SpvFromBTCSwapState.FRONTED, "eq", abortController.signal).then(() => 1),
1119
- this.waitTillState(SpvFromBTCSwapState.FAILED, "eq", abortController.signal).then(() => 2),
1120
- ]);
1121
- abortController.abort();
1122
- }
1123
- catch (e) {
1124
- abortController.abort();
1125
- if (timedOut)
1126
- return false;
1127
- throw e;
1128
- }
1129
- if (typeof (res) === "number") {
1130
- if (res === 0) {
1131
- this.logger.debug("waitTillClaimedOrFronted(): Resolved from state change (CLAIMED)");
1132
- return true;
1133
- }
1134
- if (res === 1) {
1135
- this.logger.debug("waitTillClaimedOrFronted(): Resolved from state change (FRONTED)");
1136
- return true;
1137
- }
1138
- if (res === 2) {
1139
- this.logger.debug("waitTillClaimedOrFronted(): Resolved from state change (FAILED)");
1140
- throw new Error("Swap failed while waiting for claim or front");
1141
- }
1142
- throw new Error("Invalid numeric response, this should never happen!");
1143
- }
1144
- this.logger.debug("waitTillClaimedOrFronted(): Resolved from watchdog");
1145
- if (res.type === base_1.SpvWithdrawalStateType.FRONTED) {
1146
- if (this._state !== SpvFromBTCSwapState.FRONTED ||
1147
- this._state !== SpvFromBTCSwapState.CLAIMED) {
1148
- this._frontTxId = res.txId;
1149
- await this._saveAndEmit(SpvFromBTCSwapState.FRONTED);
1150
- }
1151
- }
1152
- if (res.type === base_1.SpvWithdrawalStateType.CLAIMED) {
1153
- if (this._state !== SpvFromBTCSwapState.CLAIMED) {
1154
- this._claimTxId = res.txId;
1155
- await this._saveAndEmit(SpvFromBTCSwapState.CLAIMED);
1156
- }
1157
- }
1158
- if (res.type === base_1.SpvWithdrawalStateType.CLOSED) {
1159
- if (this._state !== SpvFromBTCSwapState.CLOSED)
1160
- await this._saveAndEmit(SpvFromBTCSwapState.CLOSED);
1161
- throw new Error("Swap failed with catastrophic error!");
1162
- }
1163
- return true;
1164
- }
1165
- /**
1166
- * Waits till the bitcoin transaction confirms and swap settled on the destination chain
1167
- *
1168
- * @param updateCallback Callback called when txId is found, and also called with subsequent confirmations
1169
- * @param checkIntervalSeconds How often to check the bitcoin transaction (5 seconds by default)
1170
- * @param abortSignal Abort signal
1171
- *
1172
- * @throws {Error} if in invalid state (must be {@link SpvFromBTCSwapState.POSTED} or
1173
- * {@link SpvFromBTCSwapState.BROADCASTED} states)
1174
- */
1175
- async waitTillExecuted(updateCallback, checkIntervalSeconds, abortSignal) {
1176
- await this.waitForBitcoinTransaction(updateCallback, checkIntervalSeconds, abortSignal);
1177
- await this.waitTillClaimedOrFronted(undefined, abortSignal);
1178
- }
1179
- //////////////////////////////
1180
- //// Storage
1181
- /**
1182
- * @inheritDoc
1183
- */
1184
- serialize() {
1185
- return {
1186
- ...super.serialize(),
1187
- quoteId: this.quoteId,
1188
- recipient: this.recipient,
1189
- vaultOwner: this.vaultOwner,
1190
- vaultId: this.vaultId.toString(10),
1191
- vaultRequiredConfirmations: this.vaultRequiredConfirmations,
1192
- vaultTokenMultipliers: this.vaultTokenMultipliers.map(val => val.toString(10)),
1193
- vaultBtcAddress: this.vaultBtcAddress,
1194
- vaultUtxo: this.vaultUtxo,
1195
- vaultUtxoValue: this.vaultUtxoValue.toString(10),
1196
- btcDestinationAddress: this.btcDestinationAddress,
1197
- btcAmount: this.btcAmount.toString(10),
1198
- btcAmountSwap: this.btcAmountSwap.toString(10),
1199
- btcAmountGas: this.btcAmountGas.toString(10),
1200
- minimumBtcFeeRate: this.minimumBtcFeeRate,
1201
- outputTotalSwap: this.outputTotalSwap.toString(10),
1202
- outputSwapToken: this.outputSwapToken,
1203
- outputTotalGas: this.outputTotalGas.toString(10),
1204
- outputGasToken: this.outputGasToken,
1205
- gasSwapFeeBtc: this.gasSwapFeeBtc.toString(10),
1206
- gasSwapFee: this.gasSwapFee.toString(10),
1207
- callerFeeShare: this.callerFeeShare.toString(10),
1208
- frontingFeeShare: this.frontingFeeShare.toString(10),
1209
- executionFeeShare: this.executionFeeShare.toString(10),
1210
- genesisSmartChainBlockHeight: this._genesisSmartChainBlockHeight,
1211
- gasPricingInfo: (0, PriceInfoType_1.serializePriceInfoType)(this.gasPricingInfo),
1212
- posted: this.posted,
1213
- senderAddress: this._senderAddress,
1214
- claimTxId: this._claimTxId,
1215
- frontTxId: this._frontTxId,
1216
- data: this._data?.serialize(),
1217
- btcTxConfirmedAt: this.btcTxConfirmedAt
1218
- };
1219
- }
1220
- //////////////////////////////
1221
- //// Swap ticks & sync
1222
- /**
1223
- * Used to set the txId of the bitcoin payment from the on-chain events listener
1224
- *
1225
- * @param txId
1226
- * @internal
1227
- */
1228
- async _setBitcoinTxId(txId) {
1229
- if (this._data == null)
1230
- return;
1231
- if (txId != this._data.btcTx.txid)
1232
- return;
1233
- if (this._senderAddress != null)
1234
- return;
1235
- const btcTx = await this.wrapper._btcRpc.getTransaction(txId);
1236
- if (btcTx == null || btcTx.inputAddresses == null)
1237
- return;
1238
- this._senderAddress = btcTx.inputAddresses[1];
1239
- }
1240
- /**
1241
- * @internal
1242
- */
1243
- async _syncStateFromBitcoin(save) {
1244
- if (this._data?.btcTx == null)
1245
- return false;
1246
- //Check if bitcoin payment was confirmed
1247
- this.btcTxLastChecked = Date.now();
1248
- const res = await this.getBitcoinPayment();
1249
- if (res == null) {
1250
- //Check inputs double-spent
1251
- for (let input of this._data.btcTx.ins) {
1252
- if (await this.wrapper._btcRpc.isSpent(input.txid + ":" + input.vout, true)) {
1253
- if (this._state === SpvFromBTCSwapState.SIGNED ||
1254
- this._state === SpvFromBTCSwapState.POSTED ||
1255
- this._state === SpvFromBTCSwapState.QUOTE_SOFT_EXPIRED ||
1256
- this._state === SpvFromBTCSwapState.DECLINED) {
1257
- //One of the inputs was double-spent
1258
- this._state = SpvFromBTCSwapState.QUOTE_EXPIRED;
1259
- }
1260
- else {
1261
- //One of the inputs was double-spent
1262
- this._state = SpvFromBTCSwapState.FAILED;
1263
- }
1264
- if (save)
1265
- await this._saveAndEmit();
1266
- return true;
1267
- }
1268
- }
1269
- }
1270
- else {
1271
- let needsSave = false;
1272
- if (res.inputAddresses != null && this._senderAddress == null) {
1273
- this._senderAddress = res.inputAddresses[1];
1274
- needsSave = true;
1275
- }
1276
- if (res.confirmations >= this.vaultRequiredConfirmations) {
1277
- if (this._state !== SpvFromBTCSwapState.BTC_TX_CONFIRMED &&
1278
- this._state !== SpvFromBTCSwapState.FRONTED &&
1279
- this._state !== SpvFromBTCSwapState.CLAIMED) {
1280
- this.btcTxConfirmedAt ??= Date.now();
1281
- this._state = SpvFromBTCSwapState.BTC_TX_CONFIRMED;
1282
- needsSave = true;
1283
- }
1284
- }
1285
- else if (this._state === SpvFromBTCSwapState.QUOTE_SOFT_EXPIRED ||
1286
- this._state === SpvFromBTCSwapState.POSTED ||
1287
- this._state === SpvFromBTCSwapState.SIGNED ||
1288
- this._state === SpvFromBTCSwapState.DECLINED) {
1289
- this._state = SpvFromBTCSwapState.BROADCASTED;
1290
- needsSave = true;
1291
- }
1292
- if (needsSave && save)
1293
- await this._saveAndEmit();
1294
- return needsSave;
1295
- }
1296
- return false;
1297
- }
1298
- /**
1299
- * Checks the swap's state on-chain and compares it to its internal state, updates/changes it according to on-chain
1300
- * data
1301
- */
1302
- async syncStateFromChain() {
1303
- let changed = false;
1304
- if (this._state === SpvFromBTCSwapState.SIGNED ||
1305
- this._state === SpvFromBTCSwapState.POSTED ||
1306
- this._state === SpvFromBTCSwapState.BROADCASTED ||
1307
- this._state === SpvFromBTCSwapState.QUOTE_SOFT_EXPIRED ||
1308
- this._state === SpvFromBTCSwapState.DECLINED ||
1309
- this._state === SpvFromBTCSwapState.BTC_TX_CONFIRMED) {
1310
- //Check BTC transaction
1311
- if (await this._syncStateFromBitcoin(false))
1312
- changed ||= true;
1313
- }
1314
- if (this._state === SpvFromBTCSwapState.BROADCASTED || this._state === SpvFromBTCSwapState.BTC_TX_CONFIRMED) {
1315
- if (await this._shouldCheckWithdrawalState()) {
1316
- const status = await this.wrapper._contract.getWithdrawalState(this._data, this._genesisSmartChainBlockHeight);
1317
- this.logger.debug("syncStateFromChain(): status of " + this._data.btcTx.txid, status);
1318
- switch (status?.type) {
1319
- case base_1.SpvWithdrawalStateType.FRONTED:
1320
- this._frontTxId = status.txId;
1321
- this._state = SpvFromBTCSwapState.FRONTED;
1322
- changed ||= true;
1323
- break;
1324
- case base_1.SpvWithdrawalStateType.CLAIMED:
1325
- this._claimTxId = status.txId;
1326
- this._state = SpvFromBTCSwapState.CLAIMED;
1327
- changed ||= true;
1328
- break;
1329
- case base_1.SpvWithdrawalStateType.CLOSED:
1330
- this._state = SpvFromBTCSwapState.CLOSED;
1331
- changed ||= true;
1332
- break;
1333
- }
1334
- }
1335
- }
1336
- if (this._state === SpvFromBTCSwapState.CREATED ||
1337
- this._state === SpvFromBTCSwapState.SIGNED ||
1338
- this._state === SpvFromBTCSwapState.POSTED) {
1339
- if (this.expiry < Date.now()) {
1340
- if (this._state === SpvFromBTCSwapState.CREATED) {
1341
- this._state = SpvFromBTCSwapState.QUOTE_EXPIRED;
1342
- }
1343
- else {
1344
- this._state = SpvFromBTCSwapState.QUOTE_SOFT_EXPIRED;
1345
- }
1346
- changed ||= true;
1347
- }
1348
- }
1349
- return changed;
1350
- }
1351
- /**
1352
- * @inheritDoc
1353
- * @internal
1354
- */
1355
- async _sync(save) {
1356
- const changed = await this.syncStateFromChain();
1357
- if (changed && save)
1358
- await this._saveAndEmit();
1359
- return changed;
1360
- }
1361
- /**
1362
- * @inheritDoc
1363
- * @internal
1364
- */
1365
- async _tick(save) {
1366
- if (this._state === SpvFromBTCSwapState.CREATED ||
1367
- this._state === SpvFromBTCSwapState.SIGNED) {
1368
- if (this.getQuoteExpiry() < Date.now()) {
1369
- this._state = SpvFromBTCSwapState.QUOTE_SOFT_EXPIRED;
1370
- if (save)
1371
- await this._saveAndEmit();
1372
- return true;
1373
- }
1374
- }
1375
- if (this._state === SpvFromBTCSwapState.QUOTE_SOFT_EXPIRED && !this.posted) {
1376
- if (this.expiry < Date.now()) {
1377
- this._state = SpvFromBTCSwapState.QUOTE_EXPIRED;
1378
- if (save)
1379
- await this._saveAndEmit();
1380
- return true;
1381
- }
1382
- }
1383
- if (this.btcTxLastChecked == null || Date.now() - this.btcTxLastChecked > 120000) {
1384
- if (this._state === SpvFromBTCSwapState.POSTED ||
1385
- this._state === SpvFromBTCSwapState.BROADCASTED) {
1386
- try {
1387
- //Check if bitcoin payment was confirmed
1388
- return await this._syncStateFromBitcoin(save);
1389
- }
1390
- catch (e) {
1391
- this.logger.error("tickSwap(" + this.getId() + "): ", e);
1392
- }
1393
- }
1394
- }
1395
- return false;
1396
- }
1397
- /**
1398
- * Checks whether an on-chain withdrawal state should be fetched for this specific swap
1399
- *
1400
- * @internal
1401
- */
1402
- async _shouldCheckWithdrawalState(frontingAddress, vaultDataUtxo) {
1403
- if (frontingAddress === undefined)
1404
- frontingAddress = await this.wrapper._contract.getFronterAddress(this.vaultOwner, this.vaultId, this._data);
1405
- if (vaultDataUtxo === undefined)
1406
- vaultDataUtxo = await this.wrapper._contract.getVaultLatestUtxo(this.vaultOwner, this.vaultId);
1407
- if (frontingAddress != null)
1408
- return true; //In case the swap is fronted there will for sure be a fronted event
1409
- if (vaultDataUtxo == null)
1410
- return true; //Vault UTXO is null (the vault closed)
1411
- const [txId, _] = vaultDataUtxo.split(":");
1412
- //Don't check both txns if their txId is equal
1413
- if (this._data.btcTx.txid === txId)
1414
- return true;
1415
- const [btcTx, latestVaultTx] = await Promise.all([
1416
- this.wrapper._btcRpc.getTransaction(this._data.btcTx.txid),
1417
- this.wrapper._btcRpc.getTransaction(txId)
1418
- ]);
1419
- if (latestVaultTx == null || latestVaultTx.blockheight == null) {
1420
- //Something must've gone horribly wrong, the latest vault utxo tx of the vault either
1421
- // cannot be found on bitcoin network or is not even confirmed yet
1422
- this.logger.debug(`_shouldCheckWithdrawalState(): Latest vault utxo not found or not confirmed on bitcoin ${txId}`);
1423
- return false;
1424
- }
1425
- if (btcTx != null) {
1426
- const btcTxHeight = btcTx.blockheight;
1427
- const latestVaultTxHeight = latestVaultTx.blockheight;
1428
- //We also need to cover the case where bitcoin tx isn't confirmed yet (hence btxTxHeight==null)
1429
- if (btcTxHeight == null || latestVaultTxHeight < btcTxHeight) {
1430
- //Definitely not claimed!
1431
- this.logger.debug(`_shouldCheckWithdrawalState(): Skipped checking withdrawal state, latestVaultTxHeight: ${latestVaultTx.blockheight}, btcTxHeight: ${btcTxHeight} and not fronted!`);
1432
- return false;
1433
- }
1434
- }
1435
- else {
1436
- //Definitely not claimed because the transaction was probably double-spent (or evicted from mempool)
1437
- this.logger.debug(`_shouldCheckWithdrawalState(): Skipped checking withdrawal state, btc tx probably replaced or evicted: ${this._data.btcTx.txid} and not fronted`);
1438
- return false;
1439
- }
1440
- return true;
1441
- }
1442
- }
1443
- exports.SpvFromBTCSwap = SpvFromBTCSwap;
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.SpvFromBTCSwap = exports.SpvFromBTCSwapState = void 0;
4
+ exports.isSpvFromBTCSwapInit = isSpvFromBTCSwapInit;
5
+ const ISwap_1 = require("../ISwap");
6
+ const base_1 = require("@atomiqlabs/base");
7
+ const SwapType_1 = require("../../enums/SwapType");
8
+ const Utils_1 = require("../../utils/Utils");
9
+ const BitcoinUtils_1 = require("../../utils/BitcoinUtils");
10
+ const btc_signer_1 = require("@scure/btc-signer");
11
+ const buffer_1 = require("buffer");
12
+ const IBitcoinWallet_1 = require("../../bitcoin/wallet/IBitcoinWallet");
13
+ const IntermediaryAPI_1 = require("../../intermediaries/apis/IntermediaryAPI");
14
+ const FeeType_1 = require("../../enums/FeeType");
15
+ const PercentagePPM_1 = require("../../types/fees/PercentagePPM");
16
+ const TokenAmount_1 = require("../../types/TokenAmount");
17
+ const Token_1 = require("../../types/Token");
18
+ const Logger_1 = require("../../utils/Logger");
19
+ const TimeoutUtils_1 = require("../../utils/TimeoutUtils");
20
+ const PriceInfoType_1 = require("../../types/PriceInfoType");
21
+ const BitcoinWalletUtils_1 = require("../../utils/BitcoinWalletUtils");
22
+ /**
23
+ * State enum for SPV vault (UTXO-controlled vault) based swaps
24
+ * @category Swaps/Bitcoin → Smart chain
25
+ */
26
+ var SpvFromBTCSwapState;
27
+ (function (SpvFromBTCSwapState) {
28
+ /**
29
+ * Catastrophic failure has occurred when processing the swap on the smart chain side,
30
+ * this implies a bug in the smart contract code or the user and intermediary deliberately
31
+ * creating a bitcoin transaction with invalid format unparsable by the smart contract.
32
+ */
33
+ SpvFromBTCSwapState[SpvFromBTCSwapState["CLOSED"] = -5] = "CLOSED";
34
+ /**
35
+ * Some of the bitcoin swap transaction inputs were double-spent, this means the swap
36
+ * has failed and no BTC was sent
37
+ */
38
+ SpvFromBTCSwapState[SpvFromBTCSwapState["FAILED"] = -4] = "FAILED";
39
+ /**
40
+ * The intermediary (LP) declined to co-sign the submitted PSBT, hence the swap failed
41
+ */
42
+ SpvFromBTCSwapState[SpvFromBTCSwapState["DECLINED"] = -3] = "DECLINED";
43
+ /**
44
+ * Swap has expired for good and there is no way how it can be executed anymore
45
+ */
46
+ SpvFromBTCSwapState[SpvFromBTCSwapState["QUOTE_EXPIRED"] = -2] = "QUOTE_EXPIRED";
47
+ /**
48
+ * A swap is almost expired, and it should be presented to the user as expired, though
49
+ * there is still a chance that it will be processed
50
+ */
51
+ SpvFromBTCSwapState[SpvFromBTCSwapState["QUOTE_SOFT_EXPIRED"] = -1] = "QUOTE_SOFT_EXPIRED";
52
+ /**
53
+ * Swap was created, use the {@link SpvFromBTCSwap.getFundedPsbt} or {@link SpvFromBTCSwap.getPsbt} functions
54
+ * to get the bitcoin swap PSBT that should be signed by the user's wallet and then submitted via the
55
+ * {@link SpvFromBTCSwap.submitPsbt} function.
56
+ */
57
+ SpvFromBTCSwapState[SpvFromBTCSwapState["CREATED"] = 0] = "CREATED";
58
+ /**
59
+ * Swap bitcoin PSBT was submitted by the client to the SDK
60
+ */
61
+ SpvFromBTCSwapState[SpvFromBTCSwapState["SIGNED"] = 1] = "SIGNED";
62
+ /**
63
+ * Swap bitcoin PSBT sent to the intermediary (LP), waiting for the intermediary co-sign
64
+ * it and broadcast. You can use the {@link SpvFromBTCSwap.waitTillClaimedOrFronted}
65
+ * function to wait till the intermediary broadcasts the transaction and the transaction
66
+ * confirms.
67
+ */
68
+ SpvFromBTCSwapState[SpvFromBTCSwapState["POSTED"] = 2] = "POSTED";
69
+ /**
70
+ * Intermediary (LP) has co-signed and broadcasted the bitcoin transaction. You can use the
71
+ * {@link SpvFromBTCSwap.waitTillClaimedOrFronted} function to wait till the transaction
72
+ * confirms.
73
+ */
74
+ SpvFromBTCSwapState[SpvFromBTCSwapState["BROADCASTED"] = 3] = "BROADCASTED";
75
+ /**
76
+ * Settlement on the destination smart chain was fronted and funds were already received
77
+ * by the user, even before the final settlement.
78
+ */
79
+ SpvFromBTCSwapState[SpvFromBTCSwapState["FRONTED"] = 4] = "FRONTED";
80
+ /**
81
+ * Bitcoin transaction confirmed with necessary amount of confirmations, wait for automatic
82
+ * settlement by the watchtower with the {@link waitTillClaimedOrFronted} function, or settle manually
83
+ * using the {@link FromBTCSwap.claim} or {@link FromBTCSwap.txsClaim} function.
84
+ */
85
+ SpvFromBTCSwapState[SpvFromBTCSwapState["BTC_TX_CONFIRMED"] = 5] = "BTC_TX_CONFIRMED";
86
+ /**
87
+ * Swap settled on the smart chain and funds received
88
+ */
89
+ SpvFromBTCSwapState[SpvFromBTCSwapState["CLAIMED"] = 6] = "CLAIMED";
90
+ })(SpvFromBTCSwapState || (exports.SpvFromBTCSwapState = SpvFromBTCSwapState = {}));
91
+ const SpvFromBTCSwapStateDescription = {
92
+ [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.",
93
+ [SpvFromBTCSwapState.FAILED]: "Some of the bitcoin swap transaction inputs were double-spent, this means the swap has failed and no BTC was sent",
94
+ [SpvFromBTCSwapState.DECLINED]: "The intermediary (LP) declined to co-sign the submitted PSBT, hence the swap failed",
95
+ [SpvFromBTCSwapState.QUOTE_EXPIRED]: "Swap has expired for good and there is no way how it can be executed anymore",
96
+ [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",
97
+ [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.",
98
+ [SpvFromBTCSwapState.SIGNED]: "Swap bitcoin PSBT was submitted by the client to the SDK",
99
+ [SpvFromBTCSwapState.POSTED]: "Swap bitcoin PSBT sent to the intermediary (LP), waiting for the intermediary co-sign it and broadcast.",
100
+ [SpvFromBTCSwapState.BROADCASTED]: "Intermediary (LP) has co-signed and broadcasted the bitcoin transaction.",
101
+ [SpvFromBTCSwapState.FRONTED]: "Settlement on the destination smart chain was fronted and funds were already received by the user, even before the final settlement.",
102
+ [SpvFromBTCSwapState.BTC_TX_CONFIRMED]: "Bitcoin transaction confirmed with necessary amount of confirmations, wait for automatic settlement by the watchtower or settle manually.",
103
+ [SpvFromBTCSwapState.CLAIMED]: "Swap settled on the smart chain and funds received"
104
+ };
105
+ function isSpvFromBTCSwapInit(obj) {
106
+ return typeof obj === "object" &&
107
+ typeof (obj.quoteId) === "string" &&
108
+ typeof (obj.recipient) === "string" &&
109
+ typeof (obj.vaultOwner) === "string" &&
110
+ typeof (obj.vaultId) === "bigint" &&
111
+ typeof (obj.vaultRequiredConfirmations) === "number" &&
112
+ Array.isArray(obj.vaultTokenMultipliers) && obj.vaultTokenMultipliers.reduce((prev, curr) => prev && typeof (curr) === "bigint", true) &&
113
+ typeof (obj.vaultBtcAddress) === "string" &&
114
+ typeof (obj.vaultUtxo) === "string" &&
115
+ typeof (obj.vaultUtxoValue) === "bigint" &&
116
+ typeof (obj.btcDestinationAddress) === "string" &&
117
+ typeof (obj.btcAmount) === "bigint" &&
118
+ typeof (obj.btcAmountSwap) === "bigint" &&
119
+ typeof (obj.btcAmountGas) === "bigint" &&
120
+ typeof (obj.minimumBtcFeeRate) === "number" &&
121
+ typeof (obj.outputTotalSwap) === "bigint" &&
122
+ typeof (obj.outputSwapToken) === "string" &&
123
+ typeof (obj.outputTotalGas) === "bigint" &&
124
+ typeof (obj.outputGasToken) === "string" &&
125
+ typeof (obj.gasSwapFeeBtc) === "bigint" &&
126
+ typeof (obj.gasSwapFee) === "bigint" &&
127
+ typeof (obj.callerFeeShare) === "bigint" &&
128
+ typeof (obj.frontingFeeShare) === "bigint" &&
129
+ typeof (obj.executionFeeShare) === "bigint" &&
130
+ typeof (obj.genesisSmartChainBlockHeight) === "number" &&
131
+ (obj.gasPricingInfo == null || (0, PriceInfoType_1.isPriceInfoType)(obj.gasPricingInfo)) &&
132
+ (0, ISwap_1.isISwapInit)(obj);
133
+ }
134
+ /**
135
+ * New spv vault (UTXO-controlled vault) based swaps for Bitcoin -> Smart chain swaps not requiring
136
+ * any initiation on the destination chain, and with the added possibility for the user to receive
137
+ * a native token on the destination chain as part of the swap (a "gas drop" feature).
138
+ *
139
+ * @category Swaps/Bitcoin → Smart chain
140
+ */
141
+ class SpvFromBTCSwap extends ISwap_1.ISwap {
142
+ constructor(wrapper, initOrObject) {
143
+ if (isSpvFromBTCSwapInit(initOrObject) && initOrObject.url != null)
144
+ initOrObject.url += "/frombtc_spv";
145
+ super(wrapper, initOrObject);
146
+ this.currentVersion = 2;
147
+ this.TYPE = SwapType_1.SwapType.SPV_VAULT_FROM_BTC;
148
+ /**
149
+ * @internal
150
+ */
151
+ this.swapStateDescription = SpvFromBTCSwapStateDescription;
152
+ /**
153
+ * @internal
154
+ */
155
+ this.swapStateName = (state) => SpvFromBTCSwapState[state];
156
+ if (isSpvFromBTCSwapInit(initOrObject)) {
157
+ this._state = SpvFromBTCSwapState.CREATED;
158
+ this.quoteId = initOrObject.quoteId;
159
+ this.recipient = initOrObject.recipient;
160
+ this.vaultOwner = initOrObject.vaultOwner;
161
+ this.vaultId = initOrObject.vaultId;
162
+ this.vaultRequiredConfirmations = initOrObject.vaultRequiredConfirmations;
163
+ this.vaultTokenMultipliers = initOrObject.vaultTokenMultipliers;
164
+ this.vaultBtcAddress = initOrObject.vaultBtcAddress;
165
+ this.vaultUtxo = initOrObject.vaultUtxo;
166
+ this.vaultUtxoValue = initOrObject.vaultUtxoValue;
167
+ this.btcDestinationAddress = initOrObject.btcDestinationAddress;
168
+ this.btcAmount = initOrObject.btcAmount;
169
+ this.btcAmountSwap = initOrObject.btcAmountSwap;
170
+ this.btcAmountGas = initOrObject.btcAmountGas;
171
+ this.minimumBtcFeeRate = initOrObject.minimumBtcFeeRate;
172
+ this.outputTotalSwap = initOrObject.outputTotalSwap;
173
+ this.outputSwapToken = initOrObject.outputSwapToken;
174
+ this.outputTotalGas = initOrObject.outputTotalGas;
175
+ this.outputGasToken = initOrObject.outputGasToken;
176
+ this.gasSwapFeeBtc = initOrObject.gasSwapFeeBtc;
177
+ this.gasSwapFee = initOrObject.gasSwapFee;
178
+ this.callerFeeShare = initOrObject.callerFeeShare;
179
+ this.frontingFeeShare = initOrObject.frontingFeeShare;
180
+ this.executionFeeShare = initOrObject.executionFeeShare;
181
+ this._genesisSmartChainBlockHeight = initOrObject.genesisSmartChainBlockHeight;
182
+ this.gasPricingInfo = initOrObject.gasPricingInfo;
183
+ const vaultAddressType = (0, BitcoinUtils_1.toCoinselectAddressType)((0, BitcoinUtils_1.toOutputScript)(this.wrapper._options.bitcoinNetwork, this.vaultBtcAddress));
184
+ if (vaultAddressType !== "p2tr" && vaultAddressType !== "p2wpkh" && vaultAddressType !== "p2wsh")
185
+ throw new Error("Vault address type must be of witness type: p2tr, p2wpkh, p2wsh");
186
+ }
187
+ else {
188
+ this.quoteId = initOrObject.quoteId;
189
+ this.recipient = initOrObject.recipient;
190
+ this.vaultOwner = initOrObject.vaultOwner;
191
+ this.vaultId = BigInt(initOrObject.vaultId);
192
+ this.vaultRequiredConfirmations = initOrObject.vaultRequiredConfirmations;
193
+ this.vaultTokenMultipliers = initOrObject.vaultTokenMultipliers.map((val) => BigInt(val));
194
+ this.vaultBtcAddress = initOrObject.vaultBtcAddress;
195
+ this.vaultUtxo = initOrObject.vaultUtxo;
196
+ this.vaultUtxoValue = BigInt(initOrObject.vaultUtxoValue);
197
+ this.btcDestinationAddress = initOrObject.btcDestinationAddress;
198
+ this.btcAmount = BigInt(initOrObject.btcAmount);
199
+ this.btcAmountSwap = BigInt(initOrObject.btcAmountSwap);
200
+ this.btcAmountGas = BigInt(initOrObject.btcAmountGas);
201
+ this.minimumBtcFeeRate = initOrObject.minimumBtcFeeRate;
202
+ this.outputTotalSwap = BigInt(initOrObject.outputTotalSwap);
203
+ this.outputSwapToken = initOrObject.outputSwapToken;
204
+ this.outputTotalGas = BigInt(initOrObject.outputTotalGas);
205
+ this.outputGasToken = initOrObject.outputGasToken;
206
+ this.gasSwapFeeBtc = BigInt(initOrObject.gasSwapFeeBtc);
207
+ this.gasSwapFee = BigInt(initOrObject.gasSwapFee);
208
+ this.callerFeeShare = BigInt(initOrObject.callerFeeShare);
209
+ this.frontingFeeShare = BigInt(initOrObject.frontingFeeShare);
210
+ this.executionFeeShare = BigInt(initOrObject.executionFeeShare);
211
+ this._genesisSmartChainBlockHeight = initOrObject.genesisSmartChainBlockHeight;
212
+ this._senderAddress = initOrObject.senderAddress;
213
+ this._claimTxId = initOrObject.claimTxId;
214
+ this._frontTxId = initOrObject.frontTxId;
215
+ this.gasPricingInfo = (0, PriceInfoType_1.deserializePriceInfoType)(initOrObject.gasPricingInfo);
216
+ this.btcTxConfirmedAt = initOrObject.btcTxConfirmedAt;
217
+ this.posted = initOrObject.posted;
218
+ if (initOrObject.data != null)
219
+ this._data = new this.wrapper._spvWithdrawalDataDeserializer(initOrObject.data);
220
+ }
221
+ this.tryCalculateSwapFee();
222
+ this.logger = (0, Logger_1.getLogger)("SPVFromBTC(" + this.getId() + "): ");
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._state === SpvFromBTCSwapState.CLAIMED || this._state === SpvFromBTCSwapState.QUOTE_EXPIRED || this._state === SpvFromBTCSwapState.FAILED;
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.wrapper._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: 500_000_000 + Math.floor(Math.random() * 1_000_000_000) //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.
591
+ */
592
+ async getPsbt() {
593
+ const res = await this.getTransactionDetails();
594
+ const psbt = new btc_signer_1.Transaction({
595
+ allowUnknownOutputs: true,
596
+ allowLegacyWitnessUtxo: true,
597
+ lockTime: res.locktime
598
+ });
599
+ psbt.addInput({
600
+ txid: res.in0txid,
601
+ index: res.in0vout,
602
+ witnessUtxo: {
603
+ amount: res.vaultAmount,
604
+ script: res.vaultScript
605
+ },
606
+ sequence: res.in0sequence
607
+ });
608
+ psbt.addOutput({
609
+ amount: res.vaultAmount,
610
+ script: res.vaultScript
611
+ });
612
+ psbt.addOutput({
613
+ amount: 0n,
614
+ script: res.out1script
615
+ });
616
+ psbt.addOutput({
617
+ amount: res.out2amount,
618
+ script: res.out2script
619
+ });
620
+ const serializedPsbt = buffer_1.Buffer.from(psbt.toPSBT());
621
+ return {
622
+ psbt,
623
+ psbtHex: serializedPsbt.toString("hex"),
624
+ psbtBase64: serializedPsbt.toString("base64"),
625
+ in1sequence: res.in1sequence
626
+ };
627
+ }
628
+ /**
629
+ * Returns the PSBT that is already funded with wallet's UTXOs (runs a coin-selection algorithm to choose UTXOs to use),
630
+ * also returns inputs indices that need to be signed by the wallet before submitting the PSBT back to the SDK with
631
+ * {@link submitPsbt}
632
+ *
633
+ * @remarks
634
+ * Note that when passing the `feeRate` argument, the fee must be at least {@link minimumBtcFeeRate} sats/vB.
635
+ *
636
+ * @param _bitcoinWallet Sender's bitcoin wallet
637
+ * @param feeRate Optional fee rate in sats/vB for the transaction
638
+ * @param additionalOutputs additional outputs to add to the PSBT - can be used to collect fees from users
639
+ */
640
+ async getFundedPsbt(_bitcoinWallet, feeRate, additionalOutputs) {
641
+ const bitcoinWallet = (0, BitcoinWalletUtils_1.toBitcoinWallet)(_bitcoinWallet, this.wrapper._btcRpc, this.wrapper._options.bitcoinNetwork);
642
+ if (feeRate != null) {
643
+ if (feeRate < this.minimumBtcFeeRate)
644
+ throw new Error("Bitcoin tx fee needs to be at least " + this.minimumBtcFeeRate + " sats/vB");
645
+ }
646
+ else {
647
+ feeRate = Math.max(this.minimumBtcFeeRate, await bitcoinWallet.getFeeRate());
648
+ }
649
+ let { psbt, in1sequence } = await this.getPsbt();
650
+ if (additionalOutputs != null)
651
+ additionalOutputs.forEach(output => {
652
+ psbt.addOutput({
653
+ amount: output.amount,
654
+ script: output.outputScript ?? (0, BitcoinUtils_1.toOutputScript)(this.wrapper._options.bitcoinNetwork, output.address)
655
+ });
656
+ });
657
+ psbt = await bitcoinWallet.fundPsbt(psbt, feeRate);
658
+ psbt.updateInput(1, { sequence: in1sequence });
659
+ //Sign every input except the first one
660
+ const signInputs = [];
661
+ for (let i = 1; i < psbt.inputsLength; i++) {
662
+ signInputs.push(i);
663
+ }
664
+ const serializedPsbt = buffer_1.Buffer.from(psbt.toPSBT());
665
+ return {
666
+ psbt,
667
+ psbtHex: serializedPsbt.toString("hex"),
668
+ psbtBase64: serializedPsbt.toString("base64"),
669
+ signInputs
670
+ };
671
+ }
672
+ /**
673
+ * @inheritDoc
674
+ */
675
+ async submitPsbt(_psbt) {
676
+ const psbt = (0, BitcoinUtils_1.parsePsbtTransaction)(_psbt);
677
+ //Ensure not expired
678
+ if (this.expiry < Date.now()) {
679
+ throw new Error("Quote expired!");
680
+ }
681
+ //Ensure valid state
682
+ if (this._state !== SpvFromBTCSwapState.QUOTE_SOFT_EXPIRED && this._state !== SpvFromBTCSwapState.CREATED) {
683
+ throw new Error("Invalid swap state!");
684
+ }
685
+ if (this.url == null)
686
+ throw new Error("LP URL not known, cannot submit PSBT!");
687
+ //Ensure all inputs except the 1st are finalized
688
+ for (let i = 1; i < psbt.inputsLength; i++) {
689
+ if ((0, btc_signer_1.getInputType)(psbt.getInput(i)).txType === "legacy")
690
+ throw new Error("Legacy (non-segwit) inputs are not allowed in the transaction!");
691
+ psbt.finalizeIdx(i);
692
+ }
693
+ const btcTx = await this.wrapper._btcRpc.parseTransaction(buffer_1.Buffer.from(psbt.toBytes(true)).toString("hex"));
694
+ const data = await this.wrapper._contract.getWithdrawalData(btcTx);
695
+ this.logger.debug("submitPsbt(): parsed withdrawal data: ", data);
696
+ //Verify correct withdrawal data
697
+ if (!data.isRecipient(this.recipient) ||
698
+ data.rawAmounts[0] * this.vaultTokenMultipliers[0] !== this.outputTotalSwap ||
699
+ (data.rawAmounts[1] ?? 0n) * this.vaultTokenMultipliers[1] !== this.outputTotalGas ||
700
+ data.callerFeeRate !== this.callerFeeShare ||
701
+ data.frontingFeeRate !== this.frontingFeeShare ||
702
+ data.executionFeeRate !== this.executionFeeShare ||
703
+ data.getSpentVaultUtxo() !== this.vaultUtxo ||
704
+ BigInt(data.getNewVaultBtcAmount()) !== this.vaultUtxoValue ||
705
+ !data.getNewVaultScript().equals((0, BitcoinUtils_1.toOutputScript)(this.wrapper._options.bitcoinNetwork, this.vaultBtcAddress)) ||
706
+ data.getExecutionData() != null) {
707
+ throw new Error("Invalid withdrawal tx data submitted!");
708
+ }
709
+ //Verify correct LP output
710
+ const lpOutput = psbt.getOutput(2);
711
+ if (lpOutput.script == null ||
712
+ lpOutput.amount !== this.btcAmount ||
713
+ !(0, BitcoinUtils_1.toOutputScript)(this.wrapper._options.bitcoinNetwork, this.btcDestinationAddress).equals(buffer_1.Buffer.from(lpOutput.script))) {
714
+ throw new Error("Invalid LP bitcoin output in transaction!");
715
+ }
716
+ //Verify vault utxo not spent yet
717
+ if (await this.wrapper._btcRpc.isSpent(this.vaultUtxo)) {
718
+ throw new Error("Vault UTXO already spent, please create new swap!");
719
+ }
720
+ //Verify tx is parsable by the contract
721
+ try {
722
+ await this.wrapper._contract.checkWithdrawalTx(data);
723
+ }
724
+ catch (e) {
725
+ throw new Error("Transaction not parsable by the contract: " + (e.message ?? e.toString()));
726
+ }
727
+ //Ensure still not expired
728
+ if (this.expiry < Date.now()) {
729
+ throw new Error("Quote expired!");
730
+ }
731
+ this._data = data;
732
+ this.initiated = true;
733
+ this.posted = true;
734
+ await this._saveAndEmit(SpvFromBTCSwapState.SIGNED);
735
+ try {
736
+ await IntermediaryAPI_1.IntermediaryAPI.initSpvFromBTC(this.chainIdentifier, this.url, {
737
+ quoteId: this.quoteId,
738
+ psbtHex: buffer_1.Buffer.from(psbt.toPSBT(0)).toString("hex")
739
+ });
740
+ await this._saveAndEmit(SpvFromBTCSwapState.POSTED);
741
+ }
742
+ catch (e) {
743
+ await this._saveAndEmit(SpvFromBTCSwapState.DECLINED);
744
+ throw e;
745
+ }
746
+ return this._data.getTxId();
747
+ }
748
+ /**
749
+ * @inheritDoc
750
+ */
751
+ async estimateBitcoinFee(_bitcoinWallet, feeRate) {
752
+ const bitcoinWallet = (0, BitcoinWalletUtils_1.toBitcoinWallet)(_bitcoinWallet, this.wrapper._btcRpc, this.wrapper._options.bitcoinNetwork);
753
+ const txFee = await bitcoinWallet.getFundedPsbtFee((await this.getPsbt()).psbt, feeRate);
754
+ if (txFee == null)
755
+ return null;
756
+ return (0, TokenAmount_1.toTokenAmount)(BigInt(txFee), Token_1.BitcoinTokens.BTC, this.wrapper._prices, this.pricingInfo);
757
+ }
758
+ /**
759
+ * @inheritDoc
760
+ */
761
+ async sendBitcoinTransaction(wallet, feeRate) {
762
+ const { psbt, psbtBase64, psbtHex, signInputs } = await this.getFundedPsbt(wallet, feeRate);
763
+ let signedPsbt;
764
+ if ((0, IBitcoinWallet_1.isIBitcoinWallet)(wallet)) {
765
+ signedPsbt = await wallet.signPsbt(psbt, signInputs);
766
+ }
767
+ else {
768
+ signedPsbt = await wallet.signPsbt({
769
+ psbt, psbtHex, psbtBase64
770
+ }, signInputs);
771
+ }
772
+ return await this.submitPsbt(signedPsbt);
773
+ }
774
+ /**
775
+ * Executes the swap with the provided bitcoin wallet
776
+ *
777
+ * @param wallet Bitcoin wallet to use to sign the bitcoin transaction
778
+ * @param callbacks Callbacks to track the progress of the swap
779
+ * @param options Optional options for the swap like feeRate, AbortSignal, and timeouts/intervals
780
+ *
781
+ * @returns {boolean} Whether a swap was settled automatically by swap watchtowers or requires manual claim by the
782
+ * user, in case `false` is returned the user should call the {@link claim} function to settle the swap on the
783
+ * destination manually
784
+ */
785
+ async execute(wallet, callbacks, options) {
786
+ if (this._state === SpvFromBTCSwapState.CLOSED)
787
+ throw new Error("Swap encountered a catastrophic failure!");
788
+ if (this._state === SpvFromBTCSwapState.FAILED)
789
+ throw new Error("Swap failed!");
790
+ if (this._state === SpvFromBTCSwapState.DECLINED)
791
+ throw new Error("Swap execution already declined by the LP!");
792
+ if (this._state === SpvFromBTCSwapState.QUOTE_EXPIRED)
793
+ throw new Error("Swap quote expired!");
794
+ if (this._state === SpvFromBTCSwapState.CLAIMED || this._state === SpvFromBTCSwapState.FRONTED)
795
+ throw new Error("Swap already settled or fronted!");
796
+ if (this._state === SpvFromBTCSwapState.CREATED) {
797
+ const txId = await this.sendBitcoinTransaction(wallet, options?.feeRate);
798
+ if (callbacks?.onSourceTransactionSent != null)
799
+ callbacks.onSourceTransactionSent(txId);
800
+ }
801
+ if (this._state === SpvFromBTCSwapState.POSTED || this._state === SpvFromBTCSwapState.BROADCASTED) {
802
+ const txId = await this.waitForBitcoinTransaction(callbacks?.onSourceTransactionConfirmationStatus, options?.btcTxCheckIntervalSeconds, options?.abortSignal);
803
+ if (callbacks?.onSourceTransactionConfirmed != null)
804
+ callbacks.onSourceTransactionConfirmed(txId);
805
+ }
806
+ // @ts-ignore
807
+ if (this._state === SpvFromBTCSwapState.CLAIMED || this._state === SpvFromBTCSwapState.FRONTED)
808
+ return true;
809
+ if (this._state === SpvFromBTCSwapState.BTC_TX_CONFIRMED) {
810
+ const success = await this.waitTillClaimedOrFronted(options?.maxWaitTillAutomaticSettlementSeconds ?? 60, options?.abortSignal);
811
+ if (success && callbacks?.onSwapSettled != null)
812
+ callbacks.onSwapSettled(this.getOutputTxId());
813
+ return success;
814
+ }
815
+ throw new Error("Unexpected state reached!");
816
+ }
817
+ /**
818
+ * @inheritDoc
819
+ *
820
+ * @param options.bitcoinFeeRate Optional fee rate to use for the created Bitcoin transaction
821
+ * @param options.bitcoinWallet Optional bitcoin wallet address specification to return a funded PSBT,
822
+ * if not provided a raw PSBT is returned instead which necessitates the implementor to manually add
823
+ * inputs to the bitcoin transaction and **set the nSequence field of the 2nd input** (input 1 -
824
+ * indexing from 0) to the value returned in `in1sequence`
825
+ */
826
+ async txsExecute(options) {
827
+ if (this._state === SpvFromBTCSwapState.CREATED) {
828
+ if (!await this._verifyQuoteValid())
829
+ throw new Error("Quote already expired or close to expiry!");
830
+ return [
831
+ {
832
+ name: "Payment",
833
+ description: "Send funds to the bitcoin swap address",
834
+ chain: "BITCOIN",
835
+ txs: [
836
+ options?.bitcoinWallet == null
837
+ ? { ...await this.getPsbt(), type: "RAW_PSBT" }
838
+ : { ...await this.getFundedPsbt(options.bitcoinWallet, options?.bitcoinFeeRate), type: "FUNDED_PSBT" }
839
+ ]
840
+ }
841
+ ];
842
+ }
843
+ throw new Error("Invalid swap state to obtain execution txns, required CREATED");
844
+ }
845
+ /**
846
+ * @inheritDoc
847
+ *
848
+ * @param options.bitcoinFeeRate Optional fee rate to use for the created Bitcoin transaction
849
+ * @param options.bitcoinWallet Optional bitcoin wallet address specification to return a funded PSBT,
850
+ * if not provided a raw PSBT is returned instead which necessitates the implementor to manually add
851
+ * inputs to the bitcoin transaction and **set the nSequence field of the 2nd input** (input 1 -
852
+ * indexing from 0) to the value returned in `in1sequence`
853
+ * @param options.manualSettlementSmartChainSigner Optional smart chain signer to create a manual claim (settlement) transaction
854
+ * @param options.maxWaitTillAutomaticSettlementSeconds Maximum time to wait for an automatic settlement after
855
+ * the bitcoin transaction is confirmed (defaults to 60 seconds)
856
+ */
857
+ async getCurrentActions(options) {
858
+ if (this._state === SpvFromBTCSwapState.CREATED) {
859
+ try {
860
+ return await this.txsExecute(options);
861
+ }
862
+ catch (e) { }
863
+ }
864
+ if (this._state === SpvFromBTCSwapState.BTC_TX_CONFIRMED) {
865
+ if (this.btcTxConfirmedAt == null ||
866
+ options?.maxWaitTillAutomaticSettlementSeconds === 0 ||
867
+ (Date.now() - this.btcTxConfirmedAt) > (options?.maxWaitTillAutomaticSettlementSeconds ?? 60) * 1000) {
868
+ return [{
869
+ name: "Claim",
870
+ description: "Manually settle (claim) the swap on the destination smart chain",
871
+ chain: this.chainIdentifier,
872
+ txs: await this.txsClaim(options?.manualSettlementSmartChainSigner)
873
+ }];
874
+ }
875
+ }
876
+ return [];
877
+ }
878
+ //////////////////////////////
879
+ //// Bitcoin tx listener
880
+ /**
881
+ * Checks whether a bitcoin payment was already made, returns the payment or null when no payment has been made.
882
+ * @internal
883
+ */
884
+ async getBitcoinPayment() {
885
+ if (this._data?.btcTx?.txid == null)
886
+ return null;
887
+ const result = await this.wrapper._btcRpc.getTransaction(this._data?.btcTx?.txid);
888
+ if (result == null)
889
+ return null;
890
+ return {
891
+ txId: result.txid,
892
+ confirmations: result.confirmations ?? 0,
893
+ targetConfirmations: this.vaultRequiredConfirmations,
894
+ inputAddresses: result.inputAddresses
895
+ };
896
+ }
897
+ /**
898
+ * @inheritDoc
899
+ *
900
+ * @throws {Error} if in invalid state (must be {@link SpvFromBTCSwapState.POSTED} or
901
+ * {@link SpvFromBTCSwapState.BROADCASTED} states)
902
+ */
903
+ async waitForBitcoinTransaction(updateCallback, checkIntervalSeconds, abortSignal) {
904
+ if (this._state !== SpvFromBTCSwapState.POSTED &&
905
+ this._state !== SpvFromBTCSwapState.BROADCASTED &&
906
+ !(this._state === SpvFromBTCSwapState.QUOTE_SOFT_EXPIRED && this.posted))
907
+ throw new Error("Must be in POSTED or BROADCASTED state!");
908
+ if (this._data == null)
909
+ throw new Error("Expected swap to have withdrawal data filled!");
910
+ const result = await this.wrapper._btcRpc.waitForTransaction(this._data.btcTx.txid, this.vaultRequiredConfirmations, (btcTx, txEtaMs) => {
911
+ if (updateCallback != null)
912
+ updateCallback(btcTx?.txid, btcTx?.confirmations, this.vaultRequiredConfirmations, txEtaMs);
913
+ if (btcTx == null)
914
+ return;
915
+ let save = false;
916
+ if (btcTx.inputAddresses != null && this._senderAddress == null) {
917
+ this._senderAddress = btcTx.inputAddresses[1];
918
+ save = true;
919
+ }
920
+ if (this._state === SpvFromBTCSwapState.POSTED || this._state == SpvFromBTCSwapState.QUOTE_SOFT_EXPIRED) {
921
+ this._state = SpvFromBTCSwapState.BROADCASTED;
922
+ save = true;
923
+ }
924
+ if (save)
925
+ this._saveAndEmit();
926
+ }, abortSignal, checkIntervalSeconds);
927
+ if (abortSignal != null)
928
+ abortSignal.throwIfAborted();
929
+ let save = false;
930
+ if (result.inputAddresses != null && this._senderAddress == null) {
931
+ this._senderAddress = result.inputAddresses[1];
932
+ save = true;
933
+ }
934
+ if (this._state !== SpvFromBTCSwapState.FRONTED &&
935
+ this._state !== SpvFromBTCSwapState.CLAIMED) {
936
+ this.btcTxConfirmedAt ??= Date.now();
937
+ this._state = SpvFromBTCSwapState.BTC_TX_CONFIRMED;
938
+ save = true;
939
+ }
940
+ if (save)
941
+ await this._saveAndEmit();
942
+ return result.txid;
943
+ }
944
+ //////////////////////////////
945
+ //// Claim
946
+ /**
947
+ * Returns transactions for settling (claiming) the swap if the swap requires manual settlement, you can check so
948
+ * with isClaimable. After sending the transaction manually be sure to call the waitTillClaimed function to wait
949
+ * till the claim transaction is observed, processed by the SDK and state of the swap properly updated.
950
+ *
951
+ * @remarks
952
+ * Might also return transactions necessary to sync the bitcoin light client.
953
+ *
954
+ * @param _signer Address of the signer to create the claim transactions for, can also be different to the recipient
955
+ *
956
+ * @throws {Error} If the swap is in invalid state (must be {@link SpvFromBTCSwapState.BTC_TX_CONFIRMED})
957
+ */
958
+ async txsClaim(_signer) {
959
+ let address = undefined;
960
+ if (_signer != null) {
961
+ if (typeof (_signer) === "string") {
962
+ address = _signer;
963
+ }
964
+ else if ((0, base_1.isAbstractSigner)(_signer)) {
965
+ address = _signer.getAddress();
966
+ }
967
+ else {
968
+ address = (await this.wrapper._chain.wrapSigner(_signer)).getAddress();
969
+ }
970
+ }
971
+ if (!this.isClaimable())
972
+ throw new Error("Must be in BTC_TX_CONFIRMED state!");
973
+ if (this._data == null)
974
+ throw new Error("Expected swap to have withdrawal data filled!");
975
+ const vaultData = await this.wrapper._contract.getVaultData(this.vaultOwner, this.vaultId);
976
+ if (vaultData == null)
977
+ throw new Error(`Vault data for ${this.vaultOwner}:${this.vaultId.toString(10)} not found (already closed???)!`);
978
+ const btcTx = await this.wrapper._btcRpc.getTransaction(this._data.btcTx.txid);
979
+ if (btcTx == null)
980
+ throw new Error(`Bitcoin transaction ${this._data.btcTx.txid} not found!`);
981
+ const txs = [btcTx];
982
+ //Trace back from current tx to the vaultData-specified UTXO
983
+ const vaultUtxo = vaultData.getUtxo();
984
+ while (txs[0].ins[0].txid + ":" + txs[0].ins[0].vout !== vaultUtxo) {
985
+ const btcTx = await this.wrapper._btcRpc.getTransaction(txs[0].ins[0].txid);
986
+ if (btcTx == null)
987
+ throw new Error(`Prior withdrawal bitcoin transaction ${this._data.btcTx.txid} not found!`);
988
+ txs.unshift(btcTx);
989
+ }
990
+ //Parse transactions to withdrawal data
991
+ const withdrawalData = [];
992
+ for (let tx of txs) {
993
+ withdrawalData.push(await this.wrapper._contract.getWithdrawalData(tx));
994
+ }
995
+ return await this.wrapper._contract.txsClaim(address ?? this._getInitiator(), vaultData, withdrawalData.map(tx => { return { tx }; }), this.wrapper._synchronizer, true);
996
+ }
997
+ /**
998
+ * Settles the swap by claiming the funds on the destination chain if the swap requires manual settlement, you can
999
+ * check so with isClaimable.
1000
+ *
1001
+ * @remarks
1002
+ * Might also sync the bitcoin light client during the process.
1003
+ *
1004
+ * @param _signer Signer to use for signing the settlement transactions, can also be different to the recipient
1005
+ * @param abortSignal Abort signal
1006
+ * @param onBeforeTxSent Optional callback triggered before the claim transaction is broadcasted
1007
+ *
1008
+ * @throws {Error} If the swap is in invalid state (must be {@link SpvFromBTCSwapState.BTC_TX_CONFIRMED})
1009
+ */
1010
+ async claim(_signer, abortSignal, onBeforeTxSent) {
1011
+ const signer = (0, base_1.isAbstractSigner)(_signer) ? _signer : await this.wrapper._chain.wrapSigner(_signer);
1012
+ let txIds;
1013
+ try {
1014
+ let txCount = 0;
1015
+ const txs = await this.txsClaim(signer);
1016
+ txIds = await this.wrapper._chain.sendAndConfirm(signer, txs, true, abortSignal, undefined, (txId) => {
1017
+ txCount++;
1018
+ if (onBeforeTxSent != null && txCount === txs.length)
1019
+ onBeforeTxSent(txId);
1020
+ return Promise.resolve();
1021
+ });
1022
+ }
1023
+ catch (e) {
1024
+ if (this._data == null)
1025
+ throw e;
1026
+ this.logger.info("claim(): Failed to claim ourselves, checking swap claim state...");
1027
+ if (this._state === SpvFromBTCSwapState.CLAIMED) {
1028
+ this.logger.info("claim(): Transaction state is CLAIMED, swap was successfully claimed by the watchtower");
1029
+ return this._claimTxId;
1030
+ }
1031
+ const withdrawalState = await this.wrapper._contract.getWithdrawalState(this._data, this._genesisSmartChainBlockHeight);
1032
+ if (withdrawalState != null && withdrawalState.type === base_1.SpvWithdrawalStateType.CLAIMED) {
1033
+ this.logger.info("claim(): Transaction status is CLAIMED, swap was successfully claimed by the watchtower");
1034
+ this._claimTxId = withdrawalState.txId;
1035
+ await this._saveAndEmit(SpvFromBTCSwapState.CLAIMED);
1036
+ return withdrawalState.txId;
1037
+ }
1038
+ throw e;
1039
+ }
1040
+ this._claimTxId = txIds[0];
1041
+ if (this._state === SpvFromBTCSwapState.POSTED || this._state === SpvFromBTCSwapState.BROADCASTED ||
1042
+ this._state === SpvFromBTCSwapState.BTC_TX_CONFIRMED || this._state === SpvFromBTCSwapState.FAILED ||
1043
+ this._state === SpvFromBTCSwapState.FRONTED) {
1044
+ await this._saveAndEmit(SpvFromBTCSwapState.CLAIMED);
1045
+ }
1046
+ return txIds[0];
1047
+ }
1048
+ /**
1049
+ * Periodically checks the chain to see whether the swap was finished (claimed or refunded)
1050
+ *
1051
+ * @param abortSignal
1052
+ * @param interval How often to check (in seconds), default to 5s
1053
+ * @internal
1054
+ */
1055
+ async watchdogWaitTillResult(abortSignal, interval = 5) {
1056
+ if (this._data == null)
1057
+ throw new Error("Cannot await the result before the btc transaction is sent!");
1058
+ let status = { type: base_1.SpvWithdrawalStateType.NOT_FOUND };
1059
+ while (status.type === base_1.SpvWithdrawalStateType.NOT_FOUND) {
1060
+ await (0, TimeoutUtils_1.timeoutPromise)(interval * 1000, abortSignal);
1061
+ try {
1062
+ //Be smart about checking withdrawal state
1063
+ if (await this._shouldCheckWithdrawalState()) {
1064
+ status = await this.wrapper._contract.getWithdrawalState(this._data, this._genesisSmartChainBlockHeight) ?? { type: base_1.SpvWithdrawalStateType.NOT_FOUND };
1065
+ }
1066
+ }
1067
+ catch (e) {
1068
+ this.logger.error("watchdogWaitTillResult(): Error when fetching commit status: ", e);
1069
+ }
1070
+ }
1071
+ if (abortSignal != null)
1072
+ abortSignal.throwIfAborted();
1073
+ return status;
1074
+ }
1075
+ /**
1076
+ * Waits till the swap is successfully settled (claimed), should be called after sending the claim (settlement)
1077
+ * transactions manually to wait till the SDK processes the settlement and updates the swap state accordingly.
1078
+ *
1079
+ * @remarks
1080
+ * This is an alias for the {@link waitTillClaimedOrFronted} function and will also resolve if the swap has
1081
+ * been fronted (not necessarily claimed)
1082
+ *
1083
+ * @param maxWaitTimeSeconds – Maximum time in seconds to wait for the swap to be settled
1084
+ * @param abortSignal – AbortSignal
1085
+ *
1086
+ * @returns Whether the swap was claimed in time or not
1087
+ */
1088
+ waitTillClaimed(maxWaitTimeSeconds, abortSignal) {
1089
+ return this.waitTillClaimedOrFronted(maxWaitTimeSeconds, abortSignal);
1090
+ }
1091
+ /**
1092
+ * Waits till the swap is successfully fronted or settled on the destination chain
1093
+ *
1094
+ * @param maxWaitTimeSeconds Maximum time in seconds to wait for the swap to be settled (by default
1095
+ * it waits indefinitely)
1096
+ * @param abortSignal Abort signal
1097
+ *
1098
+ * @returns {boolean} whether the swap was claimed or fronted automatically or not, if the swap was not claimed
1099
+ * the user can claim manually through the {@link claim} function
1100
+ */
1101
+ async waitTillClaimedOrFronted(maxWaitTimeSeconds, abortSignal) {
1102
+ if (this._state === SpvFromBTCSwapState.CLAIMED || this._state === SpvFromBTCSwapState.FRONTED)
1103
+ return Promise.resolve(true);
1104
+ const abortController = (0, Utils_1.extendAbortController)(abortSignal);
1105
+ let timedOut = false;
1106
+ if (maxWaitTimeSeconds != null) {
1107
+ const timeout = setTimeout(() => {
1108
+ timedOut = true;
1109
+ abortController.abort();
1110
+ }, maxWaitTimeSeconds * 1000);
1111
+ abortController.signal.addEventListener("abort", () => clearTimeout(timeout));
1112
+ }
1113
+ let res;
1114
+ try {
1115
+ res = await Promise.race([
1116
+ this.watchdogWaitTillResult(abortController.signal),
1117
+ this.waitTillState(SpvFromBTCSwapState.CLAIMED, "eq", abortController.signal).then(() => 0),
1118
+ this.waitTillState(SpvFromBTCSwapState.FRONTED, "eq", abortController.signal).then(() => 1),
1119
+ this.waitTillState(SpvFromBTCSwapState.FAILED, "eq", abortController.signal).then(() => 2),
1120
+ ]);
1121
+ abortController.abort();
1122
+ }
1123
+ catch (e) {
1124
+ abortController.abort();
1125
+ if (timedOut)
1126
+ return false;
1127
+ throw e;
1128
+ }
1129
+ if (typeof (res) === "number") {
1130
+ if (res === 0) {
1131
+ this.logger.debug("waitTillClaimedOrFronted(): Resolved from state change (CLAIMED)");
1132
+ return true;
1133
+ }
1134
+ if (res === 1) {
1135
+ this.logger.debug("waitTillClaimedOrFronted(): Resolved from state change (FRONTED)");
1136
+ return true;
1137
+ }
1138
+ if (res === 2) {
1139
+ this.logger.debug("waitTillClaimedOrFronted(): Resolved from state change (FAILED)");
1140
+ throw new Error("Swap failed while waiting for claim or front");
1141
+ }
1142
+ throw new Error("Invalid numeric response, this should never happen!");
1143
+ }
1144
+ this.logger.debug("waitTillClaimedOrFronted(): Resolved from watchdog");
1145
+ if (res.type === base_1.SpvWithdrawalStateType.FRONTED) {
1146
+ if (this._state !== SpvFromBTCSwapState.FRONTED ||
1147
+ this._state !== SpvFromBTCSwapState.CLAIMED) {
1148
+ this._frontTxId = res.txId;
1149
+ await this._saveAndEmit(SpvFromBTCSwapState.FRONTED);
1150
+ }
1151
+ }
1152
+ if (res.type === base_1.SpvWithdrawalStateType.CLAIMED) {
1153
+ if (this._state !== SpvFromBTCSwapState.CLAIMED) {
1154
+ this._claimTxId = res.txId;
1155
+ await this._saveAndEmit(SpvFromBTCSwapState.CLAIMED);
1156
+ }
1157
+ }
1158
+ if (res.type === base_1.SpvWithdrawalStateType.CLOSED) {
1159
+ if (this._state !== SpvFromBTCSwapState.CLOSED)
1160
+ await this._saveAndEmit(SpvFromBTCSwapState.CLOSED);
1161
+ throw new Error("Swap failed with catastrophic error!");
1162
+ }
1163
+ return true;
1164
+ }
1165
+ /**
1166
+ * Waits till the bitcoin transaction confirms and swap settled on the destination chain
1167
+ *
1168
+ * @param updateCallback Callback called when txId is found, and also called with subsequent confirmations
1169
+ * @param checkIntervalSeconds How often to check the bitcoin transaction (5 seconds by default)
1170
+ * @param abortSignal Abort signal
1171
+ *
1172
+ * @throws {Error} if in invalid state (must be {@link SpvFromBTCSwapState.POSTED} or
1173
+ * {@link SpvFromBTCSwapState.BROADCASTED} states)
1174
+ */
1175
+ async waitTillExecuted(updateCallback, checkIntervalSeconds, abortSignal) {
1176
+ await this.waitForBitcoinTransaction(updateCallback, checkIntervalSeconds, abortSignal);
1177
+ await this.waitTillClaimedOrFronted(undefined, abortSignal);
1178
+ }
1179
+ //////////////////////////////
1180
+ //// Storage
1181
+ /**
1182
+ * @inheritDoc
1183
+ */
1184
+ serialize() {
1185
+ return {
1186
+ ...super.serialize(),
1187
+ quoteId: this.quoteId,
1188
+ recipient: this.recipient,
1189
+ vaultOwner: this.vaultOwner,
1190
+ vaultId: this.vaultId.toString(10),
1191
+ vaultRequiredConfirmations: this.vaultRequiredConfirmations,
1192
+ vaultTokenMultipliers: this.vaultTokenMultipliers.map(val => val.toString(10)),
1193
+ vaultBtcAddress: this.vaultBtcAddress,
1194
+ vaultUtxo: this.vaultUtxo,
1195
+ vaultUtxoValue: this.vaultUtxoValue.toString(10),
1196
+ btcDestinationAddress: this.btcDestinationAddress,
1197
+ btcAmount: this.btcAmount.toString(10),
1198
+ btcAmountSwap: this.btcAmountSwap.toString(10),
1199
+ btcAmountGas: this.btcAmountGas.toString(10),
1200
+ minimumBtcFeeRate: this.minimumBtcFeeRate,
1201
+ outputTotalSwap: this.outputTotalSwap.toString(10),
1202
+ outputSwapToken: this.outputSwapToken,
1203
+ outputTotalGas: this.outputTotalGas.toString(10),
1204
+ outputGasToken: this.outputGasToken,
1205
+ gasSwapFeeBtc: this.gasSwapFeeBtc.toString(10),
1206
+ gasSwapFee: this.gasSwapFee.toString(10),
1207
+ callerFeeShare: this.callerFeeShare.toString(10),
1208
+ frontingFeeShare: this.frontingFeeShare.toString(10),
1209
+ executionFeeShare: this.executionFeeShare.toString(10),
1210
+ genesisSmartChainBlockHeight: this._genesisSmartChainBlockHeight,
1211
+ gasPricingInfo: (0, PriceInfoType_1.serializePriceInfoType)(this.gasPricingInfo),
1212
+ posted: this.posted,
1213
+ senderAddress: this._senderAddress,
1214
+ claimTxId: this._claimTxId,
1215
+ frontTxId: this._frontTxId,
1216
+ data: this._data?.serialize(),
1217
+ btcTxConfirmedAt: this.btcTxConfirmedAt
1218
+ };
1219
+ }
1220
+ //////////////////////////////
1221
+ //// Swap ticks & sync
1222
+ /**
1223
+ * Used to set the txId of the bitcoin payment from the on-chain events listener
1224
+ *
1225
+ * @param txId
1226
+ * @internal
1227
+ */
1228
+ async _setBitcoinTxId(txId) {
1229
+ if (this._data == null)
1230
+ return;
1231
+ if (txId != this._data.btcTx.txid)
1232
+ return;
1233
+ if (this._senderAddress != null)
1234
+ return;
1235
+ const btcTx = await this.wrapper._btcRpc.getTransaction(txId);
1236
+ if (btcTx == null || btcTx.inputAddresses == null)
1237
+ return;
1238
+ this._senderAddress = btcTx.inputAddresses[1];
1239
+ }
1240
+ /**
1241
+ * @internal
1242
+ */
1243
+ async _syncStateFromBitcoin(save) {
1244
+ if (this._data?.btcTx == null)
1245
+ return false;
1246
+ //Check if bitcoin payment was confirmed
1247
+ this.btcTxLastChecked = Date.now();
1248
+ const res = await this.getBitcoinPayment();
1249
+ if (res == null) {
1250
+ //Check inputs double-spent
1251
+ for (let input of this._data.btcTx.ins) {
1252
+ if (await this.wrapper._btcRpc.isSpent(input.txid + ":" + input.vout, true)) {
1253
+ if (this._state === SpvFromBTCSwapState.SIGNED ||
1254
+ this._state === SpvFromBTCSwapState.POSTED ||
1255
+ this._state === SpvFromBTCSwapState.QUOTE_SOFT_EXPIRED ||
1256
+ this._state === SpvFromBTCSwapState.DECLINED) {
1257
+ //One of the inputs was double-spent
1258
+ this._state = SpvFromBTCSwapState.QUOTE_EXPIRED;
1259
+ }
1260
+ else {
1261
+ //One of the inputs was double-spent
1262
+ this._state = SpvFromBTCSwapState.FAILED;
1263
+ }
1264
+ if (save)
1265
+ await this._saveAndEmit();
1266
+ return true;
1267
+ }
1268
+ }
1269
+ }
1270
+ else {
1271
+ let needsSave = false;
1272
+ if (res.inputAddresses != null && this._senderAddress == null) {
1273
+ this._senderAddress = res.inputAddresses[1];
1274
+ needsSave = true;
1275
+ }
1276
+ if (res.confirmations >= this.vaultRequiredConfirmations) {
1277
+ if (this._state !== SpvFromBTCSwapState.BTC_TX_CONFIRMED &&
1278
+ this._state !== SpvFromBTCSwapState.FRONTED &&
1279
+ this._state !== SpvFromBTCSwapState.CLAIMED) {
1280
+ this.btcTxConfirmedAt ??= Date.now();
1281
+ this._state = SpvFromBTCSwapState.BTC_TX_CONFIRMED;
1282
+ needsSave = true;
1283
+ }
1284
+ }
1285
+ else if (this._state === SpvFromBTCSwapState.QUOTE_SOFT_EXPIRED ||
1286
+ this._state === SpvFromBTCSwapState.POSTED ||
1287
+ this._state === SpvFromBTCSwapState.SIGNED ||
1288
+ this._state === SpvFromBTCSwapState.DECLINED) {
1289
+ this._state = SpvFromBTCSwapState.BROADCASTED;
1290
+ needsSave = true;
1291
+ }
1292
+ if (needsSave && save)
1293
+ await this._saveAndEmit();
1294
+ return needsSave;
1295
+ }
1296
+ return false;
1297
+ }
1298
+ /**
1299
+ * Checks the swap's state on-chain and compares it to its internal state, updates/changes it according to on-chain
1300
+ * data
1301
+ */
1302
+ async syncStateFromChain() {
1303
+ let changed = false;
1304
+ if (this._state === SpvFromBTCSwapState.SIGNED ||
1305
+ this._state === SpvFromBTCSwapState.POSTED ||
1306
+ this._state === SpvFromBTCSwapState.BROADCASTED ||
1307
+ this._state === SpvFromBTCSwapState.QUOTE_SOFT_EXPIRED ||
1308
+ this._state === SpvFromBTCSwapState.DECLINED ||
1309
+ this._state === SpvFromBTCSwapState.BTC_TX_CONFIRMED) {
1310
+ //Check BTC transaction
1311
+ if (await this._syncStateFromBitcoin(false))
1312
+ changed ||= true;
1313
+ }
1314
+ if (this._state === SpvFromBTCSwapState.BROADCASTED || this._state === SpvFromBTCSwapState.BTC_TX_CONFIRMED) {
1315
+ if (await this._shouldCheckWithdrawalState()) {
1316
+ const status = await this.wrapper._contract.getWithdrawalState(this._data, this._genesisSmartChainBlockHeight);
1317
+ this.logger.debug("syncStateFromChain(): status of " + this._data.btcTx.txid, status);
1318
+ switch (status?.type) {
1319
+ case base_1.SpvWithdrawalStateType.FRONTED:
1320
+ this._frontTxId = status.txId;
1321
+ this._state = SpvFromBTCSwapState.FRONTED;
1322
+ changed ||= true;
1323
+ break;
1324
+ case base_1.SpvWithdrawalStateType.CLAIMED:
1325
+ this._claimTxId = status.txId;
1326
+ this._state = SpvFromBTCSwapState.CLAIMED;
1327
+ changed ||= true;
1328
+ break;
1329
+ case base_1.SpvWithdrawalStateType.CLOSED:
1330
+ this._state = SpvFromBTCSwapState.CLOSED;
1331
+ changed ||= true;
1332
+ break;
1333
+ }
1334
+ }
1335
+ }
1336
+ if (this._state === SpvFromBTCSwapState.CREATED ||
1337
+ this._state === SpvFromBTCSwapState.SIGNED ||
1338
+ this._state === SpvFromBTCSwapState.POSTED) {
1339
+ if (this.expiry < Date.now()) {
1340
+ if (this._state === SpvFromBTCSwapState.CREATED) {
1341
+ this._state = SpvFromBTCSwapState.QUOTE_EXPIRED;
1342
+ }
1343
+ else {
1344
+ this._state = SpvFromBTCSwapState.QUOTE_SOFT_EXPIRED;
1345
+ }
1346
+ changed ||= true;
1347
+ }
1348
+ }
1349
+ return changed;
1350
+ }
1351
+ /**
1352
+ * @inheritDoc
1353
+ * @internal
1354
+ */
1355
+ async _sync(save) {
1356
+ const changed = await this.syncStateFromChain();
1357
+ if (changed && save)
1358
+ await this._saveAndEmit();
1359
+ return changed;
1360
+ }
1361
+ /**
1362
+ * @inheritDoc
1363
+ * @internal
1364
+ */
1365
+ async _tick(save) {
1366
+ if (this._state === SpvFromBTCSwapState.CREATED ||
1367
+ this._state === SpvFromBTCSwapState.SIGNED) {
1368
+ if (this.getQuoteExpiry() < Date.now()) {
1369
+ this._state = SpvFromBTCSwapState.QUOTE_SOFT_EXPIRED;
1370
+ if (save)
1371
+ await this._saveAndEmit();
1372
+ return true;
1373
+ }
1374
+ }
1375
+ if (this._state === SpvFromBTCSwapState.QUOTE_SOFT_EXPIRED && !this.posted) {
1376
+ if (this.expiry < Date.now()) {
1377
+ this._state = SpvFromBTCSwapState.QUOTE_EXPIRED;
1378
+ if (save)
1379
+ await this._saveAndEmit();
1380
+ return true;
1381
+ }
1382
+ }
1383
+ if (this.btcTxLastChecked == null || Date.now() - this.btcTxLastChecked > 120_000) {
1384
+ if (this._state === SpvFromBTCSwapState.POSTED ||
1385
+ this._state === SpvFromBTCSwapState.BROADCASTED) {
1386
+ try {
1387
+ //Check if bitcoin payment was confirmed
1388
+ return await this._syncStateFromBitcoin(save);
1389
+ }
1390
+ catch (e) {
1391
+ this.logger.error("tickSwap(" + this.getId() + "): ", e);
1392
+ }
1393
+ }
1394
+ }
1395
+ return false;
1396
+ }
1397
+ /**
1398
+ * Checks whether an on-chain withdrawal state should be fetched for this specific swap
1399
+ *
1400
+ * @internal
1401
+ */
1402
+ async _shouldCheckWithdrawalState(frontingAddress, vaultDataUtxo) {
1403
+ if (frontingAddress === undefined)
1404
+ frontingAddress = await this.wrapper._contract.getFronterAddress(this.vaultOwner, this.vaultId, this._data);
1405
+ if (vaultDataUtxo === undefined)
1406
+ vaultDataUtxo = await this.wrapper._contract.getVaultLatestUtxo(this.vaultOwner, this.vaultId);
1407
+ if (frontingAddress != null)
1408
+ return true; //In case the swap is fronted there will for sure be a fronted event
1409
+ if (vaultDataUtxo == null)
1410
+ return true; //Vault UTXO is null (the vault closed)
1411
+ const [txId, _] = vaultDataUtxo.split(":");
1412
+ //Don't check both txns if their txId is equal
1413
+ if (this._data.btcTx.txid === txId)
1414
+ return true;
1415
+ const [btcTx, latestVaultTx] = await Promise.all([
1416
+ this.wrapper._btcRpc.getTransaction(this._data.btcTx.txid),
1417
+ this.wrapper._btcRpc.getTransaction(txId)
1418
+ ]);
1419
+ if (latestVaultTx == null || latestVaultTx.blockheight == null) {
1420
+ //Something must've gone horribly wrong, the latest vault utxo tx of the vault either
1421
+ // cannot be found on bitcoin network or is not even confirmed yet
1422
+ this.logger.debug(`_shouldCheckWithdrawalState(): Latest vault utxo not found or not confirmed on bitcoin ${txId}`);
1423
+ return false;
1424
+ }
1425
+ if (btcTx != null) {
1426
+ const btcTxHeight = btcTx.blockheight;
1427
+ const latestVaultTxHeight = latestVaultTx.blockheight;
1428
+ //We also need to cover the case where bitcoin tx isn't confirmed yet (hence btxTxHeight==null)
1429
+ if (btcTxHeight == null || latestVaultTxHeight < btcTxHeight) {
1430
+ //Definitely not claimed!
1431
+ this.logger.debug(`_shouldCheckWithdrawalState(): Skipped checking withdrawal state, latestVaultTxHeight: ${latestVaultTx.blockheight}, btcTxHeight: ${btcTxHeight} and not fronted!`);
1432
+ return false;
1433
+ }
1434
+ }
1435
+ else {
1436
+ //Definitely not claimed because the transaction was probably double-spent (or evicted from mempool)
1437
+ this.logger.debug(`_shouldCheckWithdrawalState(): Skipped checking withdrawal state, btc tx probably replaced or evicted: ${this._data.btcTx.txid} and not fronted`);
1438
+ return false;
1439
+ }
1440
+ return true;
1441
+ }
1442
+ }
1443
+ exports.SpvFromBTCSwap = SpvFromBTCSwap;