@atomiqlabs/sdk 8.6.6 → 8.6.7

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 (225) 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 +52 -51
  5. package/dist/bitcoin/coinselect2/blackjack.d.ts +6 -6
  6. package/dist/bitcoin/coinselect2/blackjack.js +38 -37
  7. package/dist/bitcoin/coinselect2/index.d.ts +19 -17
  8. package/dist/bitcoin/coinselect2/index.js +69 -69
  9. package/dist/bitcoin/coinselect2/utils.d.ts +77 -75
  10. package/dist/bitcoin/coinselect2/utils.js +123 -123
  11. package/dist/bitcoin/wallet/BitcoinWallet.d.ts +130 -128
  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 +21 -20
  15. package/dist/bitcoin/wallet/SingleAddressBitcoinWallet.d.ts +101 -99
  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 +91 -90
  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 +44 -42
  40. package/dist/http/paramcoders/ParamDecoder.js +137 -137
  41. package/dist/http/paramcoders/ParamEncoder.d.ts +20 -18
  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 +13 -11
  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 +174 -173
  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 +199 -198
  56. package/dist/intermediaries/IntermediaryDiscovery.js +406 -406
  57. package/dist/intermediaries/apis/IntermediaryAPI.d.ts +439 -437
  58. package/dist/intermediaries/apis/IntermediaryAPI.js +603 -603
  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 -168
  74. package/dist/prices/abstract/ISwapPrice.js +279 -279
  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 +687 -686
  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 +14 -13
  111. package/dist/swaps/IBTCWalletSwap.d.ts +73 -73
  112. package/dist/swaps/IBTCWalletSwap.js +18 -17
  113. package/dist/swaps/IClaimableSwap.d.ts +49 -49
  114. package/dist/swaps/IClaimableSwap.js +15 -14
  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 +14 -13
  119. package/dist/swaps/ISwap.d.ts +387 -386
  120. package/dist/swaps/ISwap.js +346 -346
  121. package/dist/swaps/ISwapWithGasDrop.d.ts +21 -21
  122. package/dist/swaps/ISwapWithGasDrop.js +12 -11
  123. package/dist/swaps/ISwapWrapper.d.ts +285 -283
  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 +135 -133
  128. package/dist/swaps/escrow_swaps/IEscrowSwap.js +169 -169
  129. package/dist/swaps/escrow_swaps/IEscrowSwapWrapper.d.ts +115 -114
  130. package/dist/swaps/escrow_swaps/IEscrowSwapWrapper.js +134 -134
  131. package/dist/swaps/escrow_swaps/frombtc/IFromBTCLNWrapper.d.ts +101 -98
  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 +531 -529
  138. package/dist/swaps/escrow_swaps/frombtc/ln/FromBTCLNSwap.js +1285 -1285
  139. package/dist/swaps/escrow_swaps/frombtc/ln/FromBTCLNWrapper.d.ts +184 -181
  140. package/dist/swaps/escrow_swaps/frombtc/ln/FromBTCLNWrapper.js +418 -418
  141. package/dist/swaps/escrow_swaps/frombtc/ln_auto/FromBTCLNAutoSwap.d.ts +583 -581
  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 +228 -225
  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 +191 -190
  148. package/dist/swaps/escrow_swaps/frombtc/onchain/FromBTCWrapper.js +378 -378
  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 +127 -125
  154. package/dist/swaps/escrow_swaps/tobtc/ln/ToBTCLNSwap.js +256 -256
  155. package/dist/swaps/escrow_swaps/tobtc/ln/ToBTCLNWrapper.d.ts +242 -241
  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 +128 -127
  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 +214 -213
  164. package/dist/swaps/spv_swaps/SpvFromBTCWrapper.js +756 -756
  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 +69 -68
  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 +57 -56
  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 +43 -42
  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 +60 -59
  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 +18 -17
  195. package/dist/types/lnurl/LNURLPay.d.ts +61 -61
  196. package/dist/types/lnurl/LNURLPay.js +31 -30
  197. package/dist/types/lnurl/LNURLWithdraw.d.ts +48 -48
  198. package/dist/types/lnurl/LNURLWithdraw.js +27 -26
  199. package/dist/types/wallets/LightningInvoiceCreateService.d.ts +24 -24
  200. package/dist/types/wallets/LightningInvoiceCreateService.js +15 -14
  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 +70 -69
  207. package/dist/utils/BitcoinUtils.d.ts +14 -12
  208. package/dist/utils/BitcoinUtils.js +102 -101
  209. package/dist/utils/BitcoinWalletUtils.d.ts +7 -7
  210. package/dist/utils/BitcoinWalletUtils.js +14 -13
  211. package/dist/utils/Logger.d.ts +7 -7
  212. package/dist/utils/Logger.js +12 -11
  213. package/dist/utils/RetryUtils.d.ts +22 -22
  214. package/dist/utils/RetryUtils.js +67 -66
  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 +55 -54
  219. package/dist/utils/TokenUtils.d.ts +19 -19
  220. package/dist/utils/TokenUtils.js +37 -36
  221. package/dist/utils/TypeUtils.d.ts +7 -7
  222. package/dist/utils/TypeUtils.js +2 -2
  223. package/dist/utils/Utils.d.ts +58 -56
  224. package/dist/utils/Utils.js +194 -193
  225. package/package.json +1 -1
@@ -1,924 +1,924 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.IToBTCSwap = exports.ToBTCSwapState = void 0;
4
- exports.isIToBTCSwapInit = isIToBTCSwapInit;
5
- const base_1 = require("@atomiqlabs/base");
6
- const IntermediaryAPI_1 = require("../../../intermediaries/apis/IntermediaryAPI");
7
- const IntermediaryError_1 = require("../../../errors/IntermediaryError");
8
- const Utils_1 = require("../../../utils/Utils");
9
- const IEscrowSelfInitSwap_1 = require("../IEscrowSelfInitSwap");
10
- const FeeType_1 = require("../../../enums/FeeType");
11
- const PercentagePPM_1 = require("../../../types/fees/PercentagePPM");
12
- const TokenAmount_1 = require("../../../types/TokenAmount");
13
- const TimeoutUtils_1 = require("../../../utils/TimeoutUtils");
14
- function isIToBTCSwapInit(obj) {
15
- return typeof (obj.networkFee) === "bigint" &&
16
- typeof (obj.networkFeeBtc) === "bigint" &&
17
- (obj.signatureData == null || (typeof (obj.signatureData) === 'object' &&
18
- typeof (obj.signatureData.prefix) === "string" &&
19
- typeof (obj.signatureData.timeout) === "string" &&
20
- typeof (obj.signatureData.signature) === "string")) &&
21
- typeof (obj.data) === 'object' &&
22
- (0, IEscrowSelfInitSwap_1.isIEscrowSelfInitSwapInit)(obj);
23
- }
24
- /**
25
- * State enum for escrow-based Smart chain -> Bitcoin (on-chain & lightning) swaps
26
- *
27
- * @category Swaps/Smart chain → Bitcoin
28
- */
29
- var ToBTCSwapState;
30
- (function (ToBTCSwapState) {
31
- /**
32
- * Intermediary (LP) was unable to process the swap and the funds were refunded on the
33
- * source chain
34
- */
35
- ToBTCSwapState[ToBTCSwapState["REFUNDED"] = -3] = "REFUNDED";
36
- /**
37
- * Swap has expired for good and there is no way how it can be executed anymore
38
- */
39
- ToBTCSwapState[ToBTCSwapState["QUOTE_EXPIRED"] = -2] = "QUOTE_EXPIRED";
40
- /**
41
- * A swap is almost expired, and it should be presented to the user as expired, though
42
- * there is still a chance that it will be processed
43
- */
44
- ToBTCSwapState[ToBTCSwapState["QUOTE_SOFT_EXPIRED"] = -1] = "QUOTE_SOFT_EXPIRED";
45
- /**
46
- * Swap was created, use the {@link IToBTCSwap.commit} or {@link IToBTCSwap.txsCommit} to
47
- * initiate it by creating the swap escrow on the source chain
48
- */
49
- ToBTCSwapState[ToBTCSwapState["CREATED"] = 0] = "CREATED";
50
- /**
51
- * Swap escrow was initiated (committed) on the source chain, the intermediary (LP) will
52
- * now process the swap. You can wait till that happens with the {@link IToBTCSwap.waitForPayment}
53
- * function.
54
- */
55
- ToBTCSwapState[ToBTCSwapState["COMMITED"] = 1] = "COMMITED";
56
- /**
57
- * The intermediary (LP) has processed the transaction and sent out the funds on the destination chain,
58
- * but hasn't yet settled the escrow on the source chain.
59
- */
60
- ToBTCSwapState[ToBTCSwapState["SOFT_CLAIMED"] = 2] = "SOFT_CLAIMED";
61
- /**
62
- * Swap was successfully settled by the intermediary (LP) on the source chain
63
- */
64
- ToBTCSwapState[ToBTCSwapState["CLAIMED"] = 3] = "CLAIMED";
65
- /**
66
- * Intermediary (LP) was unable to process the swap and the swap escrow on the source chain
67
- * is refundable, call {@link IToBTCSwap.refund} or {@link IToBTCSwap.txsRefund} to refund
68
- */
69
- ToBTCSwapState[ToBTCSwapState["REFUNDABLE"] = 4] = "REFUNDABLE";
70
- })(ToBTCSwapState || (exports.ToBTCSwapState = ToBTCSwapState = {}));
71
- const ToBTCSwapStateDescription = {
72
- [ToBTCSwapState.REFUNDED]: "Intermediary (LP) was unable to process the swap and the funds were refunded on the source chain",
73
- [ToBTCSwapState.QUOTE_EXPIRED]: "Swap has expired for good and there is no way how it can be executed anymore",
74
- [ToBTCSwapState.QUOTE_SOFT_EXPIRED]: "A swap is expired, though there is still a chance that it will be processed",
75
- [ToBTCSwapState.CREATED]: "Swap was created, initiate it by creating the swap escrow on the source chain",
76
- [ToBTCSwapState.COMMITED]: "Swap escrow was initiated (committed) on the source chain, the intermediary (LP) will now process the swap.",
77
- [ToBTCSwapState.SOFT_CLAIMED]: "The intermediary (LP) has processed the transaction and sent out the funds on the destination chain, but hasn't yet settled the escrow on the source chain.",
78
- [ToBTCSwapState.CLAIMED]: "Swap was successfully settled by the intermediary (LP) on the source chain",
79
- [ToBTCSwapState.REFUNDABLE]: "Intermediary (LP) was unable to process the swap and the swap escrow on the source chain is refundable."
80
- };
81
- /**
82
- * Base class for escrow-based Smart chain -> Bitcoin (on-chain & lightning) swaps
83
- *
84
- * @category Swaps/Smart chain → Bitcoin
85
- */
86
- class IToBTCSwap extends IEscrowSelfInitSwap_1.IEscrowSelfInitSwap {
87
- constructor(wrapper, initOrObject) {
88
- super(wrapper, initOrObject);
89
- /**
90
- * @internal
91
- */
92
- this.swapStateDescription = ToBTCSwapStateDescription;
93
- /**
94
- * @internal
95
- */
96
- this.swapStateName = (state) => ToBTCSwapState[state];
97
- if (isIToBTCSwapInit(initOrObject)) {
98
- this._state = ToBTCSwapState.CREATED;
99
- this.networkFee = initOrObject.networkFee;
100
- this.networkFeeBtc = initOrObject.networkFeeBtc;
101
- this._data = initOrObject.data;
102
- this.signatureData = initOrObject.signatureData;
103
- }
104
- else {
105
- this.networkFee = (0, Utils_1.toBigInt)(initOrObject.networkFee);
106
- this.networkFeeBtc = (0, Utils_1.toBigInt)(initOrObject.networkFeeBtc);
107
- }
108
- }
109
- /**
110
- * @inheritDoc
111
- * @internal
112
- */
113
- getSwapData() {
114
- return this._data;
115
- }
116
- /**
117
- * @inheritDoc
118
- * @internal
119
- */
120
- upgradeVersion() {
121
- if (this.version == null) {
122
- switch (this._state) {
123
- case -2:
124
- this._state = ToBTCSwapState.REFUNDED;
125
- break;
126
- case -1:
127
- this._state = ToBTCSwapState.QUOTE_EXPIRED;
128
- break;
129
- case 0:
130
- this._state = ToBTCSwapState.CREATED;
131
- break;
132
- case 1:
133
- this._state = ToBTCSwapState.COMMITED;
134
- break;
135
- case 2:
136
- this._state = ToBTCSwapState.CLAIMED;
137
- break;
138
- case 3:
139
- this._state = ToBTCSwapState.REFUNDABLE;
140
- break;
141
- }
142
- this.version = 1;
143
- }
144
- }
145
- /**
146
- * @inheritDoc
147
- * @internal
148
- */
149
- tryRecomputeSwapPrice() {
150
- const output = this.getOutput();
151
- if (output.rawAmount != null) {
152
- if (this.swapFeeBtc == null) {
153
- this.swapFeeBtc = this.swapFee * output.rawAmount / this.getInputWithoutFee().rawAmount;
154
- }
155
- if (this.networkFeeBtc == null) {
156
- this.networkFeeBtc = this.networkFee * output.rawAmount / this.getInputWithoutFee().rawAmount;
157
- }
158
- }
159
- super.tryRecomputeSwapPrice();
160
- }
161
- /**
162
- * Returns the payment hash identifier to be sent to the LP for getStatus and getRefund
163
- * @internal
164
- */
165
- getLpIdentifier() {
166
- return this.getClaimHash();
167
- }
168
- //////////////////////////////
169
- //// Getters & utils
170
- /**
171
- * @inheritDoc
172
- */
173
- getInputAddress() {
174
- return this._getInitiator();
175
- }
176
- /**
177
- * @inheritDoc
178
- */
179
- getInputTxId() {
180
- return this._commitTxId ?? null;
181
- }
182
- /**
183
- * @inheritDoc
184
- */
185
- requiresAction() {
186
- return this.isRefundable();
187
- }
188
- /**
189
- * @inheritDoc
190
- */
191
- isFinished() {
192
- return this._state === ToBTCSwapState.CLAIMED || this._state === ToBTCSwapState.REFUNDED || this._state === ToBTCSwapState.QUOTE_EXPIRED;
193
- }
194
- /**
195
- * @inheritDoc
196
- */
197
- isRefundable() {
198
- return this._state === ToBTCSwapState.REFUNDABLE;
199
- }
200
- /**
201
- * @inheritDoc
202
- */
203
- isQuoteExpired() {
204
- return this._state === ToBTCSwapState.QUOTE_EXPIRED;
205
- }
206
- /**
207
- * @inheritDoc
208
- */
209
- isQuoteSoftExpired() {
210
- return this._state === ToBTCSwapState.QUOTE_EXPIRED || this._state === ToBTCSwapState.QUOTE_SOFT_EXPIRED;
211
- }
212
- /**
213
- * @inheritDoc
214
- */
215
- isSuccessful() {
216
- return this._state === ToBTCSwapState.CLAIMED;
217
- }
218
- /**
219
- * @inheritDoc
220
- */
221
- isFailed() {
222
- return this._state === ToBTCSwapState.REFUNDED;
223
- }
224
- /**
225
- * @inheritDoc
226
- */
227
- isInProgress() {
228
- return this._state === ToBTCSwapState.COMMITED || this._state === ToBTCSwapState.SOFT_CLAIMED;
229
- }
230
- /**
231
- * Returns the time (in UNIX milliseconds) at which the swap expires and the user is able to unilaterally
232
- * refund it with the {@link refund} or {@link txsRefund} function.
233
- */
234
- getExpiry() {
235
- return Number(this._data.getExpiry()) * 1000;
236
- }
237
- /**
238
- * @inheritDoc
239
- * @internal
240
- */
241
- _getInitiator() {
242
- return this._data.getOfferer();
243
- }
244
- //////////////////////////////
245
- //// Amounts & fees
246
- /**
247
- * Returns the swap fee charged by the intermediary (LP) on this swap
248
- *
249
- * @internal
250
- */
251
- getSwapFee() {
252
- if (this.pricingInfo == null)
253
- throw new Error("No pricing info known, cannot estimate fee!");
254
- const feeWithoutBaseFee = this.swapFeeBtc - this.pricingInfo.satsBaseFee;
255
- const output = this.getOutput();
256
- const swapFeePPM = output.rawAmount == null ? 0n : feeWithoutBaseFee * 1000000n / output.rawAmount;
257
- const amountInDstToken = (0, TokenAmount_1.toTokenAmount)(this.swapFeeBtc, this.outputToken, this.wrapper._prices, this.pricingInfo);
258
- return {
259
- amountInSrcToken: (0, TokenAmount_1.toTokenAmount)(this.swapFee, this.wrapper._tokens[this._data.getToken()], this.wrapper._prices, this.pricingInfo),
260
- amountInDstToken,
261
- currentUsdValue: amountInDstToken.currentUsdValue,
262
- usdValue: amountInDstToken.usdValue,
263
- pastUsdValue: amountInDstToken.pastUsdValue,
264
- composition: {
265
- base: (0, TokenAmount_1.toTokenAmount)(this.pricingInfo.satsBaseFee, this.outputToken, this.wrapper._prices, this.pricingInfo),
266
- percentage: (0, PercentagePPM_1.ppmToPercentage)(swapFeePPM)
267
- }
268
- };
269
- }
270
- /**
271
- * Returns network fee for on the destination chain for the swap
272
- *
273
- * @internal
274
- */
275
- getNetworkFee() {
276
- const amountInDstToken = (0, TokenAmount_1.toTokenAmount)(this.networkFeeBtc, this.outputToken, this.wrapper._prices, this.pricingInfo);
277
- return {
278
- amountInSrcToken: (0, TokenAmount_1.toTokenAmount)(this.networkFee, this.wrapper._tokens[this._data.getToken()], this.wrapper._prices, this.pricingInfo),
279
- amountInDstToken,
280
- currentUsdValue: amountInDstToken.currentUsdValue,
281
- usdValue: amountInDstToken.usdValue,
282
- pastUsdValue: amountInDstToken.pastUsdValue
283
- };
284
- }
285
- /**
286
- * @inheritDoc
287
- */
288
- getFee() {
289
- const amountInDstToken = (0, TokenAmount_1.toTokenAmount)(this.swapFeeBtc + this.networkFeeBtc, this.outputToken, this.wrapper._prices, this.pricingInfo);
290
- return {
291
- amountInSrcToken: (0, TokenAmount_1.toTokenAmount)(this.swapFee + this.networkFee, this.wrapper._tokens[this._data.getToken()], this.wrapper._prices, this.pricingInfo),
292
- amountInDstToken,
293
- currentUsdValue: amountInDstToken.currentUsdValue,
294
- usdValue: amountInDstToken.usdValue,
295
- pastUsdValue: amountInDstToken.pastUsdValue
296
- };
297
- }
298
- /**
299
- * @inheritDoc
300
- */
301
- getFeeBreakdown() {
302
- return [
303
- {
304
- type: FeeType_1.FeeType.SWAP,
305
- fee: this.getSwapFee()
306
- },
307
- {
308
- type: FeeType_1.FeeType.NETWORK_OUTPUT,
309
- fee: this.getNetworkFee()
310
- }
311
- ];
312
- }
313
- /**
314
- * @inheritDoc
315
- */
316
- getInputToken() {
317
- return this.wrapper._tokens[this._data.getToken()];
318
- }
319
- /**
320
- * @inheritDoc
321
- */
322
- getInput() {
323
- return (0, TokenAmount_1.toTokenAmount)(this._data.getAmount(), this.wrapper._tokens[this._data.getToken()], this.wrapper._prices, this.pricingInfo);
324
- }
325
- /**
326
- * @inheritDoc
327
- */
328
- getInputWithoutFee() {
329
- return (0, TokenAmount_1.toTokenAmount)(this._data.getAmount() - (this.swapFee + this.networkFee), this.wrapper._tokens[this._data.getToken()], this.wrapper._prices, this.pricingInfo);
330
- }
331
- /**
332
- * Checks if the initiator/sender on the source chain has enough balance to go through with the swap
333
- */
334
- async hasEnoughBalance() {
335
- const [balance, commitFee] = await Promise.all([
336
- this.wrapper._contract.getBalance(this._getInitiator(), this._data.getToken(), false),
337
- this._data.getToken() === this.wrapper._chain.getNativeCurrencyAddress() ? this.getCommitFee() : Promise.resolve(null)
338
- ]);
339
- let required = this._data.getAmount();
340
- if (commitFee != null)
341
- required = required + commitFee;
342
- return {
343
- enoughBalance: balance >= required,
344
- balance: (0, TokenAmount_1.toTokenAmount)(balance, this.wrapper._tokens[this._data.getToken()], this.wrapper._prices, this.pricingInfo),
345
- required: (0, TokenAmount_1.toTokenAmount)(required, this.wrapper._tokens[this._data.getToken()], this.wrapper._prices, this.pricingInfo)
346
- };
347
- }
348
- /**
349
- * Checks if the initiator/sender on the source chain has enough native token balance
350
- * to cover the transaction fee of initiating the swap
351
- */
352
- async hasEnoughForTxFees() {
353
- const [balance, commitFee] = await Promise.all([
354
- this.wrapper._contract.getBalance(this._getInitiator(), this.wrapper._chain.getNativeCurrencyAddress(), false),
355
- this.getCommitFee()
356
- ]);
357
- return {
358
- enoughBalance: balance >= commitFee,
359
- balance: (0, TokenAmount_1.toTokenAmount)(balance, this.wrapper._getNativeToken(), this.wrapper._prices),
360
- required: (0, TokenAmount_1.toTokenAmount)(commitFee, this.wrapper._getNativeToken(), this.wrapper._prices)
361
- };
362
- }
363
- //////////////////////////////
364
- //// Execution
365
- /**
366
- * Executes the swap with the provided smart chain wallet/signer
367
- *
368
- * @param signer Smart chain wallet/signer to use to sign the transaction on the source chain
369
- * @param callbacks Callbacks to track the progress of the swap
370
- * @param options Optional options for the swap like feeRate, AbortSignal, and timeouts/intervals
371
- *
372
- * @returns {boolean} Whether the swap was successfully processed by the LP, in case `false` is returned
373
- * the user can refund their funds back on the source chain by calling {@link refund}
374
- */
375
- async execute(signer, callbacks, options) {
376
- if (this._state === ToBTCSwapState.QUOTE_EXPIRED || this._state === ToBTCSwapState.QUOTE_SOFT_EXPIRED)
377
- throw new Error("Quote expired");
378
- if (this._state === ToBTCSwapState.REFUNDED)
379
- throw new Error("Swap already refunded");
380
- if (this._state === ToBTCSwapState.REFUNDABLE)
381
- throw new Error("Swap refundable, refund with swap.refund()");
382
- if (this._state === ToBTCSwapState.SOFT_CLAIMED || this._state === ToBTCSwapState.CLAIMED)
383
- throw new Error("Swap already settled!");
384
- if (this._state === ToBTCSwapState.CREATED) {
385
- const txId = await this.commit(signer, options?.abortSignal, false, callbacks?.onSourceTransactionSent);
386
- if (callbacks?.onSourceTransactionConfirmed != null)
387
- callbacks.onSourceTransactionConfirmed(txId);
388
- }
389
- // @ts-ignore
390
- if (this._state === ToBTCSwapState.CLAIMED || this._state === ToBTCSwapState.SOFT_CLAIMED)
391
- return true;
392
- if (this._state === ToBTCSwapState.COMMITED) {
393
- const success = await this.waitForPayment(options?.maxWaitTillSwapProcessedSeconds ?? 120, options?.paymentCheckIntervalSeconds, options?.abortSignal);
394
- if (success) {
395
- if (callbacks?.onSwapSettled != null)
396
- callbacks.onSwapSettled(this.getOutputTxId());
397
- return true;
398
- }
399
- else {
400
- return false;
401
- }
402
- }
403
- throw new Error("Unexpected state reached!");
404
- }
405
- /**
406
- * @inheritDoc
407
- *
408
- * @param options.skipChecks Skip checks like making sure init signature is still valid and swap wasn't commited yet
409
- * (this is handled on swap creation, if you commit right after quoting, you can use `skipChecks=true`)
410
- */
411
- async txsExecute(options) {
412
- if (this._state !== ToBTCSwapState.CREATED)
413
- throw new Error("Invalid swap state, needs to be CREATED!");
414
- const txsCommit = await this.txsCommit(options?.skipChecks);
415
- return [
416
- {
417
- name: "Commit",
418
- description: `Initiates the swap by commiting the funds to the escrow on the ${this.chainIdentifier} side`,
419
- chain: this.chainIdentifier,
420
- txs: txsCommit
421
- }
422
- ];
423
- }
424
- /**
425
- * @inheritDoc
426
- *
427
- * @param options.skipChecks Skip checks like making sure init signature is still valid and swap wasn't commited yet
428
- * (this is handled on swap creation, if you commit right after quoting, you can use `skipChecks=true`)
429
- * @param options.refundSmartChainSigner Optional smart chain signer to use when creating refunds transactions
430
- */
431
- async getCurrentActions(options) {
432
- if (this._state === ToBTCSwapState.CREATED) {
433
- try {
434
- return await this.txsExecute(options);
435
- }
436
- catch (e) { }
437
- }
438
- if (this.isRefundable()) {
439
- return [{
440
- name: "Refund",
441
- description: "Refund the swap after it failed to execute",
442
- chain: this.chainIdentifier,
443
- txs: await this.txsRefund(options?.refundSmartChainSigner)
444
- }];
445
- }
446
- return [];
447
- }
448
- //////////////////////////////
449
- //// Commit
450
- /**
451
- * @inheritDoc
452
- *
453
- * @throws {Error} When in invalid state (not {@link ToBTCSwapState.CREATED})
454
- */
455
- async txsCommit(skipChecks) {
456
- if (this._state !== ToBTCSwapState.CREATED && (!skipChecks || this._state !== ToBTCSwapState.QUOTE_SOFT_EXPIRED))
457
- throw new Error("Must be in CREATED state!");
458
- if (this.signatureData == null)
459
- throw new Error("Init signature data not known, cannot commit!");
460
- if (!this.initiated) {
461
- this.initiated = true;
462
- await this._saveAndEmit();
463
- }
464
- return await this.wrapper._contract.txsInit(this._getInitiator(), this._data, this.signatureData, skipChecks, this.feeRate).catch(e => Promise.reject(e instanceof base_1.SignatureVerificationError ? new Error("Request timed out") : e));
465
- }
466
- /**
467
- * @inheritDoc
468
- *
469
- * @throws {Error} If invalid signer is provided that doesn't match the swap data
470
- */
471
- async commit(_signer, abortSignal, skipChecks, onBeforeTxSent) {
472
- const signer = (0, base_1.isAbstractSigner)(_signer) ? _signer : await this.wrapper._chain.wrapSigner(_signer);
473
- this.checkSigner(signer);
474
- const txs = await this.txsCommit(skipChecks);
475
- let txCount = 0;
476
- const result = await this.wrapper._chain.sendAndConfirm(signer, txs, true, abortSignal, false, (txId, rawTx) => {
477
- txCount++;
478
- if (onBeforeTxSent != null && txCount === txs.length)
479
- onBeforeTxSent(txId);
480
- return Promise.resolve();
481
- });
482
- this._commitTxId = result[result.length - 1];
483
- if (this._state === ToBTCSwapState.CREATED || this._state === ToBTCSwapState.QUOTE_SOFT_EXPIRED || this._state === ToBTCSwapState.QUOTE_EXPIRED) {
484
- await this._saveAndEmit(ToBTCSwapState.COMMITED);
485
- }
486
- return this._commitTxId;
487
- }
488
- /**
489
- * @inheritDoc
490
- *
491
- * @throws {Error} If swap is not in the correct state (must be {@link ToBTCSwapState.CREATED})
492
- */
493
- async waitTillCommited(abortSignal) {
494
- if (this._state === ToBTCSwapState.COMMITED || this._state === ToBTCSwapState.CLAIMED)
495
- return Promise.resolve();
496
- if (this._state !== ToBTCSwapState.CREATED && this._state !== ToBTCSwapState.QUOTE_SOFT_EXPIRED)
497
- throw new Error("Invalid state (not CREATED)");
498
- const abortController = (0, Utils_1.extendAbortController)(abortSignal);
499
- let result;
500
- try {
501
- result = await Promise.race([
502
- this.watchdogWaitTillCommited(undefined, abortController.signal),
503
- this.waitTillState(ToBTCSwapState.COMMITED, "gte", abortController.signal).then(() => 0)
504
- ]);
505
- abortController.abort();
506
- }
507
- catch (e) {
508
- abortController.abort();
509
- throw e;
510
- }
511
- if (result === 0)
512
- this.logger.debug("waitTillCommited(): Resolved from state change");
513
- if (result === true)
514
- this.logger.debug("waitTillCommited(): Resolved from watchdog - commited");
515
- if (result === false) {
516
- this.logger.debug("waitTillCommited(): Resolved from watchdog - signature expiry");
517
- if (this._state === ToBTCSwapState.QUOTE_SOFT_EXPIRED || this._state === ToBTCSwapState.CREATED) {
518
- await this._saveAndEmit(ToBTCSwapState.QUOTE_EXPIRED);
519
- }
520
- throw new Error("Quote expired while waiting for transaction confirmation!");
521
- }
522
- if (this._state === ToBTCSwapState.QUOTE_SOFT_EXPIRED || this._state === ToBTCSwapState.CREATED || this._state === ToBTCSwapState.QUOTE_EXPIRED) {
523
- await this._saveAndEmit(ToBTCSwapState.COMMITED);
524
- }
525
- }
526
- //////////////////////////////
527
- //// Payment
528
- /**
529
- * Waits till the swap is processed by the intermediary (LP)
530
- *
531
- * @param checkIntervalSeconds How often to poll the intermediary for status (5 seconds default)
532
- * @param abortSignal Abort signal
533
- * @internal
534
- */
535
- async waitTillIntermediarySwapProcessed(checkIntervalSeconds, abortSignal) {
536
- if (this.url == null)
537
- throw new Error("LP URL not specified!");
538
- checkIntervalSeconds ??= 5;
539
- let resp = { code: IntermediaryAPI_1.RefundAuthorizationResponseCodes.PENDING, msg: "" };
540
- while (!abortSignal?.aborted && (resp.code === IntermediaryAPI_1.RefundAuthorizationResponseCodes.PENDING || resp.code === IntermediaryAPI_1.RefundAuthorizationResponseCodes.NOT_FOUND)) {
541
- resp = await IntermediaryAPI_1.IntermediaryAPI.getRefundAuthorization(this.url, this.getLpIdentifier(), this._data.getSequence());
542
- if (resp.code === IntermediaryAPI_1.RefundAuthorizationResponseCodes.PAID) {
543
- const validResponse = await this._setPaymentResult(resp.data, true);
544
- if (validResponse) {
545
- if (this._state === ToBTCSwapState.COMMITED || this._state === ToBTCSwapState.REFUNDABLE) {
546
- await this._saveAndEmit(ToBTCSwapState.SOFT_CLAIMED);
547
- }
548
- }
549
- else {
550
- resp = { code: IntermediaryAPI_1.RefundAuthorizationResponseCodes.PENDING, msg: "" };
551
- }
552
- }
553
- if (resp.code === IntermediaryAPI_1.RefundAuthorizationResponseCodes.PENDING ||
554
- resp.code === IntermediaryAPI_1.RefundAuthorizationResponseCodes.NOT_FOUND)
555
- await (0, TimeoutUtils_1.timeoutPromise)(checkIntervalSeconds * 1000, abortSignal);
556
- }
557
- return resp;
558
- }
559
- /**
560
- * Checks whether the swap was already processed by the LP and is either successful (requires proof which is
561
- * either a HTLC pre-image for LN swaps or valid txId for on-chain swap) or failed and we can cooperatively
562
- * refund.
563
- *
564
- * @param save whether to save the data
565
- * @returns `true` if swap is processed, `false` if the swap is still ongoing
566
- *
567
- * @internal
568
- */
569
- async checkIntermediarySwapProcessed(save = true) {
570
- if (this._state === ToBTCSwapState.CREATED || this._state == ToBTCSwapState.QUOTE_EXPIRED || this.url == null)
571
- return false;
572
- if (this.isFinished() || this.isRefundable())
573
- return true;
574
- //Check if that maybe already concluded according to the LP
575
- const resp = await IntermediaryAPI_1.IntermediaryAPI.getRefundAuthorization(this.url, this.getLpIdentifier(), this._data.getSequence());
576
- switch (resp.code) {
577
- case IntermediaryAPI_1.RefundAuthorizationResponseCodes.PAID:
578
- const processed = await this._setPaymentResult(resp.data, true);
579
- if (processed) {
580
- this._state = ToBTCSwapState.SOFT_CLAIMED;
581
- if (save)
582
- await this._saveAndEmit();
583
- }
584
- return processed;
585
- case IntermediaryAPI_1.RefundAuthorizationResponseCodes.REFUND_DATA:
586
- await this.wrapper._contract.isValidRefundAuthorization(this._data, resp.data);
587
- this._state = ToBTCSwapState.REFUNDABLE;
588
- if (save)
589
- await this._saveAndEmit();
590
- return true;
591
- default:
592
- return false;
593
- }
594
- }
595
- /**
596
- * A blocking promise resolving when swap was concluded by the intermediary (LP),
597
- * rejecting in case of failure
598
- *
599
- * @param maxWaitTimeSeconds Maximum time in seconds to wait for the swap to be settled, an error is thrown if the
600
- * swap is taking too long to claim
601
- * @param checkIntervalSeconds How often to poll the intermediary for answer
602
- * @param abortSignal Abort signal
603
- * @returns `true` if swap was successful, `false` if swap failed and we can refund
604
- *
605
- * @throws {IntermediaryError} If a swap is determined expired by the intermediary, but it is actually still valid
606
- * @throws {SignatureVerificationError} If the swap should be cooperatively refundable but the intermediary returned
607
- * invalid refund signature
608
- * @throws {Error} When swap expires or if the swap has invalid state (must be {@link ToBTCSwapState.COMMITED})
609
- */
610
- async waitForPayment(maxWaitTimeSeconds, checkIntervalSeconds, abortSignal) {
611
- if (this._state === ToBTCSwapState.CLAIMED)
612
- return Promise.resolve(true);
613
- if (this._state !== ToBTCSwapState.COMMITED && this._state !== ToBTCSwapState.SOFT_CLAIMED)
614
- throw new Error("Invalid state (not COMMITED)");
615
- const abortController = (0, Utils_1.extendAbortController)(abortSignal);
616
- let timedOut = false;
617
- if (maxWaitTimeSeconds != null) {
618
- const timeout = setTimeout(() => {
619
- timedOut = true;
620
- abortController.abort();
621
- }, maxWaitTimeSeconds * 1000);
622
- abortController.signal.addEventListener("abort", () => clearTimeout(timeout));
623
- }
624
- let result;
625
- try {
626
- result = await Promise.race([
627
- this.waitTillState(ToBTCSwapState.CLAIMED, "gte", abortController.signal),
628
- this.waitTillIntermediarySwapProcessed(checkIntervalSeconds, abortController.signal)
629
- ]);
630
- abortController.abort();
631
- }
632
- catch (e) {
633
- abortController.abort();
634
- if (timedOut) {
635
- throw new Error("Timed out while waiting for LP to process the swap, the LP might be unresponsive or offline!" +
636
- ` Please check later or wait till ${new Date(Number(this._data.getExpiry()) * 1000).toLocaleString()} to refund unilaterally!`);
637
- }
638
- throw e;
639
- }
640
- if (typeof result !== "object") {
641
- if (this._state === ToBTCSwapState.REFUNDABLE)
642
- throw new Error("Swap expired");
643
- this.logger.debug("waitTillRefunded(): Resolved from state change");
644
- return true;
645
- }
646
- this.logger.debug("waitTillRefunded(): Resolved from intermediary response");
647
- switch (result.code) {
648
- case IntermediaryAPI_1.RefundAuthorizationResponseCodes.PAID:
649
- return true;
650
- case IntermediaryAPI_1.RefundAuthorizationResponseCodes.REFUND_DATA:
651
- const resultData = result.data;
652
- await this.wrapper._contract.isValidRefundAuthorization(this._data, resultData);
653
- await this._saveAndEmit(ToBTCSwapState.REFUNDABLE);
654
- return false;
655
- case IntermediaryAPI_1.RefundAuthorizationResponseCodes.EXPIRED:
656
- if (await this.wrapper._contract.isExpired(this._getInitiator(), this._data))
657
- throw new Error("Swap expired");
658
- throw new IntermediaryError_1.IntermediaryError("Swap expired");
659
- case IntermediaryAPI_1.RefundAuthorizationResponseCodes.NOT_FOUND:
660
- if (this._state === ToBTCSwapState.CLAIMED)
661
- return true;
662
- throw new Error("LP swap not found");
663
- }
664
- throw new Error("Invalid response code returned by the LP");
665
- }
666
- //////////////////////////////
667
- //// Refund
668
- /**
669
- * Get the estimated smart chain transaction fee of the refund transaction
670
- */
671
- async getRefundNetworkFee() {
672
- const swapContract = this.wrapper._contract;
673
- return (0, TokenAmount_1.toTokenAmount)(await swapContract.getRefundFee(this._getInitiator(), this._data), this.wrapper._getNativeToken(), this.wrapper._prices);
674
- }
675
- /**
676
- * @inheritDoc
677
- *
678
- * @throws {IntermediaryError} If intermediary returns invalid response in case cooperative refund should be used
679
- * @throws {SignatureVerificationError} If intermediary returned invalid cooperative refund signature
680
- * @throws {Error} When state is not refundable
681
- */
682
- async txsRefund(_signer) {
683
- if (!this.isRefundable())
684
- throw new Error("Must be in REFUNDABLE state or expired!");
685
- let signer;
686
- if (_signer != null) {
687
- if (typeof (_signer) === "string") {
688
- signer = _signer;
689
- }
690
- else if ((0, base_1.isAbstractSigner)(_signer)) {
691
- signer = _signer.getAddress();
692
- }
693
- else {
694
- signer = (await this.wrapper._chain.wrapSigner(_signer)).getAddress();
695
- }
696
- }
697
- else {
698
- signer = this._getInitiator();
699
- }
700
- if (await this.wrapper._contract.isExpired(this._getInitiator(), this._data)) {
701
- return await this.wrapper._contract.txsRefund(signer, this._data, true, true);
702
- }
703
- else {
704
- if (this.url == null)
705
- throw new Error("LP URL not known, cannot get cooperative refund message, wait till expiry to refund!");
706
- const res = await IntermediaryAPI_1.IntermediaryAPI.getRefundAuthorization(this.url, this.getLpIdentifier(), this._data.getSequence());
707
- if (res.code === IntermediaryAPI_1.RefundAuthorizationResponseCodes.REFUND_DATA) {
708
- return await this.wrapper._contract.txsRefundWithAuthorization(signer, this._data, res.data, true, true);
709
- }
710
- throw new IntermediaryError_1.IntermediaryError("Invalid intermediary cooperative message returned");
711
- }
712
- }
713
- /**
714
- * @inheritDoc
715
- *
716
- * @throws {Error} If invalid signer is provided that doesn't match the swap data
717
- */
718
- async refund(_signer, abortSignal) {
719
- const signer = (0, base_1.isAbstractSigner)(_signer) ? _signer : await this.wrapper._chain.wrapSigner(_signer);
720
- const result = await this.wrapper._chain.sendAndConfirm(signer, await this.txsRefund(signer.getAddress()), true, abortSignal);
721
- this._refundTxId = result[0];
722
- if (this._state === ToBTCSwapState.COMMITED || this._state === ToBTCSwapState.REFUNDABLE || this._state === ToBTCSwapState.SOFT_CLAIMED) {
723
- await this._saveAndEmit(ToBTCSwapState.REFUNDED);
724
- }
725
- return result[0];
726
- }
727
- /**
728
- * @inheritDoc
729
- *
730
- * @throws {Error} When swap is not in a valid state (must be {@link ToBTCSwapState.COMMITED} or
731
- * {@link ToBTCSwapState.REFUNDABLE})
732
- * @throws {Error} If we tried to refund but claimer was able to claim first
733
- */
734
- async waitTillRefunded(abortSignal) {
735
- if (this._state === ToBTCSwapState.REFUNDED)
736
- return Promise.resolve();
737
- if (this._state !== ToBTCSwapState.COMMITED &&
738
- this._state !== ToBTCSwapState.SOFT_CLAIMED &&
739
- this._state !== ToBTCSwapState.REFUNDABLE)
740
- throw new Error("Invalid state (not COMMITED)");
741
- const abortController = new AbortController();
742
- if (abortSignal != null)
743
- abortSignal.addEventListener("abort", () => abortController.abort(abortSignal.reason));
744
- const res = await Promise.race([
745
- this.watchdogWaitTillResult(undefined, abortController.signal),
746
- this.waitTillState(ToBTCSwapState.REFUNDED, "eq", abortController.signal).then(() => 0),
747
- this.waitTillState(ToBTCSwapState.CLAIMED, "eq", abortController.signal).then(() => 1),
748
- ]);
749
- abortController.abort();
750
- if (res === 0) {
751
- this.logger.debug("waitTillRefunded(): Resolved from state change (REFUNDED)");
752
- return;
753
- }
754
- if (res === 1) {
755
- this.logger.debug("waitTillRefunded(): Resolved from state change (CLAIMED)");
756
- throw new Error("Tried to refund swap, but claimer claimed it in the meantime!");
757
- }
758
- this.logger.debug("waitTillRefunded(): Resolved from watchdog");
759
- if (res?.type === base_1.SwapCommitStateType.PAID) {
760
- if (this._claimTxId == null)
761
- this._claimTxId = await res.getClaimTxId();
762
- await this._saveAndEmit(ToBTCSwapState.CLAIMED);
763
- throw new Error("Tried to refund swap, but claimer claimed it in the meantime!");
764
- }
765
- if (res?.type === base_1.SwapCommitStateType.NOT_COMMITED) {
766
- if (this._refundTxId == null && res.getRefundTxId != null)
767
- this._refundTxId = await res.getRefundTxId();
768
- await this._saveAndEmit(ToBTCSwapState.REFUNDED);
769
- }
770
- }
771
- //////////////////////////////
772
- //// Storage
773
- /**
774
- * @inheritDoc
775
- */
776
- serialize() {
777
- const obj = super.serialize();
778
- return {
779
- ...obj,
780
- networkFee: this.networkFee == null ? null : this.networkFee.toString(10),
781
- networkFeeBtc: this.networkFeeBtc == null ? null : this.networkFeeBtc.toString(10)
782
- };
783
- }
784
- //////////////////////////////
785
- //// Swap ticks & sync
786
- /**
787
- * Checks the swap's state on-chain and compares it to its internal state, updates/changes it according to on-chain
788
- * data
789
- *
790
- * @private
791
- */
792
- async syncStateFromChain(quoteDefinitelyExpired, commitStatus) {
793
- if (this._state === ToBTCSwapState.CREATED ||
794
- this._state === ToBTCSwapState.QUOTE_SOFT_EXPIRED ||
795
- this._state === ToBTCSwapState.COMMITED ||
796
- this._state === ToBTCSwapState.SOFT_CLAIMED ||
797
- this._state === ToBTCSwapState.REFUNDABLE) {
798
- let quoteExpired = false;
799
- if (this._state === ToBTCSwapState.CREATED || this._state === ToBTCSwapState.QUOTE_SOFT_EXPIRED) {
800
- //Check if quote is still valid
801
- quoteExpired = quoteDefinitelyExpired ?? await this._verifyQuoteDefinitelyExpired();
802
- }
803
- commitStatus ??= await this.wrapper._contract.getCommitStatus(this._getInitiator(), this._data);
804
- if (commitStatus != null && await this._forciblySetOnchainState(commitStatus))
805
- return true;
806
- if ((this._state === ToBTCSwapState.CREATED || this._state === ToBTCSwapState.QUOTE_SOFT_EXPIRED)) {
807
- if (quoteExpired) {
808
- this._state = ToBTCSwapState.QUOTE_EXPIRED;
809
- return true;
810
- }
811
- }
812
- }
813
- return false;
814
- }
815
- /**
816
- * @inheritDoc
817
- * @internal
818
- */
819
- _shouldFetchOnchainState() {
820
- return this._state === ToBTCSwapState.CREATED ||
821
- this._state === ToBTCSwapState.QUOTE_SOFT_EXPIRED ||
822
- this._state === ToBTCSwapState.COMMITED ||
823
- this._state === ToBTCSwapState.SOFT_CLAIMED ||
824
- this._state === ToBTCSwapState.REFUNDABLE;
825
- }
826
- /**
827
- * @inheritDoc
828
- * @internal
829
- */
830
- _shouldFetchExpiryStatus() {
831
- return this._state === ToBTCSwapState.CREATED || this._state === ToBTCSwapState.QUOTE_SOFT_EXPIRED;
832
- }
833
- /**
834
- * @inheritDoc
835
- * @internal
836
- */
837
- async _sync(save, quoteDefinitelyExpired, commitStatus) {
838
- let changed = await this.syncStateFromChain(quoteDefinitelyExpired, commitStatus);
839
- if (this._state === ToBTCSwapState.COMMITED || this._state === ToBTCSwapState.SOFT_CLAIMED) {
840
- //Check if that maybe already concluded
841
- try {
842
- if (await this.checkIntermediarySwapProcessed(false))
843
- changed = true;
844
- }
845
- catch (e) {
846
- this.logger.error("_sync(): Failed to synchronize swap, error: ", e);
847
- }
848
- }
849
- if (save && changed)
850
- await this._saveAndEmit();
851
- return changed;
852
- }
853
- /**
854
- * @inheritDoc
855
- * @internal
856
- */
857
- async _forciblySetOnchainState(commitStatus) {
858
- switch (commitStatus.type) {
859
- case base_1.SwapCommitStateType.PAID:
860
- if (this._claimTxId == null && commitStatus.getClaimTxId)
861
- this._claimTxId = await commitStatus.getClaimTxId();
862
- const eventResult = await commitStatus.getClaimResult();
863
- try {
864
- await this._setPaymentResult({ secret: eventResult, txId: Buffer.from(eventResult, "hex").reverse().toString("hex") });
865
- }
866
- catch (e) {
867
- this.logger.error(`Failed to set payment result ${eventResult} on the swap!`);
868
- }
869
- this._state = ToBTCSwapState.CLAIMED;
870
- return true;
871
- case base_1.SwapCommitStateType.REFUNDABLE:
872
- this._state = ToBTCSwapState.REFUNDABLE;
873
- return true;
874
- case base_1.SwapCommitStateType.EXPIRED:
875
- if (this._refundTxId == null && commitStatus.getRefundTxId)
876
- this._refundTxId = await commitStatus.getRefundTxId();
877
- this._state = this._refundTxId == null ? ToBTCSwapState.QUOTE_EXPIRED : ToBTCSwapState.REFUNDED;
878
- return true;
879
- case base_1.SwapCommitStateType.NOT_COMMITED:
880
- if (this._refundTxId == null && commitStatus.getRefundTxId)
881
- this._refundTxId = await commitStatus.getRefundTxId();
882
- if (this._refundTxId != null) {
883
- this._state = ToBTCSwapState.REFUNDED;
884
- return true;
885
- }
886
- break;
887
- case base_1.SwapCommitStateType.COMMITED:
888
- if (this._state !== ToBTCSwapState.COMMITED && this._state !== ToBTCSwapState.REFUNDABLE && this._state !== ToBTCSwapState.SOFT_CLAIMED) {
889
- this._state = ToBTCSwapState.COMMITED;
890
- return true;
891
- }
892
- break;
893
- }
894
- return false;
895
- }
896
- /**
897
- * @inheritDoc
898
- * @internal
899
- */
900
- async _tick(save) {
901
- switch (this._state) {
902
- case ToBTCSwapState.CREATED:
903
- if (this.expiry < Date.now()) {
904
- this._state = ToBTCSwapState.QUOTE_SOFT_EXPIRED;
905
- if (save)
906
- await this._saveAndEmit();
907
- return true;
908
- }
909
- break;
910
- case ToBTCSwapState.COMMITED:
911
- case ToBTCSwapState.SOFT_CLAIMED:
912
- const expired = await this.wrapper._contract.isExpired(this._getInitiator(), this._data);
913
- if (expired) {
914
- this._state = ToBTCSwapState.REFUNDABLE;
915
- if (save)
916
- await this._saveAndEmit();
917
- return true;
918
- }
919
- break;
920
- }
921
- return false;
922
- }
923
- }
924
- exports.IToBTCSwap = IToBTCSwap;
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.IToBTCSwap = exports.ToBTCSwapState = exports.isIToBTCSwapInit = void 0;
4
+ const base_1 = require("@atomiqlabs/base");
5
+ const IntermediaryAPI_1 = require("../../../intermediaries/apis/IntermediaryAPI");
6
+ const IntermediaryError_1 = require("../../../errors/IntermediaryError");
7
+ const Utils_1 = require("../../../utils/Utils");
8
+ const IEscrowSelfInitSwap_1 = require("../IEscrowSelfInitSwap");
9
+ const FeeType_1 = require("../../../enums/FeeType");
10
+ const PercentagePPM_1 = require("../../../types/fees/PercentagePPM");
11
+ const TokenAmount_1 = require("../../../types/TokenAmount");
12
+ const TimeoutUtils_1 = require("../../../utils/TimeoutUtils");
13
+ function isIToBTCSwapInit(obj) {
14
+ return typeof (obj.networkFee) === "bigint" &&
15
+ typeof (obj.networkFeeBtc) === "bigint" &&
16
+ (obj.signatureData == null || (typeof (obj.signatureData) === 'object' &&
17
+ typeof (obj.signatureData.prefix) === "string" &&
18
+ typeof (obj.signatureData.timeout) === "string" &&
19
+ typeof (obj.signatureData.signature) === "string")) &&
20
+ typeof (obj.data) === 'object' &&
21
+ (0, IEscrowSelfInitSwap_1.isIEscrowSelfInitSwapInit)(obj);
22
+ }
23
+ exports.isIToBTCSwapInit = isIToBTCSwapInit;
24
+ /**
25
+ * State enum for escrow-based Smart chain -> Bitcoin (on-chain & lightning) swaps
26
+ *
27
+ * @category Swaps/Smart chain → Bitcoin
28
+ */
29
+ var ToBTCSwapState;
30
+ (function (ToBTCSwapState) {
31
+ /**
32
+ * Intermediary (LP) was unable to process the swap and the funds were refunded on the
33
+ * source chain
34
+ */
35
+ ToBTCSwapState[ToBTCSwapState["REFUNDED"] = -3] = "REFUNDED";
36
+ /**
37
+ * Swap has expired for good and there is no way how it can be executed anymore
38
+ */
39
+ ToBTCSwapState[ToBTCSwapState["QUOTE_EXPIRED"] = -2] = "QUOTE_EXPIRED";
40
+ /**
41
+ * A swap is almost expired, and it should be presented to the user as expired, though
42
+ * there is still a chance that it will be processed
43
+ */
44
+ ToBTCSwapState[ToBTCSwapState["QUOTE_SOFT_EXPIRED"] = -1] = "QUOTE_SOFT_EXPIRED";
45
+ /**
46
+ * Swap was created, use the {@link IToBTCSwap.commit} or {@link IToBTCSwap.txsCommit} to
47
+ * initiate it by creating the swap escrow on the source chain
48
+ */
49
+ ToBTCSwapState[ToBTCSwapState["CREATED"] = 0] = "CREATED";
50
+ /**
51
+ * Swap escrow was initiated (committed) on the source chain, the intermediary (LP) will
52
+ * now process the swap. You can wait till that happens with the {@link IToBTCSwap.waitForPayment}
53
+ * function.
54
+ */
55
+ ToBTCSwapState[ToBTCSwapState["COMMITED"] = 1] = "COMMITED";
56
+ /**
57
+ * The intermediary (LP) has processed the transaction and sent out the funds on the destination chain,
58
+ * but hasn't yet settled the escrow on the source chain.
59
+ */
60
+ ToBTCSwapState[ToBTCSwapState["SOFT_CLAIMED"] = 2] = "SOFT_CLAIMED";
61
+ /**
62
+ * Swap was successfully settled by the intermediary (LP) on the source chain
63
+ */
64
+ ToBTCSwapState[ToBTCSwapState["CLAIMED"] = 3] = "CLAIMED";
65
+ /**
66
+ * Intermediary (LP) was unable to process the swap and the swap escrow on the source chain
67
+ * is refundable, call {@link IToBTCSwap.refund} or {@link IToBTCSwap.txsRefund} to refund
68
+ */
69
+ ToBTCSwapState[ToBTCSwapState["REFUNDABLE"] = 4] = "REFUNDABLE";
70
+ })(ToBTCSwapState = exports.ToBTCSwapState || (exports.ToBTCSwapState = {}));
71
+ const ToBTCSwapStateDescription = {
72
+ [ToBTCSwapState.REFUNDED]: "Intermediary (LP) was unable to process the swap and the funds were refunded on the source chain",
73
+ [ToBTCSwapState.QUOTE_EXPIRED]: "Swap has expired for good and there is no way how it can be executed anymore",
74
+ [ToBTCSwapState.QUOTE_SOFT_EXPIRED]: "A swap is expired, though there is still a chance that it will be processed",
75
+ [ToBTCSwapState.CREATED]: "Swap was created, initiate it by creating the swap escrow on the source chain",
76
+ [ToBTCSwapState.COMMITED]: "Swap escrow was initiated (committed) on the source chain, the intermediary (LP) will now process the swap.",
77
+ [ToBTCSwapState.SOFT_CLAIMED]: "The intermediary (LP) has processed the transaction and sent out the funds on the destination chain, but hasn't yet settled the escrow on the source chain.",
78
+ [ToBTCSwapState.CLAIMED]: "Swap was successfully settled by the intermediary (LP) on the source chain",
79
+ [ToBTCSwapState.REFUNDABLE]: "Intermediary (LP) was unable to process the swap and the swap escrow on the source chain is refundable."
80
+ };
81
+ /**
82
+ * Base class for escrow-based Smart chain -> Bitcoin (on-chain & lightning) swaps
83
+ *
84
+ * @category Swaps/Smart chain → Bitcoin
85
+ */
86
+ class IToBTCSwap extends IEscrowSelfInitSwap_1.IEscrowSelfInitSwap {
87
+ constructor(wrapper, initOrObject) {
88
+ super(wrapper, initOrObject);
89
+ /**
90
+ * @internal
91
+ */
92
+ this.swapStateDescription = ToBTCSwapStateDescription;
93
+ /**
94
+ * @internal
95
+ */
96
+ this.swapStateName = (state) => ToBTCSwapState[state];
97
+ if (isIToBTCSwapInit(initOrObject)) {
98
+ this._state = ToBTCSwapState.CREATED;
99
+ this.networkFee = initOrObject.networkFee;
100
+ this.networkFeeBtc = initOrObject.networkFeeBtc;
101
+ this._data = initOrObject.data;
102
+ this.signatureData = initOrObject.signatureData;
103
+ }
104
+ else {
105
+ this.networkFee = (0, Utils_1.toBigInt)(initOrObject.networkFee);
106
+ this.networkFeeBtc = (0, Utils_1.toBigInt)(initOrObject.networkFeeBtc);
107
+ }
108
+ }
109
+ /**
110
+ * @inheritDoc
111
+ * @internal
112
+ */
113
+ getSwapData() {
114
+ return this._data;
115
+ }
116
+ /**
117
+ * @inheritDoc
118
+ * @internal
119
+ */
120
+ upgradeVersion() {
121
+ if (this.version == null) {
122
+ switch (this._state) {
123
+ case -2:
124
+ this._state = ToBTCSwapState.REFUNDED;
125
+ break;
126
+ case -1:
127
+ this._state = ToBTCSwapState.QUOTE_EXPIRED;
128
+ break;
129
+ case 0:
130
+ this._state = ToBTCSwapState.CREATED;
131
+ break;
132
+ case 1:
133
+ this._state = ToBTCSwapState.COMMITED;
134
+ break;
135
+ case 2:
136
+ this._state = ToBTCSwapState.CLAIMED;
137
+ break;
138
+ case 3:
139
+ this._state = ToBTCSwapState.REFUNDABLE;
140
+ break;
141
+ }
142
+ this.version = 1;
143
+ }
144
+ }
145
+ /**
146
+ * @inheritDoc
147
+ * @internal
148
+ */
149
+ tryRecomputeSwapPrice() {
150
+ const output = this.getOutput();
151
+ if (output.rawAmount != null) {
152
+ if (this.swapFeeBtc == null) {
153
+ this.swapFeeBtc = this.swapFee * output.rawAmount / this.getInputWithoutFee().rawAmount;
154
+ }
155
+ if (this.networkFeeBtc == null) {
156
+ this.networkFeeBtc = this.networkFee * output.rawAmount / this.getInputWithoutFee().rawAmount;
157
+ }
158
+ }
159
+ super.tryRecomputeSwapPrice();
160
+ }
161
+ /**
162
+ * Returns the payment hash identifier to be sent to the LP for getStatus and getRefund
163
+ * @internal
164
+ */
165
+ getLpIdentifier() {
166
+ return this.getClaimHash();
167
+ }
168
+ //////////////////////////////
169
+ //// Getters & utils
170
+ /**
171
+ * @inheritDoc
172
+ */
173
+ getInputAddress() {
174
+ return this._getInitiator();
175
+ }
176
+ /**
177
+ * @inheritDoc
178
+ */
179
+ getInputTxId() {
180
+ return this._commitTxId ?? null;
181
+ }
182
+ /**
183
+ * @inheritDoc
184
+ */
185
+ requiresAction() {
186
+ return this.isRefundable();
187
+ }
188
+ /**
189
+ * @inheritDoc
190
+ */
191
+ isFinished() {
192
+ return this._state === ToBTCSwapState.CLAIMED || this._state === ToBTCSwapState.REFUNDED || this._state === ToBTCSwapState.QUOTE_EXPIRED;
193
+ }
194
+ /**
195
+ * @inheritDoc
196
+ */
197
+ isRefundable() {
198
+ return this._state === ToBTCSwapState.REFUNDABLE;
199
+ }
200
+ /**
201
+ * @inheritDoc
202
+ */
203
+ isQuoteExpired() {
204
+ return this._state === ToBTCSwapState.QUOTE_EXPIRED;
205
+ }
206
+ /**
207
+ * @inheritDoc
208
+ */
209
+ isQuoteSoftExpired() {
210
+ return this._state === ToBTCSwapState.QUOTE_EXPIRED || this._state === ToBTCSwapState.QUOTE_SOFT_EXPIRED;
211
+ }
212
+ /**
213
+ * @inheritDoc
214
+ */
215
+ isSuccessful() {
216
+ return this._state === ToBTCSwapState.CLAIMED;
217
+ }
218
+ /**
219
+ * @inheritDoc
220
+ */
221
+ isFailed() {
222
+ return this._state === ToBTCSwapState.REFUNDED;
223
+ }
224
+ /**
225
+ * @inheritDoc
226
+ */
227
+ isInProgress() {
228
+ return this._state === ToBTCSwapState.COMMITED || this._state === ToBTCSwapState.SOFT_CLAIMED;
229
+ }
230
+ /**
231
+ * Returns the time (in UNIX milliseconds) at which the swap expires and the user is able to unilaterally
232
+ * refund it with the {@link refund} or {@link txsRefund} function.
233
+ */
234
+ getExpiry() {
235
+ return Number(this._data.getExpiry()) * 1000;
236
+ }
237
+ /**
238
+ * @inheritDoc
239
+ * @internal
240
+ */
241
+ _getInitiator() {
242
+ return this._data.getOfferer();
243
+ }
244
+ //////////////////////////////
245
+ //// Amounts & fees
246
+ /**
247
+ * Returns the swap fee charged by the intermediary (LP) on this swap
248
+ *
249
+ * @internal
250
+ */
251
+ getSwapFee() {
252
+ if (this.pricingInfo == null)
253
+ throw new Error("No pricing info known, cannot estimate fee!");
254
+ const feeWithoutBaseFee = this.swapFeeBtc - this.pricingInfo.satsBaseFee;
255
+ const output = this.getOutput();
256
+ const swapFeePPM = output.rawAmount == null ? 0n : feeWithoutBaseFee * 1000000n / output.rawAmount;
257
+ const amountInDstToken = (0, TokenAmount_1.toTokenAmount)(this.swapFeeBtc, this.outputToken, this.wrapper._prices, this.pricingInfo);
258
+ return {
259
+ amountInSrcToken: (0, TokenAmount_1.toTokenAmount)(this.swapFee, this.wrapper._tokens[this._data.getToken()], this.wrapper._prices, this.pricingInfo),
260
+ amountInDstToken,
261
+ currentUsdValue: amountInDstToken.currentUsdValue,
262
+ usdValue: amountInDstToken.usdValue,
263
+ pastUsdValue: amountInDstToken.pastUsdValue,
264
+ composition: {
265
+ base: (0, TokenAmount_1.toTokenAmount)(this.pricingInfo.satsBaseFee, this.outputToken, this.wrapper._prices, this.pricingInfo),
266
+ percentage: (0, PercentagePPM_1.ppmToPercentage)(swapFeePPM)
267
+ }
268
+ };
269
+ }
270
+ /**
271
+ * Returns network fee for on the destination chain for the swap
272
+ *
273
+ * @internal
274
+ */
275
+ getNetworkFee() {
276
+ const amountInDstToken = (0, TokenAmount_1.toTokenAmount)(this.networkFeeBtc, this.outputToken, this.wrapper._prices, this.pricingInfo);
277
+ return {
278
+ amountInSrcToken: (0, TokenAmount_1.toTokenAmount)(this.networkFee, this.wrapper._tokens[this._data.getToken()], this.wrapper._prices, this.pricingInfo),
279
+ amountInDstToken,
280
+ currentUsdValue: amountInDstToken.currentUsdValue,
281
+ usdValue: amountInDstToken.usdValue,
282
+ pastUsdValue: amountInDstToken.pastUsdValue
283
+ };
284
+ }
285
+ /**
286
+ * @inheritDoc
287
+ */
288
+ getFee() {
289
+ const amountInDstToken = (0, TokenAmount_1.toTokenAmount)(this.swapFeeBtc + this.networkFeeBtc, this.outputToken, this.wrapper._prices, this.pricingInfo);
290
+ return {
291
+ amountInSrcToken: (0, TokenAmount_1.toTokenAmount)(this.swapFee + this.networkFee, this.wrapper._tokens[this._data.getToken()], this.wrapper._prices, this.pricingInfo),
292
+ amountInDstToken,
293
+ currentUsdValue: amountInDstToken.currentUsdValue,
294
+ usdValue: amountInDstToken.usdValue,
295
+ pastUsdValue: amountInDstToken.pastUsdValue
296
+ };
297
+ }
298
+ /**
299
+ * @inheritDoc
300
+ */
301
+ getFeeBreakdown() {
302
+ return [
303
+ {
304
+ type: FeeType_1.FeeType.SWAP,
305
+ fee: this.getSwapFee()
306
+ },
307
+ {
308
+ type: FeeType_1.FeeType.NETWORK_OUTPUT,
309
+ fee: this.getNetworkFee()
310
+ }
311
+ ];
312
+ }
313
+ /**
314
+ * @inheritDoc
315
+ */
316
+ getInputToken() {
317
+ return this.wrapper._tokens[this._data.getToken()];
318
+ }
319
+ /**
320
+ * @inheritDoc
321
+ */
322
+ getInput() {
323
+ return (0, TokenAmount_1.toTokenAmount)(this._data.getAmount(), this.wrapper._tokens[this._data.getToken()], this.wrapper._prices, this.pricingInfo);
324
+ }
325
+ /**
326
+ * @inheritDoc
327
+ */
328
+ getInputWithoutFee() {
329
+ return (0, TokenAmount_1.toTokenAmount)(this._data.getAmount() - (this.swapFee + this.networkFee), this.wrapper._tokens[this._data.getToken()], this.wrapper._prices, this.pricingInfo);
330
+ }
331
+ /**
332
+ * Checks if the initiator/sender on the source chain has enough balance to go through with the swap
333
+ */
334
+ async hasEnoughBalance() {
335
+ const [balance, commitFee] = await Promise.all([
336
+ this.wrapper._contract.getBalance(this._getInitiator(), this._data.getToken(), false),
337
+ this._data.getToken() === this.wrapper._chain.getNativeCurrencyAddress() ? this.getCommitFee() : Promise.resolve(null)
338
+ ]);
339
+ let required = this._data.getAmount();
340
+ if (commitFee != null)
341
+ required = required + commitFee;
342
+ return {
343
+ enoughBalance: balance >= required,
344
+ balance: (0, TokenAmount_1.toTokenAmount)(balance, this.wrapper._tokens[this._data.getToken()], this.wrapper._prices, this.pricingInfo),
345
+ required: (0, TokenAmount_1.toTokenAmount)(required, this.wrapper._tokens[this._data.getToken()], this.wrapper._prices, this.pricingInfo)
346
+ };
347
+ }
348
+ /**
349
+ * Checks if the initiator/sender on the source chain has enough native token balance
350
+ * to cover the transaction fee of initiating the swap
351
+ */
352
+ async hasEnoughForTxFees() {
353
+ const [balance, commitFee] = await Promise.all([
354
+ this.wrapper._contract.getBalance(this._getInitiator(), this.wrapper._chain.getNativeCurrencyAddress(), false),
355
+ this.getCommitFee()
356
+ ]);
357
+ return {
358
+ enoughBalance: balance >= commitFee,
359
+ balance: (0, TokenAmount_1.toTokenAmount)(balance, this.wrapper._getNativeToken(), this.wrapper._prices),
360
+ required: (0, TokenAmount_1.toTokenAmount)(commitFee, this.wrapper._getNativeToken(), this.wrapper._prices)
361
+ };
362
+ }
363
+ //////////////////////////////
364
+ //// Execution
365
+ /**
366
+ * Executes the swap with the provided smart chain wallet/signer
367
+ *
368
+ * @param signer Smart chain wallet/signer to use to sign the transaction on the source chain
369
+ * @param callbacks Callbacks to track the progress of the swap
370
+ * @param options Optional options for the swap like feeRate, AbortSignal, and timeouts/intervals
371
+ *
372
+ * @returns {boolean} Whether the swap was successfully processed by the LP, in case `false` is returned
373
+ * the user can refund their funds back on the source chain by calling {@link refund}
374
+ */
375
+ async execute(signer, callbacks, options) {
376
+ if (this._state === ToBTCSwapState.QUOTE_EXPIRED || this._state === ToBTCSwapState.QUOTE_SOFT_EXPIRED)
377
+ throw new Error("Quote expired");
378
+ if (this._state === ToBTCSwapState.REFUNDED)
379
+ throw new Error("Swap already refunded");
380
+ if (this._state === ToBTCSwapState.REFUNDABLE)
381
+ throw new Error("Swap refundable, refund with swap.refund()");
382
+ if (this._state === ToBTCSwapState.SOFT_CLAIMED || this._state === ToBTCSwapState.CLAIMED)
383
+ throw new Error("Swap already settled!");
384
+ if (this._state === ToBTCSwapState.CREATED) {
385
+ const txId = await this.commit(signer, options?.abortSignal, false, callbacks?.onSourceTransactionSent);
386
+ if (callbacks?.onSourceTransactionConfirmed != null)
387
+ callbacks.onSourceTransactionConfirmed(txId);
388
+ }
389
+ // @ts-ignore
390
+ if (this._state === ToBTCSwapState.CLAIMED || this._state === ToBTCSwapState.SOFT_CLAIMED)
391
+ return true;
392
+ if (this._state === ToBTCSwapState.COMMITED) {
393
+ const success = await this.waitForPayment(options?.maxWaitTillSwapProcessedSeconds ?? 120, options?.paymentCheckIntervalSeconds, options?.abortSignal);
394
+ if (success) {
395
+ if (callbacks?.onSwapSettled != null)
396
+ callbacks.onSwapSettled(this.getOutputTxId());
397
+ return true;
398
+ }
399
+ else {
400
+ return false;
401
+ }
402
+ }
403
+ throw new Error("Unexpected state reached!");
404
+ }
405
+ /**
406
+ * @inheritDoc
407
+ *
408
+ * @param options.skipChecks Skip checks like making sure init signature is still valid and swap wasn't commited yet
409
+ * (this is handled on swap creation, if you commit right after quoting, you can use `skipChecks=true`)
410
+ */
411
+ async txsExecute(options) {
412
+ if (this._state !== ToBTCSwapState.CREATED)
413
+ throw new Error("Invalid swap state, needs to be CREATED!");
414
+ const txsCommit = await this.txsCommit(options?.skipChecks);
415
+ return [
416
+ {
417
+ name: "Commit",
418
+ description: `Initiates the swap by commiting the funds to the escrow on the ${this.chainIdentifier} side`,
419
+ chain: this.chainIdentifier,
420
+ txs: txsCommit
421
+ }
422
+ ];
423
+ }
424
+ /**
425
+ * @inheritDoc
426
+ *
427
+ * @param options.skipChecks Skip checks like making sure init signature is still valid and swap wasn't commited yet
428
+ * (this is handled on swap creation, if you commit right after quoting, you can use `skipChecks=true`)
429
+ * @param options.refundSmartChainSigner Optional smart chain signer to use when creating refunds transactions
430
+ */
431
+ async getCurrentActions(options) {
432
+ if (this._state === ToBTCSwapState.CREATED) {
433
+ try {
434
+ return await this.txsExecute(options);
435
+ }
436
+ catch (e) { }
437
+ }
438
+ if (this.isRefundable()) {
439
+ return [{
440
+ name: "Refund",
441
+ description: "Refund the swap after it failed to execute",
442
+ chain: this.chainIdentifier,
443
+ txs: await this.txsRefund(options?.refundSmartChainSigner)
444
+ }];
445
+ }
446
+ return [];
447
+ }
448
+ //////////////////////////////
449
+ //// Commit
450
+ /**
451
+ * @inheritDoc
452
+ *
453
+ * @throws {Error} When in invalid state (not {@link ToBTCSwapState.CREATED})
454
+ */
455
+ async txsCommit(skipChecks) {
456
+ if (this._state !== ToBTCSwapState.CREATED && (!skipChecks || this._state !== ToBTCSwapState.QUOTE_SOFT_EXPIRED))
457
+ throw new Error("Must be in CREATED state!");
458
+ if (this.signatureData == null)
459
+ throw new Error("Init signature data not known, cannot commit!");
460
+ if (!this.initiated) {
461
+ this.initiated = true;
462
+ await this._saveAndEmit();
463
+ }
464
+ return await this.wrapper._contract.txsInit(this._getInitiator(), this._data, this.signatureData, skipChecks, this.feeRate).catch(e => Promise.reject(e instanceof base_1.SignatureVerificationError ? new Error("Request timed out") : e));
465
+ }
466
+ /**
467
+ * @inheritDoc
468
+ *
469
+ * @throws {Error} If invalid signer is provided that doesn't match the swap data
470
+ */
471
+ async commit(_signer, abortSignal, skipChecks, onBeforeTxSent) {
472
+ const signer = (0, base_1.isAbstractSigner)(_signer) ? _signer : await this.wrapper._chain.wrapSigner(_signer);
473
+ this.checkSigner(signer);
474
+ const txs = await this.txsCommit(skipChecks);
475
+ let txCount = 0;
476
+ const result = await this.wrapper._chain.sendAndConfirm(signer, txs, true, abortSignal, false, (txId, rawTx) => {
477
+ txCount++;
478
+ if (onBeforeTxSent != null && txCount === txs.length)
479
+ onBeforeTxSent(txId);
480
+ return Promise.resolve();
481
+ });
482
+ this._commitTxId = result[result.length - 1];
483
+ if (this._state === ToBTCSwapState.CREATED || this._state === ToBTCSwapState.QUOTE_SOFT_EXPIRED || this._state === ToBTCSwapState.QUOTE_EXPIRED) {
484
+ await this._saveAndEmit(ToBTCSwapState.COMMITED);
485
+ }
486
+ return this._commitTxId;
487
+ }
488
+ /**
489
+ * @inheritDoc
490
+ *
491
+ * @throws {Error} If swap is not in the correct state (must be {@link ToBTCSwapState.CREATED})
492
+ */
493
+ async waitTillCommited(abortSignal) {
494
+ if (this._state === ToBTCSwapState.COMMITED || this._state === ToBTCSwapState.CLAIMED)
495
+ return Promise.resolve();
496
+ if (this._state !== ToBTCSwapState.CREATED && this._state !== ToBTCSwapState.QUOTE_SOFT_EXPIRED)
497
+ throw new Error("Invalid state (not CREATED)");
498
+ const abortController = (0, Utils_1.extendAbortController)(abortSignal);
499
+ let result;
500
+ try {
501
+ result = await Promise.race([
502
+ this.watchdogWaitTillCommited(undefined, abortController.signal),
503
+ this.waitTillState(ToBTCSwapState.COMMITED, "gte", abortController.signal).then(() => 0)
504
+ ]);
505
+ abortController.abort();
506
+ }
507
+ catch (e) {
508
+ abortController.abort();
509
+ throw e;
510
+ }
511
+ if (result === 0)
512
+ this.logger.debug("waitTillCommited(): Resolved from state change");
513
+ if (result === true)
514
+ this.logger.debug("waitTillCommited(): Resolved from watchdog - commited");
515
+ if (result === false) {
516
+ this.logger.debug("waitTillCommited(): Resolved from watchdog - signature expiry");
517
+ if (this._state === ToBTCSwapState.QUOTE_SOFT_EXPIRED || this._state === ToBTCSwapState.CREATED) {
518
+ await this._saveAndEmit(ToBTCSwapState.QUOTE_EXPIRED);
519
+ }
520
+ throw new Error("Quote expired while waiting for transaction confirmation!");
521
+ }
522
+ if (this._state === ToBTCSwapState.QUOTE_SOFT_EXPIRED || this._state === ToBTCSwapState.CREATED || this._state === ToBTCSwapState.QUOTE_EXPIRED) {
523
+ await this._saveAndEmit(ToBTCSwapState.COMMITED);
524
+ }
525
+ }
526
+ //////////////////////////////
527
+ //// Payment
528
+ /**
529
+ * Waits till the swap is processed by the intermediary (LP)
530
+ *
531
+ * @param checkIntervalSeconds How often to poll the intermediary for status (5 seconds default)
532
+ * @param abortSignal Abort signal
533
+ * @internal
534
+ */
535
+ async waitTillIntermediarySwapProcessed(checkIntervalSeconds, abortSignal) {
536
+ if (this.url == null)
537
+ throw new Error("LP URL not specified!");
538
+ checkIntervalSeconds ??= 5;
539
+ let resp = { code: IntermediaryAPI_1.RefundAuthorizationResponseCodes.PENDING, msg: "" };
540
+ while (!abortSignal?.aborted && (resp.code === IntermediaryAPI_1.RefundAuthorizationResponseCodes.PENDING || resp.code === IntermediaryAPI_1.RefundAuthorizationResponseCodes.NOT_FOUND)) {
541
+ resp = await IntermediaryAPI_1.IntermediaryAPI.getRefundAuthorization(this.url, this.getLpIdentifier(), this._data.getSequence());
542
+ if (resp.code === IntermediaryAPI_1.RefundAuthorizationResponseCodes.PAID) {
543
+ const validResponse = await this._setPaymentResult(resp.data, true);
544
+ if (validResponse) {
545
+ if (this._state === ToBTCSwapState.COMMITED || this._state === ToBTCSwapState.REFUNDABLE) {
546
+ await this._saveAndEmit(ToBTCSwapState.SOFT_CLAIMED);
547
+ }
548
+ }
549
+ else {
550
+ resp = { code: IntermediaryAPI_1.RefundAuthorizationResponseCodes.PENDING, msg: "" };
551
+ }
552
+ }
553
+ if (resp.code === IntermediaryAPI_1.RefundAuthorizationResponseCodes.PENDING ||
554
+ resp.code === IntermediaryAPI_1.RefundAuthorizationResponseCodes.NOT_FOUND)
555
+ await (0, TimeoutUtils_1.timeoutPromise)(checkIntervalSeconds * 1000, abortSignal);
556
+ }
557
+ return resp;
558
+ }
559
+ /**
560
+ * Checks whether the swap was already processed by the LP and is either successful (requires proof which is
561
+ * either a HTLC pre-image for LN swaps or valid txId for on-chain swap) or failed and we can cooperatively
562
+ * refund.
563
+ *
564
+ * @param save whether to save the data
565
+ * @returns `true` if swap is processed, `false` if the swap is still ongoing
566
+ *
567
+ * @internal
568
+ */
569
+ async checkIntermediarySwapProcessed(save = true) {
570
+ if (this._state === ToBTCSwapState.CREATED || this._state == ToBTCSwapState.QUOTE_EXPIRED || this.url == null)
571
+ return false;
572
+ if (this.isFinished() || this.isRefundable())
573
+ return true;
574
+ //Check if that maybe already concluded according to the LP
575
+ const resp = await IntermediaryAPI_1.IntermediaryAPI.getRefundAuthorization(this.url, this.getLpIdentifier(), this._data.getSequence());
576
+ switch (resp.code) {
577
+ case IntermediaryAPI_1.RefundAuthorizationResponseCodes.PAID:
578
+ const processed = await this._setPaymentResult(resp.data, true);
579
+ if (processed) {
580
+ this._state = ToBTCSwapState.SOFT_CLAIMED;
581
+ if (save)
582
+ await this._saveAndEmit();
583
+ }
584
+ return processed;
585
+ case IntermediaryAPI_1.RefundAuthorizationResponseCodes.REFUND_DATA:
586
+ await this.wrapper._contract.isValidRefundAuthorization(this._data, resp.data);
587
+ this._state = ToBTCSwapState.REFUNDABLE;
588
+ if (save)
589
+ await this._saveAndEmit();
590
+ return true;
591
+ default:
592
+ return false;
593
+ }
594
+ }
595
+ /**
596
+ * A blocking promise resolving when swap was concluded by the intermediary (LP),
597
+ * rejecting in case of failure
598
+ *
599
+ * @param maxWaitTimeSeconds Maximum time in seconds to wait for the swap to be settled, an error is thrown if the
600
+ * swap is taking too long to claim
601
+ * @param checkIntervalSeconds How often to poll the intermediary for answer
602
+ * @param abortSignal Abort signal
603
+ * @returns `true` if swap was successful, `false` if swap failed and we can refund
604
+ *
605
+ * @throws {IntermediaryError} If a swap is determined expired by the intermediary, but it is actually still valid
606
+ * @throws {SignatureVerificationError} If the swap should be cooperatively refundable but the intermediary returned
607
+ * invalid refund signature
608
+ * @throws {Error} When swap expires or if the swap has invalid state (must be {@link ToBTCSwapState.COMMITED})
609
+ */
610
+ async waitForPayment(maxWaitTimeSeconds, checkIntervalSeconds, abortSignal) {
611
+ if (this._state === ToBTCSwapState.CLAIMED)
612
+ return Promise.resolve(true);
613
+ if (this._state !== ToBTCSwapState.COMMITED && this._state !== ToBTCSwapState.SOFT_CLAIMED)
614
+ throw new Error("Invalid state (not COMMITED)");
615
+ const abortController = (0, Utils_1.extendAbortController)(abortSignal);
616
+ let timedOut = false;
617
+ if (maxWaitTimeSeconds != null) {
618
+ const timeout = setTimeout(() => {
619
+ timedOut = true;
620
+ abortController.abort();
621
+ }, maxWaitTimeSeconds * 1000);
622
+ abortController.signal.addEventListener("abort", () => clearTimeout(timeout));
623
+ }
624
+ let result;
625
+ try {
626
+ result = await Promise.race([
627
+ this.waitTillState(ToBTCSwapState.CLAIMED, "gte", abortController.signal),
628
+ this.waitTillIntermediarySwapProcessed(checkIntervalSeconds, abortController.signal)
629
+ ]);
630
+ abortController.abort();
631
+ }
632
+ catch (e) {
633
+ abortController.abort();
634
+ if (timedOut) {
635
+ throw new Error("Timed out while waiting for LP to process the swap, the LP might be unresponsive or offline!" +
636
+ ` Please check later or wait till ${new Date(Number(this._data.getExpiry()) * 1000).toLocaleString()} to refund unilaterally!`);
637
+ }
638
+ throw e;
639
+ }
640
+ if (typeof result !== "object") {
641
+ if (this._state === ToBTCSwapState.REFUNDABLE)
642
+ throw new Error("Swap expired");
643
+ this.logger.debug("waitTillRefunded(): Resolved from state change");
644
+ return true;
645
+ }
646
+ this.logger.debug("waitTillRefunded(): Resolved from intermediary response");
647
+ switch (result.code) {
648
+ case IntermediaryAPI_1.RefundAuthorizationResponseCodes.PAID:
649
+ return true;
650
+ case IntermediaryAPI_1.RefundAuthorizationResponseCodes.REFUND_DATA:
651
+ const resultData = result.data;
652
+ await this.wrapper._contract.isValidRefundAuthorization(this._data, resultData);
653
+ await this._saveAndEmit(ToBTCSwapState.REFUNDABLE);
654
+ return false;
655
+ case IntermediaryAPI_1.RefundAuthorizationResponseCodes.EXPIRED:
656
+ if (await this.wrapper._contract.isExpired(this._getInitiator(), this._data))
657
+ throw new Error("Swap expired");
658
+ throw new IntermediaryError_1.IntermediaryError("Swap expired");
659
+ case IntermediaryAPI_1.RefundAuthorizationResponseCodes.NOT_FOUND:
660
+ if (this._state === ToBTCSwapState.CLAIMED)
661
+ return true;
662
+ throw new Error("LP swap not found");
663
+ }
664
+ throw new Error("Invalid response code returned by the LP");
665
+ }
666
+ //////////////////////////////
667
+ //// Refund
668
+ /**
669
+ * Get the estimated smart chain transaction fee of the refund transaction
670
+ */
671
+ async getRefundNetworkFee() {
672
+ const swapContract = this.wrapper._contract;
673
+ return (0, TokenAmount_1.toTokenAmount)(await swapContract.getRefundFee(this._getInitiator(), this._data), this.wrapper._getNativeToken(), this.wrapper._prices);
674
+ }
675
+ /**
676
+ * @inheritDoc
677
+ *
678
+ * @throws {IntermediaryError} If intermediary returns invalid response in case cooperative refund should be used
679
+ * @throws {SignatureVerificationError} If intermediary returned invalid cooperative refund signature
680
+ * @throws {Error} When state is not refundable
681
+ */
682
+ async txsRefund(_signer) {
683
+ if (!this.isRefundable())
684
+ throw new Error("Must be in REFUNDABLE state or expired!");
685
+ let signer;
686
+ if (_signer != null) {
687
+ if (typeof (_signer) === "string") {
688
+ signer = _signer;
689
+ }
690
+ else if ((0, base_1.isAbstractSigner)(_signer)) {
691
+ signer = _signer.getAddress();
692
+ }
693
+ else {
694
+ signer = (await this.wrapper._chain.wrapSigner(_signer)).getAddress();
695
+ }
696
+ }
697
+ else {
698
+ signer = this._getInitiator();
699
+ }
700
+ if (await this.wrapper._contract.isExpired(this._getInitiator(), this._data)) {
701
+ return await this.wrapper._contract.txsRefund(signer, this._data, true, true);
702
+ }
703
+ else {
704
+ if (this.url == null)
705
+ throw new Error("LP URL not known, cannot get cooperative refund message, wait till expiry to refund!");
706
+ const res = await IntermediaryAPI_1.IntermediaryAPI.getRefundAuthorization(this.url, this.getLpIdentifier(), this._data.getSequence());
707
+ if (res.code === IntermediaryAPI_1.RefundAuthorizationResponseCodes.REFUND_DATA) {
708
+ return await this.wrapper._contract.txsRefundWithAuthorization(signer, this._data, res.data, true, true);
709
+ }
710
+ throw new IntermediaryError_1.IntermediaryError("Invalid intermediary cooperative message returned");
711
+ }
712
+ }
713
+ /**
714
+ * @inheritDoc
715
+ *
716
+ * @throws {Error} If invalid signer is provided that doesn't match the swap data
717
+ */
718
+ async refund(_signer, abortSignal) {
719
+ const signer = (0, base_1.isAbstractSigner)(_signer) ? _signer : await this.wrapper._chain.wrapSigner(_signer);
720
+ const result = await this.wrapper._chain.sendAndConfirm(signer, await this.txsRefund(signer.getAddress()), true, abortSignal);
721
+ this._refundTxId = result[0];
722
+ if (this._state === ToBTCSwapState.COMMITED || this._state === ToBTCSwapState.REFUNDABLE || this._state === ToBTCSwapState.SOFT_CLAIMED) {
723
+ await this._saveAndEmit(ToBTCSwapState.REFUNDED);
724
+ }
725
+ return result[0];
726
+ }
727
+ /**
728
+ * @inheritDoc
729
+ *
730
+ * @throws {Error} When swap is not in a valid state (must be {@link ToBTCSwapState.COMMITED} or
731
+ * {@link ToBTCSwapState.REFUNDABLE})
732
+ * @throws {Error} If we tried to refund but claimer was able to claim first
733
+ */
734
+ async waitTillRefunded(abortSignal) {
735
+ if (this._state === ToBTCSwapState.REFUNDED)
736
+ return Promise.resolve();
737
+ if (this._state !== ToBTCSwapState.COMMITED &&
738
+ this._state !== ToBTCSwapState.SOFT_CLAIMED &&
739
+ this._state !== ToBTCSwapState.REFUNDABLE)
740
+ throw new Error("Invalid state (not COMMITED)");
741
+ const abortController = new AbortController();
742
+ if (abortSignal != null)
743
+ abortSignal.addEventListener("abort", () => abortController.abort(abortSignal.reason));
744
+ const res = await Promise.race([
745
+ this.watchdogWaitTillResult(undefined, abortController.signal),
746
+ this.waitTillState(ToBTCSwapState.REFUNDED, "eq", abortController.signal).then(() => 0),
747
+ this.waitTillState(ToBTCSwapState.CLAIMED, "eq", abortController.signal).then(() => 1),
748
+ ]);
749
+ abortController.abort();
750
+ if (res === 0) {
751
+ this.logger.debug("waitTillRefunded(): Resolved from state change (REFUNDED)");
752
+ return;
753
+ }
754
+ if (res === 1) {
755
+ this.logger.debug("waitTillRefunded(): Resolved from state change (CLAIMED)");
756
+ throw new Error("Tried to refund swap, but claimer claimed it in the meantime!");
757
+ }
758
+ this.logger.debug("waitTillRefunded(): Resolved from watchdog");
759
+ if (res?.type === base_1.SwapCommitStateType.PAID) {
760
+ if (this._claimTxId == null)
761
+ this._claimTxId = await res.getClaimTxId();
762
+ await this._saveAndEmit(ToBTCSwapState.CLAIMED);
763
+ throw new Error("Tried to refund swap, but claimer claimed it in the meantime!");
764
+ }
765
+ if (res?.type === base_1.SwapCommitStateType.NOT_COMMITED) {
766
+ if (this._refundTxId == null && res.getRefundTxId != null)
767
+ this._refundTxId = await res.getRefundTxId();
768
+ await this._saveAndEmit(ToBTCSwapState.REFUNDED);
769
+ }
770
+ }
771
+ //////////////////////////////
772
+ //// Storage
773
+ /**
774
+ * @inheritDoc
775
+ */
776
+ serialize() {
777
+ const obj = super.serialize();
778
+ return {
779
+ ...obj,
780
+ networkFee: this.networkFee == null ? null : this.networkFee.toString(10),
781
+ networkFeeBtc: this.networkFeeBtc == null ? null : this.networkFeeBtc.toString(10)
782
+ };
783
+ }
784
+ //////////////////////////////
785
+ //// Swap ticks & sync
786
+ /**
787
+ * Checks the swap's state on-chain and compares it to its internal state, updates/changes it according to on-chain
788
+ * data
789
+ *
790
+ * @private
791
+ */
792
+ async syncStateFromChain(quoteDefinitelyExpired, commitStatus) {
793
+ if (this._state === ToBTCSwapState.CREATED ||
794
+ this._state === ToBTCSwapState.QUOTE_SOFT_EXPIRED ||
795
+ this._state === ToBTCSwapState.COMMITED ||
796
+ this._state === ToBTCSwapState.SOFT_CLAIMED ||
797
+ this._state === ToBTCSwapState.REFUNDABLE) {
798
+ let quoteExpired = false;
799
+ if (this._state === ToBTCSwapState.CREATED || this._state === ToBTCSwapState.QUOTE_SOFT_EXPIRED) {
800
+ //Check if quote is still valid
801
+ quoteExpired = quoteDefinitelyExpired ?? await this._verifyQuoteDefinitelyExpired();
802
+ }
803
+ commitStatus ??= await this.wrapper._contract.getCommitStatus(this._getInitiator(), this._data);
804
+ if (commitStatus != null && await this._forciblySetOnchainState(commitStatus))
805
+ return true;
806
+ if ((this._state === ToBTCSwapState.CREATED || this._state === ToBTCSwapState.QUOTE_SOFT_EXPIRED)) {
807
+ if (quoteExpired) {
808
+ this._state = ToBTCSwapState.QUOTE_EXPIRED;
809
+ return true;
810
+ }
811
+ }
812
+ }
813
+ return false;
814
+ }
815
+ /**
816
+ * @inheritDoc
817
+ * @internal
818
+ */
819
+ _shouldFetchOnchainState() {
820
+ return this._state === ToBTCSwapState.CREATED ||
821
+ this._state === ToBTCSwapState.QUOTE_SOFT_EXPIRED ||
822
+ this._state === ToBTCSwapState.COMMITED ||
823
+ this._state === ToBTCSwapState.SOFT_CLAIMED ||
824
+ this._state === ToBTCSwapState.REFUNDABLE;
825
+ }
826
+ /**
827
+ * @inheritDoc
828
+ * @internal
829
+ */
830
+ _shouldFetchExpiryStatus() {
831
+ return this._state === ToBTCSwapState.CREATED || this._state === ToBTCSwapState.QUOTE_SOFT_EXPIRED;
832
+ }
833
+ /**
834
+ * @inheritDoc
835
+ * @internal
836
+ */
837
+ async _sync(save, quoteDefinitelyExpired, commitStatus) {
838
+ let changed = await this.syncStateFromChain(quoteDefinitelyExpired, commitStatus);
839
+ if (this._state === ToBTCSwapState.COMMITED || this._state === ToBTCSwapState.SOFT_CLAIMED) {
840
+ //Check if that maybe already concluded
841
+ try {
842
+ if (await this.checkIntermediarySwapProcessed(false))
843
+ changed = true;
844
+ }
845
+ catch (e) {
846
+ this.logger.error("_sync(): Failed to synchronize swap, error: ", e);
847
+ }
848
+ }
849
+ if (save && changed)
850
+ await this._saveAndEmit();
851
+ return changed;
852
+ }
853
+ /**
854
+ * @inheritDoc
855
+ * @internal
856
+ */
857
+ async _forciblySetOnchainState(commitStatus) {
858
+ switch (commitStatus.type) {
859
+ case base_1.SwapCommitStateType.PAID:
860
+ if (this._claimTxId == null && commitStatus.getClaimTxId)
861
+ this._claimTxId = await commitStatus.getClaimTxId();
862
+ const eventResult = await commitStatus.getClaimResult();
863
+ try {
864
+ await this._setPaymentResult({ secret: eventResult, txId: Buffer.from(eventResult, "hex").reverse().toString("hex") });
865
+ }
866
+ catch (e) {
867
+ this.logger.error(`Failed to set payment result ${eventResult} on the swap!`);
868
+ }
869
+ this._state = ToBTCSwapState.CLAIMED;
870
+ return true;
871
+ case base_1.SwapCommitStateType.REFUNDABLE:
872
+ this._state = ToBTCSwapState.REFUNDABLE;
873
+ return true;
874
+ case base_1.SwapCommitStateType.EXPIRED:
875
+ if (this._refundTxId == null && commitStatus.getRefundTxId)
876
+ this._refundTxId = await commitStatus.getRefundTxId();
877
+ this._state = this._refundTxId == null ? ToBTCSwapState.QUOTE_EXPIRED : ToBTCSwapState.REFUNDED;
878
+ return true;
879
+ case base_1.SwapCommitStateType.NOT_COMMITED:
880
+ if (this._refundTxId == null && commitStatus.getRefundTxId)
881
+ this._refundTxId = await commitStatus.getRefundTxId();
882
+ if (this._refundTxId != null) {
883
+ this._state = ToBTCSwapState.REFUNDED;
884
+ return true;
885
+ }
886
+ break;
887
+ case base_1.SwapCommitStateType.COMMITED:
888
+ if (this._state !== ToBTCSwapState.COMMITED && this._state !== ToBTCSwapState.REFUNDABLE && this._state !== ToBTCSwapState.SOFT_CLAIMED) {
889
+ this._state = ToBTCSwapState.COMMITED;
890
+ return true;
891
+ }
892
+ break;
893
+ }
894
+ return false;
895
+ }
896
+ /**
897
+ * @inheritDoc
898
+ * @internal
899
+ */
900
+ async _tick(save) {
901
+ switch (this._state) {
902
+ case ToBTCSwapState.CREATED:
903
+ if (this.expiry < Date.now()) {
904
+ this._state = ToBTCSwapState.QUOTE_SOFT_EXPIRED;
905
+ if (save)
906
+ await this._saveAndEmit();
907
+ return true;
908
+ }
909
+ break;
910
+ case ToBTCSwapState.COMMITED:
911
+ case ToBTCSwapState.SOFT_CLAIMED:
912
+ const expired = await this.wrapper._contract.isExpired(this._getInitiator(), this._data);
913
+ if (expired) {
914
+ this._state = ToBTCSwapState.REFUNDABLE;
915
+ if (save)
916
+ await this._saveAndEmit();
917
+ return true;
918
+ }
919
+ break;
920
+ }
921
+ return false;
922
+ }
923
+ }
924
+ exports.IToBTCSwap = IToBTCSwap;