@atomiqlabs/sdk 8.1.8 → 8.3.5

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 (261) hide show
  1. package/dist/bitcoin/coinselect2/utils.d.ts +6 -0
  2. package/dist/bitcoin/wallet/BitcoinWallet.d.ts +41 -5
  3. package/dist/bitcoin/wallet/BitcoinWallet.js +36 -1
  4. package/dist/bitcoin/wallet/IBitcoinWallet.d.ts +52 -2
  5. package/dist/bitcoin/wallet/IBitcoinWallet.js +2 -1
  6. package/dist/bitcoin/wallet/SingleAddressBitcoinWallet.d.ts +42 -7
  7. package/dist/bitcoin/wallet/SingleAddressBitcoinWallet.js +36 -1
  8. package/dist/enums/FeeType.d.ts +8 -1
  9. package/dist/enums/FeeType.js +8 -1
  10. package/dist/enums/SwapAmountType.d.ts +7 -0
  11. package/dist/enums/SwapAmountType.js +7 -0
  12. package/dist/enums/SwapDirection.d.ts +7 -0
  13. package/dist/enums/SwapDirection.js +7 -0
  14. package/dist/enums/SwapType.d.ts +62 -1
  15. package/dist/enums/SwapType.js +62 -1
  16. package/dist/errors/IntermediaryError.d.ts +4 -0
  17. package/dist/errors/IntermediaryError.js +1 -0
  18. package/dist/errors/RequestError.d.ts +15 -1
  19. package/dist/errors/RequestError.js +8 -0
  20. package/dist/errors/UserError.d.ts +1 -0
  21. package/dist/errors/UserError.js +1 -0
  22. package/dist/index.d.ts +5 -5
  23. package/dist/index.js +7 -6
  24. package/dist/intermediaries/Intermediary.d.ts +61 -14
  25. package/dist/intermediaries/Intermediary.js +38 -11
  26. package/dist/intermediaries/IntermediaryDiscovery.d.ts +62 -29
  27. package/dist/intermediaries/IntermediaryDiscovery.js +39 -24
  28. package/dist/prices/RedundantSwapPrice.d.ts +26 -5
  29. package/dist/prices/RedundantSwapPrice.js +22 -2
  30. package/dist/prices/SingleSwapPrice.d.ts +10 -7
  31. package/dist/prices/SingleSwapPrice.js +11 -8
  32. package/dist/prices/SwapPriceWithChain.d.ts +56 -19
  33. package/dist/prices/SwapPriceWithChain.js +62 -25
  34. package/dist/prices/abstract/IPriceProvider.d.ts +4 -4
  35. package/dist/prices/abstract/IPriceProvider.js +1 -1
  36. package/dist/prices/abstract/ISwapPrice.d.ts +95 -46
  37. package/dist/prices/abstract/ISwapPrice.js +104 -56
  38. package/dist/prices/providers/BinancePriceProvider.d.ts +8 -1
  39. package/dist/prices/providers/BinancePriceProvider.js +8 -1
  40. package/dist/prices/providers/CoinGeckoPriceProvider.d.ts +7 -1
  41. package/dist/prices/providers/CoinGeckoPriceProvider.js +7 -1
  42. package/dist/prices/providers/CoinPaprikaPriceProvider.d.ts +7 -1
  43. package/dist/prices/providers/CoinPaprikaPriceProvider.js +7 -1
  44. package/dist/prices/providers/CustomPriceProvider.d.ts +12 -1
  45. package/dist/prices/providers/CustomPriceProvider.js +12 -1
  46. package/dist/prices/providers/KrakenPriceProvider.d.ts +10 -1
  47. package/dist/prices/providers/KrakenPriceProvider.js +10 -1
  48. package/dist/prices/providers/OKXPriceProvider.d.ts +7 -1
  49. package/dist/prices/providers/OKXPriceProvider.js +7 -1
  50. package/dist/prices/providers/abstract/ExchangePriceProvider.d.ts +3 -0
  51. package/dist/prices/providers/abstract/ExchangePriceProvider.js +3 -0
  52. package/dist/storage/IUnifiedStorage.d.ts +19 -7
  53. package/dist/storage/UnifiedSwapStorage.d.ts +33 -3
  54. package/dist/storage/UnifiedSwapStorage.js +29 -1
  55. package/dist/storage-browser/IndexedDBUnifiedStorage.d.ts +31 -7
  56. package/dist/storage-browser/IndexedDBUnifiedStorage.js +29 -6
  57. package/dist/storage-browser/LocalStorageManager.d.ts +25 -1
  58. package/dist/storage-browser/LocalStorageManager.js +25 -1
  59. package/dist/swapper/Swapper.d.ts +380 -226
  60. package/dist/swapper/Swapper.js +383 -349
  61. package/dist/swapper/SwapperFactory.d.ts +66 -18
  62. package/dist/swapper/SwapperFactory.js +24 -3
  63. package/dist/swapper/SwapperUtils.d.ts +75 -28
  64. package/dist/swapper/SwapperUtils.js +107 -60
  65. package/dist/swapper/SwapperWithChain.d.ts +286 -91
  66. package/dist/swapper/SwapperWithChain.js +218 -64
  67. package/dist/swapper/SwapperWithSigner.d.ts +229 -80
  68. package/dist/swapper/SwapperWithSigner.js +190 -44
  69. package/dist/swaps/IAddressSwap.d.ts +12 -3
  70. package/dist/swaps/IAddressSwap.js +3 -2
  71. package/dist/swaps/IBTCWalletSwap.d.ts +26 -8
  72. package/dist/swaps/IBTCWalletSwap.js +3 -2
  73. package/dist/swaps/IClaimableSwap.d.ts +38 -6
  74. package/dist/swaps/IClaimableSwap.js +3 -2
  75. package/dist/swaps/IClaimableSwapWrapper.d.ts +11 -1
  76. package/dist/swaps/IRefundableSwap.d.ts +31 -5
  77. package/dist/swaps/IRefundableSwap.js +3 -2
  78. package/dist/swaps/ISwap.d.ts +162 -24
  79. package/dist/swaps/ISwap.js +92 -35
  80. package/dist/swaps/ISwapWithGasDrop.d.ts +8 -2
  81. package/dist/swaps/ISwapWithGasDrop.js +2 -1
  82. package/dist/swaps/ISwapWrapper.d.ts +161 -52
  83. package/dist/swaps/ISwapWrapper.js +131 -73
  84. package/dist/swaps/escrow_swaps/IEscrowSelfInitSwap.d.ts +51 -6
  85. package/dist/swaps/escrow_swaps/IEscrowSelfInitSwap.js +22 -12
  86. package/dist/swaps/escrow_swaps/IEscrowSwap.d.ts +65 -12
  87. package/dist/swaps/escrow_swaps/IEscrowSwap.js +38 -19
  88. package/dist/swaps/escrow_swaps/IEscrowSwapWrapper.d.ts +39 -9
  89. package/dist/swaps/escrow_swaps/IEscrowSwapWrapper.js +30 -21
  90. package/dist/swaps/escrow_swaps/frombtc/IFromBTCLNWrapper.d.ts +31 -15
  91. package/dist/swaps/escrow_swaps/frombtc/IFromBTCLNWrapper.js +33 -18
  92. package/dist/swaps/escrow_swaps/frombtc/IFromBTCSelfInitSwap.d.ts +97 -28
  93. package/dist/swaps/escrow_swaps/frombtc/IFromBTCSelfInitSwap.js +91 -27
  94. package/dist/swaps/escrow_swaps/frombtc/IFromBTCWrapper.d.ts +22 -9
  95. package/dist/swaps/escrow_swaps/frombtc/IFromBTCWrapper.js +24 -11
  96. package/dist/swaps/escrow_swaps/frombtc/ln/FromBTCLNSwap.d.ts +278 -60
  97. package/dist/swaps/escrow_swaps/frombtc/ln/FromBTCLNSwap.js +519 -241
  98. package/dist/swaps/escrow_swaps/frombtc/ln/FromBTCLNWrapper.d.ts +77 -26
  99. package/dist/swaps/escrow_swaps/frombtc/ln/FromBTCLNWrapper.js +132 -50
  100. package/dist/swaps/escrow_swaps/frombtc/ln_auto/FromBTCLNAutoSwap.d.ts +313 -52
  101. package/dist/swaps/escrow_swaps/frombtc/ln_auto/FromBTCLNAutoSwap.js +544 -194
  102. package/dist/swaps/escrow_swaps/frombtc/ln_auto/FromBTCLNAutoWrapper.d.ts +87 -26
  103. package/dist/swaps/escrow_swaps/frombtc/ln_auto/FromBTCLNAutoWrapper.js +147 -58
  104. package/dist/swaps/escrow_swaps/frombtc/onchain/FromBTCSwap.d.ts +222 -55
  105. package/dist/swaps/escrow_swaps/frombtc/onchain/FromBTCSwap.js +462 -244
  106. package/dist/swaps/escrow_swaps/frombtc/onchain/FromBTCWrapper.d.ts +77 -23
  107. package/dist/swaps/escrow_swaps/frombtc/onchain/FromBTCWrapper.js +116 -46
  108. package/dist/swaps/escrow_swaps/tobtc/IToBTCSwap.d.ts +195 -58
  109. package/dist/swaps/escrow_swaps/tobtc/IToBTCSwap.js +324 -191
  110. package/dist/swaps/escrow_swaps/tobtc/IToBTCWrapper.d.ts +30 -5
  111. package/dist/swaps/escrow_swaps/tobtc/IToBTCWrapper.js +44 -19
  112. package/dist/swaps/escrow_swaps/tobtc/ln/ToBTCLNSwap.d.ts +61 -20
  113. package/dist/swaps/escrow_swaps/tobtc/ln/ToBTCLNSwap.js +75 -32
  114. package/dist/swaps/escrow_swaps/tobtc/ln/ToBTCLNWrapper.d.ts +76 -50
  115. package/dist/swaps/escrow_swaps/tobtc/ln/ToBTCLNWrapper.js +106 -101
  116. package/dist/swaps/escrow_swaps/tobtc/onchain/ToBTCSwap.d.ts +37 -14
  117. package/dist/swaps/escrow_swaps/tobtc/onchain/ToBTCSwap.js +66 -20
  118. package/dist/swaps/escrow_swaps/tobtc/onchain/ToBTCWrapper.d.ts +46 -17
  119. package/dist/swaps/escrow_swaps/tobtc/onchain/ToBTCWrapper.js +82 -27
  120. package/dist/swaps/spv_swaps/SpvFromBTCSwap.d.ts +350 -88
  121. package/dist/swaps/spv_swaps/SpvFromBTCSwap.js +482 -215
  122. package/dist/swaps/spv_swaps/SpvFromBTCWrapper.d.ts +76 -24
  123. package/dist/swaps/spv_swaps/SpvFromBTCWrapper.js +247 -124
  124. package/dist/swaps/trusted/ln/LnForGasSwap.d.ts +148 -20
  125. package/dist/swaps/trusted/ln/LnForGasSwap.js +175 -45
  126. package/dist/swaps/trusted/ln/LnForGasWrapper.d.ts +29 -10
  127. package/dist/swaps/trusted/ln/LnForGasWrapper.js +30 -11
  128. package/dist/swaps/trusted/onchain/OnchainForGasSwap.d.ts +202 -49
  129. package/dist/swaps/trusted/onchain/OnchainForGasSwap.js +232 -80
  130. package/dist/swaps/trusted/onchain/OnchainForGasWrapper.d.ts +34 -12
  131. package/dist/swaps/trusted/onchain/OnchainForGasWrapper.js +33 -14
  132. package/dist/types/AmountData.d.ts +2 -1
  133. package/dist/types/CustomPriceFunction.d.ts +8 -2
  134. package/dist/types/PriceInfoType.d.ts +4 -4
  135. package/dist/types/PriceInfoType.js +3 -3
  136. package/dist/types/SwapExecutionAction.d.ts +85 -4
  137. package/dist/types/SwapWithSigner.d.ts +5 -2
  138. package/dist/types/SwapWithSigner.js +5 -2
  139. package/dist/types/Token.d.ts +11 -5
  140. package/dist/types/Token.js +6 -3
  141. package/dist/types/TokenAmount.d.ts +3 -0
  142. package/dist/types/TokenAmount.js +2 -0
  143. package/dist/types/fees/Fee.d.ts +3 -2
  144. package/dist/types/fees/FeeBreakdown.d.ts +3 -2
  145. package/dist/types/fees/PercentagePPM.d.ts +4 -2
  146. package/dist/types/fees/PercentagePPM.js +2 -1
  147. package/dist/types/lnurl/LNURLPay.d.ts +20 -12
  148. package/dist/types/lnurl/LNURLPay.js +8 -4
  149. package/dist/types/lnurl/LNURLWithdraw.d.ts +17 -10
  150. package/dist/types/lnurl/LNURLWithdraw.js +8 -4
  151. package/dist/types/wallets/LightningInvoiceCreateService.d.ts +24 -0
  152. package/dist/types/wallets/LightningInvoiceCreateService.js +15 -0
  153. package/dist/types/wallets/MinimalBitcoinWalletInterface.d.ts +3 -1
  154. package/dist/types/wallets/MinimalLightningNetworkWalletInterface.d.ts +4 -2
  155. package/dist/utils/BitcoinUtils.d.ts +1 -0
  156. package/dist/utils/BitcoinUtils.js +5 -1
  157. package/dist/utils/SwapUtils.d.ts +58 -1
  158. package/dist/utils/SwapUtils.js +55 -1
  159. package/dist/utils/TokenUtils.d.ts +10 -2
  160. package/dist/utils/TokenUtils.js +12 -4
  161. package/package.json +3 -3
  162. package/src/bitcoin/coinselect2/utils.ts +6 -0
  163. package/src/bitcoin/wallet/BitcoinWallet.ts +41 -5
  164. package/src/bitcoin/wallet/IBitcoinWallet.ts +57 -2
  165. package/src/bitcoin/wallet/SingleAddressBitcoinWallet.ts +42 -6
  166. package/src/enums/FeeType.ts +8 -1
  167. package/src/enums/SwapAmountType.ts +7 -0
  168. package/src/enums/SwapDirection.ts +7 -0
  169. package/src/enums/SwapType.ts +62 -2
  170. package/src/errors/IntermediaryError.ts +4 -0
  171. package/src/errors/RequestError.ts +15 -1
  172. package/src/errors/UserError.ts +1 -0
  173. package/src/index.ts +12 -5
  174. package/src/intermediaries/Intermediary.ts +61 -14
  175. package/src/intermediaries/IntermediaryDiscovery.ts +69 -34
  176. package/src/prices/RedundantSwapPrice.ts +26 -6
  177. package/src/prices/SingleSwapPrice.ts +11 -8
  178. package/src/prices/SwapPriceWithChain.ts +63 -26
  179. package/src/prices/abstract/IPriceProvider.ts +4 -4
  180. package/src/prices/abstract/ISwapPrice.ts +115 -66
  181. package/src/prices/providers/BinancePriceProvider.ts +8 -1
  182. package/src/prices/providers/CoinGeckoPriceProvider.ts +7 -1
  183. package/src/prices/providers/CoinPaprikaPriceProvider.ts +7 -1
  184. package/src/prices/providers/CustomPriceProvider.ts +12 -1
  185. package/src/prices/providers/KrakenPriceProvider.ts +10 -1
  186. package/src/prices/providers/OKXPriceProvider.ts +7 -1
  187. package/src/prices/providers/abstract/ExchangePriceProvider.ts +3 -0
  188. package/src/storage/IUnifiedStorage.ts +19 -7
  189. package/src/storage/UnifiedSwapStorage.ts +33 -3
  190. package/src/storage-browser/IndexedDBUnifiedStorage.ts +31 -8
  191. package/src/storage-browser/LocalStorageManager.ts +25 -1
  192. package/src/swapper/Swapper.ts +599 -390
  193. package/src/swapper/SwapperFactory.ts +73 -24
  194. package/src/swapper/SwapperUtils.ts +107 -60
  195. package/src/swapper/SwapperWithChain.ts +320 -81
  196. package/src/swapper/SwapperWithSigner.ts +263 -56
  197. package/src/swaps/IAddressSwap.ts +13 -3
  198. package/src/swaps/IBTCWalletSwap.ts +26 -10
  199. package/src/swaps/IClaimableSwap.ts +41 -6
  200. package/src/swaps/IClaimableSwapWrapper.ts +11 -2
  201. package/src/swaps/IRefundableSwap.ts +34 -5
  202. package/src/swaps/ISwap.ts +224 -85
  203. package/src/swaps/ISwapWithGasDrop.ts +8 -2
  204. package/src/swaps/ISwapWrapper.ts +216 -98
  205. package/src/swaps/escrow_swaps/IEscrowSelfInitSwap.ts +64 -18
  206. package/src/swaps/escrow_swaps/IEscrowSwap.ts +83 -37
  207. package/src/swaps/escrow_swaps/IEscrowSwapWrapper.ts +61 -30
  208. package/src/swaps/escrow_swaps/frombtc/IFromBTCLNWrapper.ts +37 -19
  209. package/src/swaps/escrow_swaps/frombtc/IFromBTCSelfInitSwap.ts +123 -50
  210. package/src/swaps/escrow_swaps/frombtc/IFromBTCWrapper.ts +24 -11
  211. package/src/swaps/escrow_swaps/frombtc/ln/FromBTCLNSwap.ts +562 -258
  212. package/src/swaps/escrow_swaps/frombtc/ln/FromBTCLNWrapper.ts +156 -62
  213. package/src/swaps/escrow_swaps/frombtc/ln_auto/FromBTCLNAutoSwap.ts +592 -227
  214. package/src/swaps/escrow_swaps/frombtc/ln_auto/FromBTCLNAutoWrapper.ts +177 -74
  215. package/src/swaps/escrow_swaps/frombtc/onchain/FromBTCSwap.ts +483 -245
  216. package/src/swaps/escrow_swaps/frombtc/onchain/FromBTCWrapper.ts +141 -59
  217. package/src/swaps/escrow_swaps/tobtc/IToBTCSwap.ts +350 -195
  218. package/src/swaps/escrow_swaps/tobtc/IToBTCWrapper.ts +48 -23
  219. package/src/swaps/escrow_swaps/tobtc/ln/ToBTCLNSwap.ts +87 -40
  220. package/src/swaps/escrow_swaps/tobtc/ln/ToBTCLNWrapper.ts +110 -110
  221. package/src/swaps/escrow_swaps/tobtc/onchain/ToBTCSwap.ts +89 -34
  222. package/src/swaps/escrow_swaps/tobtc/onchain/ToBTCWrapper.ts +101 -31
  223. package/src/swaps/spv_swaps/SpvFromBTCSwap.ts +556 -259
  224. package/src/swaps/spv_swaps/SpvFromBTCWrapper.ts +292 -148
  225. package/src/swaps/trusted/ln/LnForGasSwap.ts +186 -47
  226. package/src/swaps/trusted/ln/LnForGasWrapper.ts +34 -15
  227. package/src/swaps/trusted/onchain/OnchainForGasSwap.ts +262 -88
  228. package/src/swaps/trusted/onchain/OnchainForGasWrapper.ts +41 -19
  229. package/src/types/AmountData.ts +2 -1
  230. package/src/types/CustomPriceFunction.ts +8 -2
  231. package/src/types/PriceInfoType.ts +4 -4
  232. package/src/types/SwapExecutionAction.ts +97 -5
  233. package/src/types/SwapWithSigner.ts +8 -4
  234. package/src/types/Token.ts +12 -5
  235. package/src/types/TokenAmount.ts +3 -0
  236. package/src/types/fees/Fee.ts +3 -2
  237. package/src/types/fees/FeeBreakdown.ts +3 -2
  238. package/src/types/fees/PercentagePPM.ts +4 -2
  239. package/src/types/lnurl/LNURLPay.ts +20 -12
  240. package/src/types/lnurl/LNURLWithdraw.ts +17 -10
  241. package/src/types/wallets/LightningInvoiceCreateService.ts +30 -0
  242. package/src/types/wallets/MinimalBitcoinWalletInterface.ts +3 -1
  243. package/src/types/wallets/MinimalLightningNetworkWalletInterface.ts +4 -2
  244. package/src/utils/BitcoinUtils.ts +5 -0
  245. package/src/utils/SwapUtils.ts +63 -1
  246. package/src/utils/TokenUtils.ts +12 -4
  247. package/dist/bitcoin/BitcoinRpcWithAddressIndex.d.ts +0 -68
  248. package/dist/bitcoin/BitcoinRpcWithAddressIndex.js +0 -2
  249. package/dist/bitcoin/LightningNetworkApi.d.ts +0 -12
  250. package/dist/bitcoin/LightningNetworkApi.js +0 -2
  251. package/dist/bitcoin/mempool/MempoolApi.d.ts +0 -350
  252. package/dist/bitcoin/mempool/MempoolApi.js +0 -311
  253. package/dist/bitcoin/mempool/MempoolBitcoinBlock.d.ts +0 -44
  254. package/dist/bitcoin/mempool/MempoolBitcoinBlock.js +0 -48
  255. package/dist/bitcoin/mempool/MempoolBitcoinRpc.d.ts +0 -119
  256. package/dist/bitcoin/mempool/MempoolBitcoinRpc.js +0 -361
  257. package/dist/bitcoin/mempool/synchronizer/MempoolBtcRelaySynchronizer.d.ts +0 -22
  258. package/dist/bitcoin/mempool/synchronizer/MempoolBtcRelaySynchronizer.js +0 -105
  259. package/dist/errors/PaymentAuthError.d.ts +0 -11
  260. package/dist/errors/PaymentAuthError.js +0 -23
  261. package/src/errors/PaymentAuthError.ts +0 -26
@@ -20,6 +20,7 @@ const utils_1 = require("@scure/btc-signer/utils");
20
20
  const UnifiedSwapStorage_1 = require("../storage/UnifiedSwapStorage");
21
21
  const UnifiedSwapEventListener_1 = require("../events/UnifiedSwapEventListener");
22
22
  const SpvFromBTCWrapper_1 = require("../swaps/spv_swaps/SpvFromBTCWrapper");
23
+ const SpvFromBTCSwap_1 = require("../swaps/spv_swaps/SpvFromBTCSwap");
23
24
  const SwapperUtils_1 = require("./SwapperUtils");
24
25
  const FromBTCLNAutoWrapper_1 = require("../swaps/escrow_swaps/frombtc/ln_auto/FromBTCLNAutoWrapper");
25
26
  const UserError_1 = require("../errors/UserError");
@@ -32,65 +33,41 @@ const Logger_1 = require("../utils/Logger");
32
33
  const LNURLWithdraw_1 = require("../types/lnurl/LNURLWithdraw");
33
34
  const LNURLPay_1 = require("../types/lnurl/LNURLPay");
34
35
  const RetryUtils_1 = require("../utils/RetryUtils");
35
- const btc_mempool_1 = require("@atomiqlabs/btc-mempool");
36
+ const IEscrowSwap_1 = require("../swaps/escrow_swaps/IEscrowSwap");
37
+ const LightningInvoiceCreateService_1 = require("../types/wallets/LightningInvoiceCreateService");
36
38
  /**
37
- * Core orchestrator for all swap operations with multi-chain support
39
+ * Core orchestrator for all atomiq swap operations
40
+ *
38
41
  * @category Core
39
42
  */
40
43
  class Swapper extends events_1.EventEmitter {
41
- constructor(bitcoinRpc, chainsData, pricing, tokens, messenger, options) {
44
+ /**
45
+ * @internal
46
+ */
47
+ constructor(bitcoinRpc, lightningApi, bitcoinSynchronizer, chainsData, pricing, tokens, messenger, options) {
42
48
  super();
43
49
  this.logger = (0, Logger_1.getLogger)(this.constructor.name + ": ");
44
50
  this.initialized = false;
45
- this.SwapTypeInfo = {
46
- [SwapType_1.SwapType.TO_BTC]: {
47
- requiresInputWallet: true,
48
- requiresOutputWallet: false,
49
- supportsGasDrop: false
50
- },
51
- [SwapType_1.SwapType.TO_BTCLN]: {
52
- requiresInputWallet: true,
53
- requiresOutputWallet: false,
54
- supportsGasDrop: false
55
- },
56
- [SwapType_1.SwapType.FROM_BTC]: {
57
- requiresInputWallet: false,
58
- requiresOutputWallet: true,
59
- supportsGasDrop: false
60
- },
61
- [SwapType_1.SwapType.FROM_BTCLN]: {
62
- requiresInputWallet: false,
63
- requiresOutputWallet: true,
64
- supportsGasDrop: false
65
- },
66
- [SwapType_1.SwapType.SPV_VAULT_FROM_BTC]: {
67
- requiresInputWallet: true,
68
- requiresOutputWallet: false,
69
- supportsGasDrop: true
70
- },
71
- [SwapType_1.SwapType.FROM_BTCLN_AUTO]: {
72
- requiresInputWallet: false,
73
- requiresOutputWallet: false,
74
- supportsGasDrop: true
75
- },
76
- [SwapType_1.SwapType.TRUSTED_FROM_BTC]: {
77
- requiresInputWallet: false,
78
- requiresOutputWallet: false,
79
- supportsGasDrop: false
80
- },
81
- [SwapType_1.SwapType.TRUSTED_FROM_BTCLN]: {
82
- requiresInputWallet: false,
83
- requiresOutputWallet: false,
84
- supportsGasDrop: false
85
- }
86
- };
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;
87
64
  const storagePrefix = options?.storagePrefix ?? "atomiq-";
88
65
  options ??= {};
89
66
  options.bitcoinNetwork = options.bitcoinNetwork == null ? base_1.BitcoinNetwork.TESTNET : options.bitcoinNetwork;
90
67
  const swapStorage = options.swapStorage ??= (name) => new IndexedDBUnifiedStorage_1.IndexedDBUnifiedStorage(name);
91
68
  this.options = options;
92
- this._bitcoinNetwork = options.bitcoinNetwork;
93
- this.bitcoinNetwork = options.bitcoinNetwork === base_1.BitcoinNetwork.MAINNET ? utils_1.NETWORK :
69
+ this.bitcoinNetwork = options.bitcoinNetwork;
70
+ this._btcNetwork = options.bitcoinNetwork === base_1.BitcoinNetwork.MAINNET ? utils_1.NETWORK :
94
71
  (options.bitcoinNetwork === base_1.BitcoinNetwork.TESTNET || options.bitcoinNetwork === base_1.BitcoinNetwork.TESTNET4) ? utils_1.TEST_NETWORK : {
95
72
  bech32: 'bcrt',
96
73
  pubKeyHash: 111,
@@ -99,17 +76,16 @@ class Swapper extends events_1.EventEmitter {
99
76
  };
100
77
  this.Utils = new SwapperUtils_1.SwapperUtils(this);
101
78
  this.prices = pricing;
102
- this.bitcoinRpc = bitcoinRpc;
103
- this.mempoolApi = bitcoinRpc.api;
79
+ this._bitcoinRpc = bitcoinRpc;
104
80
  this.messenger = messenger;
105
- this.tokens = {};
106
- this.tokensByTicker = {};
81
+ this._tokens = {};
82
+ this._tokensByTicker = {};
107
83
  for (let tokenData of tokens) {
108
84
  for (let chainId in tokenData.chains) {
109
85
  const chainData = tokenData.chains[chainId];
110
- this.tokens[chainId] ??= {};
111
- this.tokensByTicker[chainId] ??= {};
112
- this.tokens[chainId][chainData.address] = this.tokensByTicker[chainId][tokenData.ticker] = {
86
+ this._tokens[chainId] ??= {};
87
+ this._tokensByTicker[chainId] ??= {};
88
+ this._tokens[chainId][chainData.address] = this._tokensByTicker[chainId][tokenData.ticker] = {
113
89
  chain: "SC",
114
90
  chainId,
115
91
  ticker: tokenData.ticker,
@@ -123,9 +99,9 @@ class Swapper extends events_1.EventEmitter {
123
99
  this.swapStateListener = (swap) => {
124
100
  this.emit("swapState", swap);
125
101
  };
126
- this.chains = (0, Utils_1.objectMap)(chainsData, (chainData, key) => {
102
+ this._chains = (0, Utils_1.objectMap)(chainsData, (chainData, key) => {
127
103
  const { swapContract, chainEvents, btcRelay, chainInterface, spvVaultContract, spvVaultWithdrawalDataConstructor } = chainData;
128
- const synchronizer = new btc_mempool_1.MempoolBtcRelaySynchronizer(btcRelay, bitcoinRpc);
104
+ const synchronizer = bitcoinSynchronizer(btcRelay);
129
105
  const storageHandler = swapStorage(storagePrefix + chainData.chainId);
130
106
  const unifiedSwapStorage = new UnifiedSwapStorage_1.UnifiedSwapStorage(storageHandler, this.options.noSwapCache);
131
107
  const unifiedChainEvents = new UnifiedSwapEventListener_1.UnifiedSwapEventListener(unifiedSwapStorage, chainEvents);
@@ -134,20 +110,20 @@ class Swapper extends events_1.EventEmitter {
134
110
  getRequestTimeout: this.options.getRequestTimeout,
135
111
  postRequestTimeout: this.options.postRequestTimeout,
136
112
  });
137
- wrappers[SwapType_1.SwapType.TO_BTC] = new ToBTCWrapper_1.ToBTCWrapper(key, unifiedSwapStorage, unifiedChainEvents, chainInterface, swapContract, pricing, tokens, chainData.swapDataConstructor, this.bitcoinRpc, {
113
+ wrappers[SwapType_1.SwapType.TO_BTC] = new ToBTCWrapper_1.ToBTCWrapper(key, unifiedSwapStorage, unifiedChainEvents, chainInterface, swapContract, pricing, tokens, chainData.swapDataConstructor, this._bitcoinRpc, {
138
114
  getRequestTimeout: this.options.getRequestTimeout,
139
115
  postRequestTimeout: this.options.postRequestTimeout,
140
- bitcoinNetwork: this.bitcoinNetwork
116
+ bitcoinNetwork: this._btcNetwork
141
117
  });
142
- wrappers[SwapType_1.SwapType.FROM_BTCLN] = new FromBTCLNWrapper_1.FromBTCLNWrapper(key, unifiedSwapStorage, unifiedChainEvents, chainInterface, swapContract, pricing, tokens, chainData.swapDataConstructor, bitcoinRpc, {
118
+ wrappers[SwapType_1.SwapType.FROM_BTCLN] = new FromBTCLNWrapper_1.FromBTCLNWrapper(key, unifiedSwapStorage, unifiedChainEvents, chainInterface, swapContract, pricing, tokens, chainData.swapDataConstructor, lightningApi, {
143
119
  getRequestTimeout: this.options.getRequestTimeout,
144
120
  postRequestTimeout: this.options.postRequestTimeout,
145
- unsafeSkipLnNodeCheck: this._bitcoinNetwork === base_1.BitcoinNetwork.TESTNET4 || this._bitcoinNetwork === base_1.BitcoinNetwork.REGTEST
121
+ unsafeSkipLnNodeCheck: this.bitcoinNetwork === base_1.BitcoinNetwork.TESTNET4 || this.bitcoinNetwork === base_1.BitcoinNetwork.REGTEST
146
122
  });
147
- wrappers[SwapType_1.SwapType.FROM_BTC] = new FromBTCWrapper_1.FromBTCWrapper(key, unifiedSwapStorage, unifiedChainEvents, chainInterface, swapContract, pricing, tokens, chainData.swapDataConstructor, btcRelay, synchronizer, this.bitcoinRpc, {
123
+ wrappers[SwapType_1.SwapType.FROM_BTC] = new FromBTCWrapper_1.FromBTCWrapper(key, unifiedSwapStorage, unifiedChainEvents, chainInterface, swapContract, pricing, tokens, chainData.swapDataConstructor, btcRelay, synchronizer, this._bitcoinRpc, {
148
124
  getRequestTimeout: this.options.getRequestTimeout,
149
125
  postRequestTimeout: this.options.postRequestTimeout,
150
- bitcoinNetwork: this.bitcoinNetwork
126
+ bitcoinNetwork: this._btcNetwork
151
127
  });
152
128
  wrappers[SwapType_1.SwapType.TRUSTED_FROM_BTCLN] = new LnForGasWrapper_1.LnForGasWrapper(key, unifiedSwapStorage, unifiedChainEvents, chainInterface, pricing, tokens, {
153
129
  getRequestTimeout: this.options.getRequestTimeout,
@@ -156,20 +132,20 @@ class Swapper extends events_1.EventEmitter {
156
132
  wrappers[SwapType_1.SwapType.TRUSTED_FROM_BTC] = new OnchainForGasWrapper_1.OnchainForGasWrapper(key, unifiedSwapStorage, unifiedChainEvents, chainInterface, pricing, tokens, bitcoinRpc, {
157
133
  getRequestTimeout: this.options.getRequestTimeout,
158
134
  postRequestTimeout: this.options.postRequestTimeout,
159
- bitcoinNetwork: this.bitcoinNetwork
135
+ bitcoinNetwork: this._btcNetwork
160
136
  });
161
137
  if (spvVaultContract != null) {
162
138
  wrappers[SwapType_1.SwapType.SPV_VAULT_FROM_BTC] = new SpvFromBTCWrapper_1.SpvFromBTCWrapper(key, unifiedSwapStorage, unifiedChainEvents, chainInterface, spvVaultContract, pricing, tokens, spvVaultWithdrawalDataConstructor, btcRelay, synchronizer, bitcoinRpc, {
163
139
  getRequestTimeout: this.options.getRequestTimeout,
164
140
  postRequestTimeout: this.options.postRequestTimeout,
165
- bitcoinNetwork: this.bitcoinNetwork
141
+ bitcoinNetwork: this._btcNetwork
166
142
  });
167
143
  }
168
144
  if (swapContract.supportsInitWithoutClaimer) {
169
- wrappers[SwapType_1.SwapType.FROM_BTCLN_AUTO] = new FromBTCLNAutoWrapper_1.FromBTCLNAutoWrapper(key, unifiedSwapStorage, unifiedChainEvents, chainInterface, swapContract, pricing, tokens, chainData.swapDataConstructor, bitcoinRpc, this.messenger, {
145
+ wrappers[SwapType_1.SwapType.FROM_BTCLN_AUTO] = new FromBTCLNAutoWrapper_1.FromBTCLNAutoWrapper(key, unifiedSwapStorage, unifiedChainEvents, chainInterface, swapContract, pricing, tokens, chainData.swapDataConstructor, lightningApi, this.messenger, {
170
146
  getRequestTimeout: this.options.getRequestTimeout,
171
147
  postRequestTimeout: this.options.postRequestTimeout,
172
- unsafeSkipLnNodeCheck: this._bitcoinNetwork === base_1.BitcoinNetwork.TESTNET4 || this._bitcoinNetwork === base_1.BitcoinNetwork.REGTEST
148
+ unsafeSkipLnNodeCheck: this.bitcoinNetwork === base_1.BitcoinNetwork.TESTNET4 || this.bitcoinNetwork === base_1.BitcoinNetwork.REGTEST
173
149
  });
174
150
  }
175
151
  Object.keys(wrappers).forEach(key => wrappers[key].events.on("swapState", this.swapStateListener));
@@ -177,7 +153,7 @@ class Swapper extends events_1.EventEmitter {
177
153
  const wrapper = wrappers[val.type];
178
154
  if (wrapper == null)
179
155
  return null;
180
- return new wrapper.swapDeserializer(wrapper, val);
156
+ return new wrapper._swapDeserializer(wrapper, val);
181
157
  };
182
158
  return {
183
159
  chainEvents,
@@ -241,17 +217,17 @@ class Swapper extends events_1.EventEmitter {
241
217
  await automaticClockDriftCorrectionPromise;
242
218
  }
243
219
  const chainPromises = [];
244
- for (let chainIdentifier in this.chains) {
220
+ for (let chainIdentifier in this._chains) {
245
221
  chainPromises.push((async () => {
246
- const { swapContract, unifiedChainEvents, unifiedSwapStorage, wrappers, reviver } = this.chains[chainIdentifier];
222
+ const { swapContract, unifiedChainEvents, unifiedSwapStorage, wrappers, reviver } = this._chains[chainIdentifier];
247
223
  await swapContract.start();
248
224
  this.logger.debug("init(): Intialized swap contract: " + chainIdentifier);
249
225
  await unifiedSwapStorage.init();
250
226
  if (unifiedSwapStorage.storage instanceof IndexedDBUnifiedStorage_1.IndexedDBUnifiedStorage) {
251
227
  //Try to migrate the data here
252
228
  const storagePrefix = chainIdentifier === "SOLANA" ?
253
- "SOLv4-" + this._bitcoinNetwork + "-Swaps-" :
254
- "atomiqsdk-" + this._bitcoinNetwork + chainIdentifier + "-Swaps-";
229
+ "SOLv4-" + this.bitcoinNetwork + "-Swaps-" :
230
+ "atomiqsdk-" + this.bitcoinNetwork + chainIdentifier + "-Swaps-";
255
231
  await unifiedSwapStorage.storage.tryMigrate([
256
232
  [storagePrefix + "FromBTC", SwapType_1.SwapType.FROM_BTC],
257
233
  [storagePrefix + "FromBTCLN", SwapType_1.SwapType.FROM_BTCLN],
@@ -259,9 +235,9 @@ class Swapper extends events_1.EventEmitter {
259
235
  [storagePrefix + "ToBTCLN", SwapType_1.SwapType.TO_BTCLN]
260
236
  ], (obj) => {
261
237
  const swap = reviver(obj);
262
- if (swap.randomNonce == null) {
238
+ if (swap._randomNonce == null) {
263
239
  const oldIdentifierHash = swap.getId();
264
- swap.randomNonce = (0, Utils_1.randomBytes)(16).toString("hex");
240
+ swap._randomNonce = (0, Utils_1.randomBytes)(16).toString("hex");
265
241
  const newIdentifierHash = swap.getId();
266
242
  this.logger.info("init(): Found older swap version without randomNonce, replacing, old hash: " + oldIdentifierHash +
267
243
  " new hash: " + newIdentifierHash);
@@ -309,8 +285,8 @@ class Swapper extends events_1.EventEmitter {
309
285
  async stop() {
310
286
  if (this.initPromise)
311
287
  await this.initPromise;
312
- for (let chainIdentifier in this.chains) {
313
- const { wrappers, unifiedChainEvents } = this.chains[chainIdentifier];
288
+ for (let chainIdentifier in this._chains) {
289
+ const { wrappers, unifiedChainEvents } = this._chains[chainIdentifier];
314
290
  for (let key in wrappers) {
315
291
  const wrapper = wrappers[key];
316
292
  wrapper.events.removeListener("swapState", this.swapStateListener);
@@ -336,7 +312,7 @@ class Swapper extends events_1.EventEmitter {
336
312
  async createSwap(chainIdentifier, create, amountData, swapType, maxWaitTimeMS = 2000) {
337
313
  if (!this.initialized)
338
314
  throw new Error("Swapper not initialized, init first with swapper.init()!");
339
- if (this.chains[chainIdentifier] == null)
315
+ if (this._chains[chainIdentifier] == null)
340
316
  throw new Error("Invalid chain identifier! Unknown chain: " + chainIdentifier);
341
317
  let candidates;
342
318
  const inBtc = swapType === SwapType_1.SwapType.TO_BTCLN || swapType === SwapType_1.SwapType.TO_BTC ? !amountData.exactIn : amountData.exactIn;
@@ -374,7 +350,7 @@ class Swapper extends events_1.EventEmitter {
374
350
  }
375
351
  const abortController = new AbortController();
376
352
  this.logger.debug("createSwap() Swap candidates: ", candidates.map(lp => lp.url).join());
377
- const quotePromises = await create(candidates, abortController.signal, this.chains[chainIdentifier]);
353
+ const quotePromises = await create(candidates, abortController.signal, this._chains[chainIdentifier]);
378
354
  const promiseAll = new Promise((resolve, reject) => {
379
355
  let min;
380
356
  let max;
@@ -480,28 +456,28 @@ class Swapper extends events_1.EventEmitter {
480
456
  }
481
457
  }
482
458
  /**
483
- * Creates To BTC swap
459
+ * Creates Smart chain -> Bitcoin ({@link SwapType.TO_BTC}) swap
484
460
  *
485
- * @param chainIdentifier
486
- * @param signer
487
- * @param tokenAddress Token address to pay with
488
- * @param address Recipient's bitcoin address
489
- * @param amount Amount to send in satoshis (bitcoin's smallest denomination)
490
- * @param exactIn Whether to use exact in instead of exact out
491
- * @param additionalParams Additional parameters sent to the LP when creating the swap
492
- * @param options
461
+ * @param chainIdentifier Chain identifier string of the source smart chain
462
+ * @param signer Signer's address on the source chain
463
+ * @param tokenAddress Token address to pay with
464
+ * @param address Recipient's bitcoin address
465
+ * @param amount Amount to send in token based units (if `exactIn=true`) or receive in satoshis (if `exactIn=false`)
466
+ * @param exactIn Whether to use exact in instead of exact out
467
+ * @param additionalParams Additional parameters sent to the LP when creating the swap
468
+ * @param options Additional options for the swap
493
469
  */
494
470
  createToBTCSwap(chainIdentifier, signer, tokenAddress, address, amount, exactIn = false, additionalParams = this.options.defaultAdditionalParameters, options) {
495
- if (this.chains[chainIdentifier] == null)
471
+ if (this._chains[chainIdentifier] == null)
496
472
  throw new Error("Invalid chain identifier! Unknown chain: " + chainIdentifier);
497
473
  if (address.startsWith("bitcoin:")) {
498
474
  address = address.substring(8).split("?")[0];
499
475
  }
500
476
  if (!this.Utils.isValidBitcoinAddress(address))
501
477
  throw new Error("Invalid bitcoin address");
502
- if (!this.chains[chainIdentifier].chainInterface.isValidAddress(signer, true))
478
+ if (!this._chains[chainIdentifier].chainInterface.isValidAddress(signer, true))
503
479
  throw new Error("Invalid " + chainIdentifier + " address");
504
- signer = this.chains[chainIdentifier].chainInterface.normalizeAddress(signer);
480
+ signer = this._chains[chainIdentifier].chainInterface.normalizeAddress(signer);
505
481
  options ??= {};
506
482
  options.confirmationTarget ??= 3;
507
483
  options.confirmations ??= 2;
@@ -513,26 +489,27 @@ class Swapper extends events_1.EventEmitter {
513
489
  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);
514
490
  }
515
491
  /**
516
- * Creates To BTCLN swap
492
+ * Creates Smart chain -> Bitcoin Lightning ({@link SwapType.TO_BTCLN}) swap
517
493
  *
518
- * @param chainIdentifier
519
- * @param signer
520
- * @param tokenAddress Token address to pay with
521
- * @param paymentRequest BOLT11 lightning network invoice to be paid (needs to have a fixed amount)
522
- * @param additionalParams Additional parameters sent to the LP when creating the swap
523
- * @param options
494
+ * @param chainIdentifier Chain identifier string of the source smart chain
495
+ * @param signer Signer's address on the source chain
496
+ * @param tokenAddress Token address to pay with
497
+ * @param paymentRequest BOLT11 lightning network invoice to be paid (needs to have a fixed amount), and the swap
498
+ * amount is taken from this fixed amount, hence only exact output swaps are supported
499
+ * @param additionalParams Additional parameters sent to the LP when creating the swap
500
+ * @param options Additional options for the swap
524
501
  */
525
502
  async createToBTCLNSwap(chainIdentifier, signer, tokenAddress, paymentRequest, additionalParams = this.options.defaultAdditionalParameters, options) {
526
- if (this.chains[chainIdentifier] == null)
503
+ if (this._chains[chainIdentifier] == null)
527
504
  throw new Error("Invalid chain identifier! Unknown chain: " + chainIdentifier);
528
505
  options ??= {};
529
506
  if (paymentRequest.startsWith("lightning:"))
530
507
  paymentRequest = paymentRequest.substring(10);
531
508
  if (!this.Utils.isValidLightningInvoice(paymentRequest))
532
509
  throw new Error("Invalid lightning network invoice");
533
- if (!this.chains[chainIdentifier].chainInterface.isValidAddress(signer, true))
510
+ if (!this._chains[chainIdentifier].chainInterface.isValidAddress(signer, true))
534
511
  throw new Error("Invalid " + chainIdentifier + " address");
535
- signer = this.chains[chainIdentifier].chainInterface.normalizeAddress(signer);
512
+ signer = this._chains[chainIdentifier].chainInterface.normalizeAddress(signer);
536
513
  const parsedPR = (0, bolt11_1.decode)(paymentRequest);
537
514
  if (parsedPR.millisatoshis == null)
538
515
  throw new Error("Invalid lightning network invoice, no msat value field!");
@@ -545,25 +522,25 @@ class Swapper extends events_1.EventEmitter {
545
522
  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);
546
523
  }
547
524
  /**
548
- * Creates To BTCLN swap via LNURL-pay
525
+ * Creates Smart chain -> Bitcoin Lightning ({@link SwapType.TO_BTCLN}) swap via LNURL-pay link
549
526
  *
550
- * @param chainIdentifier
551
- * @param signer
552
- * @param tokenAddress Token address to pay with
553
- * @param lnurlPay LNURL-pay link to use for the payment
554
- * @param amount Amount to be paid in sats
555
- * @param exactIn Whether to do an exact in swap instead of exact out
556
- * @param additionalParams Additional parameters sent to the LP when creating the swap
557
- * @param options
527
+ * @param chainIdentifier Chain identifier string of the source smart chain
528
+ * @param signer Signer's address on the source chain
529
+ * @param tokenAddress Token address to pay with
530
+ * @param lnurlPay LNURL-pay link to use for the payment
531
+ * @param amount Amount to send in token based units (if `exactIn=true`) or receive in satoshis (if `exactIn=false`)
532
+ * @param exactIn Whether to do an exact in swap instead of exact out
533
+ * @param additionalParams Additional parameters sent to the LP when creating the swap
534
+ * @param options Additional options for the swap
558
535
  */
559
536
  async createToBTCLNSwapViaLNURL(chainIdentifier, signer, tokenAddress, lnurlPay, amount, exactIn = false, additionalParams = this.options.defaultAdditionalParameters, options) {
560
- if (this.chains[chainIdentifier] == null)
537
+ if (this._chains[chainIdentifier] == null)
561
538
  throw new Error("Invalid chain identifier! Unknown chain: " + chainIdentifier);
562
539
  if (typeof (lnurlPay) === "string" && !this.Utils.isValidLNURL(lnurlPay))
563
540
  throw new Error("Invalid LNURL-pay link");
564
- if (!this.chains[chainIdentifier].chainInterface.isValidAddress(signer, true))
541
+ if (!this._chains[chainIdentifier].chainInterface.isValidAddress(signer, true))
565
542
  throw new Error("Invalid " + chainIdentifier + " address");
566
- signer = this.chains[chainIdentifier].chainInterface.normalizeAddress(signer);
543
+ signer = this._chains[chainIdentifier].chainInterface.normalizeAddress(signer);
567
544
  const amountData = {
568
545
  amount,
569
546
  token: tokenAddress,
@@ -574,23 +551,23 @@ class Swapper extends events_1.EventEmitter {
574
551
  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);
575
552
  }
576
553
  /**
577
- * Creates To BTCLN swap via InvoiceCreationService
554
+ * Creates Smart chain -> Bitcoin Lightning ({@link SwapType.TO_BTCLN}) swap via {@link LightningInvoiceCreateService}
578
555
  *
579
- * @param chainIdentifier
580
- * @param signer
581
- * @param tokenAddress Token address to pay with
582
- * @param service Invoice create service object which facilitates the creation of fixed amount LN invoices
583
- * @param amount Amount to be paid in sats
584
- * @param exactIn Whether to do an exact in swap instead of exact out
585
- * @param additionalParams Additional parameters sent to the LP when creating the swap
586
- * @param options
556
+ * @param chainIdentifier Chain identifier string of the source smart chain
557
+ * @param signer Signer's address on the source chain
558
+ * @param tokenAddress Token address to pay with
559
+ * @param service Invoice create service object which facilitates the creation of fixed amount LN invoices
560
+ * @param amount Amount to send in token based units (if `exactIn=true`) or receive in satoshis (if `exactIn=false`)
561
+ * @param exactIn Whether to do an exact in swap instead of exact out
562
+ * @param additionalParams Additional parameters sent to the LP when creating the swap
563
+ * @param options Additional options for the swap
587
564
  */
588
565
  async createToBTCLNSwapViaInvoiceCreateService(chainIdentifier, signer, tokenAddress, service, amount, exactIn = false, additionalParams = this.options.defaultAdditionalParameters, options) {
589
- if (this.chains[chainIdentifier] == null)
566
+ if (this._chains[chainIdentifier] == null)
590
567
  throw new Error("Invalid chain identifier! Unknown chain: " + chainIdentifier);
591
- if (!this.chains[chainIdentifier].chainInterface.isValidAddress(signer, true))
568
+ if (!this._chains[chainIdentifier].chainInterface.isValidAddress(signer, true))
592
569
  throw new Error("Invalid " + chainIdentifier + " address");
593
- signer = this.chains[chainIdentifier].chainInterface.normalizeAddress(signer);
570
+ signer = this._chains[chainIdentifier].chainInterface.normalizeAddress(signer);
594
571
  options ??= {};
595
572
  const amountData = {
596
573
  amount,
@@ -601,200 +578,202 @@ class Swapper extends events_1.EventEmitter {
601
578
  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);
602
579
  }
603
580
  /**
604
- * Creates From BTC swap
581
+ * Creates Bitcoin -> Smart chain ({@link SwapType.SPV_VAULT_FROM_BTC}) swap
605
582
  *
606
- * @param chainIdentifier
607
- * @param signer
608
- * @param tokenAddress Token address to receive
609
- * @param amount Amount to receive, in satoshis (bitcoin's smallest denomination)
610
- * @param exactOut Whether to use a exact out instead of exact in
611
- * @param additionalParams Additional parameters sent to the LP when creating the swap
612
- * @param options
583
+ * @param chainIdentifier Chain identifier string of the destination smart chain
584
+ * @param recipient Recipient address on the destination chain
585
+ * @param tokenAddress Token address to receive
586
+ * @param amount Amount to send in satoshis (if `exactOut=false`) or receive in token based units (if `exactOut=true`)
587
+ * @param exactOut Whether to use a exact out instead of exact in
588
+ * @param additionalParams Additional parameters sent to the LP when creating the swap
589
+ * @param options Additional options for the swap
613
590
  */
614
- async createFromBTCSwapNew(chainIdentifier, signer, tokenAddress, amount, exactOut = false, additionalParams = this.options.defaultAdditionalParameters, options) {
615
- if (this.chains[chainIdentifier] == null)
591
+ async createFromBTCSwapNew(chainIdentifier, recipient, tokenAddress, amount, exactOut = false, additionalParams = this.options.defaultAdditionalParameters, options) {
592
+ if (this._chains[chainIdentifier] == null)
616
593
  throw new Error("Invalid chain identifier! Unknown chain: " + chainIdentifier);
617
- if (!this.chains[chainIdentifier].chainInterface.isValidAddress(signer, true))
594
+ if (!this._chains[chainIdentifier].chainInterface.isValidAddress(recipient, true))
618
595
  throw new Error("Invalid " + chainIdentifier + " address");
619
- signer = this.chains[chainIdentifier].chainInterface.normalizeAddress(signer);
596
+ recipient = this._chains[chainIdentifier].chainInterface.normalizeAddress(recipient);
620
597
  const amountData = {
621
598
  amount,
622
599
  token: tokenAddress,
623
600
  exactIn: !exactOut
624
601
  };
625
- return this.createSwap(chainIdentifier, (candidates, abortSignal, chain) => Promise.resolve(chain.wrappers[SwapType_1.SwapType.SPV_VAULT_FROM_BTC].create(signer, amountData, candidates, options, additionalParams, abortSignal)), amountData, SwapType_1.SwapType.SPV_VAULT_FROM_BTC);
602
+ 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);
626
603
  }
627
604
  /**
628
- * Creates From BTC swap
605
+ * Creates LEGACY Bitcoin -> Smart chain ({@link SwapType.FROM_BTC}) swap
629
606
  *
630
- * @param chainIdentifier
631
- * @param signer
632
- * @param tokenAddress Token address to receive
633
- * @param amount Amount to receive, in satoshis (bitcoin's smallest denomination)
634
- * @param exactOut Whether to use a exact out instead of exact in
635
- * @param additionalParams Additional parameters sent to the LP when creating the swap
636
- * @param options
607
+ * @param chainIdentifier Chain identifier string of the destination smart chain
608
+ * @param recipient Recipient address on the destination chain
609
+ * @param tokenAddress Token address to receive
610
+ * @param amount Amount to send in satoshis (if `exactOut=false`) or receive in token based units (if `exactOut=true`)
611
+ * @param exactOut Whether to use a exact out instead of exact in
612
+ * @param additionalParams Additional parameters sent to the LP when creating the swap
613
+ * @param options Additional options for the swap
637
614
  */
638
- async createFromBTCSwap(chainIdentifier, signer, tokenAddress, amount, exactOut = false, additionalParams = this.options.defaultAdditionalParameters, options) {
639
- if (this.chains[chainIdentifier] == null)
615
+ async createFromBTCSwap(chainIdentifier, recipient, tokenAddress, amount, exactOut = false, additionalParams = this.options.defaultAdditionalParameters, options) {
616
+ if (this._chains[chainIdentifier] == null)
640
617
  throw new Error("Invalid chain identifier! Unknown chain: " + chainIdentifier);
641
- if (!this.chains[chainIdentifier].chainInterface.isValidAddress(signer, true))
618
+ if (!this._chains[chainIdentifier].chainInterface.isValidAddress(recipient, true))
642
619
  throw new Error("Invalid " + chainIdentifier + " address");
643
- signer = this.chains[chainIdentifier].chainInterface.normalizeAddress(signer);
620
+ recipient = this._chains[chainIdentifier].chainInterface.normalizeAddress(recipient);
644
621
  const amountData = {
645
622
  amount,
646
623
  token: tokenAddress,
647
624
  exactIn: !exactOut
648
625
  };
649
- return this.createSwap(chainIdentifier, (candidates, abortSignal, chain) => Promise.resolve(chain.wrappers[SwapType_1.SwapType.FROM_BTC].create(signer, amountData, candidates, options, additionalParams, abortSignal)), amountData, SwapType_1.SwapType.FROM_BTC);
626
+ 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);
650
627
  }
651
628
  /**
652
- * Creates From BTCLN swap
629
+ * Creates LEGACY Bitcoin Lightning -> Smart chain ({@link SwapType.FROM_BTCLN}) swap
653
630
  *
654
- * @param chainIdentifier
655
- * @param signer
656
- * @param tokenAddress Token address to receive
657
- * @param amount Amount to receive, in satoshis (bitcoin's smallest denomination)
658
- * @param exactOut Whether to use exact out instead of exact in
659
- * @param additionalParams Additional parameters sent to the LP when creating the swap
660
- * @param options
631
+ * @param chainIdentifier Chain identifier string of the destination smart chain
632
+ * @param recipient Recipient address on the destination chain
633
+ * @param tokenAddress Token address to receive
634
+ * @param amount Amount to send in satoshis (if `exactOut=false`) or receive in token based units (if `exactOut=true`)
635
+ * @param exactOut Whether to use a exact out instead of exact in
636
+ * @param additionalParams Additional parameters sent to the LP when creating the swap
637
+ * @param options Additional options for the swap
661
638
  */
662
- async createFromBTCLNSwap(chainIdentifier, signer, tokenAddress, amount, exactOut = false, additionalParams = this.options.defaultAdditionalParameters, options) {
663
- if (this.chains[chainIdentifier] == null)
639
+ async createFromBTCLNSwap(chainIdentifier, recipient, tokenAddress, amount, exactOut = false, additionalParams = this.options.defaultAdditionalParameters, options) {
640
+ if (this._chains[chainIdentifier] == null)
664
641
  throw new Error("Invalid chain identifier! Unknown chain: " + chainIdentifier);
665
- if (!this.chains[chainIdentifier].chainInterface.isValidAddress(signer, true))
642
+ if (!this._chains[chainIdentifier].chainInterface.isValidAddress(recipient, true))
666
643
  throw new Error("Invalid " + chainIdentifier + " address");
667
- signer = this.chains[chainIdentifier].chainInterface.normalizeAddress(signer);
644
+ recipient = this._chains[chainIdentifier].chainInterface.normalizeAddress(recipient);
668
645
  const amountData = {
669
646
  amount,
670
647
  token: tokenAddress,
671
648
  exactIn: !exactOut
672
649
  };
673
- return this.createSwap(chainIdentifier, (candidates, abortSignal, chain) => Promise.resolve(chain.wrappers[SwapType_1.SwapType.FROM_BTCLN].create(signer, amountData, candidates, options, additionalParams, abortSignal)), amountData, SwapType_1.SwapType.FROM_BTCLN);
650
+ 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);
674
651
  }
675
652
  /**
676
- * Creates From BTCLN swap, withdrawing from LNURL-withdraw
653
+ * Creates LEGACY Bitcoin Lightning -> Smart chain ({@link SwapType.FROM_BTCLN}) swap, withdrawing from
654
+ * an LNURL-withdraw link
677
655
  *
678
- * @param chainIdentifier
679
- * @param signer
680
- * @param tokenAddress Token address to receive
681
- * @param lnurl LNURL-withdraw to pull the funds from
682
- * @param amount Amount to receive, in satoshis (bitcoin's smallest denomination)
683
- * @param exactOut Whether to use exact out instead of exact in
684
- * @param additionalParams Additional parameters sent to the LP when creating the swap
656
+ * @param chainIdentifier Chain identifier string of the destination smart chain
657
+ * @param recipient Recipient address on the destination chain
658
+ * @param tokenAddress Token address to receive
659
+ * @param lnurl LNURL-withdraw link to pull the funds from
660
+ * @param amount Amount to send in satoshis (if `exactOut=false`) or receive in token based units (if `exactOut=true`)
661
+ * @param exactOut Whether to use a exact out instead of exact in
662
+ * @param additionalParams Additional parameters sent to the LP when creating the swap
685
663
  */
686
- async createFromBTCLNSwapViaLNURL(chainIdentifier, signer, tokenAddress, lnurl, amount, exactOut = false, additionalParams = this.options.defaultAdditionalParameters) {
687
- if (this.chains[chainIdentifier] == null)
664
+ async createFromBTCLNSwapViaLNURL(chainIdentifier, recipient, tokenAddress, lnurl, amount, exactOut = false, additionalParams = this.options.defaultAdditionalParameters) {
665
+ if (this._chains[chainIdentifier] == null)
688
666
  throw new Error("Invalid chain identifier! Unknown chain: " + chainIdentifier);
689
667
  if (typeof (lnurl) === "string" && !this.Utils.isValidLNURL(lnurl))
690
668
  throw new Error("Invalid LNURL-withdraw link");
691
- if (!this.chains[chainIdentifier].chainInterface.isValidAddress(signer, true))
669
+ if (!this._chains[chainIdentifier].chainInterface.isValidAddress(recipient, true))
692
670
  throw new Error("Invalid " + chainIdentifier + " address");
693
- signer = this.chains[chainIdentifier].chainInterface.normalizeAddress(signer);
671
+ recipient = this._chains[chainIdentifier].chainInterface.normalizeAddress(recipient);
694
672
  const amountData = {
695
673
  amount,
696
674
  token: tokenAddress,
697
675
  exactIn: !exactOut
698
676
  };
699
- return this.createSwap(chainIdentifier, (candidates, abortSignal, chain) => chain.wrappers[SwapType_1.SwapType.FROM_BTCLN].createViaLNURL(signer, typeof (lnurl) === "string" ? (lnurl.startsWith("lightning:") ? lnurl.substring(10) : lnurl) : lnurl.params, amountData, candidates, additionalParams, abortSignal), amountData, SwapType_1.SwapType.FROM_BTCLN);
677
+ 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, additionalParams, abortSignal), amountData, SwapType_1.SwapType.FROM_BTCLN);
700
678
  }
701
679
  /**
702
- * Creates From BTCLN swap using new protocol
680
+ * Creates Bitcoin Lightning -> Smart chain ({@link SwapType.FROM_BTCLN_AUTO}) swap
703
681
  *
704
- * @param chainIdentifier
705
- * @param signer
706
- * @param tokenAddress Token address to receive
707
- * @param amount Amount to receive, in satoshis (bitcoin's smallest denomination)
708
- * @param exactOut Whether to use exact out instead of exact in
709
- * @param additionalParams Additional parameters sent to the LP when creating the swap
710
- * @param options
682
+ * @param chainIdentifier Chain identifier string of the destination smart chain
683
+ * @param recipient Recipient address on the destination chain
684
+ * @param tokenAddress Token address to receive
685
+ * @param amount Amount to send in satoshis (if `exactOut=false`) or receive in token based units (if `exactOut=true`)
686
+ * @param exactOut Whether to use a exact out instead of exact in
687
+ * @param additionalParams Additional parameters sent to the LP when creating the swap
688
+ * @param options Additional options for the swap
711
689
  */
712
- async createFromBTCLNSwapNew(chainIdentifier, signer, tokenAddress, amount, exactOut = false, additionalParams = this.options.defaultAdditionalParameters, options) {
713
- if (this.chains[chainIdentifier] == null)
690
+ async createFromBTCLNSwapNew(chainIdentifier, recipient, tokenAddress, amount, exactOut = false, additionalParams = this.options.defaultAdditionalParameters, options) {
691
+ if (this._chains[chainIdentifier] == null)
714
692
  throw new Error("Invalid chain identifier! Unknown chain: " + chainIdentifier);
715
- if (!this.chains[chainIdentifier].chainInterface.isValidAddress(signer, true))
693
+ if (!this._chains[chainIdentifier].chainInterface.isValidAddress(recipient, true))
716
694
  throw new Error("Invalid " + chainIdentifier + " address");
717
- signer = this.chains[chainIdentifier].chainInterface.normalizeAddress(signer);
695
+ recipient = this._chains[chainIdentifier].chainInterface.normalizeAddress(recipient);
718
696
  const amountData = {
719
697
  amount,
720
698
  token: tokenAddress,
721
699
  exactIn: !exactOut
722
700
  };
723
- return this.createSwap(chainIdentifier, (candidates, abortSignal, chain) => Promise.resolve(chain.wrappers[SwapType_1.SwapType.FROM_BTCLN_AUTO].create(signer, amountData, candidates, options, additionalParams, abortSignal)), amountData, SwapType_1.SwapType.FROM_BTCLN_AUTO);
701
+ 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);
724
702
  }
725
703
  /**
726
- * Creates From BTCLN swap using new protocol, withdrawing from LNURL-withdraw
704
+ * Creates Bitcoin Lightning -> Smart chain ({@link SwapType.FROM_BTCLN_AUTO}) swap, withdrawing from
705
+ * an LNURL-withdraw link
727
706
  *
728
- * @param chainIdentifier
729
- * @param signer
730
- * @param tokenAddress Token address to receive
731
- * @param lnurl LNURL-withdraw to pull the funds from
732
- * @param amount Amount to receive, in satoshis (bitcoin's smallest denomination)
733
- * @param exactOut Whether to use exact out instead of exact in
734
- * @param additionalParams Additional parameters sent to the LP when creating the swap
735
- * @param options
707
+ * @param chainIdentifier Chain identifier string of the destination smart chain
708
+ * @param recipient Recipient address on the destination chain
709
+ * @param tokenAddress Token address to receive
710
+ * @param lnurl LNURL-withdraw link to pull the funds from
711
+ * @param amount Amount to send in satoshis (if `exactOut=false`) or receive in token based units (if `exactOut=true`)
712
+ * @param exactOut Whether to use a exact out instead of exact in
713
+ * @param additionalParams Additional parameters sent to the LP when creating the swap
714
+ * @param options Additional options for the swap
736
715
  */
737
- async createFromBTCLNSwapNewViaLNURL(chainIdentifier, signer, tokenAddress, lnurl, amount, exactOut = false, additionalParams = this.options.defaultAdditionalParameters, options) {
738
- if (this.chains[chainIdentifier] == null)
716
+ async createFromBTCLNSwapNewViaLNURL(chainIdentifier, recipient, tokenAddress, lnurl, amount, exactOut = false, additionalParams = this.options.defaultAdditionalParameters, options) {
717
+ if (this._chains[chainIdentifier] == null)
739
718
  throw new Error("Invalid chain identifier! Unknown chain: " + chainIdentifier);
740
719
  if (typeof (lnurl) === "string" && !this.Utils.isValidLNURL(lnurl))
741
720
  throw new Error("Invalid LNURL-withdraw link");
742
- if (!this.chains[chainIdentifier].chainInterface.isValidAddress(signer, true))
721
+ if (!this._chains[chainIdentifier].chainInterface.isValidAddress(recipient, true))
743
722
  throw new Error("Invalid " + chainIdentifier + " address");
744
- signer = this.chains[chainIdentifier].chainInterface.normalizeAddress(signer);
723
+ recipient = this._chains[chainIdentifier].chainInterface.normalizeAddress(recipient);
745
724
  const amountData = {
746
725
  amount,
747
726
  token: tokenAddress,
748
727
  exactIn: !exactOut
749
728
  };
750
- return this.createSwap(chainIdentifier, (candidates, abortSignal, chain) => chain.wrappers[SwapType_1.SwapType.FROM_BTCLN_AUTO].createViaLNURL(signer, typeof (lnurl) === "string" ? (lnurl.startsWith("lightning:") ? lnurl.substring(10) : lnurl) : lnurl.params, amountData, candidates, options, additionalParams, abortSignal), amountData, SwapType_1.SwapType.FROM_BTCLN_AUTO);
729
+ 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);
751
730
  }
752
731
  /**
753
- * Creates trusted LN for Gas swap
732
+ * Creates a trusted Bitcoin Lightning -> Smart chain ({@link SwapType.TRUSTED_FROM_BTCLN}) gas swap
754
733
  *
755
- * @param chainId
756
- * @param signer
757
- * @param amount Amount of native token to receive, in base units
734
+ * @param chainIdentifier Chain identifier string of the destination smart chain
735
+ * @param recipient Recipient address on the destination chain
736
+ * @param amount Amount of native token to receive, in base units
758
737
  * @param trustedIntermediaryOrUrl URL or Intermediary object of the trusted intermediary to use, otherwise uses default
759
- * @throws {Error} If no trusted intermediary specified
738
+ * @throws {Error} If no trusted intermediary specified
760
739
  */
761
- createTrustedLNForGasSwap(chainId, signer, amount, trustedIntermediaryOrUrl) {
762
- if (this.chains[chainId] == null)
763
- throw new Error("Invalid chain identifier! Unknown chain: " + chainId);
764
- if (!this.chains[chainId].chainInterface.isValidAddress(signer, true))
765
- throw new Error("Invalid " + chainId + " address");
766
- signer = this.chains[chainId].chainInterface.normalizeAddress(signer);
740
+ createTrustedLNForGasSwap(chainIdentifier, recipient, amount, trustedIntermediaryOrUrl) {
741
+ if (this._chains[chainIdentifier] == null)
742
+ throw new Error("Invalid chain identifier! Unknown chain: " + chainIdentifier);
743
+ if (!this._chains[chainIdentifier].chainInterface.isValidAddress(recipient, true))
744
+ throw new Error("Invalid " + chainIdentifier + " address");
745
+ recipient = this._chains[chainIdentifier].chainInterface.normalizeAddress(recipient);
767
746
  const useUrl = trustedIntermediaryOrUrl ?? this.defaultTrustedIntermediary ?? this.options.defaultTrustedIntermediaryUrl;
768
747
  if (useUrl == null)
769
748
  throw new Error("No trusted intermediary specified!");
770
- return this.chains[chainId].wrappers[SwapType_1.SwapType.TRUSTED_FROM_BTCLN].create(signer, amount, useUrl);
749
+ return this._chains[chainIdentifier].wrappers[SwapType_1.SwapType.TRUSTED_FROM_BTCLN].create(recipient, amount, useUrl);
771
750
  }
772
751
  /**
773
- * Creates trusted BTC on-chain for Gas swap
752
+ * Creates a trusted Bitcoin -> Smart chain ({@link SwapType.TRUSTED_FROM_BTC}) gas swap
774
753
  *
775
- * @param chainId
776
- * @param signer
777
- * @param amount Amount of native token to receive, in base units
778
- * @param refundAddress Bitcoin refund address, in case the swap fails
779
- * @param trustedIntermediaryOrUrl URL or Intermediary object of the trusted intermediary to use, otherwise uses default
780
- * @throws {Error} If no trusted intermediary specified
754
+ * @param chainIdentifier Chain identifier string of the destination smart chain
755
+ * @param recipient Recipient address on the destination chain
756
+ * @param amount Amount of native token to receive, in base units
757
+ * @param refundAddress Bitcoin refund address, in case the swap fails the funds are refunded here
758
+ * @param trustedIntermediaryOrUrl URL or Intermediary object of the trusted intermediary to use, otherwise uses default
759
+ * @throws {Error} If no trusted intermediary specified
781
760
  */
782
- createTrustedOnchainForGasSwap(chainId, signer, amount, refundAddress, trustedIntermediaryOrUrl) {
783
- if (this.chains[chainId] == null)
784
- throw new Error("Invalid chain identifier! Unknown chain: " + chainId);
785
- if (!this.chains[chainId].chainInterface.isValidAddress(signer, true))
786
- throw new Error("Invalid " + chainId + " address");
787
- signer = this.chains[chainId].chainInterface.normalizeAddress(signer);
761
+ createTrustedOnchainForGasSwap(chainIdentifier, recipient, amount, refundAddress, trustedIntermediaryOrUrl) {
762
+ if (this._chains[chainIdentifier] == null)
763
+ throw new Error("Invalid chain identifier! Unknown chain: " + chainIdentifier);
764
+ if (!this._chains[chainIdentifier].chainInterface.isValidAddress(recipient, true))
765
+ throw new Error("Invalid " + chainIdentifier + " address");
766
+ recipient = this._chains[chainIdentifier].chainInterface.normalizeAddress(recipient);
788
767
  const useUrl = trustedIntermediaryOrUrl ?? this.defaultTrustedIntermediary ?? this.options.defaultTrustedIntermediaryUrl;
789
768
  if (useUrl == null)
790
769
  throw new Error("No trusted intermediary specified!");
791
- return this.chains[chainId].wrappers[SwapType_1.SwapType.TRUSTED_FROM_BTC].create(signer, amount, useUrl, refundAddress);
770
+ return this._chains[chainIdentifier].wrappers[SwapType_1.SwapType.TRUSTED_FROM_BTC].create(recipient, amount, useUrl, refundAddress);
792
771
  }
793
772
  /**
794
773
  * Creates a swap from srcToken to dstToken, of a specific token amount, either specifying input amount (exactIn=true)
795
774
  * or output amount (exactIn=false), NOTE: For regular -> BTC-LN (lightning) swaps the passed amount is ignored and
796
775
  * invoice's pre-set amount is used instead.
797
- * @deprecated Use swap() instead
776
+ * @deprecated Use {@link swap} instead
798
777
  *
799
778
  * @param signer Smartchain (Solana, Starknet, etc.) address of the user
800
779
  * @param srcToken Source token of the swap, user pays this token
@@ -813,9 +792,9 @@ class Swapper extends events_1.EventEmitter {
813
792
  }
814
793
  }
815
794
  /**
816
- * Creates a swap from srcToken to dstToken, of a specific token amount, either specifying input amount (exactIn=true)
817
- * or output amount (exactIn=false), NOTE: For regular SmartChain -> BTC-LN (lightning) swaps the passed amount is ignored and
818
- * invoice's pre-set amount is used instead, use LNURL-pay for dynamic amounts
795
+ * Creates a swap from srcToken to dstToken, of a specific token amount, either specifying input amount (if `exactIn=true`)
796
+ * or output amount (if `exactIn=false`), NOTE: For regular Smart chain -> BTC-LN (lightning) swaps the passed amount is ignored and
797
+ * invoice's pre-set amount is used instead, use LNURL-pay links for dynamic amounts
819
798
  *
820
799
  * @param _srcToken Source token of the swap, user pays this token
821
800
  * @param _dstToken Destination token of the swap, user receives this token
@@ -874,7 +853,7 @@ class Swapper extends events_1.EventEmitter {
874
853
  throw new Error("Amount cannot be null for to btcln swaps via LNURL-pay!");
875
854
  return this.createToBTCLNSwapViaLNURL(srcToken.chainId, src, srcToken.address, dst, amount, !!exactIn, undefined, options);
876
855
  }
877
- else if ((0, ToBTCLNWrapper_1.isInvoiceCreateService)(dst)) {
856
+ else if ((0, LightningInvoiceCreateService_1.isLightningInvoiceCreateService)(dst)) {
878
857
  if (amount == null)
879
858
  throw new Error("Amount cannot be null for to btcln swaps via InvoiceCreateService!");
880
859
  return this.createToBTCLNSwapViaInvoiceCreateService(srcToken.chainId, src, srcToken.address, dst, amount, !!exactIn, undefined, options);
@@ -907,28 +886,28 @@ class Swapper extends events_1.EventEmitter {
907
886
  if (signer != null)
908
887
  queryParams.push({ key: "initiator", value: signer });
909
888
  if (chainId == null) {
910
- const res = await Promise.all(Object.keys(this.chains).map((chainId) => {
911
- const { unifiedSwapStorage, reviver } = this.chains[chainId];
889
+ const res = await Promise.all(Object.keys(this._chains).map((chainId) => {
890
+ const { unifiedSwapStorage, reviver } = this._chains[chainId];
912
891
  return unifiedSwapStorage.query([queryParams], reviver);
913
892
  }));
914
893
  return res.flat();
915
894
  }
916
895
  else {
917
- const { unifiedSwapStorage, reviver } = this.chains[chainId];
896
+ const { unifiedSwapStorage, reviver } = this._chains[chainId];
918
897
  return await unifiedSwapStorage.query([queryParams], reviver);
919
898
  }
920
899
  }
921
900
  async getActionableSwaps(chainId, signer) {
922
901
  if (chainId == null) {
923
- const res = await Promise.all(Object.keys(this.chains).map((chainId) => {
924
- const { unifiedSwapStorage, reviver, wrappers } = this.chains[chainId];
902
+ const res = await Promise.all(Object.keys(this._chains).map((chainId) => {
903
+ const { unifiedSwapStorage, reviver, wrappers } = this._chains[chainId];
925
904
  const queryParams = [];
926
905
  for (let key in wrappers) {
927
906
  const wrapper = wrappers[key];
928
907
  const swapTypeQueryParams = [{ key: "type", value: wrapper.TYPE }];
929
908
  if (signer != null)
930
909
  swapTypeQueryParams.push({ key: "initiator", value: signer });
931
- swapTypeQueryParams.push({ key: "state", value: wrapper.pendingSwapStates });
910
+ swapTypeQueryParams.push({ key: "state", value: wrapper._pendingSwapStates });
932
911
  queryParams.push(swapTypeQueryParams);
933
912
  }
934
913
  return unifiedSwapStorage.query(queryParams, reviver);
@@ -936,14 +915,14 @@ class Swapper extends events_1.EventEmitter {
936
915
  return res.flat().filter(swap => swap.requiresAction());
937
916
  }
938
917
  else {
939
- const { unifiedSwapStorage, reviver, wrappers } = this.chains[chainId];
918
+ const { unifiedSwapStorage, reviver, wrappers } = this._chains[chainId];
940
919
  const queryParams = [];
941
920
  for (let key in wrappers) {
942
921
  const wrapper = wrappers[key];
943
922
  const swapTypeQueryParams = [{ key: "type", value: wrapper.TYPE }];
944
923
  if (signer != null)
945
924
  swapTypeQueryParams.push({ key: "initiator", value: signer });
946
- swapTypeQueryParams.push({ key: "state", value: wrapper.pendingSwapStates });
925
+ swapTypeQueryParams.push({ key: "state", value: wrapper._pendingSwapStates });
947
926
  queryParams.push(swapTypeQueryParams);
948
927
  }
949
928
  return (await unifiedSwapStorage.query(queryParams, reviver)).filter(swap => swap.requiresAction());
@@ -951,14 +930,14 @@ class Swapper extends events_1.EventEmitter {
951
930
  }
952
931
  async getRefundableSwaps(chainId, signer) {
953
932
  if (chainId == null) {
954
- const res = await Promise.all(Object.keys(this.chains).map((chainId) => {
955
- const { unifiedSwapStorage, reviver, wrappers } = this.chains[chainId];
933
+ const res = await Promise.all(Object.keys(this._chains).map((chainId) => {
934
+ const { unifiedSwapStorage, reviver, wrappers } = this._chains[chainId];
956
935
  const queryParams = [];
957
936
  for (let wrapper of [wrappers[SwapType_1.SwapType.TO_BTCLN], wrappers[SwapType_1.SwapType.TO_BTC]]) {
958
937
  const swapTypeQueryParams = [{ key: "type", value: wrapper.TYPE }];
959
938
  if (signer != null)
960
939
  swapTypeQueryParams.push({ key: "initiator", value: signer });
961
- swapTypeQueryParams.push({ key: "state", value: wrapper.refundableSwapStates });
940
+ swapTypeQueryParams.push({ key: "state", value: wrapper._refundableSwapStates });
962
941
  queryParams.push(swapTypeQueryParams);
963
942
  }
964
943
  return unifiedSwapStorage.query(queryParams, reviver);
@@ -966,13 +945,13 @@ class Swapper extends events_1.EventEmitter {
966
945
  return res.flat().filter(swap => swap.isRefundable());
967
946
  }
968
947
  else {
969
- const { unifiedSwapStorage, reviver, wrappers } = this.chains[chainId];
948
+ const { unifiedSwapStorage, reviver, wrappers } = this._chains[chainId];
970
949
  const queryParams = [];
971
950
  for (let wrapper of [wrappers[SwapType_1.SwapType.TO_BTCLN], wrappers[SwapType_1.SwapType.TO_BTC]]) {
972
951
  const swapTypeQueryParams = [{ key: "type", value: wrapper.TYPE }];
973
952
  if (signer != null)
974
953
  swapTypeQueryParams.push({ key: "initiator", value: signer });
975
- swapTypeQueryParams.push({ key: "state", value: wrapper.refundableSwapStates });
954
+ swapTypeQueryParams.push({ key: "state", value: wrapper._refundableSwapStates });
976
955
  queryParams.push(swapTypeQueryParams);
977
956
  }
978
957
  const result = await unifiedSwapStorage.query(queryParams, reviver);
@@ -981,8 +960,8 @@ class Swapper extends events_1.EventEmitter {
981
960
  }
982
961
  async getClaimableSwaps(chainId, signer) {
983
962
  if (chainId == null) {
984
- const res = await Promise.all(Object.keys(this.chains).map((chainId) => {
985
- const { unifiedSwapStorage, reviver, wrappers } = this.chains[chainId];
963
+ const res = await Promise.all(Object.keys(this._chains).map((chainId) => {
964
+ const { unifiedSwapStorage, reviver, wrappers } = this._chains[chainId];
986
965
  const queryParams = [];
987
966
  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]]) {
988
967
  if (wrapper == null)
@@ -990,7 +969,7 @@ class Swapper extends events_1.EventEmitter {
990
969
  const swapTypeQueryParams = [{ key: "type", value: wrapper.TYPE }];
991
970
  if (signer != null)
992
971
  swapTypeQueryParams.push({ key: "initiator", value: signer });
993
- swapTypeQueryParams.push({ key: "state", value: wrapper.claimableSwapStates });
972
+ swapTypeQueryParams.push({ key: "state", value: wrapper._claimableSwapStates });
994
973
  queryParams.push(swapTypeQueryParams);
995
974
  }
996
975
  return unifiedSwapStorage.query(queryParams, reviver);
@@ -998,7 +977,7 @@ class Swapper extends events_1.EventEmitter {
998
977
  return res.flat().filter(swap => swap.isClaimable());
999
978
  }
1000
979
  else {
1001
- const { unifiedSwapStorage, reviver, wrappers } = this.chains[chainId];
980
+ const { unifiedSwapStorage, reviver, wrappers } = this._chains[chainId];
1002
981
  const queryParams = [];
1003
982
  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]]) {
1004
983
  if (wrapper == null)
@@ -1006,7 +985,7 @@ class Swapper extends events_1.EventEmitter {
1006
985
  const swapTypeQueryParams = [{ key: "type", value: wrapper.TYPE }];
1007
986
  if (signer != null)
1008
987
  swapTypeQueryParams.push({ key: "initiator", value: signer });
1009
- swapTypeQueryParams.push({ key: "state", value: wrapper.claimableSwapStates });
988
+ swapTypeQueryParams.push({ key: "state", value: wrapper._claimableSwapStates });
1010
989
  queryParams.push(swapTypeQueryParams);
1011
990
  }
1012
991
  const result = await unifiedSwapStorage.query(queryParams, reviver);
@@ -1016,9 +995,9 @@ class Swapper extends events_1.EventEmitter {
1016
995
  async getSwapById(id, chainId, signer) {
1017
996
  //Check in pending swaps first
1018
997
  if (chainId != null) {
1019
- for (let key in this.chains[chainId].wrappers) {
1020
- const wrapper = this.chains[chainId].wrappers[key];
1021
- const result = wrapper.pendingSwaps.get(id)?.deref();
998
+ for (let key in this._chains[chainId].wrappers) {
999
+ const wrapper = this._chains[chainId].wrappers[key];
1000
+ const result = wrapper._getPendingSwap(id);
1022
1001
  if (result != null) {
1023
1002
  if (signer != null) {
1024
1003
  if (result._getInitiator() === signer)
@@ -1031,10 +1010,10 @@ class Swapper extends events_1.EventEmitter {
1031
1010
  }
1032
1011
  }
1033
1012
  else {
1034
- for (let chainId in this.chains) {
1035
- for (let key in this.chains[chainId].wrappers) {
1036
- const wrapper = this.chains[chainId].wrappers[key];
1037
- const result = wrapper.pendingSwaps.get(id)?.deref();
1013
+ for (let chainId in this._chains) {
1014
+ for (let key in this._chains[chainId].wrappers) {
1015
+ const wrapper = this._chains[chainId].wrappers[key];
1016
+ const result = wrapper._getPendingSwap(id);
1038
1017
  if (result != null) {
1039
1018
  if (signer != null) {
1040
1019
  if (result._getInitiator() === signer)
@@ -1052,24 +1031,24 @@ class Swapper extends events_1.EventEmitter {
1052
1031
  queryParams.push({ key: "initiator", value: signer });
1053
1032
  queryParams.push({ key: "id", value: id });
1054
1033
  if (chainId == null) {
1055
- const res = await Promise.all(Object.keys(this.chains).map((chainId) => {
1056
- const { unifiedSwapStorage, reviver } = this.chains[chainId];
1034
+ const res = await Promise.all(Object.keys(this._chains).map((chainId) => {
1035
+ const { unifiedSwapStorage, reviver } = this._chains[chainId];
1057
1036
  return unifiedSwapStorage.query([queryParams], reviver);
1058
1037
  }));
1059
1038
  return res.flat()[0];
1060
1039
  }
1061
1040
  else {
1062
- const { unifiedSwapStorage, reviver } = this.chains[chainId];
1041
+ const { unifiedSwapStorage, reviver } = this._chains[chainId];
1063
1042
  return (await unifiedSwapStorage.query([queryParams], reviver))[0];
1064
1043
  }
1065
1044
  }
1066
1045
  /**
1067
- * Returns the swap with a proper return type, or undefined, if not found, or has wrong type
1046
+ * Returns the swap with a proper return type, or `undefined` if not found or has wrong type
1068
1047
  *
1069
- * @param id
1070
- * @param chainId
1071
- * @param swapType
1072
- * @param signer
1048
+ * @param id An ID of the swap ({@link ISwap.getId})
1049
+ * @param chainId Chain identifier of the smart chain where the swap was initiated
1050
+ * @param swapType Type of the swap
1051
+ * @param signer An optional required smart chain signer address to fetch the swap for
1073
1052
  */
1074
1053
  async getTypedSwapById(id, chainId, swapType, signer) {
1075
1054
  let _swapType = swapType;
@@ -1077,10 +1056,10 @@ class Swapper extends events_1.EventEmitter {
1077
1056
  _swapType = SwapType_1.SwapType.SPV_VAULT_FROM_BTC;
1078
1057
  if (swapType === SwapType_1.SwapType.FROM_BTCLN && this.supportsSwapType(chainId, SwapType_1.SwapType.FROM_BTCLN_AUTO))
1079
1058
  _swapType = SwapType_1.SwapType.FROM_BTCLN_AUTO;
1080
- const wrapper = this.chains[chainId].wrappers[_swapType];
1059
+ const wrapper = this._chains[chainId].wrappers[_swapType];
1081
1060
  if (wrapper == null)
1082
1061
  return;
1083
- const result = wrapper.pendingSwaps.get(id)?.deref();
1062
+ const result = wrapper._getPendingSwap(id);
1084
1063
  if (result != null) {
1085
1064
  if (signer != null) {
1086
1065
  if (result._getInitiator() === signer)
@@ -1094,20 +1073,20 @@ class Swapper extends events_1.EventEmitter {
1094
1073
  if (signer != null)
1095
1074
  queryParams.push({ key: "initiator", value: signer });
1096
1075
  queryParams.push({ key: "id", value: id });
1097
- const { unifiedSwapStorage, reviver } = this.chains[chainId];
1076
+ const { unifiedSwapStorage, reviver } = this._chains[chainId];
1098
1077
  const swap = (await unifiedSwapStorage.query([queryParams], reviver))[0];
1099
1078
  if ((0, SwapUtils_1.isSwapType)(swap, swapType))
1100
1079
  return swap;
1101
1080
  }
1102
1081
  async syncSwapsForChain(chainId, signer) {
1103
- const { unifiedSwapStorage, reviver, wrappers } = this.chains[chainId];
1082
+ const { unifiedSwapStorage, reviver, wrappers } = this._chains[chainId];
1104
1083
  const queryParams = [];
1105
1084
  for (let key in wrappers) {
1106
1085
  const wrapper = wrappers[key];
1107
1086
  const swapTypeQueryParams = [{ key: "type", value: wrapper.TYPE }];
1108
1087
  if (signer != null)
1109
1088
  swapTypeQueryParams.push({ key: "initiator", value: signer });
1110
- swapTypeQueryParams.push({ key: "state", value: wrapper.pendingSwapStates });
1089
+ swapTypeQueryParams.push({ key: "state", value: wrapper._pendingSwapStates });
1111
1090
  queryParams.push(swapTypeQueryParams);
1112
1091
  }
1113
1092
  this.logger.debug("_syncSwaps(): Querying swaps swaps for chain " + chainId + "!");
@@ -1134,14 +1113,48 @@ class Swapper extends events_1.EventEmitter {
1134
1113
  removeSwaps.forEach(swap => swap._emitEvent());
1135
1114
  }
1136
1115
  /**
1137
- * Synchronizes swaps from chain, this is usually ran when SDK is initialized, deletes expired quotes
1116
+ * Deletes the swaps from the persistent storage backend. Note that some data (like lightning network
1117
+ * amounts and bolt11 invoices) are purely off-chain and can never be recovered later just from
1118
+ * on-chain data!
1119
+ *
1120
+ * @param chainId Optional, to only delete swaps for this smart chain
1121
+ * @param signer Optional, to only delete swaps for this smart chain signer (`chainId` param must be
1122
+ * set to delete only signer's swaps)
1123
+ */
1124
+ async wipeStorage(chainId, signer) {
1125
+ if (chainId == null) {
1126
+ const swaps = await this.getAllSwaps();
1127
+ const chainSwaps = {};
1128
+ swaps.forEach(swap => (chainSwaps[swap.chainIdentifier] ??= []).push(swap));
1129
+ for (let chainId in chainSwaps) {
1130
+ const currentChainSwaps = chainSwaps[chainId];
1131
+ if (this._chains[chainId] == null) {
1132
+ this.logger.warn(`wipeStorage(): Attempted to remove ${currentChainSwaps.length} swaps on ${chainId}, but smart chain not known!`);
1133
+ continue;
1134
+ }
1135
+ await this._chains[chainId].unifiedSwapStorage.removeAll(currentChainSwaps);
1136
+ this.logger.debug(`wipeStorage(): Successfully removed ${currentChainSwaps.length} swaps on ${chainId}!`);
1137
+ }
1138
+ }
1139
+ else {
1140
+ if (this._chains[chainId] == null)
1141
+ throw new Error(`wipeStorage(): Smart chain with identifier ${chainId} not found!`);
1142
+ const swaps = await this.getAllSwaps(chainId, signer);
1143
+ await this._chains[chainId].unifiedSwapStorage.removeAll(swaps);
1144
+ this.logger.debug(`wipeStorage(): Successfully removed ${swaps.length} swaps on ${chainId}!`);
1145
+ }
1146
+ }
1147
+ /**
1148
+ * Synchronizes swaps from on-chain, this is ran automatically when SDK is initialized, hence
1149
+ * should only be ran manually when `dontCheckPastSwaps=true` is passed in the swapper options,
1150
+ * also deletes expired quotes
1138
1151
  *
1139
- * @param chainId
1140
- * @param signer
1152
+ * @param chainId Optional chain identifier to only run swap sync for a single smart chain
1153
+ * @param signer Optional signer to only run swap sync for swaps initiated by this signer
1141
1154
  */
1142
1155
  async _syncSwaps(chainId, signer) {
1143
1156
  if (chainId == null) {
1144
- await Promise.all(Object.keys(this.chains).map((chainId) => {
1157
+ await Promise.all(Object.keys(this._chains).map((chainId) => {
1145
1158
  return this.syncSwapsForChain(chainId, signer);
1146
1159
  }));
1147
1160
  }
@@ -1150,18 +1163,27 @@ class Swapper extends events_1.EventEmitter {
1150
1163
  }
1151
1164
  }
1152
1165
  /**
1153
- * Attempts to recover partial swap data from on-chain historical data
1166
+ * Recovers swaps from on-chain historical data.
1154
1167
  *
1155
- * @param chainId
1156
- * @param signer
1157
- * @param startBlockheight
1168
+ * Please note that the recovered swaps might not be complete (i.e. missing amounts or addresses), as some
1169
+ * of the swap data is purely off-chain and can never be recovered purely from on-chain data. This
1170
+ * functions tries to recover as much swap data as possible.
1171
+ *
1172
+ * @param chainId Smart chain identifier string to recover the swaps from
1173
+ * @param signer Signer address to recover the swaps for
1174
+ * @param startBlockheight Optional starting blockheight for swap data recovery, will only check swaps
1175
+ * initiated after this blockheight
1158
1176
  */
1159
1177
  async recoverSwaps(chainId, signer, startBlockheight) {
1160
- const { swapContract, unifiedSwapStorage, reviver, wrappers } = this.chains[chainId];
1161
- if (swapContract.getHistoricalSwaps == null)
1178
+ const { spvVaultContract, swapContract, unifiedSwapStorage, reviver, wrappers } = this._chains[chainId];
1179
+ if (swapContract.getHistoricalSwaps == null ||
1180
+ (spvVaultContract != null && spvVaultContract.getHistoricalWithdrawalStates == null))
1162
1181
  throw new Error(`Historical swap recovery is not supported for ${chainId}`);
1163
- const { swaps } = await swapContract.getHistoricalSwaps(signer);
1182
+ const { swaps } = await swapContract.getHistoricalSwaps(signer, startBlockheight);
1183
+ const spvVaultData = await spvVaultContract?.getHistoricalWithdrawalStates(signer, startBlockheight);
1164
1184
  const escrowHashes = Object.keys(swaps);
1185
+ if (spvVaultData != null)
1186
+ Object.keys(spvVaultData.withdrawals).forEach(btcTxId => escrowHashes.push(btcTxId));
1165
1187
  this.logger.debug(`recoverSwaps(): Loaded on-chain data for ${escrowHashes.length} swaps`);
1166
1188
  this.logger.debug(`recoverSwaps(): Fetching if swap escrowHashes are known: ${escrowHashes.join(", ")}`);
1167
1189
  const knownSwapsArray = await unifiedSwapStorage.query([[{ key: "escrowHash", value: escrowHashes }]], reviver);
@@ -1176,16 +1198,21 @@ class Swapper extends events_1.EventEmitter {
1176
1198
  for (let escrowHash in swaps) {
1177
1199
  const { init, state } = swaps[escrowHash];
1178
1200
  const knownSwap = knownSwaps[escrowHash];
1179
- if (init == null) {
1180
- if (knownSwap == null)
1181
- this.logger.warn(`recoverSwaps(): Fetched ${escrowHash} swap state, but swap not found locally!`);
1182
- //TODO: Update the existing swaps here
1183
- this.logger.debug(`recoverSwaps(): Skipping ${escrowHash} swap: swap already known and in local storage!`);
1201
+ if (knownSwap == null) {
1202
+ if (init == null) {
1203
+ this.logger.warn(`recoverSwaps(escrow): Fetched ${escrowHash} swap state, but swap not found locally!`);
1204
+ continue;
1205
+ }
1206
+ }
1207
+ else if (knownSwap instanceof IEscrowSwap_1.IEscrowSwap) {
1208
+ this.logger.debug(`recoverSwaps(escrow): Forcibly updating ${escrowHash} swap: swap already known and in local storage!`);
1209
+ if (await knownSwap._forciblySetOnchainState(state)) {
1210
+ await knownSwap._save();
1211
+ }
1184
1212
  continue;
1185
1213
  }
1186
- if (knownSwap != null) {
1187
- //TODO: Update the existing swaps here
1188
- this.logger.debug(`recoverSwaps(): Skipping ${escrowHash} swap: swap already known and in local storage!`);
1214
+ else {
1215
+ this.logger.debug(`recoverSwaps(escrow): Skipping ${escrowHash} swap: swap already known and in local storage!`);
1189
1216
  continue;
1190
1217
  }
1191
1218
  const data = init.data;
@@ -1228,12 +1255,53 @@ class Swapper extends events_1.EventEmitter {
1228
1255
  }
1229
1256
  else {
1230
1257
  if (typeIdentified)
1231
- this.logger.debug(`recoverSwaps(): Swap data type correctly identified but swap returned is null for swap ${escrowHash}`);
1258
+ this.logger.debug(`recoverSwaps(escrow): Swap data type correctly identified but swap returned is null for swap ${escrowHash}`);
1259
+ }
1260
+ }
1261
+ if (spvVaultContract != null && spvVaultData != null) {
1262
+ const vaultsData = await spvVaultContract.getMultipleVaultData(Object.keys(spvVaultData.withdrawals)
1263
+ .map(btcTxId => ({
1264
+ owner: spvVaultData.withdrawals[btcTxId].owner,
1265
+ vaultId: spvVaultData.withdrawals[btcTxId].vaultId
1266
+ })));
1267
+ for (let btcTxId in spvVaultData.withdrawals) {
1268
+ const state = spvVaultData.withdrawals[btcTxId];
1269
+ const knownSwap = knownSwaps[btcTxId];
1270
+ if (knownSwap != null) {
1271
+ if (knownSwap instanceof SpvFromBTCSwap_1.SpvFromBTCSwap) {
1272
+ this.logger.debug(`recoverSwaps(spv_vault): Forcibly updating ${btcTxId} swap: swap already known and in local storage!`);
1273
+ //TODO: Forcibly set on-chain state to the swap
1274
+ // if(await knownSwap._forciblySetOnchainState(state)) {
1275
+ // await knownSwap._save();
1276
+ // }
1277
+ continue;
1278
+ }
1279
+ else {
1280
+ this.logger.debug(`recoverSwaps(spv_vault): Skipping ${btcTxId} swap: swap already known and in local storage!`);
1281
+ continue;
1282
+ }
1283
+ }
1284
+ const lp = this.intermediaryDiscovery.intermediaries.find(val => val.supportsChain(chainId) && state.owner.toLowerCase() === val.getAddress(chainId).toLowerCase());
1285
+ const swap = await wrappers[SwapType_1.SwapType.SPV_VAULT_FROM_BTC].recoverFromState(state, vaultsData[state.owner]?.[state.vaultId.toString(10)], lp);
1286
+ if (swap != null) {
1287
+ recoveredSwaps.push(swap);
1288
+ }
1289
+ else {
1290
+ this.logger.debug(`recoverSwaps(spv_vault): Swap data type correctly identified but swap returned is null for swap ${btcTxId}`);
1291
+ }
1232
1292
  }
1233
1293
  }
1234
1294
  this.logger.debug(`recoverSwaps(): Successfully recovered ${recoveredSwaps.length} swaps!`);
1235
1295
  return recoveredSwaps;
1236
1296
  }
1297
+ /**
1298
+ * Returns the {@link Token} object for a given token
1299
+ *
1300
+ * @param tickerOrAddress Token to return the object for, can use multiple formats:
1301
+ * - a) token ticker, such as `"BTC"`, `"SOL"`, etc.
1302
+ * - b) token ticker prefixed with smart chain identifier, such as `"SOLANA-SOL"`, `"SOLANA-USDC"`, etc.
1303
+ * - c) token address
1304
+ */
1237
1305
  getToken(tickerOrAddress) {
1238
1306
  //Btc tokens - BTC, BTCLN, BTC-LN
1239
1307
  if (tickerOrAddress === "BTC")
@@ -1243,23 +1311,23 @@ class Swapper extends events_1.EventEmitter {
1243
1311
  //Check if the ticker is in format <chainId>-<ticker>, i.e. SOLANA-USDC, STARKNET-WBTC
1244
1312
  if (tickerOrAddress.includes("-")) {
1245
1313
  const [chainId, ticker] = tickerOrAddress.split("-");
1246
- const token = this.tokensByTicker[chainId]?.[ticker];
1314
+ const token = this._tokensByTicker[chainId]?.[ticker];
1247
1315
  if (token == null)
1248
1316
  throw new UserError_1.UserError(`Not found ticker: ${ticker} for chainId: ${chainId}`);
1249
1317
  return token;
1250
1318
  }
1251
1319
  const possibleTokens = [];
1252
- for (let chainId in this.chains) {
1253
- const chain = this.chains[chainId];
1320
+ for (let chainId in this._chains) {
1321
+ const chain = this._chains[chainId];
1254
1322
  if (chain.chainInterface.isValidToken(tickerOrAddress)) {
1255
1323
  //Try to find in known token addresses
1256
- const token = this.tokens[chainId]?.[tickerOrAddress];
1324
+ const token = this._tokens[chainId]?.[tickerOrAddress];
1257
1325
  if (token != null)
1258
1326
  return token;
1259
1327
  }
1260
1328
  else {
1261
1329
  //Check in known tickers
1262
- const token = this.tokensByTicker[chainId]?.[tickerOrAddress];
1330
+ const token = this._tokensByTicker[chainId]?.[tickerOrAddress];
1263
1331
  if (token != null)
1264
1332
  possibleTokens.push(token);
1265
1333
  }
@@ -1274,28 +1342,34 @@ class Swapper extends events_1.EventEmitter {
1274
1342
  /**
1275
1343
  * Creates a child swapper instance with a given smart chain
1276
1344
  *
1277
- * @param chainIdentifier
1345
+ * @param chainIdentifier Smart chain identifier for the created child swapper instance
1278
1346
  */
1279
1347
  withChain(chainIdentifier) {
1280
- if (this.chains[chainIdentifier] == null)
1348
+ if (this._chains[chainIdentifier] == null)
1281
1349
  throw new Error("Invalid chain identifier! Unknown chain: " + chainIdentifier);
1282
1350
  return new SwapperWithChain_1.SwapperWithChain(this, chainIdentifier);
1283
1351
  }
1284
1352
  /**
1285
- * Returns supported smart chains
1353
+ * Returns an array of all the supported smart chains
1286
1354
  */
1287
1355
  getSmartChains() {
1288
- return Object.keys(this.chains);
1356
+ return Object.keys(this._chains);
1289
1357
  }
1290
1358
  /**
1291
1359
  * Returns whether the SDK supports a given swap type on a given chain based on currently known LPs
1292
1360
  *
1293
- * @param chainId
1294
- * @param swapType
1361
+ * @param chainId Smart chain identifier string
1362
+ * @param swapType Swap protocol type
1295
1363
  */
1296
1364
  supportsSwapType(chainId, swapType) {
1297
- return (this.chains[chainId]?.wrappers[swapType] != null);
1365
+ return (this._chains[chainId]?.wrappers[swapType] != null);
1298
1366
  }
1367
+ /**
1368
+ * Returns type of the swap based on input and output tokens specified
1369
+ *
1370
+ * @param srcToken Source token
1371
+ * @param dstToken Destination token
1372
+ */
1299
1373
  getSwapType(srcToken, dstToken) {
1300
1374
  if ((0, Token_1.isSCToken)(srcToken)) {
1301
1375
  if (!(0, Token_1.isBtcToken)(dstToken))
@@ -1332,8 +1406,8 @@ class Swapper extends events_1.EventEmitter {
1332
1406
  /**
1333
1407
  * Returns minimum/maximum limits for inputs and outputs for a swap between given tokens
1334
1408
  *
1335
- * @param srcToken
1336
- * @param dstToken
1409
+ * @param srcToken Source token
1410
+ * @param dstToken Destination token
1337
1411
  */
1338
1412
  getSwapLimits(srcToken, dstToken) {
1339
1413
  const swapType = this.getSwapType(srcToken, dstToken);
@@ -1365,7 +1439,7 @@ class Swapper extends events_1.EventEmitter {
1365
1439
  };
1366
1440
  }
1367
1441
  /**
1368
- * Returns supported tokens for a given direction
1442
+ * Returns an array of supported tokens either on the input or on the output of a swap
1369
1443
  *
1370
1444
  * @param input Whether to return input tokens or output tokens
1371
1445
  */
@@ -1421,7 +1495,7 @@ class Swapper extends events_1.EventEmitter {
1421
1495
  output.push(Token_1.BitcoinTokens.BTC);
1422
1496
  for (let chainId in tokens) {
1423
1497
  tokens[chainId].forEach(tokenAddress => {
1424
- const token = this.tokens?.[chainId]?.[tokenAddress];
1498
+ const token = this._tokens?.[chainId]?.[tokenAddress];
1425
1499
  if (token != null)
1426
1500
  output.push(token);
1427
1501
  });
@@ -1456,7 +1530,7 @@ class Swapper extends events_1.EventEmitter {
1456
1530
  const output = [];
1457
1531
  for (let chainId in tokens) {
1458
1532
  tokens[chainId].forEach(tokenAddress => {
1459
- const token = this.tokens?.[chainId]?.[tokenAddress];
1533
+ const token = this._tokens?.[chainId]?.[tokenAddress];
1460
1534
  if (token != null)
1461
1535
  output.push(token);
1462
1536
  });
@@ -1466,7 +1540,7 @@ class Swapper extends events_1.EventEmitter {
1466
1540
  /**
1467
1541
  * Returns the set of supported token addresses by all the intermediaries we know of offering a specific swapType service
1468
1542
  *
1469
- * @param chainIdentifier
1543
+ * @param chainIdentifier Chain identifier string
1470
1544
  * @param swapType Specific swap type for which to obtain supported tokens
1471
1545
  */
1472
1546
  getSupportedTokenAddresses(chainIdentifier, swapType) {
@@ -1527,45 +1601,5 @@ class Swapper extends events_1.EventEmitter {
1527
1601
  }
1528
1602
  }
1529
1603
  }
1530
- getSwapBounds(chainIdentifier) {
1531
- if (chainIdentifier == null) {
1532
- return this.intermediaryDiscovery.getMultichainSwapBounds();
1533
- }
1534
- else {
1535
- return this.intermediaryDiscovery.getSwapBounds(chainIdentifier);
1536
- }
1537
- }
1538
- /**
1539
- * Returns maximum possible swap amount
1540
- * @deprecated Use getSwapLimits() instead!
1541
- *
1542
- * @param chainIdentifier
1543
- * @param type Type of the swap
1544
- * @param token Token of the swap
1545
- */
1546
- getMaximum(chainIdentifier, type, token) {
1547
- if (this.intermediaryDiscovery != null) {
1548
- const max = this.intermediaryDiscovery.getSwapMaximum(chainIdentifier, type, token);
1549
- if (max != null)
1550
- return BigInt(max);
1551
- }
1552
- return 0n;
1553
- }
1554
- /**
1555
- * Returns minimum possible swap amount
1556
- * @deprecated Use getSwapLimits() instead!
1557
- *
1558
- * @param chainIdentifier
1559
- * @param type Type of swap
1560
- * @param token Token of the swap
1561
- */
1562
- getMinimum(chainIdentifier, type, token) {
1563
- if (this.intermediaryDiscovery != null) {
1564
- const min = this.intermediaryDiscovery.getSwapMinimum(chainIdentifier, type, token);
1565
- if (min != null)
1566
- return BigInt(min);
1567
- }
1568
- return 0n;
1569
- }
1570
1604
  }
1571
1605
  exports.Swapper = Swapper;