@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,1603 +1,1603 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.Swapper = void 0;
4
- const base_1 = require("@atomiqlabs/base");
5
- const ToBTCLNWrapper_1 = require("../swaps/escrow_swaps/tobtc/ln/ToBTCLNWrapper");
6
- const ToBTCWrapper_1 = require("../swaps/escrow_swaps/tobtc/onchain/ToBTCWrapper");
7
- const FromBTCLNWrapper_1 = require("../swaps/escrow_swaps/frombtc/ln/FromBTCLNWrapper");
8
- const FromBTCWrapper_1 = require("../swaps/escrow_swaps/frombtc/onchain/FromBTCWrapper");
9
- const IntermediaryDiscovery_1 = require("../intermediaries/IntermediaryDiscovery");
10
- const bolt11_1 = require("@atomiqlabs/bolt11");
11
- const IntermediaryError_1 = require("../errors/IntermediaryError");
12
- const SwapType_1 = require("../enums/SwapType");
13
- const LnForGasWrapper_1 = require("../swaps/trusted/ln/LnForGasWrapper");
14
- const events_1 = require("events");
15
- const Utils_1 = require("../utils/Utils");
16
- const RequestError_1 = require("../errors/RequestError");
17
- const SwapperWithChain_1 = require("./SwapperWithChain");
18
- const OnchainForGasWrapper_1 = require("../swaps/trusted/onchain/OnchainForGasWrapper");
19
- const utils_1 = require("@scure/btc-signer/utils");
20
- const UnifiedSwapStorage_1 = require("../storage/UnifiedSwapStorage");
21
- const UnifiedSwapEventListener_1 = require("../events/UnifiedSwapEventListener");
22
- const SpvFromBTCWrapper_1 = require("../swaps/spv_swaps/SpvFromBTCWrapper");
23
- const SpvFromBTCSwap_1 = require("../swaps/spv_swaps/SpvFromBTCSwap");
24
- const SwapperUtils_1 = require("./SwapperUtils");
25
- const FromBTCLNAutoWrapper_1 = require("../swaps/escrow_swaps/frombtc/ln_auto/FromBTCLNAutoWrapper");
26
- const UserError_1 = require("../errors/UserError");
27
- const AutomaticClockDriftCorrection_1 = require("../utils/AutomaticClockDriftCorrection");
28
- const SwapUtils_1 = require("../utils/SwapUtils");
29
- const IndexedDBUnifiedStorage_1 = require("../storage-browser/IndexedDBUnifiedStorage");
30
- const TokenAmount_1 = require("../types/TokenAmount");
31
- const Token_1 = require("../types/Token");
32
- const Logger_1 = require("../utils/Logger");
33
- const LNURLWithdraw_1 = require("../types/lnurl/LNURLWithdraw");
34
- const LNURLPay_1 = require("../types/lnurl/LNURLPay");
35
- const RetryUtils_1 = require("../utils/RetryUtils");
36
- const IEscrowSwap_1 = require("../swaps/escrow_swaps/IEscrowSwap");
37
- const LightningInvoiceCreateService_1 = require("../types/wallets/LightningInvoiceCreateService");
38
- /**
39
- * Core orchestrator for all atomiq swap operations
40
- *
41
- * @category Core
42
- */
43
- class Swapper extends events_1.EventEmitter {
44
- /**
45
- * @internal
46
- */
47
- constructor(bitcoinRpc, lightningApi, bitcoinSynchronizer, chainsData, pricing, tokens, messenger, options) {
48
- super();
49
- this.logger = (0, Logger_1.getLogger)(this.constructor.name + ": ");
50
- this.initialized = false;
51
- /**
52
- * Helper information about various swap protocol and their features:
53
- * - `requiresInputWallet`: Whether a swap requires a connected wallet on the input chain able to sign
54
- * arbitrary transaction
55
- * - `requiresOutputWallet`: Whether a swap requires a connected wallet on the output chain able to sign
56
- * arbitrary transactions
57
- * - `supportsGasDrop`: Whether a swap supports the "gas drop" feature, allowing to user to receive a small
58
- * amount of native token as part of the swap when swapping to smart chains
59
- *
60
- * Uses a `Record` type here, use the {@link SwapProtocolInfo} import for a literal readonly type, with
61
- * pre-filled exact values in the type.
62
- */
63
- this.SwapTypeInfo = SwapUtils_1.SwapProtocolInfo;
64
- const storagePrefix = options?.storagePrefix ?? "atomiq-";
65
- options ??= {};
66
- options.saveUninitializedSwaps ??= true;
67
- options.bitcoinNetwork = options.bitcoinNetwork == null ? base_1.BitcoinNetwork.TESTNET : options.bitcoinNetwork;
68
- const swapStorage = options.swapStorage ??= (name) => new IndexedDBUnifiedStorage_1.IndexedDBUnifiedStorage(name);
69
- this.options = options;
70
- this.bitcoinNetwork = options.bitcoinNetwork;
71
- this._btcNetwork = options.bitcoinNetwork === base_1.BitcoinNetwork.MAINNET ? utils_1.NETWORK :
72
- (options.bitcoinNetwork === base_1.BitcoinNetwork.TESTNET || options.bitcoinNetwork === base_1.BitcoinNetwork.TESTNET4) ? utils_1.TEST_NETWORK : {
73
- bech32: 'bcrt',
74
- pubKeyHash: 111,
75
- scriptHash: 196,
76
- wif: 239
77
- };
78
- this.Utils = new SwapperUtils_1.SwapperUtils(this);
79
- this.prices = pricing;
80
- this._bitcoinRpc = bitcoinRpc;
81
- this.messenger = messenger;
82
- this._tokens = {};
83
- this._tokensByTicker = {};
84
- for (let tokenData of tokens) {
85
- const chainId = tokenData.chainId;
86
- this._tokens[chainId] ??= {};
87
- this._tokensByTicker[chainId] ??= {};
88
- this._tokens[chainId][tokenData.address] = this._tokensByTicker[chainId][tokenData.ticker] = tokenData;
89
- }
90
- this.swapStateListener = (swap) => {
91
- this.emit("swapState", swap);
92
- };
93
- this._chains = (0, Utils_1.objectMap)(chainsData, (chainData, key) => {
94
- const { swapContract, chainEvents, btcRelay, chainInterface, spvVaultContract, spvVaultWithdrawalDataConstructor, chainId } = chainData;
95
- const synchronizer = bitcoinSynchronizer(btcRelay);
96
- const storageHandler = swapStorage(storagePrefix + chainId);
97
- const unifiedSwapStorage = new UnifiedSwapStorage_1.UnifiedSwapStorage(storageHandler, this.options.noSwapCache);
98
- const unifiedChainEvents = new UnifiedSwapEventListener_1.UnifiedSwapEventListener(unifiedSwapStorage, chainEvents);
99
- const wrappers = {};
100
- wrappers[SwapType_1.SwapType.TO_BTCLN] = new ToBTCLNWrapper_1.ToBTCLNWrapper(key, unifiedSwapStorage, unifiedChainEvents, chainInterface, swapContract, pricing, this._tokens[chainId], chainData.swapDataConstructor, {
101
- getRequestTimeout: this.options.getRequestTimeout,
102
- postRequestTimeout: this.options.postRequestTimeout,
103
- saveUninitializedSwaps: this.options.saveUninitializedSwaps,
104
- });
105
- wrappers[SwapType_1.SwapType.TO_BTC] = new ToBTCWrapper_1.ToBTCWrapper(key, unifiedSwapStorage, unifiedChainEvents, chainInterface, swapContract, pricing, this._tokens[chainId], chainData.swapDataConstructor, this._bitcoinRpc, {
106
- getRequestTimeout: this.options.getRequestTimeout,
107
- postRequestTimeout: this.options.postRequestTimeout,
108
- saveUninitializedSwaps: this.options.saveUninitializedSwaps,
109
- bitcoinNetwork: this._btcNetwork
110
- });
111
- wrappers[SwapType_1.SwapType.FROM_BTCLN] = new FromBTCLNWrapper_1.FromBTCLNWrapper(key, unifiedSwapStorage, unifiedChainEvents, chainInterface, swapContract, pricing, this._tokens[chainId], chainData.swapDataConstructor, lightningApi, {
112
- getRequestTimeout: this.options.getRequestTimeout,
113
- postRequestTimeout: this.options.postRequestTimeout,
114
- saveUninitializedSwaps: this.options.saveUninitializedSwaps,
115
- unsafeSkipLnNodeCheck: this.bitcoinNetwork === base_1.BitcoinNetwork.TESTNET4 || this.bitcoinNetwork === base_1.BitcoinNetwork.REGTEST
116
- });
117
- wrappers[SwapType_1.SwapType.FROM_BTC] = new FromBTCWrapper_1.FromBTCWrapper(key, unifiedSwapStorage, unifiedChainEvents, chainInterface, swapContract, pricing, this._tokens[chainId], chainData.swapDataConstructor, btcRelay, synchronizer, this._bitcoinRpc, {
118
- getRequestTimeout: this.options.getRequestTimeout,
119
- postRequestTimeout: this.options.postRequestTimeout,
120
- saveUninitializedSwaps: this.options.saveUninitializedSwaps,
121
- bitcoinNetwork: this._btcNetwork
122
- });
123
- wrappers[SwapType_1.SwapType.TRUSTED_FROM_BTCLN] = new LnForGasWrapper_1.LnForGasWrapper(key, unifiedSwapStorage, unifiedChainEvents, chainInterface, pricing, this._tokens[chainId], {
124
- getRequestTimeout: this.options.getRequestTimeout,
125
- postRequestTimeout: this.options.postRequestTimeout,
126
- saveUninitializedSwaps: this.options.saveUninitializedSwaps,
127
- });
128
- wrappers[SwapType_1.SwapType.TRUSTED_FROM_BTC] = new OnchainForGasWrapper_1.OnchainForGasWrapper(key, unifiedSwapStorage, unifiedChainEvents, chainInterface, pricing, this._tokens[chainId], bitcoinRpc, {
129
- getRequestTimeout: this.options.getRequestTimeout,
130
- postRequestTimeout: this.options.postRequestTimeout,
131
- saveUninitializedSwaps: this.options.saveUninitializedSwaps,
132
- bitcoinNetwork: this._btcNetwork
133
- });
134
- if (spvVaultContract != null) {
135
- wrappers[SwapType_1.SwapType.SPV_VAULT_FROM_BTC] = new SpvFromBTCWrapper_1.SpvFromBTCWrapper(key, unifiedSwapStorage, unifiedChainEvents, chainInterface, spvVaultContract, pricing, this._tokens[chainId], spvVaultWithdrawalDataConstructor, btcRelay, synchronizer, bitcoinRpc, {
136
- getRequestTimeout: this.options.getRequestTimeout,
137
- postRequestTimeout: this.options.postRequestTimeout,
138
- saveUninitializedSwaps: this.options.saveUninitializedSwaps,
139
- bitcoinNetwork: this._btcNetwork
140
- });
141
- }
142
- if (swapContract.supportsInitWithoutClaimer) {
143
- wrappers[SwapType_1.SwapType.FROM_BTCLN_AUTO] = new FromBTCLNAutoWrapper_1.FromBTCLNAutoWrapper(key, unifiedSwapStorage, unifiedChainEvents, chainInterface, swapContract, pricing, this._tokens[chainId], chainData.swapDataConstructor, lightningApi, this.messenger, {
144
- getRequestTimeout: this.options.getRequestTimeout,
145
- postRequestTimeout: this.options.postRequestTimeout,
146
- saveUninitializedSwaps: this.options.saveUninitializedSwaps,
147
- unsafeSkipLnNodeCheck: this.bitcoinNetwork === base_1.BitcoinNetwork.TESTNET4 || this.bitcoinNetwork === base_1.BitcoinNetwork.REGTEST
148
- });
149
- }
150
- Object.keys(wrappers).forEach(key => wrappers[key].events.on("swapState", this.swapStateListener));
151
- const reviver = (val) => {
152
- const wrapper = wrappers[val.type];
153
- if (wrapper == null)
154
- return null;
155
- return new wrapper._swapDeserializer(wrapper, val);
156
- };
157
- return {
158
- chainEvents,
159
- spvVaultContract,
160
- swapContract,
161
- chainInterface,
162
- btcRelay,
163
- synchronizer,
164
- wrappers,
165
- unifiedChainEvents,
166
- unifiedSwapStorage,
167
- reviver
168
- };
169
- });
170
- const contracts = (0, Utils_1.objectMap)(chainsData, (data) => data.swapContract);
171
- if (options.intermediaryUrl != null) {
172
- this.intermediaryDiscovery = new IntermediaryDiscovery_1.IntermediaryDiscovery(contracts, options.registryUrl, Array.isArray(options.intermediaryUrl) ? options.intermediaryUrl : [options.intermediaryUrl], options.getRequestTimeout);
173
- }
174
- else {
175
- this.intermediaryDiscovery = new IntermediaryDiscovery_1.IntermediaryDiscovery(contracts, options.registryUrl, undefined, options.getRequestTimeout);
176
- }
177
- this.intermediaryDiscovery.on("removed", (intermediaries) => {
178
- this.emit("lpsRemoved", intermediaries);
179
- });
180
- this.intermediaryDiscovery.on("added", (intermediaries) => {
181
- this.emit("lpsAdded", intermediaries);
182
- });
183
- }
184
- async _init() {
185
- this.logger.debug("init(): Initializing swapper...");
186
- const abortController = new AbortController();
187
- const promises = [];
188
- let automaticClockDriftCorrectionPromise = undefined;
189
- if (this.options.automaticClockDriftCorrection) {
190
- promises.push(automaticClockDriftCorrectionPromise = (0, RetryUtils_1.tryWithRetries)(AutomaticClockDriftCorrection_1.correctClock, undefined, undefined, abortController.signal).catch((err) => {
191
- abortController.abort(err);
192
- }));
193
- }
194
- this.logger.debug("init(): Initializing intermediary discovery");
195
- if (!this.options.dontFetchLPs)
196
- promises.push(this.intermediaryDiscovery.init(abortController.signal).catch(err => {
197
- if (abortController.signal.aborted)
198
- return;
199
- this.logger.error("init(): Failed to fetch intermediaries/LPs: ", err);
200
- }));
201
- if (this.options.defaultTrustedIntermediaryUrl != null) {
202
- promises.push(this.intermediaryDiscovery.getIntermediary(this.options.defaultTrustedIntermediaryUrl, abortController.signal)
203
- .then(val => {
204
- if (val == null)
205
- throw new Error("Cannot get trusted LP");
206
- this.defaultTrustedIntermediary = val;
207
- })
208
- .catch(err => {
209
- if (abortController.signal.aborted)
210
- return;
211
- this.logger.error("init(): Failed to contact trusted LP url: ", err);
212
- }));
213
- }
214
- if (automaticClockDriftCorrectionPromise != null) {
215
- //We should await the promises here before checking the swaps
216
- await automaticClockDriftCorrectionPromise;
217
- }
218
- const chainPromises = [];
219
- for (let chainIdentifier in this._chains) {
220
- chainPromises.push((async () => {
221
- const { chainInterface, swapContract, unifiedChainEvents, unifiedSwapStorage, wrappers, reviver } = this._chains[chainIdentifier];
222
- const _chainInterface = chainInterface;
223
- if (_chainInterface.verifyNetwork != null) {
224
- await _chainInterface.verifyNetwork(this.bitcoinNetwork);
225
- }
226
- await swapContract.start();
227
- this.logger.debug("init(): Intialized swap contract: " + chainIdentifier);
228
- await unifiedSwapStorage.init();
229
- if (unifiedSwapStorage.storage instanceof IndexedDBUnifiedStorage_1.IndexedDBUnifiedStorage) {
230
- //Try to migrate the data here
231
- const storagePrefix = chainIdentifier === "SOLANA" ?
232
- "SOLv4-" + this.bitcoinNetwork + "-Swaps-" :
233
- "atomiqsdk-" + this.bitcoinNetwork + chainIdentifier + "-Swaps-";
234
- await unifiedSwapStorage.storage.tryMigrate([
235
- [storagePrefix + "FromBTC", SwapType_1.SwapType.FROM_BTC],
236
- [storagePrefix + "FromBTCLN", SwapType_1.SwapType.FROM_BTCLN],
237
- [storagePrefix + "ToBTC", SwapType_1.SwapType.TO_BTC],
238
- [storagePrefix + "ToBTCLN", SwapType_1.SwapType.TO_BTCLN]
239
- ], (obj) => {
240
- const swap = reviver(obj);
241
- if (swap._randomNonce == null) {
242
- const oldIdentifierHash = swap.getId();
243
- swap._randomNonce = (0, Utils_1.randomBytes)(16).toString("hex");
244
- const newIdentifierHash = swap.getId();
245
- this.logger.info("init(): Found older swap version without randomNonce, replacing, old hash: " + oldIdentifierHash +
246
- " new hash: " + newIdentifierHash);
247
- }
248
- return swap;
249
- });
250
- }
251
- if (!this.options.noEvents)
252
- await unifiedChainEvents.start();
253
- this.logger.debug("init(): Intialized events: " + chainIdentifier);
254
- for (let key in wrappers) {
255
- // this.logger.debug("init(): Initializing "+SwapType[key]+": "+chainIdentifier);
256
- await wrappers[key].init(this.options.noTimers, this.options.dontCheckPastSwaps);
257
- }
258
- })());
259
- }
260
- await Promise.all(chainPromises);
261
- await Promise.all(promises);
262
- this.logger.debug("init(): Initializing messenger");
263
- await this.messenger.init();
264
- }
265
- /**
266
- * Initializes the swap storage and loads existing swaps, needs to be called before any other action
267
- */
268
- async init() {
269
- if (this.initialized)
270
- return;
271
- if (this.initPromise != null) {
272
- await this.initPromise;
273
- return;
274
- }
275
- try {
276
- const promise = this._init();
277
- this.initPromise = promise;
278
- await promise;
279
- delete this.initPromise;
280
- this.initialized = true;
281
- }
282
- catch (e) {
283
- delete this.initPromise;
284
- throw e;
285
- }
286
- }
287
- /**
288
- * Stops listening for onchain events and closes this Swapper instance
289
- */
290
- async stop() {
291
- if (this.initPromise)
292
- await this.initPromise;
293
- for (let chainIdentifier in this._chains) {
294
- const { wrappers, unifiedChainEvents } = this._chains[chainIdentifier];
295
- for (let key in wrappers) {
296
- const wrapper = wrappers[key];
297
- wrapper.events.removeListener("swapState", this.swapStateListener);
298
- await wrapper.stop();
299
- }
300
- await unifiedChainEvents.stop();
301
- await this.messenger.stop();
302
- }
303
- this.initialized = false;
304
- }
305
- /**
306
- * Creates swap & handles intermediary, quote selection
307
- *
308
- * @param chainIdentifier
309
- * @param create Callback to create the
310
- * @param amountData Amount data as passed to the function
311
- * @param swapType Swap type of the execution
312
- * @param maxWaitTimeMS Maximum waiting time after the first intermediary returns the quote
313
- * @private
314
- * @throws {Error} when no intermediary was found
315
- * @throws {Error} if the chain with the provided identifier cannot be found
316
- */
317
- async createSwap(chainIdentifier, create, amountData, swapType, maxWaitTimeMS = 2000) {
318
- if (!this.initialized)
319
- throw new Error("Swapper not initialized, init first with swapper.init()!");
320
- if (this._chains[chainIdentifier] == null)
321
- throw new Error("Invalid chain identifier! Unknown chain: " + chainIdentifier);
322
- let candidates;
323
- const inBtc = swapType === SwapType_1.SwapType.TO_BTCLN || swapType === SwapType_1.SwapType.TO_BTC ? !amountData.exactIn : amountData.exactIn;
324
- if (!inBtc) {
325
- //Get candidates not based on the amount
326
- candidates = this.intermediaryDiscovery.getSwapCandidates(chainIdentifier, swapType, amountData.token);
327
- }
328
- else {
329
- candidates = this.intermediaryDiscovery.getSwapCandidates(chainIdentifier, swapType, amountData.token, amountData.amount);
330
- }
331
- let swapLimitsChanged = false;
332
- if (candidates.length === 0) {
333
- this.logger.warn("createSwap(): No valid intermediary found to execute the swap with, reloading intermediary database...");
334
- await this.intermediaryDiscovery.reloadIntermediaries();
335
- swapLimitsChanged = true;
336
- if (!inBtc) {
337
- //Get candidates not based on the amount
338
- candidates = this.intermediaryDiscovery.getSwapCandidates(chainIdentifier, swapType, amountData.token);
339
- }
340
- else {
341
- candidates = this.intermediaryDiscovery.getSwapCandidates(chainIdentifier, swapType, amountData.token, amountData.amount);
342
- if (candidates.length === 0) {
343
- const min = this.intermediaryDiscovery.getSwapMinimum(chainIdentifier, swapType, amountData.token);
344
- const max = this.intermediaryDiscovery.getSwapMaximum(chainIdentifier, swapType, amountData.token);
345
- if (min != null && max != null) {
346
- if (amountData.amount < BigInt(min))
347
- throw new RequestError_1.OutOfBoundsError("Swap amount too low! Try swapping a higher amount.", 200, BigInt(min), BigInt(max));
348
- if (amountData.amount > BigInt(max))
349
- throw new RequestError_1.OutOfBoundsError("Swap amount too high! Try swapping a lower amount.", 200, BigInt(min), BigInt(max));
350
- }
351
- }
352
- }
353
- if (candidates.length === 0)
354
- throw new Error("No intermediary found for the requested pair and amount! You can try swapping different pair or higher/lower amount.");
355
- }
356
- const abortController = new AbortController();
357
- this.logger.debug("createSwap() Swap candidates: ", candidates.map(lp => lp.url).join());
358
- const quotePromises = await create(candidates, abortController.signal, this._chains[chainIdentifier]);
359
- const promiseAll = new Promise((resolve, reject) => {
360
- let min;
361
- let max;
362
- let error;
363
- let numResolved = 0;
364
- let quotes = [];
365
- let timeout;
366
- quotePromises.forEach(data => {
367
- data.quote.then(quote => {
368
- if (numResolved === 0) {
369
- timeout = setTimeout(() => {
370
- abortController.abort(new Error("Timed out waiting for quote!"));
371
- resolve(quotes);
372
- }, maxWaitTimeMS);
373
- }
374
- numResolved++;
375
- quotes.push({
376
- quote,
377
- intermediary: data.intermediary
378
- });
379
- if (numResolved === quotePromises.length) {
380
- clearTimeout(timeout);
381
- resolve(quotes);
382
- return;
383
- }
384
- }).catch(e => {
385
- numResolved++;
386
- if (e instanceof IntermediaryError_1.IntermediaryError) {
387
- //Blacklist that node
388
- this.intermediaryDiscovery.removeIntermediary(data.intermediary);
389
- swapLimitsChanged = true;
390
- }
391
- else if (e instanceof RequestError_1.OutOfBoundsError) {
392
- if (min == null || max == null) {
393
- min = e.min;
394
- max = e.max;
395
- }
396
- else {
397
- min = (0, Utils_1.bigIntMin)(min, e.min);
398
- max = (0, Utils_1.bigIntMax)(max, e.max);
399
- }
400
- data.intermediary.swapBounds[swapType] ??= {};
401
- data.intermediary.swapBounds[swapType][chainIdentifier] ??= {};
402
- const tokenBoundsData = (data.intermediary.swapBounds[swapType][chainIdentifier][amountData.token] ??= { input: {}, output: {} });
403
- if (amountData.exactIn) {
404
- tokenBoundsData.input = { min: e.min, max: e.max };
405
- }
406
- else {
407
- tokenBoundsData.output = { min: e.min, max: e.max };
408
- }
409
- swapLimitsChanged = true;
410
- }
411
- this.logger.warn("createSwap(): Intermediary " + data.intermediary.url + " error: ", e);
412
- error = e;
413
- if (numResolved === quotePromises.length) {
414
- if (timeout != null)
415
- clearTimeout(timeout);
416
- if (quotes.length > 0) {
417
- resolve(quotes);
418
- return;
419
- }
420
- if (min != null && max != null) {
421
- let msg = "Swap amount too high or too low! Try swapping a different amount.";
422
- if (min > amountData.amount)
423
- msg = "Swap amount too low! Try swapping a higher amount.";
424
- if (max < amountData.amount)
425
- msg = "Swap amount too high! Try swapping a lower amount.";
426
- reject(new RequestError_1.OutOfBoundsError(msg, 400, min, max));
427
- return;
428
- }
429
- reject(error);
430
- }
431
- });
432
- });
433
- });
434
- try {
435
- const quotes = await promiseAll;
436
- //TODO: Intermediary's reputation is not taken into account!
437
- quotes.sort((a, b) => {
438
- if (amountData.exactIn) {
439
- //Compare outputs
440
- return (0, Utils_1.bigIntCompare)(b.quote.getOutput().rawAmount, a.quote.getOutput().rawAmount);
441
- }
442
- else {
443
- //Compare inputs
444
- return (0, Utils_1.bigIntCompare)(a.quote.getInput().rawAmount, b.quote.getInput().rawAmount);
445
- }
446
- });
447
- this.logger.debug("createSwap(): Sorted quotes, best price to worst: ", quotes);
448
- if (swapLimitsChanged)
449
- this.emit("swapLimitsChanged");
450
- const quote = quotes[0].quote;
451
- await quote._save();
452
- return quote;
453
- }
454
- catch (e) {
455
- if (swapLimitsChanged)
456
- this.emit("swapLimitsChanged");
457
- throw e;
458
- }
459
- }
460
- /**
461
- * Creates Smart chain -> Bitcoin ({@link SwapType.TO_BTC}) swap
462
- *
463
- * @param chainIdentifier Chain identifier string of the source smart chain
464
- * @param signer Signer's address on the source chain
465
- * @param tokenAddress Token address to pay with
466
- * @param address Recipient's bitcoin address
467
- * @param amount Amount to send in token based units (if `exactIn=true`) or receive in satoshis (if `exactIn=false`)
468
- * @param exactIn Whether to use exact in instead of exact out
469
- * @param additionalParams Additional parameters sent to the LP when creating the swap
470
- * @param options Additional options for the swap
471
- */
472
- createToBTCSwap(chainIdentifier, signer, tokenAddress, address, amount, exactIn = false, additionalParams = this.options.defaultAdditionalParameters, options) {
473
- if (this._chains[chainIdentifier] == null)
474
- throw new Error("Invalid chain identifier! Unknown chain: " + chainIdentifier);
475
- if (address.startsWith("bitcoin:")) {
476
- address = address.substring(8).split("?")[0];
477
- }
478
- if (!this.Utils.isValidBitcoinAddress(address))
479
- throw new Error("Invalid bitcoin address");
480
- if (!this._chains[chainIdentifier].chainInterface.isValidAddress(signer, true))
481
- throw new Error("Invalid " + chainIdentifier + " address");
482
- signer = this._chains[chainIdentifier].chainInterface.normalizeAddress(signer);
483
- const amountData = {
484
- amount,
485
- token: tokenAddress,
486
- exactIn
487
- };
488
- return this.createSwap(chainIdentifier, (candidates, abortSignal, chain) => Promise.resolve(chain.wrappers[SwapType_1.SwapType.TO_BTC].create(signer, address, amountData, candidates, options, additionalParams, abortSignal)), amountData, SwapType_1.SwapType.TO_BTC);
489
- }
490
- /**
491
- * Creates Smart chain -> Bitcoin Lightning ({@link SwapType.TO_BTCLN}) swap
492
- *
493
- * @param chainIdentifier Chain identifier string of the source smart chain
494
- * @param signer Signer's address on the source chain
495
- * @param tokenAddress Token address to pay with
496
- * @param paymentRequest BOLT11 lightning network invoice to be paid (needs to have a fixed amount), and the swap
497
- * amount is taken from this fixed amount, hence only exact output swaps are supported
498
- * @param additionalParams Additional parameters sent to the LP when creating the swap
499
- * @param options Additional options for the swap
500
- */
501
- async createToBTCLNSwap(chainIdentifier, signer, tokenAddress, paymentRequest, additionalParams = this.options.defaultAdditionalParameters, options) {
502
- if (this._chains[chainIdentifier] == null)
503
- throw new Error("Invalid chain identifier! Unknown chain: " + chainIdentifier);
504
- if (paymentRequest.startsWith("lightning:"))
505
- paymentRequest = paymentRequest.substring(10);
506
- if (!this.Utils.isValidLightningInvoice(paymentRequest))
507
- throw new Error("Invalid lightning network invoice");
508
- if (!this._chains[chainIdentifier].chainInterface.isValidAddress(signer, true))
509
- throw new Error("Invalid " + chainIdentifier + " address");
510
- signer = this._chains[chainIdentifier].chainInterface.normalizeAddress(signer);
511
- const parsedPR = (0, bolt11_1.decode)(paymentRequest);
512
- if (parsedPR.millisatoshis == null)
513
- throw new Error("Invalid lightning network invoice, no msat value field!");
514
- const amountData = {
515
- amount: (BigInt(parsedPR.millisatoshis) + 999n) / 1000n,
516
- token: tokenAddress,
517
- exactIn: false
518
- };
519
- return this.createSwap(chainIdentifier, (candidates, abortSignal, chain) => chain.wrappers[SwapType_1.SwapType.TO_BTCLN].create(signer, paymentRequest, amountData, candidates, options, additionalParams, abortSignal), amountData, SwapType_1.SwapType.TO_BTCLN);
520
- }
521
- /**
522
- * Creates Smart chain -> Bitcoin Lightning ({@link SwapType.TO_BTCLN}) swap via LNURL-pay link
523
- *
524
- * @param chainIdentifier Chain identifier string of the source smart chain
525
- * @param signer Signer's address on the source chain
526
- * @param tokenAddress Token address to pay with
527
- * @param lnurlPay LNURL-pay link to use for the payment
528
- * @param amount Amount to send in token based units (if `exactIn=true`) or receive in satoshis (if `exactIn=false`)
529
- * @param exactIn Whether to do an exact in swap instead of exact out
530
- * @param additionalParams Additional parameters sent to the LP when creating the swap
531
- * @param options Additional options for the swap
532
- */
533
- async createToBTCLNSwapViaLNURL(chainIdentifier, signer, tokenAddress, lnurlPay, amount, exactIn = false, additionalParams = this.options.defaultAdditionalParameters, options) {
534
- if (this._chains[chainIdentifier] == null)
535
- throw new Error("Invalid chain identifier! Unknown chain: " + chainIdentifier);
536
- if (typeof (lnurlPay) === "string" && !this.Utils.isValidLNURL(lnurlPay))
537
- throw new Error("Invalid LNURL-pay link");
538
- if (!this._chains[chainIdentifier].chainInterface.isValidAddress(signer, true))
539
- throw new Error("Invalid " + chainIdentifier + " address");
540
- signer = this._chains[chainIdentifier].chainInterface.normalizeAddress(signer);
541
- const amountData = {
542
- amount,
543
- token: tokenAddress,
544
- exactIn
545
- };
546
- return this.createSwap(chainIdentifier, (candidates, abortSignal, chain) => chain.wrappers[SwapType_1.SwapType.TO_BTCLN].createViaLNURL(signer, typeof (lnurlPay) === "string" ? (lnurlPay.startsWith("lightning:") ? lnurlPay.substring(10) : lnurlPay) : lnurlPay.params, amountData, candidates, options, additionalParams, abortSignal), amountData, SwapType_1.SwapType.TO_BTCLN);
547
- }
548
- /**
549
- * Creates Smart chain -> Bitcoin Lightning ({@link SwapType.TO_BTCLN}) swap via {@link LightningInvoiceCreateService}
550
- *
551
- * @param chainIdentifier Chain identifier string of the source smart chain
552
- * @param signer Signer's address on the source chain
553
- * @param tokenAddress Token address to pay with
554
- * @param service Invoice create service object which facilitates the creation of fixed amount LN invoices
555
- * @param amount Amount to send in token based units (if `exactIn=true`) or receive in satoshis (if `exactIn=false`)
556
- * @param exactIn Whether to do an exact in swap instead of exact out
557
- * @param additionalParams Additional parameters sent to the LP when creating the swap
558
- * @param options Additional options for the swap
559
- */
560
- async createToBTCLNSwapViaInvoiceCreateService(chainIdentifier, signer, tokenAddress, service, amount, exactIn = false, additionalParams = this.options.defaultAdditionalParameters, options) {
561
- if (this._chains[chainIdentifier] == null)
562
- throw new Error("Invalid chain identifier! Unknown chain: " + chainIdentifier);
563
- if (!this._chains[chainIdentifier].chainInterface.isValidAddress(signer, true))
564
- throw new Error("Invalid " + chainIdentifier + " address");
565
- signer = this._chains[chainIdentifier].chainInterface.normalizeAddress(signer);
566
- const amountData = {
567
- amount,
568
- token: tokenAddress,
569
- exactIn
570
- };
571
- return this.createSwap(chainIdentifier, (candidates, abortSignal, chain) => chain.wrappers[SwapType_1.SwapType.TO_BTCLN].createViaInvoiceCreateService(signer, Promise.resolve(service), amountData, candidates, options, additionalParams, abortSignal), amountData, SwapType_1.SwapType.TO_BTCLN);
572
- }
573
- /**
574
- * Creates Bitcoin -> Smart chain ({@link SwapType.SPV_VAULT_FROM_BTC}) swap
575
- *
576
- * @param chainIdentifier Chain identifier string of the destination smart chain
577
- * @param recipient Recipient address on the destination chain
578
- * @param tokenAddress Token address to receive
579
- * @param amount Amount to send in satoshis (if `exactOut=false`) or receive in token based units (if `exactOut=true`)
580
- * @param exactOut Whether to use a exact out instead of exact in
581
- * @param additionalParams Additional parameters sent to the LP when creating the swap
582
- * @param options Additional options for the swap
583
- */
584
- async createFromBTCSwapNew(chainIdentifier, recipient, tokenAddress, amount, exactOut = false, additionalParams = this.options.defaultAdditionalParameters, options) {
585
- if (this._chains[chainIdentifier] == null)
586
- throw new Error("Invalid chain identifier! Unknown chain: " + chainIdentifier);
587
- if (!this._chains[chainIdentifier].chainInterface.isValidAddress(recipient, true))
588
- throw new Error("Invalid " + chainIdentifier + " address");
589
- recipient = this._chains[chainIdentifier].chainInterface.normalizeAddress(recipient);
590
- const amountData = {
591
- amount,
592
- token: tokenAddress,
593
- exactIn: !exactOut
594
- };
595
- return this.createSwap(chainIdentifier, (candidates, abortSignal, chain) => Promise.resolve(chain.wrappers[SwapType_1.SwapType.SPV_VAULT_FROM_BTC].create(recipient, amountData, candidates, options, additionalParams, abortSignal)), amountData, SwapType_1.SwapType.SPV_VAULT_FROM_BTC);
596
- }
597
- /**
598
- * Creates LEGACY Bitcoin -> Smart chain ({@link SwapType.FROM_BTC}) swap
599
- *
600
- * @param chainIdentifier Chain identifier string of the destination smart chain
601
- * @param recipient Recipient address on the destination chain
602
- * @param tokenAddress Token address to receive
603
- * @param amount Amount to send in satoshis (if `exactOut=false`) or receive in token based units (if `exactOut=true`)
604
- * @param exactOut Whether to use a exact out instead of exact in
605
- * @param additionalParams Additional parameters sent to the LP when creating the swap
606
- * @param options Additional options for the swap
607
- */
608
- async createFromBTCSwap(chainIdentifier, recipient, tokenAddress, amount, exactOut = false, additionalParams = this.options.defaultAdditionalParameters, options) {
609
- if (this._chains[chainIdentifier] == null)
610
- throw new Error("Invalid chain identifier! Unknown chain: " + chainIdentifier);
611
- if (!this._chains[chainIdentifier].chainInterface.isValidAddress(recipient, true))
612
- throw new Error("Invalid " + chainIdentifier + " address");
613
- recipient = this._chains[chainIdentifier].chainInterface.normalizeAddress(recipient);
614
- const amountData = {
615
- amount,
616
- token: tokenAddress,
617
- exactIn: !exactOut
618
- };
619
- return this.createSwap(chainIdentifier, (candidates, abortSignal, chain) => Promise.resolve(chain.wrappers[SwapType_1.SwapType.FROM_BTC].create(recipient, amountData, candidates, options, additionalParams, abortSignal)), amountData, SwapType_1.SwapType.FROM_BTC);
620
- }
621
- /**
622
- * Creates LEGACY Bitcoin Lightning -> Smart chain ({@link SwapType.FROM_BTCLN}) swap
623
- *
624
- * @param chainIdentifier Chain identifier string of the destination smart chain
625
- * @param recipient Recipient address on the destination chain
626
- * @param tokenAddress Token address to receive
627
- * @param amount Amount to send in satoshis (if `exactOut=false`) or receive in token based units (if `exactOut=true`)
628
- * @param exactOut Whether to use a exact out instead of exact in
629
- * @param additionalParams Additional parameters sent to the LP when creating the swap
630
- * @param options Additional options for the swap
631
- */
632
- async createFromBTCLNSwap(chainIdentifier, recipient, tokenAddress, amount, exactOut = false, additionalParams = this.options.defaultAdditionalParameters, options) {
633
- if (this._chains[chainIdentifier] == null)
634
- throw new Error("Invalid chain identifier! Unknown chain: " + chainIdentifier);
635
- if (!this._chains[chainIdentifier].chainInterface.isValidAddress(recipient, true))
636
- throw new Error("Invalid " + chainIdentifier + " address");
637
- recipient = this._chains[chainIdentifier].chainInterface.normalizeAddress(recipient);
638
- const amountData = {
639
- amount,
640
- token: tokenAddress,
641
- exactIn: !exactOut
642
- };
643
- return this.createSwap(chainIdentifier, (candidates, abortSignal, chain) => Promise.resolve(chain.wrappers[SwapType_1.SwapType.FROM_BTCLN].create(recipient, amountData, candidates, options, additionalParams, abortSignal)), amountData, SwapType_1.SwapType.FROM_BTCLN);
644
- }
645
- /**
646
- * Creates LEGACY Bitcoin Lightning -> Smart chain ({@link SwapType.FROM_BTCLN}) swap, withdrawing from
647
- * an LNURL-withdraw link
648
- *
649
- * @param chainIdentifier Chain identifier string of the destination smart chain
650
- * @param recipient Recipient address on the destination chain
651
- * @param tokenAddress Token address to receive
652
- * @param lnurl LNURL-withdraw link to pull the funds from
653
- * @param amount Amount to send in satoshis (if `exactOut=false`) or receive in token based units (if `exactOut=true`)
654
- * @param exactOut Whether to use a exact out instead of exact in
655
- * @param additionalParams Additional parameters sent to the LP when creating the swap
656
- * @param options Additional options for the swap
657
- */
658
- async createFromBTCLNSwapViaLNURL(chainIdentifier, recipient, tokenAddress, lnurl, amount, exactOut = false, additionalParams = this.options.defaultAdditionalParameters, options) {
659
- if (this._chains[chainIdentifier] == null)
660
- throw new Error("Invalid chain identifier! Unknown chain: " + chainIdentifier);
661
- if (typeof (lnurl) === "string" && !this.Utils.isValidLNURL(lnurl))
662
- throw new Error("Invalid LNURL-withdraw link");
663
- if (!this._chains[chainIdentifier].chainInterface.isValidAddress(recipient, true))
664
- throw new Error("Invalid " + chainIdentifier + " address");
665
- recipient = this._chains[chainIdentifier].chainInterface.normalizeAddress(recipient);
666
- const amountData = {
667
- amount,
668
- token: tokenAddress,
669
- exactIn: !exactOut
670
- };
671
- return this.createSwap(chainIdentifier, (candidates, abortSignal, chain) => chain.wrappers[SwapType_1.SwapType.FROM_BTCLN].createViaLNURL(recipient, typeof (lnurl) === "string" ? (lnurl.startsWith("lightning:") ? lnurl.substring(10) : lnurl) : lnurl.params, amountData, candidates, options, additionalParams, abortSignal), amountData, SwapType_1.SwapType.FROM_BTCLN);
672
- }
673
- /**
674
- * Creates Bitcoin Lightning -> Smart chain ({@link SwapType.FROM_BTCLN_AUTO}) swap
675
- *
676
- * @param chainIdentifier Chain identifier string of the destination smart chain
677
- * @param recipient Recipient address on the destination chain
678
- * @param tokenAddress Token address to receive
679
- * @param amount Amount to send in satoshis (if `exactOut=false`) or receive in token based units (if `exactOut=true`)
680
- * @param exactOut Whether to use a exact out instead of exact in
681
- * @param additionalParams Additional parameters sent to the LP when creating the swap
682
- * @param options Additional options for the swap
683
- */
684
- async createFromBTCLNSwapNew(chainIdentifier, recipient, tokenAddress, amount, exactOut = false, additionalParams = this.options.defaultAdditionalParameters, options) {
685
- if (this._chains[chainIdentifier] == null)
686
- throw new Error("Invalid chain identifier! Unknown chain: " + chainIdentifier);
687
- if (!this._chains[chainIdentifier].chainInterface.isValidAddress(recipient, true))
688
- throw new Error("Invalid " + chainIdentifier + " address");
689
- recipient = this._chains[chainIdentifier].chainInterface.normalizeAddress(recipient);
690
- const amountData = {
691
- amount,
692
- token: tokenAddress,
693
- exactIn: !exactOut
694
- };
695
- return this.createSwap(chainIdentifier, (candidates, abortSignal, chain) => Promise.resolve(chain.wrappers[SwapType_1.SwapType.FROM_BTCLN_AUTO].create(recipient, amountData, candidates, options, additionalParams, abortSignal)), amountData, SwapType_1.SwapType.FROM_BTCLN_AUTO);
696
- }
697
- /**
698
- * Creates Bitcoin Lightning -> Smart chain ({@link SwapType.FROM_BTCLN_AUTO}) swap, withdrawing from
699
- * an LNURL-withdraw link
700
- *
701
- * @param chainIdentifier Chain identifier string of the destination smart chain
702
- * @param recipient Recipient address on the destination chain
703
- * @param tokenAddress Token address to receive
704
- * @param lnurl LNURL-withdraw link to pull the funds from
705
- * @param amount Amount to send in satoshis (if `exactOut=false`) or receive in token based units (if `exactOut=true`)
706
- * @param exactOut Whether to use a exact out instead of exact in
707
- * @param additionalParams Additional parameters sent to the LP when creating the swap
708
- * @param options Additional options for the swap
709
- */
710
- async createFromBTCLNSwapNewViaLNURL(chainIdentifier, recipient, tokenAddress, lnurl, amount, exactOut = false, additionalParams = this.options.defaultAdditionalParameters, options) {
711
- if (this._chains[chainIdentifier] == null)
712
- throw new Error("Invalid chain identifier! Unknown chain: " + chainIdentifier);
713
- if (typeof (lnurl) === "string" && !this.Utils.isValidLNURL(lnurl))
714
- throw new Error("Invalid LNURL-withdraw link");
715
- if (!this._chains[chainIdentifier].chainInterface.isValidAddress(recipient, true))
716
- throw new Error("Invalid " + chainIdentifier + " address");
717
- recipient = this._chains[chainIdentifier].chainInterface.normalizeAddress(recipient);
718
- const amountData = {
719
- amount,
720
- token: tokenAddress,
721
- exactIn: !exactOut
722
- };
723
- return this.createSwap(chainIdentifier, (candidates, abortSignal, chain) => chain.wrappers[SwapType_1.SwapType.FROM_BTCLN_AUTO].createViaLNURL(recipient, typeof (lnurl) === "string" ? (lnurl.startsWith("lightning:") ? lnurl.substring(10) : lnurl) : lnurl.params, amountData, candidates, options, additionalParams, abortSignal), amountData, SwapType_1.SwapType.FROM_BTCLN_AUTO);
724
- }
725
- /**
726
- * Creates a trusted Bitcoin Lightning -> Smart chain ({@link SwapType.TRUSTED_FROM_BTCLN}) gas swap
727
- *
728
- * @param chainIdentifier Chain identifier string of the destination smart chain
729
- * @param recipient Recipient address on the destination chain
730
- * @param amount Amount of native token to receive, in base units
731
- * @param trustedIntermediaryOrUrl URL or Intermediary object of the trusted intermediary to use, otherwise uses default
732
- * @throws {Error} If no trusted intermediary specified
733
- */
734
- async createTrustedLNForGasSwap(chainIdentifier, recipient, amount, trustedIntermediaryOrUrl) {
735
- if (this._chains[chainIdentifier] == null)
736
- throw new Error("Invalid chain identifier! Unknown chain: " + chainIdentifier);
737
- if (!this._chains[chainIdentifier].chainInterface.isValidAddress(recipient, true))
738
- throw new Error("Invalid " + chainIdentifier + " address");
739
- recipient = this._chains[chainIdentifier].chainInterface.normalizeAddress(recipient);
740
- const useUrl = trustedIntermediaryOrUrl ?? this.defaultTrustedIntermediary ?? this.options.defaultTrustedIntermediaryUrl;
741
- if (useUrl == null)
742
- throw new Error("No trusted intermediary specified!");
743
- const swap = await this._chains[chainIdentifier].wrappers[SwapType_1.SwapType.TRUSTED_FROM_BTCLN].create(recipient, amount, useUrl);
744
- await swap._save();
745
- return swap;
746
- }
747
- /**
748
- * Creates a trusted Bitcoin -> Smart chain ({@link SwapType.TRUSTED_FROM_BTC}) gas swap
749
- *
750
- * @param chainIdentifier Chain identifier string of the destination smart chain
751
- * @param recipient Recipient address on the destination chain
752
- * @param amount Amount of native token to receive, in base units
753
- * @param refundAddress Bitcoin refund address, in case the swap fails the funds are refunded here
754
- * @param trustedIntermediaryOrUrl URL or Intermediary object of the trusted intermediary to use, otherwise uses default
755
- * @throws {Error} If no trusted intermediary specified
756
- */
757
- async createTrustedOnchainForGasSwap(chainIdentifier, recipient, amount, refundAddress, trustedIntermediaryOrUrl) {
758
- if (this._chains[chainIdentifier] == null)
759
- throw new Error("Invalid chain identifier! Unknown chain: " + chainIdentifier);
760
- if (!this._chains[chainIdentifier].chainInterface.isValidAddress(recipient, true))
761
- throw new Error("Invalid " + chainIdentifier + " address");
762
- recipient = this._chains[chainIdentifier].chainInterface.normalizeAddress(recipient);
763
- const useUrl = trustedIntermediaryOrUrl ?? this.defaultTrustedIntermediary ?? this.options.defaultTrustedIntermediaryUrl;
764
- if (useUrl == null)
765
- throw new Error("No trusted intermediary specified!");
766
- const swap = await this._chains[chainIdentifier].wrappers[SwapType_1.SwapType.TRUSTED_FROM_BTC].create(recipient, amount, useUrl, refundAddress);
767
- await swap._save();
768
- return swap;
769
- }
770
- /**
771
- * Creates a swap from srcToken to dstToken, of a specific token amount, either specifying input amount (exactIn=true)
772
- * or output amount (exactIn=false), NOTE: For regular -> BTC-LN (lightning) swaps the passed amount is ignored and
773
- * invoice's pre-set amount is used instead.
774
- * @deprecated Use {@link swap} instead
775
- *
776
- * @param signer Smartchain (Solana, Starknet, etc.) address of the user
777
- * @param srcToken Source token of the swap, user pays this token
778
- * @param dstToken Destination token of the swap, user receives this token
779
- * @param amount Amount of the swap
780
- * @param exactIn Whether the amount specified is an input amount (exactIn=true) or an output amount (exactIn=false)
781
- * @param addressLnurlLightningInvoice Bitcoin on-chain address, lightning invoice, LNURL-pay to pay or
782
- * LNURL-withdrawal to withdraw money from
783
- */
784
- create(signer, srcToken, dstToken, amount, exactIn, addressLnurlLightningInvoice) {
785
- if (srcToken.chain === "BTC") {
786
- return this.swap(srcToken, dstToken, amount, exactIn, addressLnurlLightningInvoice, signer);
787
- }
788
- else {
789
- return this.swap(srcToken, dstToken, amount, exactIn, signer, addressLnurlLightningInvoice);
790
- }
791
- }
792
- /**
793
- * Creates a swap from srcToken to dstToken, of a specific token amount, either specifying input amount (if `exactIn=true`)
794
- * or output amount (if `exactIn=false`), NOTE: For regular Smart chain -> BTC-LN (lightning) swaps the passed amount is ignored and
795
- * invoice's pre-set amount is used instead, use LNURL-pay links for dynamic amounts
796
- *
797
- * @param _srcToken Source token of the swap, user pays this token
798
- * @param _dstToken Destination token of the swap, user receives this token
799
- * @param _amount Amount of the swap either in base units as {bigint} or in human readable format (with decimals) as {string}
800
- * @param exactIn Whether the amount specified is an input amount (exactIn=true) or an output amount (exactIn=false)
801
- * @param src Source wallet/lnurl-withdraw of the swap
802
- * @param dst Destination smart chain address, bitcoin on-chain address, lightning invoice, LNURL-pay
803
- * @param options Options for the swap
804
- */
805
- swap(_srcToken, _dstToken, _amount, exactIn, src, dst, options) {
806
- const srcToken = typeof (_srcToken) === "string" ? this.getToken(_srcToken) : _srcToken;
807
- const dstToken = typeof (_dstToken) === "string" ? this.getToken(_dstToken) : _dstToken;
808
- const amount = _amount == null ? null : (typeof (_amount) === "bigint" ? _amount : (0, Utils_1.fromDecimal)(_amount, exactIn ? srcToken.decimals : dstToken.decimals));
809
- if ((0, Token_1.isBtcToken)(srcToken)) {
810
- if ((0, Token_1.isSCToken)(dstToken)) {
811
- if (typeof (dst) !== "string")
812
- throw new Error("Destination for BTC/BTC-LN -> smart chain swaps must be a smart chain address!");
813
- if (amount == null)
814
- throw new Error("Amount cannot be null for from btc swaps!");
815
- if (srcToken.lightning) {
816
- //FROM_BTCLN
817
- if (src != null) {
818
- if (typeof (src) !== "string" && !(0, LNURLWithdraw_1.isLNURLWithdraw)(src))
819
- throw new Error("LNURL must be a string or LNURLWithdraw object!");
820
- return this.supportsSwapType(dstToken.chainId, SwapType_1.SwapType.FROM_BTCLN_AUTO) ?
821
- this.createFromBTCLNSwapNewViaLNURL(dstToken.chainId, dst, dstToken.address, src, amount, !exactIn, undefined, options) :
822
- this.createFromBTCLNSwapViaLNURL(dstToken.chainId, dst, dstToken.address, src, amount, !exactIn, undefined, options);
823
- }
824
- else {
825
- return this.supportsSwapType(dstToken.chainId, SwapType_1.SwapType.FROM_BTCLN_AUTO) ?
826
- this.createFromBTCLNSwapNew(dstToken.chainId, dst, dstToken.address, amount, !exactIn, undefined, options) :
827
- this.createFromBTCLNSwap(dstToken.chainId, dst, dstToken.address, amount, !exactIn, undefined, options);
828
- }
829
- }
830
- else {
831
- //FROM_BTC
832
- if (this.supportsSwapType(dstToken.chainId, SwapType_1.SwapType.SPV_VAULT_FROM_BTC)) {
833
- return this.createFromBTCSwapNew(dstToken.chainId, dst, dstToken.address, amount, !exactIn, undefined, options);
834
- }
835
- else {
836
- return this.createFromBTCSwap(dstToken.chainId, dst, dstToken.address, amount, !exactIn, undefined, options);
837
- }
838
- }
839
- }
840
- }
841
- else if ((0, Token_1.isSCToken)(srcToken)) {
842
- if ((0, Token_1.isBtcToken)(dstToken)) {
843
- if (typeof (src) !== "string")
844
- throw new Error("Source address for BTC/BTC-LN -> smart chain swaps must be a smart chain address!");
845
- if (dstToken.lightning) {
846
- //TO_BTCLN
847
- if (typeof (dst) !== "string" && !(0, LNURLPay_1.isLNURLPay)(dst))
848
- throw new Error("Destination LNURL link/lightning invoice must be a string or LNURLPay object!");
849
- if ((0, LNURLPay_1.isLNURLPay)(dst) || this.Utils.isValidLNURL(dst)) {
850
- if (amount == null)
851
- throw new Error("Amount cannot be null for to btcln swaps via LNURL-pay!");
852
- return this.createToBTCLNSwapViaLNURL(srcToken.chainId, src, srcToken.address, dst, amount, !!exactIn, undefined, options);
853
- }
854
- else if ((0, LightningInvoiceCreateService_1.isLightningInvoiceCreateService)(dst)) {
855
- if (amount == null)
856
- throw new Error("Amount cannot be null for to btcln swaps via InvoiceCreateService!");
857
- return this.createToBTCLNSwapViaInvoiceCreateService(srcToken.chainId, src, srcToken.address, dst, amount, !!exactIn, undefined, options);
858
- }
859
- else if (this.Utils.isLightningInvoice(dst)) {
860
- if (!this.Utils.isValidLightningInvoice(dst))
861
- throw new Error("Invalid lightning invoice specified, lightning invoice MUST contain pre-set amount!");
862
- if (exactIn)
863
- throw new Error("Only exact out swaps are possible with lightning invoices, use LNURL links for exact in lightning swaps!");
864
- return this.createToBTCLNSwap(srcToken.chainId, src, srcToken.address, dst, undefined, options);
865
- }
866
- else {
867
- throw new Error("Supplied parameter is not LNURL link nor lightning invoice (bolt11)!");
868
- }
869
- }
870
- else {
871
- //TO_BTC
872
- if (typeof (dst) !== "string")
873
- throw new Error("Destination bitcoin address must be a string!");
874
- if (amount == null)
875
- throw new Error("Amount cannot be null for to btc swaps!");
876
- return this.createToBTCSwap(srcToken.chainId, src, srcToken.address, dst, amount, !!exactIn, undefined, options);
877
- }
878
- }
879
- }
880
- throw new Error("Unsupported swap type");
881
- }
882
- async getAllSwaps(chainId, signer) {
883
- const queryParams = [];
884
- if (signer != null)
885
- queryParams.push({ key: "initiator", value: signer });
886
- if (chainId == null) {
887
- const res = await Promise.all(Object.keys(this._chains).map((chainId) => {
888
- const { unifiedSwapStorage, reviver } = this._chains[chainId];
889
- return unifiedSwapStorage.query([queryParams], reviver);
890
- }));
891
- return res.flat();
892
- }
893
- else {
894
- const { unifiedSwapStorage, reviver } = this._chains[chainId];
895
- return await unifiedSwapStorage.query([queryParams], reviver);
896
- }
897
- }
898
- async getActionableSwaps(chainId, signer) {
899
- if (chainId == null) {
900
- const res = await Promise.all(Object.keys(this._chains).map((chainId) => {
901
- const { unifiedSwapStorage, reviver, wrappers } = this._chains[chainId];
902
- const queryParams = [];
903
- for (let key in wrappers) {
904
- const wrapper = wrappers[key];
905
- const swapTypeQueryParams = [{ key: "type", value: wrapper.TYPE }];
906
- if (signer != null)
907
- swapTypeQueryParams.push({ key: "initiator", value: signer });
908
- swapTypeQueryParams.push({ key: "state", value: wrapper._pendingSwapStates });
909
- queryParams.push(swapTypeQueryParams);
910
- }
911
- return unifiedSwapStorage.query(queryParams, reviver);
912
- }));
913
- return res.flat().filter(swap => swap.requiresAction());
914
- }
915
- else {
916
- const { unifiedSwapStorage, reviver, wrappers } = this._chains[chainId];
917
- const queryParams = [];
918
- for (let key in wrappers) {
919
- const wrapper = wrappers[key];
920
- const swapTypeQueryParams = [{ key: "type", value: wrapper.TYPE }];
921
- if (signer != null)
922
- swapTypeQueryParams.push({ key: "initiator", value: signer });
923
- swapTypeQueryParams.push({ key: "state", value: wrapper._pendingSwapStates });
924
- queryParams.push(swapTypeQueryParams);
925
- }
926
- return (await unifiedSwapStorage.query(queryParams, reviver)).filter(swap => swap.requiresAction());
927
- }
928
- }
929
- async getRefundableSwaps(chainId, signer) {
930
- if (chainId == null) {
931
- const res = await Promise.all(Object.keys(this._chains).map((chainId) => {
932
- const { unifiedSwapStorage, reviver, wrappers } = this._chains[chainId];
933
- const queryParams = [];
934
- for (let wrapper of [wrappers[SwapType_1.SwapType.TO_BTCLN], wrappers[SwapType_1.SwapType.TO_BTC]]) {
935
- const swapTypeQueryParams = [{ key: "type", value: wrapper.TYPE }];
936
- if (signer != null)
937
- swapTypeQueryParams.push({ key: "initiator", value: signer });
938
- swapTypeQueryParams.push({ key: "state", value: wrapper._refundableSwapStates });
939
- queryParams.push(swapTypeQueryParams);
940
- }
941
- return unifiedSwapStorage.query(queryParams, reviver);
942
- }));
943
- return res.flat().filter(swap => swap.isRefundable());
944
- }
945
- else {
946
- const { unifiedSwapStorage, reviver, wrappers } = this._chains[chainId];
947
- const queryParams = [];
948
- for (let wrapper of [wrappers[SwapType_1.SwapType.TO_BTCLN], wrappers[SwapType_1.SwapType.TO_BTC]]) {
949
- const swapTypeQueryParams = [{ key: "type", value: wrapper.TYPE }];
950
- if (signer != null)
951
- swapTypeQueryParams.push({ key: "initiator", value: signer });
952
- swapTypeQueryParams.push({ key: "state", value: wrapper._refundableSwapStates });
953
- queryParams.push(swapTypeQueryParams);
954
- }
955
- const result = await unifiedSwapStorage.query(queryParams, reviver);
956
- return result.filter(swap => swap.isRefundable());
957
- }
958
- }
959
- async getClaimableSwaps(chainId, signer) {
960
- if (chainId == null) {
961
- const res = await Promise.all(Object.keys(this._chains).map((chainId) => {
962
- const { unifiedSwapStorage, reviver, wrappers } = this._chains[chainId];
963
- const queryParams = [];
964
- for (let wrapper of [wrappers[SwapType_1.SwapType.FROM_BTC], wrappers[SwapType_1.SwapType.FROM_BTCLN], wrappers[SwapType_1.SwapType.SPV_VAULT_FROM_BTC], wrappers[SwapType_1.SwapType.FROM_BTCLN_AUTO]]) {
965
- if (wrapper == null)
966
- continue;
967
- const swapTypeQueryParams = [{ key: "type", value: wrapper.TYPE }];
968
- if (signer != null)
969
- swapTypeQueryParams.push({ key: "initiator", value: signer });
970
- swapTypeQueryParams.push({ key: "state", value: wrapper._claimableSwapStates });
971
- queryParams.push(swapTypeQueryParams);
972
- }
973
- return unifiedSwapStorage.query(queryParams, reviver);
974
- }));
975
- return res.flat().filter(swap => swap.isClaimable());
976
- }
977
- else {
978
- const { unifiedSwapStorage, reviver, wrappers } = this._chains[chainId];
979
- const queryParams = [];
980
- for (let wrapper of [wrappers[SwapType_1.SwapType.FROM_BTC], wrappers[SwapType_1.SwapType.FROM_BTCLN], wrappers[SwapType_1.SwapType.SPV_VAULT_FROM_BTC], wrappers[SwapType_1.SwapType.FROM_BTCLN_AUTO]]) {
981
- if (wrapper == null)
982
- continue;
983
- const swapTypeQueryParams = [{ key: "type", value: wrapper.TYPE }];
984
- if (signer != null)
985
- swapTypeQueryParams.push({ key: "initiator", value: signer });
986
- swapTypeQueryParams.push({ key: "state", value: wrapper._claimableSwapStates });
987
- queryParams.push(swapTypeQueryParams);
988
- }
989
- const result = await unifiedSwapStorage.query(queryParams, reviver);
990
- return result.filter(swap => swap.isClaimable());
991
- }
992
- }
993
- async getSwapById(id, chainId, signer) {
994
- //Check in pending swaps first
995
- if (chainId != null) {
996
- for (let key in this._chains[chainId].wrappers) {
997
- const wrapper = this._chains[chainId].wrappers[key];
998
- const result = wrapper._getPendingSwap(id);
999
- if (result != null) {
1000
- if (signer != null) {
1001
- if (result._getInitiator() === signer)
1002
- return result;
1003
- }
1004
- else {
1005
- return result;
1006
- }
1007
- }
1008
- }
1009
- }
1010
- else {
1011
- for (let chainId in this._chains) {
1012
- for (let key in this._chains[chainId].wrappers) {
1013
- const wrapper = this._chains[chainId].wrappers[key];
1014
- const result = wrapper._getPendingSwap(id);
1015
- if (result != null) {
1016
- if (signer != null) {
1017
- if (result._getInitiator() === signer)
1018
- return result;
1019
- }
1020
- else {
1021
- return result;
1022
- }
1023
- }
1024
- }
1025
- }
1026
- }
1027
- const queryParams = [];
1028
- if (signer != null)
1029
- queryParams.push({ key: "initiator", value: signer });
1030
- queryParams.push({ key: "id", value: id });
1031
- if (chainId == null) {
1032
- const res = await Promise.all(Object.keys(this._chains).map((chainId) => {
1033
- const { unifiedSwapStorage, reviver } = this._chains[chainId];
1034
- return unifiedSwapStorage.query([queryParams], reviver);
1035
- }));
1036
- return res.flat()[0];
1037
- }
1038
- else {
1039
- const { unifiedSwapStorage, reviver } = this._chains[chainId];
1040
- return (await unifiedSwapStorage.query([queryParams], reviver))[0];
1041
- }
1042
- }
1043
- /**
1044
- * Returns the swap with a proper return type, or `undefined` if not found or has wrong type
1045
- *
1046
- * @param id An ID of the swap ({@link ISwap.getId})
1047
- * @param chainId Chain identifier of the smart chain where the swap was initiated
1048
- * @param swapType Type of the swap
1049
- * @param signer An optional required smart chain signer address to fetch the swap for
1050
- */
1051
- async getTypedSwapById(id, chainId, swapType, signer) {
1052
- let _swapType = swapType;
1053
- if (swapType === SwapType_1.SwapType.FROM_BTC && this.supportsSwapType(chainId, SwapType_1.SwapType.SPV_VAULT_FROM_BTC))
1054
- _swapType = SwapType_1.SwapType.SPV_VAULT_FROM_BTC;
1055
- if (swapType === SwapType_1.SwapType.FROM_BTCLN && this.supportsSwapType(chainId, SwapType_1.SwapType.FROM_BTCLN_AUTO))
1056
- _swapType = SwapType_1.SwapType.FROM_BTCLN_AUTO;
1057
- const wrapper = this._chains[chainId].wrappers[_swapType];
1058
- if (wrapper == null)
1059
- return;
1060
- const result = wrapper._getPendingSwap(id);
1061
- if (result != null) {
1062
- if (signer != null) {
1063
- if (result._getInitiator() === signer)
1064
- return result;
1065
- }
1066
- else {
1067
- return result;
1068
- }
1069
- }
1070
- const queryParams = [];
1071
- if (signer != null)
1072
- queryParams.push({ key: "initiator", value: signer });
1073
- queryParams.push({ key: "id", value: id });
1074
- const { unifiedSwapStorage, reviver } = this._chains[chainId];
1075
- const swap = (await unifiedSwapStorage.query([queryParams], reviver))[0];
1076
- if ((0, SwapUtils_1.isSwapType)(swap, swapType))
1077
- return swap;
1078
- }
1079
- async syncSwapsForChain(chainId, signer) {
1080
- const { unifiedSwapStorage, reviver, wrappers } = this._chains[chainId];
1081
- const queryParams = [];
1082
- for (let key in wrappers) {
1083
- const wrapper = wrappers[key];
1084
- const swapTypeQueryParams = [{ key: "type", value: wrapper.TYPE }];
1085
- if (signer != null)
1086
- swapTypeQueryParams.push({ key: "initiator", value: signer });
1087
- swapTypeQueryParams.push({ key: "state", value: wrapper._pendingSwapStates });
1088
- queryParams.push(swapTypeQueryParams);
1089
- }
1090
- this.logger.debug("_syncSwaps(): Querying swaps swaps for chain " + chainId + "!");
1091
- const swaps = await unifiedSwapStorage.query(queryParams, reviver);
1092
- this.logger.debug("_syncSwaps(): Syncing " + swaps.length + " swaps!");
1093
- const changedSwaps = [];
1094
- const removeSwaps = [];
1095
- const assortedSwaps = {};
1096
- swaps.forEach(swap => {
1097
- (assortedSwaps[swap.getType()] ??= []).push(swap);
1098
- });
1099
- for (let key in assortedSwaps) {
1100
- const swapType = key;
1101
- const wrapperSwaps = assortedSwaps[swapType];
1102
- const wrapper = wrappers[swapType];
1103
- const result = await wrapper.checkPastSwaps(wrapperSwaps, true);
1104
- changedSwaps.push(...result.changedSwaps);
1105
- removeSwaps.push(...result.removeSwaps);
1106
- }
1107
- this.logger.debug("_syncSwaps(): Done syncing " + swaps.length + " swaps, saving " + changedSwaps.length + " changed swaps, removing " + removeSwaps.length + " swaps!");
1108
- await unifiedSwapStorage.saveAll(changedSwaps);
1109
- await unifiedSwapStorage.removeAll(removeSwaps);
1110
- changedSwaps.forEach(swap => swap._emitEvent());
1111
- removeSwaps.forEach(swap => swap._emitEvent());
1112
- }
1113
- /**
1114
- * Deletes the swaps from the persistent storage backend. Note that some data (like lightning network
1115
- * amounts and bolt11 invoices) are purely off-chain and can never be recovered later just from
1116
- * on-chain data!
1117
- *
1118
- * @param chainId Optional, to only delete swaps for this smart chain
1119
- * @param signer Optional, to only delete swaps for this smart chain signer (`chainId` param must be
1120
- * set to delete only signer's swaps)
1121
- */
1122
- async wipeStorage(chainId, signer) {
1123
- if (chainId == null) {
1124
- const swaps = await this.getAllSwaps();
1125
- const chainSwaps = {};
1126
- swaps.forEach(swap => (chainSwaps[swap.chainIdentifier] ??= []).push(swap));
1127
- for (let chainId in chainSwaps) {
1128
- const currentChainSwaps = chainSwaps[chainId];
1129
- if (this._chains[chainId] == null) {
1130
- this.logger.warn(`wipeStorage(): Attempted to remove ${currentChainSwaps.length} swaps on ${chainId}, but smart chain not known!`);
1131
- continue;
1132
- }
1133
- await this._chains[chainId].unifiedSwapStorage.removeAll(currentChainSwaps);
1134
- this.logger.debug(`wipeStorage(): Successfully removed ${currentChainSwaps.length} swaps on ${chainId}!`);
1135
- }
1136
- }
1137
- else {
1138
- if (this._chains[chainId] == null)
1139
- throw new Error(`wipeStorage(): Smart chain with identifier ${chainId} not found!`);
1140
- const swaps = await this.getAllSwaps(chainId, signer);
1141
- await this._chains[chainId].unifiedSwapStorage.removeAll(swaps);
1142
- this.logger.debug(`wipeStorage(): Successfully removed ${swaps.length} swaps on ${chainId}!`);
1143
- }
1144
- }
1145
- /**
1146
- * Synchronizes swaps from on-chain, this is ran automatically when SDK is initialized, hence
1147
- * should only be ran manually when `dontCheckPastSwaps=true` is passed in the swapper options,
1148
- * also deletes expired quotes
1149
- *
1150
- * @param chainId Optional chain identifier to only run swap sync for a single smart chain
1151
- * @param signer Optional signer to only run swap sync for swaps initiated by this signer
1152
- */
1153
- async _syncSwaps(chainId, signer) {
1154
- if (chainId == null) {
1155
- await Promise.all(Object.keys(this._chains).map((chainId) => {
1156
- return this.syncSwapsForChain(chainId, signer);
1157
- }));
1158
- }
1159
- else {
1160
- await this.syncSwapsForChain(chainId, signer);
1161
- }
1162
- }
1163
- /**
1164
- * Recovers swaps from on-chain historical data.
1165
- *
1166
- * Please note that the recovered swaps might not be complete (i.e. missing amounts or addresses), as some
1167
- * of the swap data is purely off-chain and can never be recovered purely from on-chain data. This
1168
- * functions tries to recover as much swap data as possible.
1169
- *
1170
- * @param chainId Smart chain identifier string to recover the swaps from
1171
- * @param signer Signer address to recover the swaps for
1172
- * @param startBlockheight Optional starting blockheight for swap data recovery, will only check swaps
1173
- * initiated after this blockheight
1174
- */
1175
- async recoverSwaps(chainId, signer, startBlockheight) {
1176
- const { spvVaultContract, swapContract, unifiedSwapStorage, reviver, wrappers } = this._chains[chainId];
1177
- if (swapContract.getHistoricalSwaps == null ||
1178
- (spvVaultContract != null && spvVaultContract.getHistoricalWithdrawalStates == null))
1179
- throw new Error(`Historical swap recovery is not supported for ${chainId}`);
1180
- const { swaps } = await swapContract.getHistoricalSwaps(signer, startBlockheight);
1181
- const spvVaultData = await spvVaultContract?.getHistoricalWithdrawalStates(signer, startBlockheight);
1182
- const escrowHashes = Object.keys(swaps);
1183
- if (spvVaultData != null)
1184
- Object.keys(spvVaultData.withdrawals).forEach(btcTxId => escrowHashes.push(btcTxId));
1185
- this.logger.debug(`recoverSwaps(): Loaded on-chain data for ${escrowHashes.length} swaps`);
1186
- this.logger.debug(`recoverSwaps(): Fetching if swap escrowHashes are known: ${escrowHashes.join(", ")}`);
1187
- const knownSwapsArray = await unifiedSwapStorage.query([[{ key: "escrowHash", value: escrowHashes }]], reviver);
1188
- const knownSwaps = {};
1189
- knownSwapsArray.forEach(val => {
1190
- const escrowHash = val._getEscrowHash();
1191
- if (escrowHash != null)
1192
- knownSwaps[escrowHash] = val;
1193
- });
1194
- this.logger.debug(`recoverSwaps(): Fetched known swaps escrowHashes: ${Object.keys(knownSwaps).join(", ")}`);
1195
- const recoveredSwaps = [];
1196
- for (let escrowHash in swaps) {
1197
- const { init, state } = swaps[escrowHash];
1198
- const knownSwap = knownSwaps[escrowHash];
1199
- if (knownSwap == null) {
1200
- if (init == null) {
1201
- this.logger.warn(`recoverSwaps(escrow): Fetched ${escrowHash} swap state, but swap not found locally!`);
1202
- continue;
1203
- }
1204
- }
1205
- else if (knownSwap instanceof IEscrowSwap_1.IEscrowSwap) {
1206
- this.logger.debug(`recoverSwaps(escrow): Forcibly updating ${escrowHash} swap: swap already known and in local storage!`);
1207
- if (await knownSwap._forciblySetOnchainState(state)) {
1208
- await knownSwap._save();
1209
- }
1210
- continue;
1211
- }
1212
- else {
1213
- this.logger.debug(`recoverSwaps(escrow): Skipping ${escrowHash} swap: swap already known and in local storage!`);
1214
- continue;
1215
- }
1216
- const data = init.data;
1217
- //Classify swap
1218
- let swap;
1219
- let typeIdentified = false;
1220
- if (data.getType() === base_1.ChainSwapType.HTLC) {
1221
- if (data.isOfferer(signer)) {
1222
- //To BTCLN
1223
- typeIdentified = true;
1224
- const lp = this.intermediaryDiscovery.intermediaries.find(val => val.supportsChain(chainId) && data.isClaimer(val.getAddress(chainId)));
1225
- swap = await wrappers[SwapType_1.SwapType.TO_BTCLN].recoverFromSwapDataAndState(init, state, lp);
1226
- }
1227
- else if (data.isClaimer(signer)) {
1228
- //From BTCLN
1229
- typeIdentified = true;
1230
- const lp = this.intermediaryDiscovery.intermediaries.find(val => val.supportsChain(chainId) && data.isOfferer(val.getAddress(chainId)));
1231
- if (this.supportsSwapType(chainId, SwapType_1.SwapType.FROM_BTCLN_AUTO)) {
1232
- swap = await wrappers[SwapType_1.SwapType.FROM_BTCLN_AUTO].recoverFromSwapDataAndState(init, state, lp);
1233
- }
1234
- else {
1235
- swap = await wrappers[SwapType_1.SwapType.FROM_BTCLN].recoverFromSwapDataAndState(init, state, lp);
1236
- }
1237
- }
1238
- }
1239
- else if (data.getType() === base_1.ChainSwapType.CHAIN_NONCED) {
1240
- //To BTC
1241
- typeIdentified = true;
1242
- const lp = this.intermediaryDiscovery.intermediaries.find(val => val.supportsChain(chainId) && data.isClaimer(val.getAddress(chainId)));
1243
- swap = await wrappers[SwapType_1.SwapType.TO_BTC].recoverFromSwapDataAndState(init, state, lp);
1244
- }
1245
- else if (data.getType() === base_1.ChainSwapType.CHAIN) {
1246
- //From BTC
1247
- typeIdentified = true;
1248
- const lp = this.intermediaryDiscovery.intermediaries.find(val => val.supportsChain(chainId) && data.isOfferer(val.getAddress(chainId)));
1249
- swap = await wrappers[SwapType_1.SwapType.FROM_BTC].recoverFromSwapDataAndState(init, state, lp);
1250
- }
1251
- if (swap != null) {
1252
- recoveredSwaps.push(swap);
1253
- }
1254
- else {
1255
- if (typeIdentified)
1256
- this.logger.debug(`recoverSwaps(escrow): Swap data type correctly identified but swap returned is null for swap ${escrowHash}`);
1257
- }
1258
- }
1259
- if (spvVaultContract != null && spvVaultData != null) {
1260
- const vaultsData = await spvVaultContract.getMultipleVaultData(Object.keys(spvVaultData.withdrawals)
1261
- .map(btcTxId => ({
1262
- owner: spvVaultData.withdrawals[btcTxId].owner,
1263
- vaultId: spvVaultData.withdrawals[btcTxId].vaultId
1264
- })));
1265
- for (let btcTxId in spvVaultData.withdrawals) {
1266
- const state = spvVaultData.withdrawals[btcTxId];
1267
- const knownSwap = knownSwaps[btcTxId];
1268
- if (knownSwap != null) {
1269
- if (knownSwap instanceof SpvFromBTCSwap_1.SpvFromBTCSwap) {
1270
- this.logger.debug(`recoverSwaps(spv_vault): Forcibly updating ${btcTxId} swap: swap already known and in local storage!`);
1271
- //TODO: Forcibly set on-chain state to the swap
1272
- // if(await knownSwap._forciblySetOnchainState(state)) {
1273
- // await knownSwap._save();
1274
- // }
1275
- continue;
1276
- }
1277
- else {
1278
- this.logger.debug(`recoverSwaps(spv_vault): Skipping ${btcTxId} swap: swap already known and in local storage!`);
1279
- continue;
1280
- }
1281
- }
1282
- const lp = this.intermediaryDiscovery.intermediaries.find(val => val.supportsChain(chainId) && state.owner.toLowerCase() === val.getAddress(chainId).toLowerCase());
1283
- const swap = await wrappers[SwapType_1.SwapType.SPV_VAULT_FROM_BTC].recoverFromState(state, vaultsData[state.owner]?.[state.vaultId.toString(10)], lp);
1284
- if (swap != null) {
1285
- recoveredSwaps.push(swap);
1286
- }
1287
- else {
1288
- this.logger.debug(`recoverSwaps(spv_vault): Swap data type correctly identified but swap returned is null for swap ${btcTxId}`);
1289
- }
1290
- }
1291
- }
1292
- this.logger.debug(`recoverSwaps(): Successfully recovered ${recoveredSwaps.length} swaps!`);
1293
- return recoveredSwaps;
1294
- }
1295
- /**
1296
- * Returns the {@link Token} object for a given token
1297
- *
1298
- * @param tickerOrAddress Token to return the object for, can use multiple formats:
1299
- * - a) token ticker, such as `"BTC"`, `"SOL"`, etc.
1300
- * - b) token ticker prefixed with smart chain identifier, such as `"SOLANA-SOL"`, `"SOLANA-USDC"`, etc.
1301
- * - c) token address
1302
- */
1303
- getToken(tickerOrAddress) {
1304
- //Btc tokens - BTC, BTCLN, BTC-LN
1305
- if (tickerOrAddress === "BTC" || tickerOrAddress === "BITCOIN-BTC")
1306
- return Token_1.BitcoinTokens.BTC;
1307
- if (tickerOrAddress === "BTCLN" || tickerOrAddress === "BTC-LN" || tickerOrAddress === "LIGHTNING-BTC")
1308
- return Token_1.BitcoinTokens.BTCLN;
1309
- //Check if the ticker is in format <chainId>-<ticker>, i.e. SOLANA-USDC, STARKNET-WBTC
1310
- if (tickerOrAddress.includes("-")) {
1311
- const [chainId, ticker] = tickerOrAddress.split("-");
1312
- const token = this._tokensByTicker[chainId]?.[ticker];
1313
- if (token == null)
1314
- throw new UserError_1.UserError(`Not found ticker: ${ticker} for chainId: ${chainId}`);
1315
- return token;
1316
- }
1317
- const possibleTokens = [];
1318
- for (let chainId in this._chains) {
1319
- const chain = this._chains[chainId];
1320
- if (chain.chainInterface.isValidToken(tickerOrAddress)) {
1321
- //Try to find in known token addresses
1322
- const token = this._tokens[chainId]?.[tickerOrAddress];
1323
- if (token != null)
1324
- return token;
1325
- }
1326
- else {
1327
- //Check in known tickers
1328
- const token = this._tokensByTicker[chainId]?.[tickerOrAddress];
1329
- if (token != null)
1330
- possibleTokens.push(token);
1331
- }
1332
- }
1333
- if (possibleTokens.length === 0)
1334
- throw new UserError_1.UserError(`Specified token address or ticker ${tickerOrAddress} not found!`);
1335
- //In case we've found the token in multiple chains
1336
- if (possibleTokens.length > 1)
1337
- throw new UserError_1.UserError(`A ticker ${tickerOrAddress} has been found in multiple chains, narrow it down by using <chainId>-${tickerOrAddress} notation`);
1338
- return possibleTokens[0];
1339
- }
1340
- /**
1341
- * Creates a child swapper instance with a given smart chain
1342
- *
1343
- * @param chainIdentifier Smart chain identifier for the created child swapper instance
1344
- */
1345
- withChain(chainIdentifier) {
1346
- if (this._chains[chainIdentifier] == null)
1347
- throw new Error("Invalid chain identifier! Unknown chain: " + chainIdentifier);
1348
- return new SwapperWithChain_1.SwapperWithChain(this, chainIdentifier);
1349
- }
1350
- /**
1351
- * Returns an array of all the supported smart chains
1352
- */
1353
- getSmartChains() {
1354
- return Object.keys(this._chains);
1355
- }
1356
- /**
1357
- * Returns whether the SDK supports a given swap type on a given chain based on currently known LPs
1358
- *
1359
- * @param chainId Smart chain identifier string
1360
- * @param swapType Swap protocol type
1361
- */
1362
- supportsSwapType(chainId, swapType) {
1363
- return (this._chains[chainId]?.wrappers[swapType] != null);
1364
- }
1365
- /**
1366
- * Returns type of the swap based on input and output tokens specified
1367
- *
1368
- * @param srcToken Source token
1369
- * @param dstToken Destination token
1370
- */
1371
- getSwapType(srcToken, dstToken) {
1372
- if ((0, Token_1.isSCToken)(srcToken)) {
1373
- if (!(0, Token_1.isBtcToken)(dstToken))
1374
- throw new Error("Swap not supported");
1375
- if (dstToken.lightning) {
1376
- return SwapType_1.SwapType.TO_BTCLN;
1377
- }
1378
- else {
1379
- return SwapType_1.SwapType.TO_BTC;
1380
- }
1381
- }
1382
- else if ((0, Token_1.isBtcToken)(srcToken)) {
1383
- if (!(0, Token_1.isSCToken)(dstToken))
1384
- throw new Error("Swap not supported");
1385
- if (srcToken.lightning) {
1386
- if (this.supportsSwapType(dstToken.chainId, SwapType_1.SwapType.FROM_BTCLN_AUTO)) {
1387
- return SwapType_1.SwapType.FROM_BTCLN_AUTO;
1388
- }
1389
- else {
1390
- return SwapType_1.SwapType.FROM_BTCLN;
1391
- }
1392
- }
1393
- else {
1394
- if (this.supportsSwapType(dstToken.chainId, SwapType_1.SwapType.SPV_VAULT_FROM_BTC)) {
1395
- return SwapType_1.SwapType.SPV_VAULT_FROM_BTC;
1396
- }
1397
- else {
1398
- return SwapType_1.SwapType.FROM_BTC;
1399
- }
1400
- }
1401
- }
1402
- throw new Error("Swap not supported");
1403
- }
1404
- /**
1405
- * Returns minimum/maximum limits for inputs and outputs for a swap between given tokens
1406
- *
1407
- * @param srcToken Source token
1408
- * @param dstToken Destination token
1409
- */
1410
- getSwapLimits(srcToken, dstToken) {
1411
- const swapType = this.getSwapType(srcToken, dstToken);
1412
- const scToken = (0, Token_1.isSCToken)(srcToken) ? srcToken : (0, Token_1.isSCToken)(dstToken) ? dstToken : null;
1413
- if (scToken == null)
1414
- throw new Error("At least one token needs to be a smart chain token!");
1415
- const result = {
1416
- input: {},
1417
- output: {}
1418
- };
1419
- for (let lp of this.intermediaryDiscovery.intermediaries) {
1420
- const lpMinMax = lp.getSwapLimits(swapType, scToken.chainId, scToken.address);
1421
- if (lpMinMax == null)
1422
- continue;
1423
- result.input.min = result.input.min == null ? lpMinMax.input.min : (0, Utils_1.bigIntMin)(result.input.min, lpMinMax.input.min);
1424
- result.input.max = result.input.max == null ? lpMinMax.input.max : (0, Utils_1.bigIntMax)(result.input.max, lpMinMax.input.max);
1425
- result.output.min = result.output.min == null ? lpMinMax.output.min : (0, Utils_1.bigIntMin)(result.output.min, lpMinMax.output.min);
1426
- result.output.max = result.output.max == null ? lpMinMax.output.max : (0, Utils_1.bigIntMax)(result.output.max, lpMinMax.output.max);
1427
- }
1428
- return {
1429
- input: {
1430
- min: (0, TokenAmount_1.toTokenAmount)(result.input.min ?? 1n, srcToken, this.prices),
1431
- max: result.input.max == null ? undefined : (0, TokenAmount_1.toTokenAmount)(result.input.max, srcToken, this.prices),
1432
- },
1433
- output: {
1434
- min: (0, TokenAmount_1.toTokenAmount)(result.output.min ?? 1n, dstToken, this.prices),
1435
- max: result.output.max == null ? undefined : (0, TokenAmount_1.toTokenAmount)(result.output.max, dstToken, this.prices),
1436
- }
1437
- };
1438
- }
1439
- /**
1440
- * Returns an array of supported tokens either on the input or on the output of a swap
1441
- *
1442
- * @param input Whether to return input tokens or output tokens
1443
- */
1444
- getSupportedTokens(input) {
1445
- const tokens = {};
1446
- let lightning = false;
1447
- let btc = false;
1448
- this.intermediaryDiscovery.intermediaries.forEach(lp => {
1449
- for (let swapType of [SwapType_1.SwapType.TO_BTC, SwapType_1.SwapType.TO_BTCLN, SwapType_1.SwapType.FROM_BTC, SwapType_1.SwapType.FROM_BTCLN, SwapType_1.SwapType.SPV_VAULT_FROM_BTC, SwapType_1.SwapType.FROM_BTCLN_AUTO]) {
1450
- if (lp.services[swapType]?.chainTokens == null)
1451
- continue;
1452
- for (let chainId of this.getSmartChains()) {
1453
- if (this.supportsSwapType(chainId, SwapType_1.SwapType.SPV_VAULT_FROM_BTC) ? swapType === SwapType_1.SwapType.FROM_BTC : swapType === SwapType_1.SwapType.SPV_VAULT_FROM_BTC)
1454
- continue;
1455
- if (this.supportsSwapType(chainId, SwapType_1.SwapType.FROM_BTCLN_AUTO) ? swapType === SwapType_1.SwapType.FROM_BTCLN : swapType === SwapType_1.SwapType.FROM_BTCLN_AUTO)
1456
- continue;
1457
- const chainTokens = lp.services[swapType]?.chainTokens?.[chainId];
1458
- if (chainTokens == null)
1459
- continue;
1460
- for (let tokenAddress of chainTokens) {
1461
- if (input) {
1462
- if (swapType === SwapType_1.SwapType.TO_BTC || swapType === SwapType_1.SwapType.TO_BTCLN) {
1463
- tokens[chainId] ??= new Set();
1464
- tokens[chainId].add(tokenAddress);
1465
- }
1466
- if (swapType === SwapType_1.SwapType.FROM_BTCLN || swapType === SwapType_1.SwapType.FROM_BTCLN_AUTO) {
1467
- lightning = true;
1468
- }
1469
- if (swapType === SwapType_1.SwapType.FROM_BTC || swapType === SwapType_1.SwapType.SPV_VAULT_FROM_BTC) {
1470
- btc = true;
1471
- }
1472
- }
1473
- else {
1474
- if (swapType === SwapType_1.SwapType.FROM_BTCLN || swapType === SwapType_1.SwapType.FROM_BTC || swapType === SwapType_1.SwapType.SPV_VAULT_FROM_BTC || swapType === SwapType_1.SwapType.FROM_BTCLN_AUTO) {
1475
- tokens[chainId] ??= new Set();
1476
- tokens[chainId].add(tokenAddress);
1477
- }
1478
- if (swapType === SwapType_1.SwapType.TO_BTCLN) {
1479
- lightning = true;
1480
- }
1481
- if (swapType === SwapType_1.SwapType.TO_BTC) {
1482
- btc = true;
1483
- }
1484
- }
1485
- }
1486
- }
1487
- }
1488
- });
1489
- const output = [];
1490
- if (lightning)
1491
- output.push(Token_1.BitcoinTokens.BTCLN);
1492
- if (btc)
1493
- output.push(Token_1.BitcoinTokens.BTC);
1494
- for (let chainId in tokens) {
1495
- tokens[chainId].forEach(tokenAddress => {
1496
- const token = this._tokens?.[chainId]?.[tokenAddress];
1497
- if (token != null)
1498
- output.push(token);
1499
- });
1500
- }
1501
- return output;
1502
- }
1503
- /**
1504
- * Returns a set of supported tokens by all the intermediaries offering a specific swap service
1505
- *
1506
- * @param _swapType Swap service type to check supported tokens for
1507
- */
1508
- getSupportedTokensForSwapType(_swapType) {
1509
- const tokens = {};
1510
- this.intermediaryDiscovery.intermediaries.forEach(lp => {
1511
- for (let chainId of this.getSmartChains()) {
1512
- let swapType = _swapType;
1513
- if (swapType === SwapType_1.SwapType.FROM_BTC && this.supportsSwapType(chainId, SwapType_1.SwapType.SPV_VAULT_FROM_BTC))
1514
- swapType = SwapType_1.SwapType.SPV_VAULT_FROM_BTC;
1515
- if (swapType === SwapType_1.SwapType.FROM_BTCLN && this.supportsSwapType(chainId, SwapType_1.SwapType.FROM_BTCLN_AUTO))
1516
- swapType = SwapType_1.SwapType.FROM_BTCLN_AUTO;
1517
- if (lp.services[swapType]?.chainTokens == null)
1518
- break;
1519
- const chainTokens = lp.services[swapType]?.chainTokens?.[chainId];
1520
- if (chainTokens == null)
1521
- continue;
1522
- for (let tokenAddress of chainTokens) {
1523
- tokens[chainId] ??= new Set();
1524
- tokens[chainId].add(tokenAddress);
1525
- }
1526
- }
1527
- });
1528
- const output = [];
1529
- for (let chainId in tokens) {
1530
- tokens[chainId].forEach(tokenAddress => {
1531
- const token = this._tokens?.[chainId]?.[tokenAddress];
1532
- if (token != null)
1533
- output.push(token);
1534
- });
1535
- }
1536
- return output;
1537
- }
1538
- /**
1539
- * Returns the set of supported token addresses by all the intermediaries we know of offering a specific swapType service
1540
- *
1541
- * @param chainIdentifier Chain identifier string
1542
- * @param swapType Specific swap type for which to obtain supported tokens
1543
- */
1544
- getSupportedTokenAddresses(chainIdentifier, swapType) {
1545
- const set = new Set();
1546
- this.intermediaryDiscovery.intermediaries.forEach(lp => {
1547
- const chainTokens = lp.services[swapType]?.chainTokens?.[chainIdentifier];
1548
- if (chainTokens == null)
1549
- return;
1550
- chainTokens.forEach(token => set.add(token));
1551
- });
1552
- return set;
1553
- }
1554
- /**
1555
- * Returns tokens that you can swap to (if input=true) from a given token,
1556
- * or tokens that you can swap from (if input=false) to a given token
1557
- */
1558
- getSwapCounterTokens(token, input) {
1559
- if ((0, Token_1.isSCToken)(token)) {
1560
- const result = [];
1561
- if (input) {
1562
- //TO_BTC or TO_BTCLN
1563
- if (this.getSupportedTokenAddresses(token.chainId, SwapType_1.SwapType.TO_BTCLN).has(token.address)) {
1564
- result.push(Token_1.BitcoinTokens.BTCLN);
1565
- }
1566
- if (this.getSupportedTokenAddresses(token.chainId, SwapType_1.SwapType.TO_BTC).has(token.address)) {
1567
- result.push(Token_1.BitcoinTokens.BTC);
1568
- }
1569
- }
1570
- else {
1571
- //FROM_BTC or FROM_BTCLN
1572
- const fromLightningSwapType = this.supportsSwapType(token.chainId, SwapType_1.SwapType.FROM_BTCLN_AUTO) ? SwapType_1.SwapType.FROM_BTCLN_AUTO : SwapType_1.SwapType.FROM_BTCLN;
1573
- if (this.getSupportedTokenAddresses(token.chainId, fromLightningSwapType).has(token.address)) {
1574
- result.push(Token_1.BitcoinTokens.BTCLN);
1575
- }
1576
- const fromOnchainSwapType = this.supportsSwapType(token.chainId, SwapType_1.SwapType.SPV_VAULT_FROM_BTC) ? SwapType_1.SwapType.SPV_VAULT_FROM_BTC : SwapType_1.SwapType.FROM_BTC;
1577
- if (this.getSupportedTokenAddresses(token.chainId, fromOnchainSwapType).has(token.address)) {
1578
- result.push(Token_1.BitcoinTokens.BTC);
1579
- }
1580
- }
1581
- return result;
1582
- }
1583
- else {
1584
- if (input) {
1585
- if (token.lightning) {
1586
- return this.getSupportedTokensForSwapType(SwapType_1.SwapType.FROM_BTCLN);
1587
- }
1588
- else {
1589
- return this.getSupportedTokensForSwapType(SwapType_1.SwapType.FROM_BTC);
1590
- }
1591
- }
1592
- else {
1593
- if (token.lightning) {
1594
- return this.getSupportedTokensForSwapType(SwapType_1.SwapType.TO_BTCLN);
1595
- }
1596
- else {
1597
- return this.getSupportedTokensForSwapType(SwapType_1.SwapType.TO_BTC);
1598
- }
1599
- }
1600
- }
1601
- }
1602
- }
1603
- exports.Swapper = Swapper;
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.Swapper = void 0;
4
+ const base_1 = require("@atomiqlabs/base");
5
+ const ToBTCLNWrapper_1 = require("../swaps/escrow_swaps/tobtc/ln/ToBTCLNWrapper");
6
+ const ToBTCWrapper_1 = require("../swaps/escrow_swaps/tobtc/onchain/ToBTCWrapper");
7
+ const FromBTCLNWrapper_1 = require("../swaps/escrow_swaps/frombtc/ln/FromBTCLNWrapper");
8
+ const FromBTCWrapper_1 = require("../swaps/escrow_swaps/frombtc/onchain/FromBTCWrapper");
9
+ const IntermediaryDiscovery_1 = require("../intermediaries/IntermediaryDiscovery");
10
+ const bolt11_1 = require("@atomiqlabs/bolt11");
11
+ const IntermediaryError_1 = require("../errors/IntermediaryError");
12
+ const SwapType_1 = require("../enums/SwapType");
13
+ const LnForGasWrapper_1 = require("../swaps/trusted/ln/LnForGasWrapper");
14
+ const events_1 = require("events");
15
+ const Utils_1 = require("../utils/Utils");
16
+ const RequestError_1 = require("../errors/RequestError");
17
+ const SwapperWithChain_1 = require("./SwapperWithChain");
18
+ const OnchainForGasWrapper_1 = require("../swaps/trusted/onchain/OnchainForGasWrapper");
19
+ const utils_1 = require("@scure/btc-signer/utils");
20
+ const UnifiedSwapStorage_1 = require("../storage/UnifiedSwapStorage");
21
+ const UnifiedSwapEventListener_1 = require("../events/UnifiedSwapEventListener");
22
+ const SpvFromBTCWrapper_1 = require("../swaps/spv_swaps/SpvFromBTCWrapper");
23
+ const SpvFromBTCSwap_1 = require("../swaps/spv_swaps/SpvFromBTCSwap");
24
+ const SwapperUtils_1 = require("./SwapperUtils");
25
+ const FromBTCLNAutoWrapper_1 = require("../swaps/escrow_swaps/frombtc/ln_auto/FromBTCLNAutoWrapper");
26
+ const UserError_1 = require("../errors/UserError");
27
+ const AutomaticClockDriftCorrection_1 = require("../utils/AutomaticClockDriftCorrection");
28
+ const SwapUtils_1 = require("../utils/SwapUtils");
29
+ const IndexedDBUnifiedStorage_1 = require("../storage-browser/IndexedDBUnifiedStorage");
30
+ const TokenAmount_1 = require("../types/TokenAmount");
31
+ const Token_1 = require("../types/Token");
32
+ const Logger_1 = require("../utils/Logger");
33
+ const LNURLWithdraw_1 = require("../types/lnurl/LNURLWithdraw");
34
+ const LNURLPay_1 = require("../types/lnurl/LNURLPay");
35
+ const RetryUtils_1 = require("../utils/RetryUtils");
36
+ const IEscrowSwap_1 = require("../swaps/escrow_swaps/IEscrowSwap");
37
+ const LightningInvoiceCreateService_1 = require("../types/wallets/LightningInvoiceCreateService");
38
+ /**
39
+ * Core orchestrator for all atomiq swap operations
40
+ *
41
+ * @category Core
42
+ */
43
+ class Swapper extends events_1.EventEmitter {
44
+ /**
45
+ * @internal
46
+ */
47
+ constructor(bitcoinRpc, lightningApi, bitcoinSynchronizer, chainsData, pricing, tokens, messenger, options) {
48
+ super();
49
+ this.logger = (0, Logger_1.getLogger)(this.constructor.name + ": ");
50
+ this.initialized = false;
51
+ /**
52
+ * Helper information about various swap protocol and their features:
53
+ * - `requiresInputWallet`: Whether a swap requires a connected wallet on the input chain able to sign
54
+ * arbitrary transaction
55
+ * - `requiresOutputWallet`: Whether a swap requires a connected wallet on the output chain able to sign
56
+ * arbitrary transactions
57
+ * - `supportsGasDrop`: Whether a swap supports the "gas drop" feature, allowing to user to receive a small
58
+ * amount of native token as part of the swap when swapping to smart chains
59
+ *
60
+ * Uses a `Record` type here, use the {@link SwapProtocolInfo} import for a literal readonly type, with
61
+ * pre-filled exact values in the type.
62
+ */
63
+ this.SwapTypeInfo = SwapUtils_1.SwapProtocolInfo;
64
+ const storagePrefix = options?.storagePrefix ?? "atomiq-";
65
+ options ??= {};
66
+ options.saveUninitializedSwaps ??= true;
67
+ options.bitcoinNetwork = options.bitcoinNetwork == null ? base_1.BitcoinNetwork.TESTNET : options.bitcoinNetwork;
68
+ const swapStorage = options.swapStorage ??= (name) => new IndexedDBUnifiedStorage_1.IndexedDBUnifiedStorage(name);
69
+ this.options = options;
70
+ this.bitcoinNetwork = options.bitcoinNetwork;
71
+ this._btcNetwork = options.bitcoinNetwork === base_1.BitcoinNetwork.MAINNET ? utils_1.NETWORK :
72
+ (options.bitcoinNetwork === base_1.BitcoinNetwork.TESTNET || options.bitcoinNetwork === base_1.BitcoinNetwork.TESTNET4) ? utils_1.TEST_NETWORK : {
73
+ bech32: 'bcrt',
74
+ pubKeyHash: 111,
75
+ scriptHash: 196,
76
+ wif: 239
77
+ };
78
+ this.Utils = new SwapperUtils_1.SwapperUtils(this);
79
+ this.prices = pricing;
80
+ this._bitcoinRpc = bitcoinRpc;
81
+ this.messenger = messenger;
82
+ this._tokens = {};
83
+ this._tokensByTicker = {};
84
+ for (let tokenData of tokens) {
85
+ const chainId = tokenData.chainId;
86
+ this._tokens[chainId] ??= {};
87
+ this._tokensByTicker[chainId] ??= {};
88
+ this._tokens[chainId][tokenData.address] = this._tokensByTicker[chainId][tokenData.ticker] = tokenData;
89
+ }
90
+ this.swapStateListener = (swap) => {
91
+ this.emit("swapState", swap);
92
+ };
93
+ this._chains = (0, Utils_1.objectMap)(chainsData, (chainData, key) => {
94
+ const { swapContract, chainEvents, btcRelay, chainInterface, spvVaultContract, spvVaultWithdrawalDataConstructor, chainId } = chainData;
95
+ const synchronizer = bitcoinSynchronizer(btcRelay);
96
+ const storageHandler = swapStorage(storagePrefix + chainId);
97
+ const unifiedSwapStorage = new UnifiedSwapStorage_1.UnifiedSwapStorage(storageHandler, this.options.noSwapCache);
98
+ const unifiedChainEvents = new UnifiedSwapEventListener_1.UnifiedSwapEventListener(unifiedSwapStorage, chainEvents);
99
+ const wrappers = {};
100
+ wrappers[SwapType_1.SwapType.TO_BTCLN] = new ToBTCLNWrapper_1.ToBTCLNWrapper(key, unifiedSwapStorage, unifiedChainEvents, chainInterface, swapContract, pricing, this._tokens[chainId], chainData.swapDataConstructor, {
101
+ getRequestTimeout: this.options.getRequestTimeout,
102
+ postRequestTimeout: this.options.postRequestTimeout,
103
+ saveUninitializedSwaps: this.options.saveUninitializedSwaps,
104
+ });
105
+ wrappers[SwapType_1.SwapType.TO_BTC] = new ToBTCWrapper_1.ToBTCWrapper(key, unifiedSwapStorage, unifiedChainEvents, chainInterface, swapContract, pricing, this._tokens[chainId], chainData.swapDataConstructor, this._bitcoinRpc, {
106
+ getRequestTimeout: this.options.getRequestTimeout,
107
+ postRequestTimeout: this.options.postRequestTimeout,
108
+ saveUninitializedSwaps: this.options.saveUninitializedSwaps,
109
+ bitcoinNetwork: this._btcNetwork
110
+ });
111
+ wrappers[SwapType_1.SwapType.FROM_BTCLN] = new FromBTCLNWrapper_1.FromBTCLNWrapper(key, unifiedSwapStorage, unifiedChainEvents, chainInterface, swapContract, pricing, this._tokens[chainId], chainData.swapDataConstructor, lightningApi, {
112
+ getRequestTimeout: this.options.getRequestTimeout,
113
+ postRequestTimeout: this.options.postRequestTimeout,
114
+ saveUninitializedSwaps: this.options.saveUninitializedSwaps,
115
+ unsafeSkipLnNodeCheck: this.bitcoinNetwork === base_1.BitcoinNetwork.TESTNET4 || this.bitcoinNetwork === base_1.BitcoinNetwork.REGTEST
116
+ });
117
+ wrappers[SwapType_1.SwapType.FROM_BTC] = new FromBTCWrapper_1.FromBTCWrapper(key, unifiedSwapStorage, unifiedChainEvents, chainInterface, swapContract, pricing, this._tokens[chainId], chainData.swapDataConstructor, btcRelay, synchronizer, this._bitcoinRpc, {
118
+ getRequestTimeout: this.options.getRequestTimeout,
119
+ postRequestTimeout: this.options.postRequestTimeout,
120
+ saveUninitializedSwaps: this.options.saveUninitializedSwaps,
121
+ bitcoinNetwork: this._btcNetwork
122
+ });
123
+ wrappers[SwapType_1.SwapType.TRUSTED_FROM_BTCLN] = new LnForGasWrapper_1.LnForGasWrapper(key, unifiedSwapStorage, unifiedChainEvents, chainInterface, pricing, this._tokens[chainId], {
124
+ getRequestTimeout: this.options.getRequestTimeout,
125
+ postRequestTimeout: this.options.postRequestTimeout,
126
+ saveUninitializedSwaps: this.options.saveUninitializedSwaps,
127
+ });
128
+ wrappers[SwapType_1.SwapType.TRUSTED_FROM_BTC] = new OnchainForGasWrapper_1.OnchainForGasWrapper(key, unifiedSwapStorage, unifiedChainEvents, chainInterface, pricing, this._tokens[chainId], bitcoinRpc, {
129
+ getRequestTimeout: this.options.getRequestTimeout,
130
+ postRequestTimeout: this.options.postRequestTimeout,
131
+ saveUninitializedSwaps: this.options.saveUninitializedSwaps,
132
+ bitcoinNetwork: this._btcNetwork
133
+ });
134
+ if (spvVaultContract != null) {
135
+ wrappers[SwapType_1.SwapType.SPV_VAULT_FROM_BTC] = new SpvFromBTCWrapper_1.SpvFromBTCWrapper(key, unifiedSwapStorage, unifiedChainEvents, chainInterface, spvVaultContract, pricing, this._tokens[chainId], spvVaultWithdrawalDataConstructor, btcRelay, synchronizer, bitcoinRpc, {
136
+ getRequestTimeout: this.options.getRequestTimeout,
137
+ postRequestTimeout: this.options.postRequestTimeout,
138
+ saveUninitializedSwaps: this.options.saveUninitializedSwaps,
139
+ bitcoinNetwork: this._btcNetwork
140
+ });
141
+ }
142
+ if (swapContract.supportsInitWithoutClaimer) {
143
+ wrappers[SwapType_1.SwapType.FROM_BTCLN_AUTO] = new FromBTCLNAutoWrapper_1.FromBTCLNAutoWrapper(key, unifiedSwapStorage, unifiedChainEvents, chainInterface, swapContract, pricing, this._tokens[chainId], chainData.swapDataConstructor, lightningApi, this.messenger, {
144
+ getRequestTimeout: this.options.getRequestTimeout,
145
+ postRequestTimeout: this.options.postRequestTimeout,
146
+ saveUninitializedSwaps: this.options.saveUninitializedSwaps,
147
+ unsafeSkipLnNodeCheck: this.bitcoinNetwork === base_1.BitcoinNetwork.TESTNET4 || this.bitcoinNetwork === base_1.BitcoinNetwork.REGTEST
148
+ });
149
+ }
150
+ Object.keys(wrappers).forEach(key => wrappers[key].events.on("swapState", this.swapStateListener));
151
+ const reviver = (val) => {
152
+ const wrapper = wrappers[val.type];
153
+ if (wrapper == null)
154
+ return null;
155
+ return new wrapper._swapDeserializer(wrapper, val);
156
+ };
157
+ return {
158
+ chainEvents,
159
+ spvVaultContract,
160
+ swapContract,
161
+ chainInterface,
162
+ btcRelay,
163
+ synchronizer,
164
+ wrappers,
165
+ unifiedChainEvents,
166
+ unifiedSwapStorage,
167
+ reviver
168
+ };
169
+ });
170
+ const contracts = (0, Utils_1.objectMap)(chainsData, (data) => data.swapContract);
171
+ if (options.intermediaryUrl != null) {
172
+ this.intermediaryDiscovery = new IntermediaryDiscovery_1.IntermediaryDiscovery(contracts, options.registryUrl, Array.isArray(options.intermediaryUrl) ? options.intermediaryUrl : [options.intermediaryUrl], options.getRequestTimeout);
173
+ }
174
+ else {
175
+ this.intermediaryDiscovery = new IntermediaryDiscovery_1.IntermediaryDiscovery(contracts, options.registryUrl, undefined, options.getRequestTimeout);
176
+ }
177
+ this.intermediaryDiscovery.on("removed", (intermediaries) => {
178
+ this.emit("lpsRemoved", intermediaries);
179
+ });
180
+ this.intermediaryDiscovery.on("added", (intermediaries) => {
181
+ this.emit("lpsAdded", intermediaries);
182
+ });
183
+ }
184
+ async _init() {
185
+ this.logger.debug("init(): Initializing swapper...");
186
+ const abortController = new AbortController();
187
+ const promises = [];
188
+ let automaticClockDriftCorrectionPromise = undefined;
189
+ if (this.options.automaticClockDriftCorrection) {
190
+ promises.push(automaticClockDriftCorrectionPromise = (0, RetryUtils_1.tryWithRetries)(AutomaticClockDriftCorrection_1.correctClock, undefined, undefined, abortController.signal).catch((err) => {
191
+ abortController.abort(err);
192
+ }));
193
+ }
194
+ this.logger.debug("init(): Initializing intermediary discovery");
195
+ if (!this.options.dontFetchLPs)
196
+ promises.push(this.intermediaryDiscovery.init(abortController.signal).catch(err => {
197
+ if (abortController.signal.aborted)
198
+ return;
199
+ this.logger.error("init(): Failed to fetch intermediaries/LPs: ", err);
200
+ }));
201
+ if (this.options.defaultTrustedIntermediaryUrl != null) {
202
+ promises.push(this.intermediaryDiscovery.getIntermediary(this.options.defaultTrustedIntermediaryUrl, abortController.signal)
203
+ .then(val => {
204
+ if (val == null)
205
+ throw new Error("Cannot get trusted LP");
206
+ this.defaultTrustedIntermediary = val;
207
+ })
208
+ .catch(err => {
209
+ if (abortController.signal.aborted)
210
+ return;
211
+ this.logger.error("init(): Failed to contact trusted LP url: ", err);
212
+ }));
213
+ }
214
+ if (automaticClockDriftCorrectionPromise != null) {
215
+ //We should await the promises here before checking the swaps
216
+ await automaticClockDriftCorrectionPromise;
217
+ }
218
+ const chainPromises = [];
219
+ for (let chainIdentifier in this._chains) {
220
+ chainPromises.push((async () => {
221
+ const { chainInterface, swapContract, unifiedChainEvents, unifiedSwapStorage, wrappers, reviver } = this._chains[chainIdentifier];
222
+ const _chainInterface = chainInterface;
223
+ if (_chainInterface.verifyNetwork != null) {
224
+ await _chainInterface.verifyNetwork(this.bitcoinNetwork);
225
+ }
226
+ await swapContract.start();
227
+ this.logger.debug("init(): Intialized swap contract: " + chainIdentifier);
228
+ await unifiedSwapStorage.init();
229
+ if (unifiedSwapStorage.storage instanceof IndexedDBUnifiedStorage_1.IndexedDBUnifiedStorage) {
230
+ //Try to migrate the data here
231
+ const storagePrefix = chainIdentifier === "SOLANA" ?
232
+ "SOLv4-" + this.bitcoinNetwork + "-Swaps-" :
233
+ "atomiqsdk-" + this.bitcoinNetwork + chainIdentifier + "-Swaps-";
234
+ await unifiedSwapStorage.storage.tryMigrate([
235
+ [storagePrefix + "FromBTC", SwapType_1.SwapType.FROM_BTC],
236
+ [storagePrefix + "FromBTCLN", SwapType_1.SwapType.FROM_BTCLN],
237
+ [storagePrefix + "ToBTC", SwapType_1.SwapType.TO_BTC],
238
+ [storagePrefix + "ToBTCLN", SwapType_1.SwapType.TO_BTCLN]
239
+ ], (obj) => {
240
+ const swap = reviver(obj);
241
+ if (swap._randomNonce == null) {
242
+ const oldIdentifierHash = swap.getId();
243
+ swap._randomNonce = (0, Utils_1.randomBytes)(16).toString("hex");
244
+ const newIdentifierHash = swap.getId();
245
+ this.logger.info("init(): Found older swap version without randomNonce, replacing, old hash: " + oldIdentifierHash +
246
+ " new hash: " + newIdentifierHash);
247
+ }
248
+ return swap;
249
+ });
250
+ }
251
+ if (!this.options.noEvents)
252
+ await unifiedChainEvents.start();
253
+ this.logger.debug("init(): Intialized events: " + chainIdentifier);
254
+ for (let key in wrappers) {
255
+ // this.logger.debug("init(): Initializing "+SwapType[key]+": "+chainIdentifier);
256
+ await wrappers[key].init(this.options.noTimers, this.options.dontCheckPastSwaps);
257
+ }
258
+ })());
259
+ }
260
+ await Promise.all(chainPromises);
261
+ await Promise.all(promises);
262
+ this.logger.debug("init(): Initializing messenger");
263
+ await this.messenger.init();
264
+ }
265
+ /**
266
+ * Initializes the swap storage and loads existing swaps, needs to be called before any other action
267
+ */
268
+ async init() {
269
+ if (this.initialized)
270
+ return;
271
+ if (this.initPromise != null) {
272
+ await this.initPromise;
273
+ return;
274
+ }
275
+ try {
276
+ const promise = this._init();
277
+ this.initPromise = promise;
278
+ await promise;
279
+ delete this.initPromise;
280
+ this.initialized = true;
281
+ }
282
+ catch (e) {
283
+ delete this.initPromise;
284
+ throw e;
285
+ }
286
+ }
287
+ /**
288
+ * Stops listening for onchain events and closes this Swapper instance
289
+ */
290
+ async stop() {
291
+ if (this.initPromise)
292
+ await this.initPromise;
293
+ for (let chainIdentifier in this._chains) {
294
+ const { wrappers, unifiedChainEvents } = this._chains[chainIdentifier];
295
+ for (let key in wrappers) {
296
+ const wrapper = wrappers[key];
297
+ wrapper.events.removeListener("swapState", this.swapStateListener);
298
+ await wrapper.stop();
299
+ }
300
+ await unifiedChainEvents.stop();
301
+ await this.messenger.stop();
302
+ }
303
+ this.initialized = false;
304
+ }
305
+ /**
306
+ * Creates swap & handles intermediary, quote selection
307
+ *
308
+ * @param chainIdentifier
309
+ * @param create Callback to create the
310
+ * @param amountData Amount data as passed to the function
311
+ * @param swapType Swap type of the execution
312
+ * @param maxWaitTimeMS Maximum waiting time after the first intermediary returns the quote
313
+ * @private
314
+ * @throws {Error} when no intermediary was found
315
+ * @throws {Error} if the chain with the provided identifier cannot be found
316
+ */
317
+ async createSwap(chainIdentifier, create, amountData, swapType, maxWaitTimeMS = 2000) {
318
+ if (!this.initialized)
319
+ throw new Error("Swapper not initialized, init first with swapper.init()!");
320
+ if (this._chains[chainIdentifier] == null)
321
+ throw new Error("Invalid chain identifier! Unknown chain: " + chainIdentifier);
322
+ let candidates;
323
+ const inBtc = swapType === SwapType_1.SwapType.TO_BTCLN || swapType === SwapType_1.SwapType.TO_BTC ? !amountData.exactIn : amountData.exactIn;
324
+ if (!inBtc) {
325
+ //Get candidates not based on the amount
326
+ candidates = this.intermediaryDiscovery.getSwapCandidates(chainIdentifier, swapType, amountData.token);
327
+ }
328
+ else {
329
+ candidates = this.intermediaryDiscovery.getSwapCandidates(chainIdentifier, swapType, amountData.token, amountData.amount);
330
+ }
331
+ let swapLimitsChanged = false;
332
+ if (candidates.length === 0) {
333
+ this.logger.warn("createSwap(): No valid intermediary found to execute the swap with, reloading intermediary database...");
334
+ await this.intermediaryDiscovery.reloadIntermediaries();
335
+ swapLimitsChanged = true;
336
+ if (!inBtc) {
337
+ //Get candidates not based on the amount
338
+ candidates = this.intermediaryDiscovery.getSwapCandidates(chainIdentifier, swapType, amountData.token);
339
+ }
340
+ else {
341
+ candidates = this.intermediaryDiscovery.getSwapCandidates(chainIdentifier, swapType, amountData.token, amountData.amount);
342
+ if (candidates.length === 0) {
343
+ const min = this.intermediaryDiscovery.getSwapMinimum(chainIdentifier, swapType, amountData.token);
344
+ const max = this.intermediaryDiscovery.getSwapMaximum(chainIdentifier, swapType, amountData.token);
345
+ if (min != null && max != null) {
346
+ if (amountData.amount < BigInt(min))
347
+ throw new RequestError_1.OutOfBoundsError("Swap amount too low! Try swapping a higher amount.", 200, BigInt(min), BigInt(max));
348
+ if (amountData.amount > BigInt(max))
349
+ throw new RequestError_1.OutOfBoundsError("Swap amount too high! Try swapping a lower amount.", 200, BigInt(min), BigInt(max));
350
+ }
351
+ }
352
+ }
353
+ if (candidates.length === 0)
354
+ throw new Error("No intermediary found for the requested pair and amount! You can try swapping different pair or higher/lower amount.");
355
+ }
356
+ const abortController = new AbortController();
357
+ this.logger.debug("createSwap() Swap candidates: ", candidates.map(lp => lp.url).join());
358
+ const quotePromises = await create(candidates, abortController.signal, this._chains[chainIdentifier]);
359
+ const promiseAll = new Promise((resolve, reject) => {
360
+ let min;
361
+ let max;
362
+ let error;
363
+ let numResolved = 0;
364
+ let quotes = [];
365
+ let timeout;
366
+ quotePromises.forEach(data => {
367
+ data.quote.then(quote => {
368
+ if (numResolved === 0) {
369
+ timeout = setTimeout(() => {
370
+ abortController.abort(new Error("Timed out waiting for quote!"));
371
+ resolve(quotes);
372
+ }, maxWaitTimeMS);
373
+ }
374
+ numResolved++;
375
+ quotes.push({
376
+ quote,
377
+ intermediary: data.intermediary
378
+ });
379
+ if (numResolved === quotePromises.length) {
380
+ clearTimeout(timeout);
381
+ resolve(quotes);
382
+ return;
383
+ }
384
+ }).catch(e => {
385
+ numResolved++;
386
+ if (e instanceof IntermediaryError_1.IntermediaryError) {
387
+ //Blacklist that node
388
+ this.intermediaryDiscovery.removeIntermediary(data.intermediary);
389
+ swapLimitsChanged = true;
390
+ }
391
+ else if (e instanceof RequestError_1.OutOfBoundsError) {
392
+ if (min == null || max == null) {
393
+ min = e.min;
394
+ max = e.max;
395
+ }
396
+ else {
397
+ min = (0, Utils_1.bigIntMin)(min, e.min);
398
+ max = (0, Utils_1.bigIntMax)(max, e.max);
399
+ }
400
+ data.intermediary.swapBounds[swapType] ??= {};
401
+ data.intermediary.swapBounds[swapType][chainIdentifier] ??= {};
402
+ const tokenBoundsData = (data.intermediary.swapBounds[swapType][chainIdentifier][amountData.token] ??= { input: {}, output: {} });
403
+ if (amountData.exactIn) {
404
+ tokenBoundsData.input = { min: e.min, max: e.max };
405
+ }
406
+ else {
407
+ tokenBoundsData.output = { min: e.min, max: e.max };
408
+ }
409
+ swapLimitsChanged = true;
410
+ }
411
+ this.logger.warn("createSwap(): Intermediary " + data.intermediary.url + " error: ", e);
412
+ error = e;
413
+ if (numResolved === quotePromises.length) {
414
+ if (timeout != null)
415
+ clearTimeout(timeout);
416
+ if (quotes.length > 0) {
417
+ resolve(quotes);
418
+ return;
419
+ }
420
+ if (min != null && max != null) {
421
+ let msg = "Swap amount too high or too low! Try swapping a different amount.";
422
+ if (min > amountData.amount)
423
+ msg = "Swap amount too low! Try swapping a higher amount.";
424
+ if (max < amountData.amount)
425
+ msg = "Swap amount too high! Try swapping a lower amount.";
426
+ reject(new RequestError_1.OutOfBoundsError(msg, 400, min, max));
427
+ return;
428
+ }
429
+ reject(error);
430
+ }
431
+ });
432
+ });
433
+ });
434
+ try {
435
+ const quotes = await promiseAll;
436
+ //TODO: Intermediary's reputation is not taken into account!
437
+ quotes.sort((a, b) => {
438
+ if (amountData.exactIn) {
439
+ //Compare outputs
440
+ return (0, Utils_1.bigIntCompare)(b.quote.getOutput().rawAmount, a.quote.getOutput().rawAmount);
441
+ }
442
+ else {
443
+ //Compare inputs
444
+ return (0, Utils_1.bigIntCompare)(a.quote.getInput().rawAmount, b.quote.getInput().rawAmount);
445
+ }
446
+ });
447
+ this.logger.debug("createSwap(): Sorted quotes, best price to worst: ", quotes);
448
+ if (swapLimitsChanged)
449
+ this.emit("swapLimitsChanged");
450
+ const quote = quotes[0].quote;
451
+ await quote._save();
452
+ return quote;
453
+ }
454
+ catch (e) {
455
+ if (swapLimitsChanged)
456
+ this.emit("swapLimitsChanged");
457
+ throw e;
458
+ }
459
+ }
460
+ /**
461
+ * Creates Smart chain -> Bitcoin ({@link SwapType.TO_BTC}) swap
462
+ *
463
+ * @param chainIdentifier Chain identifier string of the source smart chain
464
+ * @param signer Signer's address on the source chain
465
+ * @param tokenAddress Token address to pay with
466
+ * @param address Recipient's bitcoin address
467
+ * @param amount Amount to send in token based units (if `exactIn=true`) or receive in satoshis (if `exactIn=false`)
468
+ * @param exactIn Whether to use exact in instead of exact out
469
+ * @param additionalParams Additional parameters sent to the LP when creating the swap
470
+ * @param options Additional options for the swap
471
+ */
472
+ createToBTCSwap(chainIdentifier, signer, tokenAddress, address, amount, exactIn = false, additionalParams = this.options.defaultAdditionalParameters, options) {
473
+ if (this._chains[chainIdentifier] == null)
474
+ throw new Error("Invalid chain identifier! Unknown chain: " + chainIdentifier);
475
+ if (address.startsWith("bitcoin:")) {
476
+ address = address.substring(8).split("?")[0];
477
+ }
478
+ if (!this.Utils.isValidBitcoinAddress(address))
479
+ throw new Error("Invalid bitcoin address");
480
+ if (!this._chains[chainIdentifier].chainInterface.isValidAddress(signer, true))
481
+ throw new Error("Invalid " + chainIdentifier + " address");
482
+ signer = this._chains[chainIdentifier].chainInterface.normalizeAddress(signer);
483
+ const amountData = {
484
+ amount,
485
+ token: tokenAddress,
486
+ exactIn
487
+ };
488
+ return this.createSwap(chainIdentifier, (candidates, abortSignal, chain) => Promise.resolve(chain.wrappers[SwapType_1.SwapType.TO_BTC].create(signer, address, amountData, candidates, options, additionalParams, abortSignal)), amountData, SwapType_1.SwapType.TO_BTC);
489
+ }
490
+ /**
491
+ * Creates Smart chain -> Bitcoin Lightning ({@link SwapType.TO_BTCLN}) swap
492
+ *
493
+ * @param chainIdentifier Chain identifier string of the source smart chain
494
+ * @param signer Signer's address on the source chain
495
+ * @param tokenAddress Token address to pay with
496
+ * @param paymentRequest BOLT11 lightning network invoice to be paid (needs to have a fixed amount), and the swap
497
+ * amount is taken from this fixed amount, hence only exact output swaps are supported
498
+ * @param additionalParams Additional parameters sent to the LP when creating the swap
499
+ * @param options Additional options for the swap
500
+ */
501
+ async createToBTCLNSwap(chainIdentifier, signer, tokenAddress, paymentRequest, additionalParams = this.options.defaultAdditionalParameters, options) {
502
+ if (this._chains[chainIdentifier] == null)
503
+ throw new Error("Invalid chain identifier! Unknown chain: " + chainIdentifier);
504
+ if (paymentRequest.startsWith("lightning:"))
505
+ paymentRequest = paymentRequest.substring(10);
506
+ if (!this.Utils.isValidLightningInvoice(paymentRequest))
507
+ throw new Error("Invalid lightning network invoice");
508
+ if (!this._chains[chainIdentifier].chainInterface.isValidAddress(signer, true))
509
+ throw new Error("Invalid " + chainIdentifier + " address");
510
+ signer = this._chains[chainIdentifier].chainInterface.normalizeAddress(signer);
511
+ const parsedPR = (0, bolt11_1.decode)(paymentRequest);
512
+ if (parsedPR.millisatoshis == null)
513
+ throw new Error("Invalid lightning network invoice, no msat value field!");
514
+ const amountData = {
515
+ amount: (BigInt(parsedPR.millisatoshis) + 999n) / 1000n,
516
+ token: tokenAddress,
517
+ exactIn: false
518
+ };
519
+ return this.createSwap(chainIdentifier, (candidates, abortSignal, chain) => chain.wrappers[SwapType_1.SwapType.TO_BTCLN].create(signer, paymentRequest, amountData, candidates, options, additionalParams, abortSignal), amountData, SwapType_1.SwapType.TO_BTCLN);
520
+ }
521
+ /**
522
+ * Creates Smart chain -> Bitcoin Lightning ({@link SwapType.TO_BTCLN}) swap via LNURL-pay link
523
+ *
524
+ * @param chainIdentifier Chain identifier string of the source smart chain
525
+ * @param signer Signer's address on the source chain
526
+ * @param tokenAddress Token address to pay with
527
+ * @param lnurlPay LNURL-pay link to use for the payment
528
+ * @param amount Amount to send in token based units (if `exactIn=true`) or receive in satoshis (if `exactIn=false`)
529
+ * @param exactIn Whether to do an exact in swap instead of exact out
530
+ * @param additionalParams Additional parameters sent to the LP when creating the swap
531
+ * @param options Additional options for the swap
532
+ */
533
+ async createToBTCLNSwapViaLNURL(chainIdentifier, signer, tokenAddress, lnurlPay, amount, exactIn = false, additionalParams = this.options.defaultAdditionalParameters, options) {
534
+ if (this._chains[chainIdentifier] == null)
535
+ throw new Error("Invalid chain identifier! Unknown chain: " + chainIdentifier);
536
+ if (typeof (lnurlPay) === "string" && !this.Utils.isValidLNURL(lnurlPay))
537
+ throw new Error("Invalid LNURL-pay link");
538
+ if (!this._chains[chainIdentifier].chainInterface.isValidAddress(signer, true))
539
+ throw new Error("Invalid " + chainIdentifier + " address");
540
+ signer = this._chains[chainIdentifier].chainInterface.normalizeAddress(signer);
541
+ const amountData = {
542
+ amount,
543
+ token: tokenAddress,
544
+ exactIn
545
+ };
546
+ return this.createSwap(chainIdentifier, (candidates, abortSignal, chain) => chain.wrappers[SwapType_1.SwapType.TO_BTCLN].createViaLNURL(signer, typeof (lnurlPay) === "string" ? (lnurlPay.startsWith("lightning:") ? lnurlPay.substring(10) : lnurlPay) : lnurlPay.params, amountData, candidates, options, additionalParams, abortSignal), amountData, SwapType_1.SwapType.TO_BTCLN);
547
+ }
548
+ /**
549
+ * Creates Smart chain -> Bitcoin Lightning ({@link SwapType.TO_BTCLN}) swap via {@link LightningInvoiceCreateService}
550
+ *
551
+ * @param chainIdentifier Chain identifier string of the source smart chain
552
+ * @param signer Signer's address on the source chain
553
+ * @param tokenAddress Token address to pay with
554
+ * @param service Invoice create service object which facilitates the creation of fixed amount LN invoices
555
+ * @param amount Amount to send in token based units (if `exactIn=true`) or receive in satoshis (if `exactIn=false`)
556
+ * @param exactIn Whether to do an exact in swap instead of exact out
557
+ * @param additionalParams Additional parameters sent to the LP when creating the swap
558
+ * @param options Additional options for the swap
559
+ */
560
+ async createToBTCLNSwapViaInvoiceCreateService(chainIdentifier, signer, tokenAddress, service, amount, exactIn = false, additionalParams = this.options.defaultAdditionalParameters, options) {
561
+ if (this._chains[chainIdentifier] == null)
562
+ throw new Error("Invalid chain identifier! Unknown chain: " + chainIdentifier);
563
+ if (!this._chains[chainIdentifier].chainInterface.isValidAddress(signer, true))
564
+ throw new Error("Invalid " + chainIdentifier + " address");
565
+ signer = this._chains[chainIdentifier].chainInterface.normalizeAddress(signer);
566
+ const amountData = {
567
+ amount,
568
+ token: tokenAddress,
569
+ exactIn
570
+ };
571
+ return this.createSwap(chainIdentifier, (candidates, abortSignal, chain) => chain.wrappers[SwapType_1.SwapType.TO_BTCLN].createViaInvoiceCreateService(signer, Promise.resolve(service), amountData, candidates, options, additionalParams, abortSignal), amountData, SwapType_1.SwapType.TO_BTCLN);
572
+ }
573
+ /**
574
+ * Creates Bitcoin -> Smart chain ({@link SwapType.SPV_VAULT_FROM_BTC}) swap
575
+ *
576
+ * @param chainIdentifier Chain identifier string of the destination smart chain
577
+ * @param recipient Recipient address on the destination chain
578
+ * @param tokenAddress Token address to receive
579
+ * @param amount Amount to send in satoshis (if `exactOut=false`) or receive in token based units (if `exactOut=true`)
580
+ * @param exactOut Whether to use a exact out instead of exact in
581
+ * @param additionalParams Additional parameters sent to the LP when creating the swap
582
+ * @param options Additional options for the swap
583
+ */
584
+ async createFromBTCSwapNew(chainIdentifier, recipient, tokenAddress, amount, exactOut = false, additionalParams = this.options.defaultAdditionalParameters, options) {
585
+ if (this._chains[chainIdentifier] == null)
586
+ throw new Error("Invalid chain identifier! Unknown chain: " + chainIdentifier);
587
+ if (!this._chains[chainIdentifier].chainInterface.isValidAddress(recipient, true))
588
+ throw new Error("Invalid " + chainIdentifier + " address");
589
+ recipient = this._chains[chainIdentifier].chainInterface.normalizeAddress(recipient);
590
+ const amountData = {
591
+ amount,
592
+ token: tokenAddress,
593
+ exactIn: !exactOut
594
+ };
595
+ return this.createSwap(chainIdentifier, (candidates, abortSignal, chain) => Promise.resolve(chain.wrappers[SwapType_1.SwapType.SPV_VAULT_FROM_BTC].create(recipient, amountData, candidates, options, additionalParams, abortSignal)), amountData, SwapType_1.SwapType.SPV_VAULT_FROM_BTC);
596
+ }
597
+ /**
598
+ * Creates LEGACY Bitcoin -> Smart chain ({@link SwapType.FROM_BTC}) swap
599
+ *
600
+ * @param chainIdentifier Chain identifier string of the destination smart chain
601
+ * @param recipient Recipient address on the destination chain
602
+ * @param tokenAddress Token address to receive
603
+ * @param amount Amount to send in satoshis (if `exactOut=false`) or receive in token based units (if `exactOut=true`)
604
+ * @param exactOut Whether to use a exact out instead of exact in
605
+ * @param additionalParams Additional parameters sent to the LP when creating the swap
606
+ * @param options Additional options for the swap
607
+ */
608
+ async createFromBTCSwap(chainIdentifier, recipient, tokenAddress, amount, exactOut = false, additionalParams = this.options.defaultAdditionalParameters, options) {
609
+ if (this._chains[chainIdentifier] == null)
610
+ throw new Error("Invalid chain identifier! Unknown chain: " + chainIdentifier);
611
+ if (!this._chains[chainIdentifier].chainInterface.isValidAddress(recipient, true))
612
+ throw new Error("Invalid " + chainIdentifier + " address");
613
+ recipient = this._chains[chainIdentifier].chainInterface.normalizeAddress(recipient);
614
+ const amountData = {
615
+ amount,
616
+ token: tokenAddress,
617
+ exactIn: !exactOut
618
+ };
619
+ return this.createSwap(chainIdentifier, (candidates, abortSignal, chain) => Promise.resolve(chain.wrappers[SwapType_1.SwapType.FROM_BTC].create(recipient, amountData, candidates, options, additionalParams, abortSignal)), amountData, SwapType_1.SwapType.FROM_BTC);
620
+ }
621
+ /**
622
+ * Creates LEGACY Bitcoin Lightning -> Smart chain ({@link SwapType.FROM_BTCLN}) swap
623
+ *
624
+ * @param chainIdentifier Chain identifier string of the destination smart chain
625
+ * @param recipient Recipient address on the destination chain
626
+ * @param tokenAddress Token address to receive
627
+ * @param amount Amount to send in satoshis (if `exactOut=false`) or receive in token based units (if `exactOut=true`)
628
+ * @param exactOut Whether to use a exact out instead of exact in
629
+ * @param additionalParams Additional parameters sent to the LP when creating the swap
630
+ * @param options Additional options for the swap
631
+ */
632
+ async createFromBTCLNSwap(chainIdentifier, recipient, tokenAddress, amount, exactOut = false, additionalParams = this.options.defaultAdditionalParameters, options) {
633
+ if (this._chains[chainIdentifier] == null)
634
+ throw new Error("Invalid chain identifier! Unknown chain: " + chainIdentifier);
635
+ if (!this._chains[chainIdentifier].chainInterface.isValidAddress(recipient, true))
636
+ throw new Error("Invalid " + chainIdentifier + " address");
637
+ recipient = this._chains[chainIdentifier].chainInterface.normalizeAddress(recipient);
638
+ const amountData = {
639
+ amount,
640
+ token: tokenAddress,
641
+ exactIn: !exactOut
642
+ };
643
+ return this.createSwap(chainIdentifier, (candidates, abortSignal, chain) => Promise.resolve(chain.wrappers[SwapType_1.SwapType.FROM_BTCLN].create(recipient, amountData, candidates, options, additionalParams, abortSignal)), amountData, SwapType_1.SwapType.FROM_BTCLN);
644
+ }
645
+ /**
646
+ * Creates LEGACY Bitcoin Lightning -> Smart chain ({@link SwapType.FROM_BTCLN}) swap, withdrawing from
647
+ * an LNURL-withdraw link
648
+ *
649
+ * @param chainIdentifier Chain identifier string of the destination smart chain
650
+ * @param recipient Recipient address on the destination chain
651
+ * @param tokenAddress Token address to receive
652
+ * @param lnurl LNURL-withdraw link to pull the funds from
653
+ * @param amount Amount to send in satoshis (if `exactOut=false`) or receive in token based units (if `exactOut=true`)
654
+ * @param exactOut Whether to use a exact out instead of exact in
655
+ * @param additionalParams Additional parameters sent to the LP when creating the swap
656
+ * @param options Additional options for the swap
657
+ */
658
+ async createFromBTCLNSwapViaLNURL(chainIdentifier, recipient, tokenAddress, lnurl, amount, exactOut = false, additionalParams = this.options.defaultAdditionalParameters, options) {
659
+ if (this._chains[chainIdentifier] == null)
660
+ throw new Error("Invalid chain identifier! Unknown chain: " + chainIdentifier);
661
+ if (typeof (lnurl) === "string" && !this.Utils.isValidLNURL(lnurl))
662
+ throw new Error("Invalid LNURL-withdraw link");
663
+ if (!this._chains[chainIdentifier].chainInterface.isValidAddress(recipient, true))
664
+ throw new Error("Invalid " + chainIdentifier + " address");
665
+ recipient = this._chains[chainIdentifier].chainInterface.normalizeAddress(recipient);
666
+ const amountData = {
667
+ amount,
668
+ token: tokenAddress,
669
+ exactIn: !exactOut
670
+ };
671
+ return this.createSwap(chainIdentifier, (candidates, abortSignal, chain) => chain.wrappers[SwapType_1.SwapType.FROM_BTCLN].createViaLNURL(recipient, typeof (lnurl) === "string" ? (lnurl.startsWith("lightning:") ? lnurl.substring(10) : lnurl) : lnurl.params, amountData, candidates, options, additionalParams, abortSignal), amountData, SwapType_1.SwapType.FROM_BTCLN);
672
+ }
673
+ /**
674
+ * Creates Bitcoin Lightning -> Smart chain ({@link SwapType.FROM_BTCLN_AUTO}) swap
675
+ *
676
+ * @param chainIdentifier Chain identifier string of the destination smart chain
677
+ * @param recipient Recipient address on the destination chain
678
+ * @param tokenAddress Token address to receive
679
+ * @param amount Amount to send in satoshis (if `exactOut=false`) or receive in token based units (if `exactOut=true`)
680
+ * @param exactOut Whether to use a exact out instead of exact in
681
+ * @param additionalParams Additional parameters sent to the LP when creating the swap
682
+ * @param options Additional options for the swap
683
+ */
684
+ async createFromBTCLNSwapNew(chainIdentifier, recipient, tokenAddress, amount, exactOut = false, additionalParams = this.options.defaultAdditionalParameters, options) {
685
+ if (this._chains[chainIdentifier] == null)
686
+ throw new Error("Invalid chain identifier! Unknown chain: " + chainIdentifier);
687
+ if (!this._chains[chainIdentifier].chainInterface.isValidAddress(recipient, true))
688
+ throw new Error("Invalid " + chainIdentifier + " address");
689
+ recipient = this._chains[chainIdentifier].chainInterface.normalizeAddress(recipient);
690
+ const amountData = {
691
+ amount,
692
+ token: tokenAddress,
693
+ exactIn: !exactOut
694
+ };
695
+ return this.createSwap(chainIdentifier, (candidates, abortSignal, chain) => Promise.resolve(chain.wrappers[SwapType_1.SwapType.FROM_BTCLN_AUTO].create(recipient, amountData, candidates, options, additionalParams, abortSignal)), amountData, SwapType_1.SwapType.FROM_BTCLN_AUTO);
696
+ }
697
+ /**
698
+ * Creates Bitcoin Lightning -> Smart chain ({@link SwapType.FROM_BTCLN_AUTO}) swap, withdrawing from
699
+ * an LNURL-withdraw link
700
+ *
701
+ * @param chainIdentifier Chain identifier string of the destination smart chain
702
+ * @param recipient Recipient address on the destination chain
703
+ * @param tokenAddress Token address to receive
704
+ * @param lnurl LNURL-withdraw link to pull the funds from
705
+ * @param amount Amount to send in satoshis (if `exactOut=false`) or receive in token based units (if `exactOut=true`)
706
+ * @param exactOut Whether to use a exact out instead of exact in
707
+ * @param additionalParams Additional parameters sent to the LP when creating the swap
708
+ * @param options Additional options for the swap
709
+ */
710
+ async createFromBTCLNSwapNewViaLNURL(chainIdentifier, recipient, tokenAddress, lnurl, amount, exactOut = false, additionalParams = this.options.defaultAdditionalParameters, options) {
711
+ if (this._chains[chainIdentifier] == null)
712
+ throw new Error("Invalid chain identifier! Unknown chain: " + chainIdentifier);
713
+ if (typeof (lnurl) === "string" && !this.Utils.isValidLNURL(lnurl))
714
+ throw new Error("Invalid LNURL-withdraw link");
715
+ if (!this._chains[chainIdentifier].chainInterface.isValidAddress(recipient, true))
716
+ throw new Error("Invalid " + chainIdentifier + " address");
717
+ recipient = this._chains[chainIdentifier].chainInterface.normalizeAddress(recipient);
718
+ const amountData = {
719
+ amount,
720
+ token: tokenAddress,
721
+ exactIn: !exactOut
722
+ };
723
+ return this.createSwap(chainIdentifier, (candidates, abortSignal, chain) => chain.wrappers[SwapType_1.SwapType.FROM_BTCLN_AUTO].createViaLNURL(recipient, typeof (lnurl) === "string" ? (lnurl.startsWith("lightning:") ? lnurl.substring(10) : lnurl) : lnurl.params, amountData, candidates, options, additionalParams, abortSignal), amountData, SwapType_1.SwapType.FROM_BTCLN_AUTO);
724
+ }
725
+ /**
726
+ * Creates a trusted Bitcoin Lightning -> Smart chain ({@link SwapType.TRUSTED_FROM_BTCLN}) gas swap
727
+ *
728
+ * @param chainIdentifier Chain identifier string of the destination smart chain
729
+ * @param recipient Recipient address on the destination chain
730
+ * @param amount Amount of native token to receive, in base units
731
+ * @param trustedIntermediaryOrUrl URL or Intermediary object of the trusted intermediary to use, otherwise uses default
732
+ * @throws {Error} If no trusted intermediary specified
733
+ */
734
+ async createTrustedLNForGasSwap(chainIdentifier, recipient, amount, trustedIntermediaryOrUrl) {
735
+ if (this._chains[chainIdentifier] == null)
736
+ throw new Error("Invalid chain identifier! Unknown chain: " + chainIdentifier);
737
+ if (!this._chains[chainIdentifier].chainInterface.isValidAddress(recipient, true))
738
+ throw new Error("Invalid " + chainIdentifier + " address");
739
+ recipient = this._chains[chainIdentifier].chainInterface.normalizeAddress(recipient);
740
+ const useUrl = trustedIntermediaryOrUrl ?? this.defaultTrustedIntermediary ?? this.options.defaultTrustedIntermediaryUrl;
741
+ if (useUrl == null)
742
+ throw new Error("No trusted intermediary specified!");
743
+ const swap = await this._chains[chainIdentifier].wrappers[SwapType_1.SwapType.TRUSTED_FROM_BTCLN].create(recipient, amount, useUrl);
744
+ await swap._save();
745
+ return swap;
746
+ }
747
+ /**
748
+ * Creates a trusted Bitcoin -> Smart chain ({@link SwapType.TRUSTED_FROM_BTC}) gas swap
749
+ *
750
+ * @param chainIdentifier Chain identifier string of the destination smart chain
751
+ * @param recipient Recipient address on the destination chain
752
+ * @param amount Amount of native token to receive, in base units
753
+ * @param refundAddress Bitcoin refund address, in case the swap fails the funds are refunded here
754
+ * @param trustedIntermediaryOrUrl URL or Intermediary object of the trusted intermediary to use, otherwise uses default
755
+ * @throws {Error} If no trusted intermediary specified
756
+ */
757
+ async createTrustedOnchainForGasSwap(chainIdentifier, recipient, amount, refundAddress, trustedIntermediaryOrUrl) {
758
+ if (this._chains[chainIdentifier] == null)
759
+ throw new Error("Invalid chain identifier! Unknown chain: " + chainIdentifier);
760
+ if (!this._chains[chainIdentifier].chainInterface.isValidAddress(recipient, true))
761
+ throw new Error("Invalid " + chainIdentifier + " address");
762
+ recipient = this._chains[chainIdentifier].chainInterface.normalizeAddress(recipient);
763
+ const useUrl = trustedIntermediaryOrUrl ?? this.defaultTrustedIntermediary ?? this.options.defaultTrustedIntermediaryUrl;
764
+ if (useUrl == null)
765
+ throw new Error("No trusted intermediary specified!");
766
+ const swap = await this._chains[chainIdentifier].wrappers[SwapType_1.SwapType.TRUSTED_FROM_BTC].create(recipient, amount, useUrl, refundAddress);
767
+ await swap._save();
768
+ return swap;
769
+ }
770
+ /**
771
+ * Creates a swap from srcToken to dstToken, of a specific token amount, either specifying input amount (exactIn=true)
772
+ * or output amount (exactIn=false), NOTE: For regular -> BTC-LN (lightning) swaps the passed amount is ignored and
773
+ * invoice's pre-set amount is used instead.
774
+ * @deprecated Use {@link swap} instead
775
+ *
776
+ * @param signer Smartchain (Solana, Starknet, etc.) address of the user
777
+ * @param srcToken Source token of the swap, user pays this token
778
+ * @param dstToken Destination token of the swap, user receives this token
779
+ * @param amount Amount of the swap
780
+ * @param exactIn Whether the amount specified is an input amount (exactIn=true) or an output amount (exactIn=false)
781
+ * @param addressLnurlLightningInvoice Bitcoin on-chain address, lightning invoice, LNURL-pay to pay or
782
+ * LNURL-withdrawal to withdraw money from
783
+ */
784
+ create(signer, srcToken, dstToken, amount, exactIn, addressLnurlLightningInvoice) {
785
+ if (srcToken.chain === "BTC") {
786
+ return this.swap(srcToken, dstToken, amount, exactIn, addressLnurlLightningInvoice, signer);
787
+ }
788
+ else {
789
+ return this.swap(srcToken, dstToken, amount, exactIn, signer, addressLnurlLightningInvoice);
790
+ }
791
+ }
792
+ /**
793
+ * Creates a swap from srcToken to dstToken, of a specific token amount, either specifying input amount (if `exactIn=true`)
794
+ * or output amount (if `exactIn=false`), NOTE: For regular Smart chain -> BTC-LN (lightning) swaps the passed amount is ignored and
795
+ * invoice's pre-set amount is used instead, use LNURL-pay links for dynamic amounts
796
+ *
797
+ * @param _srcToken Source token of the swap, user pays this token
798
+ * @param _dstToken Destination token of the swap, user receives this token
799
+ * @param _amount Amount of the swap either in base units as {bigint} or in human readable format (with decimals) as {string}
800
+ * @param exactIn Whether the amount specified is an input amount (exactIn=true) or an output amount (exactIn=false)
801
+ * @param src Source wallet/lnurl-withdraw of the swap
802
+ * @param dst Destination smart chain address, bitcoin on-chain address, lightning invoice, LNURL-pay
803
+ * @param options Options for the swap
804
+ */
805
+ swap(_srcToken, _dstToken, _amount, exactIn, src, dst, options) {
806
+ const srcToken = typeof (_srcToken) === "string" ? this.getToken(_srcToken) : _srcToken;
807
+ const dstToken = typeof (_dstToken) === "string" ? this.getToken(_dstToken) : _dstToken;
808
+ const amount = _amount == null ? null : (typeof (_amount) === "bigint" ? _amount : (0, Utils_1.fromDecimal)(_amount, exactIn ? srcToken.decimals : dstToken.decimals));
809
+ if ((0, Token_1.isBtcToken)(srcToken)) {
810
+ if ((0, Token_1.isSCToken)(dstToken)) {
811
+ if (typeof (dst) !== "string")
812
+ throw new Error("Destination for BTC/BTC-LN -> smart chain swaps must be a smart chain address!");
813
+ if (amount == null)
814
+ throw new Error("Amount cannot be null for from btc swaps!");
815
+ if (srcToken.lightning) {
816
+ //FROM_BTCLN
817
+ if (src != null) {
818
+ if (typeof (src) !== "string" && !(0, LNURLWithdraw_1.isLNURLWithdraw)(src))
819
+ throw new Error("LNURL must be a string or LNURLWithdraw object!");
820
+ return this.supportsSwapType(dstToken.chainId, SwapType_1.SwapType.FROM_BTCLN_AUTO) ?
821
+ this.createFromBTCLNSwapNewViaLNURL(dstToken.chainId, dst, dstToken.address, src, amount, !exactIn, undefined, options) :
822
+ this.createFromBTCLNSwapViaLNURL(dstToken.chainId, dst, dstToken.address, src, amount, !exactIn, undefined, options);
823
+ }
824
+ else {
825
+ return this.supportsSwapType(dstToken.chainId, SwapType_1.SwapType.FROM_BTCLN_AUTO) ?
826
+ this.createFromBTCLNSwapNew(dstToken.chainId, dst, dstToken.address, amount, !exactIn, undefined, options) :
827
+ this.createFromBTCLNSwap(dstToken.chainId, dst, dstToken.address, amount, !exactIn, undefined, options);
828
+ }
829
+ }
830
+ else {
831
+ //FROM_BTC
832
+ if (this.supportsSwapType(dstToken.chainId, SwapType_1.SwapType.SPV_VAULT_FROM_BTC)) {
833
+ return this.createFromBTCSwapNew(dstToken.chainId, dst, dstToken.address, amount, !exactIn, undefined, options);
834
+ }
835
+ else {
836
+ return this.createFromBTCSwap(dstToken.chainId, dst, dstToken.address, amount, !exactIn, undefined, options);
837
+ }
838
+ }
839
+ }
840
+ }
841
+ else if ((0, Token_1.isSCToken)(srcToken)) {
842
+ if ((0, Token_1.isBtcToken)(dstToken)) {
843
+ if (typeof (src) !== "string")
844
+ throw new Error("Source address for BTC/BTC-LN -> smart chain swaps must be a smart chain address!");
845
+ if (dstToken.lightning) {
846
+ //TO_BTCLN
847
+ if (typeof (dst) !== "string" && !(0, LNURLPay_1.isLNURLPay)(dst))
848
+ throw new Error("Destination LNURL link/lightning invoice must be a string or LNURLPay object!");
849
+ if ((0, LNURLPay_1.isLNURLPay)(dst) || this.Utils.isValidLNURL(dst)) {
850
+ if (amount == null)
851
+ throw new Error("Amount cannot be null for to btcln swaps via LNURL-pay!");
852
+ return this.createToBTCLNSwapViaLNURL(srcToken.chainId, src, srcToken.address, dst, amount, !!exactIn, undefined, options);
853
+ }
854
+ else if ((0, LightningInvoiceCreateService_1.isLightningInvoiceCreateService)(dst)) {
855
+ if (amount == null)
856
+ throw new Error("Amount cannot be null for to btcln swaps via InvoiceCreateService!");
857
+ return this.createToBTCLNSwapViaInvoiceCreateService(srcToken.chainId, src, srcToken.address, dst, amount, !!exactIn, undefined, options);
858
+ }
859
+ else if (this.Utils.isLightningInvoice(dst)) {
860
+ if (!this.Utils.isValidLightningInvoice(dst))
861
+ throw new Error("Invalid lightning invoice specified, lightning invoice MUST contain pre-set amount!");
862
+ if (exactIn)
863
+ throw new Error("Only exact out swaps are possible with lightning invoices, use LNURL links for exact in lightning swaps!");
864
+ return this.createToBTCLNSwap(srcToken.chainId, src, srcToken.address, dst, undefined, options);
865
+ }
866
+ else {
867
+ throw new Error("Supplied parameter is not LNURL link nor lightning invoice (bolt11)!");
868
+ }
869
+ }
870
+ else {
871
+ //TO_BTC
872
+ if (typeof (dst) !== "string")
873
+ throw new Error("Destination bitcoin address must be a string!");
874
+ if (amount == null)
875
+ throw new Error("Amount cannot be null for to btc swaps!");
876
+ return this.createToBTCSwap(srcToken.chainId, src, srcToken.address, dst, amount, !!exactIn, undefined, options);
877
+ }
878
+ }
879
+ }
880
+ throw new Error("Unsupported swap type");
881
+ }
882
+ async getAllSwaps(chainId, signer) {
883
+ const queryParams = [];
884
+ if (signer != null)
885
+ queryParams.push({ key: "initiator", value: signer });
886
+ if (chainId == null) {
887
+ const res = await Promise.all(Object.keys(this._chains).map((chainId) => {
888
+ const { unifiedSwapStorage, reviver } = this._chains[chainId];
889
+ return unifiedSwapStorage.query([queryParams], reviver);
890
+ }));
891
+ return res.flat();
892
+ }
893
+ else {
894
+ const { unifiedSwapStorage, reviver } = this._chains[chainId];
895
+ return await unifiedSwapStorage.query([queryParams], reviver);
896
+ }
897
+ }
898
+ async getActionableSwaps(chainId, signer) {
899
+ if (chainId == null) {
900
+ const res = await Promise.all(Object.keys(this._chains).map((chainId) => {
901
+ const { unifiedSwapStorage, reviver, wrappers } = this._chains[chainId];
902
+ const queryParams = [];
903
+ for (let key in wrappers) {
904
+ const wrapper = wrappers[key];
905
+ const swapTypeQueryParams = [{ key: "type", value: wrapper.TYPE }];
906
+ if (signer != null)
907
+ swapTypeQueryParams.push({ key: "initiator", value: signer });
908
+ swapTypeQueryParams.push({ key: "state", value: wrapper._pendingSwapStates });
909
+ queryParams.push(swapTypeQueryParams);
910
+ }
911
+ return unifiedSwapStorage.query(queryParams, reviver);
912
+ }));
913
+ return res.flat().filter(swap => swap.requiresAction());
914
+ }
915
+ else {
916
+ const { unifiedSwapStorage, reviver, wrappers } = this._chains[chainId];
917
+ const queryParams = [];
918
+ for (let key in wrappers) {
919
+ const wrapper = wrappers[key];
920
+ const swapTypeQueryParams = [{ key: "type", value: wrapper.TYPE }];
921
+ if (signer != null)
922
+ swapTypeQueryParams.push({ key: "initiator", value: signer });
923
+ swapTypeQueryParams.push({ key: "state", value: wrapper._pendingSwapStates });
924
+ queryParams.push(swapTypeQueryParams);
925
+ }
926
+ return (await unifiedSwapStorage.query(queryParams, reviver)).filter(swap => swap.requiresAction());
927
+ }
928
+ }
929
+ async getRefundableSwaps(chainId, signer) {
930
+ if (chainId == null) {
931
+ const res = await Promise.all(Object.keys(this._chains).map((chainId) => {
932
+ const { unifiedSwapStorage, reviver, wrappers } = this._chains[chainId];
933
+ const queryParams = [];
934
+ for (let wrapper of [wrappers[SwapType_1.SwapType.TO_BTCLN], wrappers[SwapType_1.SwapType.TO_BTC]]) {
935
+ const swapTypeQueryParams = [{ key: "type", value: wrapper.TYPE }];
936
+ if (signer != null)
937
+ swapTypeQueryParams.push({ key: "initiator", value: signer });
938
+ swapTypeQueryParams.push({ key: "state", value: wrapper._refundableSwapStates });
939
+ queryParams.push(swapTypeQueryParams);
940
+ }
941
+ return unifiedSwapStorage.query(queryParams, reviver);
942
+ }));
943
+ return res.flat().filter(swap => swap.isRefundable());
944
+ }
945
+ else {
946
+ const { unifiedSwapStorage, reviver, wrappers } = this._chains[chainId];
947
+ const queryParams = [];
948
+ for (let wrapper of [wrappers[SwapType_1.SwapType.TO_BTCLN], wrappers[SwapType_1.SwapType.TO_BTC]]) {
949
+ const swapTypeQueryParams = [{ key: "type", value: wrapper.TYPE }];
950
+ if (signer != null)
951
+ swapTypeQueryParams.push({ key: "initiator", value: signer });
952
+ swapTypeQueryParams.push({ key: "state", value: wrapper._refundableSwapStates });
953
+ queryParams.push(swapTypeQueryParams);
954
+ }
955
+ const result = await unifiedSwapStorage.query(queryParams, reviver);
956
+ return result.filter(swap => swap.isRefundable());
957
+ }
958
+ }
959
+ async getClaimableSwaps(chainId, signer) {
960
+ if (chainId == null) {
961
+ const res = await Promise.all(Object.keys(this._chains).map((chainId) => {
962
+ const { unifiedSwapStorage, reviver, wrappers } = this._chains[chainId];
963
+ const queryParams = [];
964
+ for (let wrapper of [wrappers[SwapType_1.SwapType.FROM_BTC], wrappers[SwapType_1.SwapType.FROM_BTCLN], wrappers[SwapType_1.SwapType.SPV_VAULT_FROM_BTC], wrappers[SwapType_1.SwapType.FROM_BTCLN_AUTO]]) {
965
+ if (wrapper == null)
966
+ continue;
967
+ const swapTypeQueryParams = [{ key: "type", value: wrapper.TYPE }];
968
+ if (signer != null)
969
+ swapTypeQueryParams.push({ key: "initiator", value: signer });
970
+ swapTypeQueryParams.push({ key: "state", value: wrapper._claimableSwapStates });
971
+ queryParams.push(swapTypeQueryParams);
972
+ }
973
+ return unifiedSwapStorage.query(queryParams, reviver);
974
+ }));
975
+ return res.flat().filter(swap => swap.isClaimable());
976
+ }
977
+ else {
978
+ const { unifiedSwapStorage, reviver, wrappers } = this._chains[chainId];
979
+ const queryParams = [];
980
+ for (let wrapper of [wrappers[SwapType_1.SwapType.FROM_BTC], wrappers[SwapType_1.SwapType.FROM_BTCLN], wrappers[SwapType_1.SwapType.SPV_VAULT_FROM_BTC], wrappers[SwapType_1.SwapType.FROM_BTCLN_AUTO]]) {
981
+ if (wrapper == null)
982
+ continue;
983
+ const swapTypeQueryParams = [{ key: "type", value: wrapper.TYPE }];
984
+ if (signer != null)
985
+ swapTypeQueryParams.push({ key: "initiator", value: signer });
986
+ swapTypeQueryParams.push({ key: "state", value: wrapper._claimableSwapStates });
987
+ queryParams.push(swapTypeQueryParams);
988
+ }
989
+ const result = await unifiedSwapStorage.query(queryParams, reviver);
990
+ return result.filter(swap => swap.isClaimable());
991
+ }
992
+ }
993
+ async getSwapById(id, chainId, signer) {
994
+ //Check in pending swaps first
995
+ if (chainId != null) {
996
+ for (let key in this._chains[chainId].wrappers) {
997
+ const wrapper = this._chains[chainId].wrappers[key];
998
+ const result = wrapper._getPendingSwap(id);
999
+ if (result != null) {
1000
+ if (signer != null) {
1001
+ if (result._getInitiator() === signer)
1002
+ return result;
1003
+ }
1004
+ else {
1005
+ return result;
1006
+ }
1007
+ }
1008
+ }
1009
+ }
1010
+ else {
1011
+ for (let chainId in this._chains) {
1012
+ for (let key in this._chains[chainId].wrappers) {
1013
+ const wrapper = this._chains[chainId].wrappers[key];
1014
+ const result = wrapper._getPendingSwap(id);
1015
+ if (result != null) {
1016
+ if (signer != null) {
1017
+ if (result._getInitiator() === signer)
1018
+ return result;
1019
+ }
1020
+ else {
1021
+ return result;
1022
+ }
1023
+ }
1024
+ }
1025
+ }
1026
+ }
1027
+ const queryParams = [];
1028
+ if (signer != null)
1029
+ queryParams.push({ key: "initiator", value: signer });
1030
+ queryParams.push({ key: "id", value: id });
1031
+ if (chainId == null) {
1032
+ const res = await Promise.all(Object.keys(this._chains).map((chainId) => {
1033
+ const { unifiedSwapStorage, reviver } = this._chains[chainId];
1034
+ return unifiedSwapStorage.query([queryParams], reviver);
1035
+ }));
1036
+ return res.flat()[0];
1037
+ }
1038
+ else {
1039
+ const { unifiedSwapStorage, reviver } = this._chains[chainId];
1040
+ return (await unifiedSwapStorage.query([queryParams], reviver))[0];
1041
+ }
1042
+ }
1043
+ /**
1044
+ * Returns the swap with a proper return type, or `undefined` if not found or has wrong type
1045
+ *
1046
+ * @param id An ID of the swap ({@link ISwap.getId})
1047
+ * @param chainId Chain identifier of the smart chain where the swap was initiated
1048
+ * @param swapType Type of the swap
1049
+ * @param signer An optional required smart chain signer address to fetch the swap for
1050
+ */
1051
+ async getTypedSwapById(id, chainId, swapType, signer) {
1052
+ let _swapType = swapType;
1053
+ if (swapType === SwapType_1.SwapType.FROM_BTC && this.supportsSwapType(chainId, SwapType_1.SwapType.SPV_VAULT_FROM_BTC))
1054
+ _swapType = SwapType_1.SwapType.SPV_VAULT_FROM_BTC;
1055
+ if (swapType === SwapType_1.SwapType.FROM_BTCLN && this.supportsSwapType(chainId, SwapType_1.SwapType.FROM_BTCLN_AUTO))
1056
+ _swapType = SwapType_1.SwapType.FROM_BTCLN_AUTO;
1057
+ const wrapper = this._chains[chainId].wrappers[_swapType];
1058
+ if (wrapper == null)
1059
+ return;
1060
+ const result = wrapper._getPendingSwap(id);
1061
+ if (result != null) {
1062
+ if (signer != null) {
1063
+ if (result._getInitiator() === signer)
1064
+ return result;
1065
+ }
1066
+ else {
1067
+ return result;
1068
+ }
1069
+ }
1070
+ const queryParams = [];
1071
+ if (signer != null)
1072
+ queryParams.push({ key: "initiator", value: signer });
1073
+ queryParams.push({ key: "id", value: id });
1074
+ const { unifiedSwapStorage, reviver } = this._chains[chainId];
1075
+ const swap = (await unifiedSwapStorage.query([queryParams], reviver))[0];
1076
+ if ((0, SwapUtils_1.isSwapType)(swap, swapType))
1077
+ return swap;
1078
+ }
1079
+ async syncSwapsForChain(chainId, signer) {
1080
+ const { unifiedSwapStorage, reviver, wrappers } = this._chains[chainId];
1081
+ const queryParams = [];
1082
+ for (let key in wrappers) {
1083
+ const wrapper = wrappers[key];
1084
+ const swapTypeQueryParams = [{ key: "type", value: wrapper.TYPE }];
1085
+ if (signer != null)
1086
+ swapTypeQueryParams.push({ key: "initiator", value: signer });
1087
+ swapTypeQueryParams.push({ key: "state", value: wrapper._pendingSwapStates });
1088
+ queryParams.push(swapTypeQueryParams);
1089
+ }
1090
+ this.logger.debug("_syncSwaps(): Querying swaps swaps for chain " + chainId + "!");
1091
+ const swaps = await unifiedSwapStorage.query(queryParams, reviver);
1092
+ this.logger.debug("_syncSwaps(): Syncing " + swaps.length + " swaps!");
1093
+ const changedSwaps = [];
1094
+ const removeSwaps = [];
1095
+ const assortedSwaps = {};
1096
+ swaps.forEach(swap => {
1097
+ (assortedSwaps[swap.getType()] ??= []).push(swap);
1098
+ });
1099
+ for (let key in assortedSwaps) {
1100
+ const swapType = key;
1101
+ const wrapperSwaps = assortedSwaps[swapType];
1102
+ const wrapper = wrappers[swapType];
1103
+ const result = await wrapper.checkPastSwaps(wrapperSwaps, true);
1104
+ changedSwaps.push(...result.changedSwaps);
1105
+ removeSwaps.push(...result.removeSwaps);
1106
+ }
1107
+ this.logger.debug("_syncSwaps(): Done syncing " + swaps.length + " swaps, saving " + changedSwaps.length + " changed swaps, removing " + removeSwaps.length + " swaps!");
1108
+ await unifiedSwapStorage.saveAll(changedSwaps);
1109
+ await unifiedSwapStorage.removeAll(removeSwaps);
1110
+ changedSwaps.forEach(swap => swap._emitEvent());
1111
+ removeSwaps.forEach(swap => swap._emitEvent());
1112
+ }
1113
+ /**
1114
+ * Deletes the swaps from the persistent storage backend. Note that some data (like lightning network
1115
+ * amounts and bolt11 invoices) are purely off-chain and can never be recovered later just from
1116
+ * on-chain data!
1117
+ *
1118
+ * @param chainId Optional, to only delete swaps for this smart chain
1119
+ * @param signer Optional, to only delete swaps for this smart chain signer (`chainId` param must be
1120
+ * set to delete only signer's swaps)
1121
+ */
1122
+ async wipeStorage(chainId, signer) {
1123
+ if (chainId == null) {
1124
+ const swaps = await this.getAllSwaps();
1125
+ const chainSwaps = {};
1126
+ swaps.forEach(swap => (chainSwaps[swap.chainIdentifier] ??= []).push(swap));
1127
+ for (let chainId in chainSwaps) {
1128
+ const currentChainSwaps = chainSwaps[chainId];
1129
+ if (this._chains[chainId] == null) {
1130
+ this.logger.warn(`wipeStorage(): Attempted to remove ${currentChainSwaps.length} swaps on ${chainId}, but smart chain not known!`);
1131
+ continue;
1132
+ }
1133
+ await this._chains[chainId].unifiedSwapStorage.removeAll(currentChainSwaps);
1134
+ this.logger.debug(`wipeStorage(): Successfully removed ${currentChainSwaps.length} swaps on ${chainId}!`);
1135
+ }
1136
+ }
1137
+ else {
1138
+ if (this._chains[chainId] == null)
1139
+ throw new Error(`wipeStorage(): Smart chain with identifier ${chainId} not found!`);
1140
+ const swaps = await this.getAllSwaps(chainId, signer);
1141
+ await this._chains[chainId].unifiedSwapStorage.removeAll(swaps);
1142
+ this.logger.debug(`wipeStorage(): Successfully removed ${swaps.length} swaps on ${chainId}!`);
1143
+ }
1144
+ }
1145
+ /**
1146
+ * Synchronizes swaps from on-chain, this is ran automatically when SDK is initialized, hence
1147
+ * should only be ran manually when `dontCheckPastSwaps=true` is passed in the swapper options,
1148
+ * also deletes expired quotes
1149
+ *
1150
+ * @param chainId Optional chain identifier to only run swap sync for a single smart chain
1151
+ * @param signer Optional signer to only run swap sync for swaps initiated by this signer
1152
+ */
1153
+ async _syncSwaps(chainId, signer) {
1154
+ if (chainId == null) {
1155
+ await Promise.all(Object.keys(this._chains).map((chainId) => {
1156
+ return this.syncSwapsForChain(chainId, signer);
1157
+ }));
1158
+ }
1159
+ else {
1160
+ await this.syncSwapsForChain(chainId, signer);
1161
+ }
1162
+ }
1163
+ /**
1164
+ * Recovers swaps from on-chain historical data.
1165
+ *
1166
+ * Please note that the recovered swaps might not be complete (i.e. missing amounts or addresses), as some
1167
+ * of the swap data is purely off-chain and can never be recovered purely from on-chain data. This
1168
+ * functions tries to recover as much swap data as possible.
1169
+ *
1170
+ * @param chainId Smart chain identifier string to recover the swaps from
1171
+ * @param signer Signer address to recover the swaps for
1172
+ * @param startBlockheight Optional starting blockheight for swap data recovery, will only check swaps
1173
+ * initiated after this blockheight
1174
+ */
1175
+ async recoverSwaps(chainId, signer, startBlockheight) {
1176
+ const { spvVaultContract, swapContract, unifiedSwapStorage, reviver, wrappers } = this._chains[chainId];
1177
+ if (swapContract.getHistoricalSwaps == null ||
1178
+ (spvVaultContract != null && spvVaultContract.getHistoricalWithdrawalStates == null))
1179
+ throw new Error(`Historical swap recovery is not supported for ${chainId}`);
1180
+ const { swaps } = await swapContract.getHistoricalSwaps(signer, startBlockheight);
1181
+ const spvVaultData = await spvVaultContract?.getHistoricalWithdrawalStates(signer, startBlockheight);
1182
+ const escrowHashes = Object.keys(swaps);
1183
+ if (spvVaultData != null)
1184
+ Object.keys(spvVaultData.withdrawals).forEach(btcTxId => escrowHashes.push(btcTxId));
1185
+ this.logger.debug(`recoverSwaps(): Loaded on-chain data for ${escrowHashes.length} swaps`);
1186
+ this.logger.debug(`recoverSwaps(): Fetching if swap escrowHashes are known: ${escrowHashes.join(", ")}`);
1187
+ const knownSwapsArray = await unifiedSwapStorage.query([[{ key: "escrowHash", value: escrowHashes }]], reviver);
1188
+ const knownSwaps = {};
1189
+ knownSwapsArray.forEach(val => {
1190
+ const escrowHash = val._getEscrowHash();
1191
+ if (escrowHash != null)
1192
+ knownSwaps[escrowHash] = val;
1193
+ });
1194
+ this.logger.debug(`recoverSwaps(): Fetched known swaps escrowHashes: ${Object.keys(knownSwaps).join(", ")}`);
1195
+ const recoveredSwaps = [];
1196
+ for (let escrowHash in swaps) {
1197
+ const { init, state } = swaps[escrowHash];
1198
+ const knownSwap = knownSwaps[escrowHash];
1199
+ if (knownSwap == null) {
1200
+ if (init == null) {
1201
+ this.logger.warn(`recoverSwaps(escrow): Fetched ${escrowHash} swap state, but swap not found locally!`);
1202
+ continue;
1203
+ }
1204
+ }
1205
+ else if (knownSwap instanceof IEscrowSwap_1.IEscrowSwap) {
1206
+ this.logger.debug(`recoverSwaps(escrow): Forcibly updating ${escrowHash} swap: swap already known and in local storage!`);
1207
+ if (await knownSwap._forciblySetOnchainState(state)) {
1208
+ await knownSwap._save();
1209
+ }
1210
+ continue;
1211
+ }
1212
+ else {
1213
+ this.logger.debug(`recoverSwaps(escrow): Skipping ${escrowHash} swap: swap already known and in local storage!`);
1214
+ continue;
1215
+ }
1216
+ const data = init.data;
1217
+ //Classify swap
1218
+ let swap;
1219
+ let typeIdentified = false;
1220
+ if (data.getType() === base_1.ChainSwapType.HTLC) {
1221
+ if (data.isOfferer(signer)) {
1222
+ //To BTCLN
1223
+ typeIdentified = true;
1224
+ const lp = this.intermediaryDiscovery.intermediaries.find(val => val.supportsChain(chainId) && data.isClaimer(val.getAddress(chainId)));
1225
+ swap = await wrappers[SwapType_1.SwapType.TO_BTCLN].recoverFromSwapDataAndState(init, state, lp);
1226
+ }
1227
+ else if (data.isClaimer(signer)) {
1228
+ //From BTCLN
1229
+ typeIdentified = true;
1230
+ const lp = this.intermediaryDiscovery.intermediaries.find(val => val.supportsChain(chainId) && data.isOfferer(val.getAddress(chainId)));
1231
+ if (this.supportsSwapType(chainId, SwapType_1.SwapType.FROM_BTCLN_AUTO)) {
1232
+ swap = await wrappers[SwapType_1.SwapType.FROM_BTCLN_AUTO].recoverFromSwapDataAndState(init, state, lp);
1233
+ }
1234
+ else {
1235
+ swap = await wrappers[SwapType_1.SwapType.FROM_BTCLN].recoverFromSwapDataAndState(init, state, lp);
1236
+ }
1237
+ }
1238
+ }
1239
+ else if (data.getType() === base_1.ChainSwapType.CHAIN_NONCED) {
1240
+ //To BTC
1241
+ typeIdentified = true;
1242
+ const lp = this.intermediaryDiscovery.intermediaries.find(val => val.supportsChain(chainId) && data.isClaimer(val.getAddress(chainId)));
1243
+ swap = await wrappers[SwapType_1.SwapType.TO_BTC].recoverFromSwapDataAndState(init, state, lp);
1244
+ }
1245
+ else if (data.getType() === base_1.ChainSwapType.CHAIN) {
1246
+ //From BTC
1247
+ typeIdentified = true;
1248
+ const lp = this.intermediaryDiscovery.intermediaries.find(val => val.supportsChain(chainId) && data.isOfferer(val.getAddress(chainId)));
1249
+ swap = await wrappers[SwapType_1.SwapType.FROM_BTC].recoverFromSwapDataAndState(init, state, lp);
1250
+ }
1251
+ if (swap != null) {
1252
+ recoveredSwaps.push(swap);
1253
+ }
1254
+ else {
1255
+ if (typeIdentified)
1256
+ this.logger.debug(`recoverSwaps(escrow): Swap data type correctly identified but swap returned is null for swap ${escrowHash}`);
1257
+ }
1258
+ }
1259
+ if (spvVaultContract != null && spvVaultData != null) {
1260
+ const vaultsData = await spvVaultContract.getMultipleVaultData(Object.keys(spvVaultData.withdrawals)
1261
+ .map(btcTxId => ({
1262
+ owner: spvVaultData.withdrawals[btcTxId].owner,
1263
+ vaultId: spvVaultData.withdrawals[btcTxId].vaultId
1264
+ })));
1265
+ for (let btcTxId in spvVaultData.withdrawals) {
1266
+ const state = spvVaultData.withdrawals[btcTxId];
1267
+ const knownSwap = knownSwaps[btcTxId];
1268
+ if (knownSwap != null) {
1269
+ if (knownSwap instanceof SpvFromBTCSwap_1.SpvFromBTCSwap) {
1270
+ this.logger.debug(`recoverSwaps(spv_vault): Forcibly updating ${btcTxId} swap: swap already known and in local storage!`);
1271
+ //TODO: Forcibly set on-chain state to the swap
1272
+ // if(await knownSwap._forciblySetOnchainState(state)) {
1273
+ // await knownSwap._save();
1274
+ // }
1275
+ continue;
1276
+ }
1277
+ else {
1278
+ this.logger.debug(`recoverSwaps(spv_vault): Skipping ${btcTxId} swap: swap already known and in local storage!`);
1279
+ continue;
1280
+ }
1281
+ }
1282
+ const lp = this.intermediaryDiscovery.intermediaries.find(val => val.supportsChain(chainId) && state.owner.toLowerCase() === val.getAddress(chainId).toLowerCase());
1283
+ const swap = await wrappers[SwapType_1.SwapType.SPV_VAULT_FROM_BTC].recoverFromState(state, vaultsData[state.owner]?.[state.vaultId.toString(10)], lp);
1284
+ if (swap != null) {
1285
+ recoveredSwaps.push(swap);
1286
+ }
1287
+ else {
1288
+ this.logger.debug(`recoverSwaps(spv_vault): Swap data type correctly identified but swap returned is null for swap ${btcTxId}`);
1289
+ }
1290
+ }
1291
+ }
1292
+ this.logger.debug(`recoverSwaps(): Successfully recovered ${recoveredSwaps.length} swaps!`);
1293
+ return recoveredSwaps;
1294
+ }
1295
+ /**
1296
+ * Returns the {@link Token} object for a given token
1297
+ *
1298
+ * @param tickerOrAddress Token to return the object for, can use multiple formats:
1299
+ * - a) token ticker, such as `"BTC"`, `"SOL"`, etc.
1300
+ * - b) token ticker prefixed with smart chain identifier, such as `"SOLANA-SOL"`, `"SOLANA-USDC"`, etc.
1301
+ * - c) token address
1302
+ */
1303
+ getToken(tickerOrAddress) {
1304
+ //Btc tokens - BTC, BTCLN, BTC-LN
1305
+ if (tickerOrAddress === "BTC" || tickerOrAddress === "BITCOIN-BTC")
1306
+ return Token_1.BitcoinTokens.BTC;
1307
+ if (tickerOrAddress === "BTCLN" || tickerOrAddress === "BTC-LN" || tickerOrAddress === "LIGHTNING-BTC")
1308
+ return Token_1.BitcoinTokens.BTCLN;
1309
+ //Check if the ticker is in format <chainId>-<ticker>, i.e. SOLANA-USDC, STARKNET-WBTC
1310
+ if (tickerOrAddress.includes("-")) {
1311
+ const [chainId, ticker] = tickerOrAddress.split("-");
1312
+ const token = this._tokensByTicker[chainId]?.[ticker];
1313
+ if (token == null)
1314
+ throw new UserError_1.UserError(`Not found ticker: ${ticker} for chainId: ${chainId}`);
1315
+ return token;
1316
+ }
1317
+ const possibleTokens = [];
1318
+ for (let chainId in this._chains) {
1319
+ const chain = this._chains[chainId];
1320
+ if (chain.chainInterface.isValidToken(tickerOrAddress)) {
1321
+ //Try to find in known token addresses
1322
+ const token = this._tokens[chainId]?.[tickerOrAddress];
1323
+ if (token != null)
1324
+ return token;
1325
+ }
1326
+ else {
1327
+ //Check in known tickers
1328
+ const token = this._tokensByTicker[chainId]?.[tickerOrAddress];
1329
+ if (token != null)
1330
+ possibleTokens.push(token);
1331
+ }
1332
+ }
1333
+ if (possibleTokens.length === 0)
1334
+ throw new UserError_1.UserError(`Specified token address or ticker ${tickerOrAddress} not found!`);
1335
+ //In case we've found the token in multiple chains
1336
+ if (possibleTokens.length > 1)
1337
+ throw new UserError_1.UserError(`A ticker ${tickerOrAddress} has been found in multiple chains, narrow it down by using <chainId>-${tickerOrAddress} notation`);
1338
+ return possibleTokens[0];
1339
+ }
1340
+ /**
1341
+ * Creates a child swapper instance with a given smart chain
1342
+ *
1343
+ * @param chainIdentifier Smart chain identifier for the created child swapper instance
1344
+ */
1345
+ withChain(chainIdentifier) {
1346
+ if (this._chains[chainIdentifier] == null)
1347
+ throw new Error("Invalid chain identifier! Unknown chain: " + chainIdentifier);
1348
+ return new SwapperWithChain_1.SwapperWithChain(this, chainIdentifier);
1349
+ }
1350
+ /**
1351
+ * Returns an array of all the supported smart chains
1352
+ */
1353
+ getSmartChains() {
1354
+ return Object.keys(this._chains);
1355
+ }
1356
+ /**
1357
+ * Returns whether the SDK supports a given swap type on a given chain based on currently known LPs
1358
+ *
1359
+ * @param chainId Smart chain identifier string
1360
+ * @param swapType Swap protocol type
1361
+ */
1362
+ supportsSwapType(chainId, swapType) {
1363
+ return (this._chains[chainId]?.wrappers[swapType] != null);
1364
+ }
1365
+ /**
1366
+ * Returns type of the swap based on input and output tokens specified
1367
+ *
1368
+ * @param srcToken Source token
1369
+ * @param dstToken Destination token
1370
+ */
1371
+ getSwapType(srcToken, dstToken) {
1372
+ if ((0, Token_1.isSCToken)(srcToken)) {
1373
+ if (!(0, Token_1.isBtcToken)(dstToken))
1374
+ throw new Error("Swap not supported");
1375
+ if (dstToken.lightning) {
1376
+ return SwapType_1.SwapType.TO_BTCLN;
1377
+ }
1378
+ else {
1379
+ return SwapType_1.SwapType.TO_BTC;
1380
+ }
1381
+ }
1382
+ else if ((0, Token_1.isBtcToken)(srcToken)) {
1383
+ if (!(0, Token_1.isSCToken)(dstToken))
1384
+ throw new Error("Swap not supported");
1385
+ if (srcToken.lightning) {
1386
+ if (this.supportsSwapType(dstToken.chainId, SwapType_1.SwapType.FROM_BTCLN_AUTO)) {
1387
+ return SwapType_1.SwapType.FROM_BTCLN_AUTO;
1388
+ }
1389
+ else {
1390
+ return SwapType_1.SwapType.FROM_BTCLN;
1391
+ }
1392
+ }
1393
+ else {
1394
+ if (this.supportsSwapType(dstToken.chainId, SwapType_1.SwapType.SPV_VAULT_FROM_BTC)) {
1395
+ return SwapType_1.SwapType.SPV_VAULT_FROM_BTC;
1396
+ }
1397
+ else {
1398
+ return SwapType_1.SwapType.FROM_BTC;
1399
+ }
1400
+ }
1401
+ }
1402
+ throw new Error("Swap not supported");
1403
+ }
1404
+ /**
1405
+ * Returns minimum/maximum limits for inputs and outputs for a swap between given tokens
1406
+ *
1407
+ * @param srcToken Source token
1408
+ * @param dstToken Destination token
1409
+ */
1410
+ getSwapLimits(srcToken, dstToken) {
1411
+ const swapType = this.getSwapType(srcToken, dstToken);
1412
+ const scToken = (0, Token_1.isSCToken)(srcToken) ? srcToken : (0, Token_1.isSCToken)(dstToken) ? dstToken : null;
1413
+ if (scToken == null)
1414
+ throw new Error("At least one token needs to be a smart chain token!");
1415
+ const result = {
1416
+ input: {},
1417
+ output: {}
1418
+ };
1419
+ for (let lp of this.intermediaryDiscovery.intermediaries) {
1420
+ const lpMinMax = lp.getSwapLimits(swapType, scToken.chainId, scToken.address);
1421
+ if (lpMinMax == null)
1422
+ continue;
1423
+ result.input.min = result.input.min == null ? lpMinMax.input.min : (0, Utils_1.bigIntMin)(result.input.min, lpMinMax.input.min);
1424
+ result.input.max = result.input.max == null ? lpMinMax.input.max : (0, Utils_1.bigIntMax)(result.input.max, lpMinMax.input.max);
1425
+ result.output.min = result.output.min == null ? lpMinMax.output.min : (0, Utils_1.bigIntMin)(result.output.min, lpMinMax.output.min);
1426
+ result.output.max = result.output.max == null ? lpMinMax.output.max : (0, Utils_1.bigIntMax)(result.output.max, lpMinMax.output.max);
1427
+ }
1428
+ return {
1429
+ input: {
1430
+ min: (0, TokenAmount_1.toTokenAmount)(result.input.min ?? 1n, srcToken, this.prices),
1431
+ max: result.input.max == null ? undefined : (0, TokenAmount_1.toTokenAmount)(result.input.max, srcToken, this.prices),
1432
+ },
1433
+ output: {
1434
+ min: (0, TokenAmount_1.toTokenAmount)(result.output.min ?? 1n, dstToken, this.prices),
1435
+ max: result.output.max == null ? undefined : (0, TokenAmount_1.toTokenAmount)(result.output.max, dstToken, this.prices),
1436
+ }
1437
+ };
1438
+ }
1439
+ /**
1440
+ * Returns an array of supported tokens either on the input or on the output of a swap
1441
+ *
1442
+ * @param input Whether to return input tokens or output tokens
1443
+ */
1444
+ getSupportedTokens(input) {
1445
+ const tokens = {};
1446
+ let lightning = false;
1447
+ let btc = false;
1448
+ this.intermediaryDiscovery.intermediaries.forEach(lp => {
1449
+ for (let swapType of [SwapType_1.SwapType.TO_BTC, SwapType_1.SwapType.TO_BTCLN, SwapType_1.SwapType.FROM_BTC, SwapType_1.SwapType.FROM_BTCLN, SwapType_1.SwapType.SPV_VAULT_FROM_BTC, SwapType_1.SwapType.FROM_BTCLN_AUTO]) {
1450
+ if (lp.services[swapType]?.chainTokens == null)
1451
+ continue;
1452
+ for (let chainId of this.getSmartChains()) {
1453
+ if (this.supportsSwapType(chainId, SwapType_1.SwapType.SPV_VAULT_FROM_BTC) ? swapType === SwapType_1.SwapType.FROM_BTC : swapType === SwapType_1.SwapType.SPV_VAULT_FROM_BTC)
1454
+ continue;
1455
+ if (this.supportsSwapType(chainId, SwapType_1.SwapType.FROM_BTCLN_AUTO) ? swapType === SwapType_1.SwapType.FROM_BTCLN : swapType === SwapType_1.SwapType.FROM_BTCLN_AUTO)
1456
+ continue;
1457
+ const chainTokens = lp.services[swapType]?.chainTokens?.[chainId];
1458
+ if (chainTokens == null)
1459
+ continue;
1460
+ for (let tokenAddress of chainTokens) {
1461
+ if (input) {
1462
+ if (swapType === SwapType_1.SwapType.TO_BTC || swapType === SwapType_1.SwapType.TO_BTCLN) {
1463
+ tokens[chainId] ??= new Set();
1464
+ tokens[chainId].add(tokenAddress);
1465
+ }
1466
+ if (swapType === SwapType_1.SwapType.FROM_BTCLN || swapType === SwapType_1.SwapType.FROM_BTCLN_AUTO) {
1467
+ lightning = true;
1468
+ }
1469
+ if (swapType === SwapType_1.SwapType.FROM_BTC || swapType === SwapType_1.SwapType.SPV_VAULT_FROM_BTC) {
1470
+ btc = true;
1471
+ }
1472
+ }
1473
+ else {
1474
+ if (swapType === SwapType_1.SwapType.FROM_BTCLN || swapType === SwapType_1.SwapType.FROM_BTC || swapType === SwapType_1.SwapType.SPV_VAULT_FROM_BTC || swapType === SwapType_1.SwapType.FROM_BTCLN_AUTO) {
1475
+ tokens[chainId] ??= new Set();
1476
+ tokens[chainId].add(tokenAddress);
1477
+ }
1478
+ if (swapType === SwapType_1.SwapType.TO_BTCLN) {
1479
+ lightning = true;
1480
+ }
1481
+ if (swapType === SwapType_1.SwapType.TO_BTC) {
1482
+ btc = true;
1483
+ }
1484
+ }
1485
+ }
1486
+ }
1487
+ }
1488
+ });
1489
+ const output = [];
1490
+ if (lightning)
1491
+ output.push(Token_1.BitcoinTokens.BTCLN);
1492
+ if (btc)
1493
+ output.push(Token_1.BitcoinTokens.BTC);
1494
+ for (let chainId in tokens) {
1495
+ tokens[chainId].forEach(tokenAddress => {
1496
+ const token = this._tokens?.[chainId]?.[tokenAddress];
1497
+ if (token != null)
1498
+ output.push(token);
1499
+ });
1500
+ }
1501
+ return output;
1502
+ }
1503
+ /**
1504
+ * Returns a set of supported tokens by all the intermediaries offering a specific swap service
1505
+ *
1506
+ * @param _swapType Swap service type to check supported tokens for
1507
+ */
1508
+ getSupportedTokensForSwapType(_swapType) {
1509
+ const tokens = {};
1510
+ this.intermediaryDiscovery.intermediaries.forEach(lp => {
1511
+ for (let chainId of this.getSmartChains()) {
1512
+ let swapType = _swapType;
1513
+ if (swapType === SwapType_1.SwapType.FROM_BTC && this.supportsSwapType(chainId, SwapType_1.SwapType.SPV_VAULT_FROM_BTC))
1514
+ swapType = SwapType_1.SwapType.SPV_VAULT_FROM_BTC;
1515
+ if (swapType === SwapType_1.SwapType.FROM_BTCLN && this.supportsSwapType(chainId, SwapType_1.SwapType.FROM_BTCLN_AUTO))
1516
+ swapType = SwapType_1.SwapType.FROM_BTCLN_AUTO;
1517
+ if (lp.services[swapType]?.chainTokens == null)
1518
+ break;
1519
+ const chainTokens = lp.services[swapType]?.chainTokens?.[chainId];
1520
+ if (chainTokens == null)
1521
+ continue;
1522
+ for (let tokenAddress of chainTokens) {
1523
+ tokens[chainId] ??= new Set();
1524
+ tokens[chainId].add(tokenAddress);
1525
+ }
1526
+ }
1527
+ });
1528
+ const output = [];
1529
+ for (let chainId in tokens) {
1530
+ tokens[chainId].forEach(tokenAddress => {
1531
+ const token = this._tokens?.[chainId]?.[tokenAddress];
1532
+ if (token != null)
1533
+ output.push(token);
1534
+ });
1535
+ }
1536
+ return output;
1537
+ }
1538
+ /**
1539
+ * Returns the set of supported token addresses by all the intermediaries we know of offering a specific swapType service
1540
+ *
1541
+ * @param chainIdentifier Chain identifier string
1542
+ * @param swapType Specific swap type for which to obtain supported tokens
1543
+ */
1544
+ getSupportedTokenAddresses(chainIdentifier, swapType) {
1545
+ const set = new Set();
1546
+ this.intermediaryDiscovery.intermediaries.forEach(lp => {
1547
+ const chainTokens = lp.services[swapType]?.chainTokens?.[chainIdentifier];
1548
+ if (chainTokens == null)
1549
+ return;
1550
+ chainTokens.forEach(token => set.add(token));
1551
+ });
1552
+ return set;
1553
+ }
1554
+ /**
1555
+ * Returns tokens that you can swap to (if input=true) from a given token,
1556
+ * or tokens that you can swap from (if input=false) to a given token
1557
+ */
1558
+ getSwapCounterTokens(token, input) {
1559
+ if ((0, Token_1.isSCToken)(token)) {
1560
+ const result = [];
1561
+ if (input) {
1562
+ //TO_BTC or TO_BTCLN
1563
+ if (this.getSupportedTokenAddresses(token.chainId, SwapType_1.SwapType.TO_BTCLN).has(token.address)) {
1564
+ result.push(Token_1.BitcoinTokens.BTCLN);
1565
+ }
1566
+ if (this.getSupportedTokenAddresses(token.chainId, SwapType_1.SwapType.TO_BTC).has(token.address)) {
1567
+ result.push(Token_1.BitcoinTokens.BTC);
1568
+ }
1569
+ }
1570
+ else {
1571
+ //FROM_BTC or FROM_BTCLN
1572
+ const fromLightningSwapType = this.supportsSwapType(token.chainId, SwapType_1.SwapType.FROM_BTCLN_AUTO) ? SwapType_1.SwapType.FROM_BTCLN_AUTO : SwapType_1.SwapType.FROM_BTCLN;
1573
+ if (this.getSupportedTokenAddresses(token.chainId, fromLightningSwapType).has(token.address)) {
1574
+ result.push(Token_1.BitcoinTokens.BTCLN);
1575
+ }
1576
+ const fromOnchainSwapType = this.supportsSwapType(token.chainId, SwapType_1.SwapType.SPV_VAULT_FROM_BTC) ? SwapType_1.SwapType.SPV_VAULT_FROM_BTC : SwapType_1.SwapType.FROM_BTC;
1577
+ if (this.getSupportedTokenAddresses(token.chainId, fromOnchainSwapType).has(token.address)) {
1578
+ result.push(Token_1.BitcoinTokens.BTC);
1579
+ }
1580
+ }
1581
+ return result;
1582
+ }
1583
+ else {
1584
+ if (input) {
1585
+ if (token.lightning) {
1586
+ return this.getSupportedTokensForSwapType(SwapType_1.SwapType.FROM_BTCLN);
1587
+ }
1588
+ else {
1589
+ return this.getSupportedTokensForSwapType(SwapType_1.SwapType.FROM_BTC);
1590
+ }
1591
+ }
1592
+ else {
1593
+ if (token.lightning) {
1594
+ return this.getSupportedTokensForSwapType(SwapType_1.SwapType.TO_BTCLN);
1595
+ }
1596
+ else {
1597
+ return this.getSupportedTokensForSwapType(SwapType_1.SwapType.TO_BTC);
1598
+ }
1599
+ }
1600
+ }
1601
+ }
1602
+ }
1603
+ exports.Swapper = Swapper;