@atomiqlabs/lp-lib 17.5.1 → 17.5.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (170) hide show
  1. package/LICENSE +201 -201
  2. package/dist/fees/IBtcFeeEstimator.d.ts +3 -3
  3. package/dist/fees/IBtcFeeEstimator.js +2 -2
  4. package/dist/index.d.ts +43 -43
  5. package/dist/index.js +59 -59
  6. package/dist/info/InfoHandler.d.ts +17 -17
  7. package/dist/info/InfoHandler.js +61 -61
  8. package/dist/plugins/IPlugin.d.ts +158 -158
  9. package/dist/plugins/IPlugin.js +35 -35
  10. package/dist/plugins/PluginManager.d.ts +115 -115
  11. package/dist/plugins/PluginManager.js +304 -304
  12. package/dist/prices/BinanceSwapPrice.d.ts +29 -29
  13. package/dist/prices/BinanceSwapPrice.js +79 -79
  14. package/dist/prices/CoinGeckoSwapPrice.d.ts +33 -33
  15. package/dist/prices/CoinGeckoSwapPrice.js +51 -51
  16. package/dist/prices/ISwapPrice.d.ts +43 -43
  17. package/dist/prices/ISwapPrice.js +55 -55
  18. package/dist/prices/OKXSwapPrice.d.ts +29 -29
  19. package/dist/prices/OKXSwapPrice.js +79 -79
  20. package/dist/storage/IIntermediaryStorage.d.ts +18 -18
  21. package/dist/storage/IIntermediaryStorage.js +2 -2
  22. package/dist/storagemanager/IntermediaryStorageManager.d.ts +19 -19
  23. package/dist/storagemanager/IntermediaryStorageManager.js +111 -111
  24. package/dist/storagemanager/StorageManager.d.ts +13 -13
  25. package/dist/storagemanager/StorageManager.js +64 -64
  26. package/dist/swaps/SwapHandler.d.ts +178 -178
  27. package/dist/swaps/SwapHandler.js +225 -225
  28. package/dist/swaps/SwapHandlerSwap.d.ts +80 -80
  29. package/dist/swaps/SwapHandlerSwap.js +78 -78
  30. package/dist/swaps/assertions/AmountAssertions.d.ts +37 -37
  31. package/dist/swaps/assertions/AmountAssertions.js +83 -83
  32. package/dist/swaps/assertions/FromBtcAmountAssertions.d.ts +76 -76
  33. package/dist/swaps/assertions/FromBtcAmountAssertions.js +189 -189
  34. package/dist/swaps/assertions/LightningAssertions.d.ts +44 -44
  35. package/dist/swaps/assertions/LightningAssertions.js +86 -86
  36. package/dist/swaps/assertions/ToBtcAmountAssertions.d.ts +53 -53
  37. package/dist/swaps/assertions/ToBtcAmountAssertions.js +154 -154
  38. package/dist/swaps/escrow/EscrowHandler.d.ts +50 -50
  39. package/dist/swaps/escrow/EscrowHandler.js +151 -151
  40. package/dist/swaps/escrow/EscrowHandlerSwap.d.ts +35 -35
  41. package/dist/swaps/escrow/EscrowHandlerSwap.js +69 -69
  42. package/dist/swaps/escrow/FromBtcBaseSwap.d.ts +14 -14
  43. package/dist/swaps/escrow/FromBtcBaseSwap.js +32 -32
  44. package/dist/swaps/escrow/FromBtcBaseSwapHandler.d.ts +102 -102
  45. package/dist/swaps/escrow/FromBtcBaseSwapHandler.js +210 -210
  46. package/dist/swaps/escrow/ToBtcBaseSwap.d.ts +36 -36
  47. package/dist/swaps/escrow/ToBtcBaseSwap.js +67 -67
  48. package/dist/swaps/escrow/ToBtcBaseSwapHandler.d.ts +53 -53
  49. package/dist/swaps/escrow/ToBtcBaseSwapHandler.js +81 -81
  50. package/dist/swaps/escrow/frombtc_abstract/FromBtcAbs.d.ts +84 -84
  51. package/dist/swaps/escrow/frombtc_abstract/FromBtcAbs.js +329 -329
  52. package/dist/swaps/escrow/frombtc_abstract/FromBtcSwapAbs.d.ts +22 -22
  53. package/dist/swaps/escrow/frombtc_abstract/FromBtcSwapAbs.js +53 -53
  54. package/dist/swaps/escrow/frombtcln_abstract/FromBtcLnAbs.d.ts +115 -115
  55. package/dist/swaps/escrow/frombtcln_abstract/FromBtcLnAbs.js +719 -719
  56. package/dist/swaps/escrow/frombtcln_abstract/FromBtcLnSwapAbs.d.ts +34 -34
  57. package/dist/swaps/escrow/frombtcln_abstract/FromBtcLnSwapAbs.js +94 -94
  58. package/dist/swaps/escrow/frombtcln_autoinit/FromBtcLnAuto.d.ts +119 -119
  59. package/dist/swaps/escrow/frombtcln_autoinit/FromBtcLnAuto.js +730 -730
  60. package/dist/swaps/escrow/frombtcln_autoinit/FromBtcLnAutoSwap.d.ts +56 -56
  61. package/dist/swaps/escrow/frombtcln_autoinit/FromBtcLnAutoSwap.js +123 -123
  62. package/dist/swaps/escrow/tobtc_abstract/ToBtcAbs.d.ts +170 -170
  63. package/dist/swaps/escrow/tobtc_abstract/ToBtcAbs.js +769 -769
  64. package/dist/swaps/escrow/tobtc_abstract/ToBtcSwapAbs.d.ts +29 -29
  65. package/dist/swaps/escrow/tobtc_abstract/ToBtcSwapAbs.js +67 -67
  66. package/dist/swaps/escrow/tobtcln_abstract/ToBtcLnAbs.d.ts +178 -178
  67. package/dist/swaps/escrow/tobtcln_abstract/ToBtcLnAbs.js +912 -912
  68. package/dist/swaps/escrow/tobtcln_abstract/ToBtcLnSwapAbs.d.ts +25 -25
  69. package/dist/swaps/escrow/tobtcln_abstract/ToBtcLnSwapAbs.js +61 -61
  70. package/dist/swaps/spv_vault_swap/SpvVault.d.ts +45 -45
  71. package/dist/swaps/spv_vault_swap/SpvVault.js +148 -148
  72. package/dist/swaps/spv_vault_swap/SpvVaultSwap.d.ts +71 -71
  73. package/dist/swaps/spv_vault_swap/SpvVaultSwap.js +165 -165
  74. package/dist/swaps/spv_vault_swap/SpvVaultSwapHandler.d.ts +72 -72
  75. package/dist/swaps/spv_vault_swap/SpvVaultSwapHandler.js +710 -710
  76. package/dist/swaps/spv_vault_swap/SpvVaults.d.ts +70 -70
  77. package/dist/swaps/spv_vault_swap/SpvVaults.js +554 -554
  78. package/dist/swaps/spv_vault_swap/StickyAddress.d.ts +6 -6
  79. package/dist/swaps/spv_vault_swap/StickyAddress.js +19 -19
  80. package/dist/swaps/trusted/frombtc_trusted/FromBtcTrusted.d.ts +52 -52
  81. package/dist/swaps/trusted/frombtc_trusted/FromBtcTrusted.js +677 -677
  82. package/dist/swaps/trusted/frombtc_trusted/FromBtcTrustedSwap.d.ts +53 -53
  83. package/dist/swaps/trusted/frombtc_trusted/FromBtcTrustedSwap.js +121 -121
  84. package/dist/swaps/trusted/frombtcln_trusted/FromBtcLnTrusted.d.ts +77 -77
  85. package/dist/swaps/trusted/frombtcln_trusted/FromBtcLnTrusted.js +518 -518
  86. package/dist/swaps/trusted/frombtcln_trusted/FromBtcLnTrustedSwap.d.ts +35 -35
  87. package/dist/swaps/trusted/frombtcln_trusted/FromBtcLnTrustedSwap.js +84 -84
  88. package/dist/utils/BitcoinUtils.d.ts +4 -4
  89. package/dist/utils/BitcoinUtils.js +61 -61
  90. package/dist/utils/Utils.d.ts +32 -32
  91. package/dist/utils/Utils.js +130 -130
  92. package/dist/utils/paramcoders/IParamReader.d.ts +5 -5
  93. package/dist/utils/paramcoders/IParamReader.js +2 -2
  94. package/dist/utils/paramcoders/IParamWriter.d.ts +4 -4
  95. package/dist/utils/paramcoders/IParamWriter.js +2 -2
  96. package/dist/utils/paramcoders/LegacyParamEncoder.d.ts +10 -10
  97. package/dist/utils/paramcoders/LegacyParamEncoder.js +22 -22
  98. package/dist/utils/paramcoders/ParamDecoder.d.ts +25 -25
  99. package/dist/utils/paramcoders/ParamDecoder.js +222 -222
  100. package/dist/utils/paramcoders/ParamEncoder.d.ts +9 -9
  101. package/dist/utils/paramcoders/ParamEncoder.js +22 -22
  102. package/dist/utils/paramcoders/SchemaVerifier.d.ts +21 -21
  103. package/dist/utils/paramcoders/SchemaVerifier.js +84 -84
  104. package/dist/utils/paramcoders/server/ServerParamDecoder.d.ts +8 -8
  105. package/dist/utils/paramcoders/server/ServerParamDecoder.js +107 -107
  106. package/dist/utils/paramcoders/server/ServerParamEncoder.d.ts +11 -11
  107. package/dist/utils/paramcoders/server/ServerParamEncoder.js +65 -65
  108. package/dist/wallets/IBitcoinWallet.d.ts +155 -155
  109. package/dist/wallets/IBitcoinWallet.js +100 -100
  110. package/dist/wallets/ILightningWallet.d.ts +137 -137
  111. package/dist/wallets/ILightningWallet.js +37 -37
  112. package/dist/wallets/ISpvVaultSigner.d.ts +7 -7
  113. package/dist/wallets/ISpvVaultSigner.js +2 -2
  114. package/package.json +37 -37
  115. package/src/fees/IBtcFeeEstimator.ts +6 -6
  116. package/src/index.ts +54 -54
  117. package/src/info/InfoHandler.ts +106 -106
  118. package/src/plugins/IPlugin.ts +196 -196
  119. package/src/plugins/PluginManager.ts +389 -389
  120. package/src/prices/BinanceSwapPrice.ts +101 -101
  121. package/src/prices/CoinGeckoSwapPrice.ts +75 -75
  122. package/src/prices/ISwapPrice.ts +88 -88
  123. package/src/prices/OKXSwapPrice.ts +101 -101
  124. package/src/storage/IIntermediaryStorage.ts +19 -19
  125. package/src/storagemanager/IntermediaryStorageManager.ts +118 -118
  126. package/src/storagemanager/StorageManager.ts +78 -78
  127. package/src/swaps/SwapHandler.ts +337 -337
  128. package/src/swaps/SwapHandlerSwap.ts +143 -143
  129. package/src/swaps/assertions/AmountAssertions.ts +97 -97
  130. package/src/swaps/assertions/FromBtcAmountAssertions.ts +257 -257
  131. package/src/swaps/assertions/LightningAssertions.ts +103 -103
  132. package/src/swaps/assertions/ToBtcAmountAssertions.ts +209 -209
  133. package/src/swaps/escrow/EscrowHandler.ts +172 -172
  134. package/src/swaps/escrow/EscrowHandlerSwap.ts +86 -86
  135. package/src/swaps/escrow/FromBtcBaseSwap.ts +38 -38
  136. package/src/swaps/escrow/FromBtcBaseSwapHandler.ts +286 -286
  137. package/src/swaps/escrow/ToBtcBaseSwap.ts +85 -85
  138. package/src/swaps/escrow/ToBtcBaseSwapHandler.ts +129 -129
  139. package/src/swaps/escrow/frombtc_abstract/FromBtcAbs.ts +468 -468
  140. package/src/swaps/escrow/frombtc_abstract/FromBtcSwapAbs.ts +65 -65
  141. package/src/swaps/escrow/frombtcln_abstract/FromBtcLnAbs.ts +900 -900
  142. package/src/swaps/escrow/frombtcln_abstract/FromBtcLnSwapAbs.ts +145 -145
  143. package/src/swaps/escrow/frombtcln_autoinit/FromBtcLnAuto.ts +892 -892
  144. package/src/swaps/escrow/frombtcln_autoinit/FromBtcLnAutoSwap.ts +200 -200
  145. package/src/swaps/escrow/tobtc_abstract/ToBtcAbs.ts +947 -947
  146. package/src/swaps/escrow/tobtc_abstract/ToBtcSwapAbs.ts +112 -112
  147. package/src/swaps/escrow/tobtcln_abstract/ToBtcLnAbs.ts +1167 -1167
  148. package/src/swaps/escrow/tobtcln_abstract/ToBtcLnSwapAbs.ts +84 -84
  149. package/src/swaps/spv_vault_swap/SpvVault.ts +182 -182
  150. package/src/swaps/spv_vault_swap/SpvVaultSwap.ts +239 -239
  151. package/src/swaps/spv_vault_swap/SpvVaultSwapHandler.ts +897 -897
  152. package/src/swaps/spv_vault_swap/SpvVaults.ts +640 -640
  153. package/src/swaps/spv_vault_swap/StickyAddress.ts +20 -20
  154. package/src/swaps/trusted/frombtc_trusted/FromBtcTrusted.ts +782 -782
  155. package/src/swaps/trusted/frombtc_trusted/FromBtcTrustedSwap.ts +189 -189
  156. package/src/swaps/trusted/frombtcln_trusted/FromBtcLnTrusted.ts +622 -622
  157. package/src/swaps/trusted/frombtcln_trusted/FromBtcLnTrustedSwap.ts +125 -125
  158. package/src/utils/BitcoinUtils.ts +59 -59
  159. package/src/utils/Utils.ts +152 -152
  160. package/src/utils/paramcoders/IParamReader.ts +7 -7
  161. package/src/utils/paramcoders/IParamWriter.ts +8 -8
  162. package/src/utils/paramcoders/LegacyParamEncoder.ts +27 -27
  163. package/src/utils/paramcoders/ParamDecoder.ts +218 -218
  164. package/src/utils/paramcoders/ParamEncoder.ts +29 -29
  165. package/src/utils/paramcoders/SchemaVerifier.ts +96 -96
  166. package/src/utils/paramcoders/server/ServerParamDecoder.ts +118 -118
  167. package/src/utils/paramcoders/server/ServerParamEncoder.ts +75 -75
  168. package/src/wallets/IBitcoinWallet.ts +246 -246
  169. package/src/wallets/ILightningWallet.ts +201 -201
  170. package/src/wallets/ISpvVaultSigner.ts +10 -10
@@ -1,225 +1,225 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.SwapHandler = exports.SwapHandlerType = void 0;
4
- const PluginManager_1 = require("../plugins/PluginManager");
5
- const Utils_1 = require("../utils/Utils");
6
- var SwapHandlerType;
7
- (function (SwapHandlerType) {
8
- SwapHandlerType["TO_BTC"] = "TO_BTC";
9
- SwapHandlerType["FROM_BTC"] = "FROM_BTC";
10
- SwapHandlerType["TO_BTCLN"] = "TO_BTCLN";
11
- SwapHandlerType["FROM_BTCLN"] = "FROM_BTCLN";
12
- SwapHandlerType["FROM_BTCLN_TRUSTED"] = "FROM_BTCLN_TRUSTED";
13
- SwapHandlerType["FROM_BTC_TRUSTED"] = "FROM_BTC_TRUSTED";
14
- SwapHandlerType["FROM_BTC_SPV"] = "FROM_BTC_SPV";
15
- SwapHandlerType["FROM_BTCLN_AUTO"] = "FROM_BTCLN_AUTO";
16
- })(SwapHandlerType = exports.SwapHandlerType || (exports.SwapHandlerType = {}));
17
- /**
18
- * An abstract class defining a singular swap service
19
- */
20
- class SwapHandler {
21
- constructor(storageDirectory, path, chainsData, swapPricing) {
22
- this.inflightSwaps = new Set();
23
- this.logger = (0, Utils_1.getLogger)(() => "SwapHandler(" + this.type + "): ");
24
- this.swapLogger = {
25
- debug: (swap, msg, ...args) => this.logger.debug(swap.getIdentifier() + ": " + msg, ...args),
26
- info: (swap, msg, ...args) => this.logger.info(swap.getIdentifier() + ": " + msg, ...args),
27
- warn: (swap, msg, ...args) => this.logger.warn(swap.getIdentifier() + ": " + msg, ...args),
28
- error: (swap, msg, ...args) => this.logger.error(swap.getIdentifier() + ": " + msg, ...args)
29
- };
30
- this.storageManager = storageDirectory;
31
- this.chains = chainsData;
32
- this.path = path;
33
- this.swapPricing = swapPricing;
34
- this.allowedTokens = {};
35
- for (let chainId in chainsData.chains) {
36
- this.allowedTokens[chainId] = new Set(chainsData.chains[chainId].allowedTokens);
37
- }
38
- }
39
- getChain(identifier) {
40
- if (this.chains.chains[identifier] == null)
41
- throw {
42
- code: 20200,
43
- msg: "Invalid chain specified!"
44
- };
45
- return this.chains.chains[identifier];
46
- }
47
- /**
48
- * Starts the watchdog checking past swaps for expiry or claim eligibility.
49
- */
50
- async startWatchdog() {
51
- let rerun;
52
- rerun = async () => {
53
- await this.processPastSwaps().catch(e => this.logger.error("startWatchdog(): Error when processing past swaps: ", e));
54
- setTimeout(rerun, this.config.swapCheckInterval);
55
- };
56
- await rerun();
57
- }
58
- async loadData(ctor) {
59
- await this.storageManager.loadData(ctor);
60
- //Check if all swaps contain a valid amount
61
- for (let { obj: swap, hash, sequence } of await this.storageManager.query([])) {
62
- if (hash !== swap.getIdentifierHash() || sequence !== (swap.getSequence() ?? 0n)) {
63
- this.swapLogger.info(swap, "loadData(): Swap storage key or sequence mismatch, fixing," +
64
- " old hash: " + hash + " new hash: " + swap.getIdentifierHash() +
65
- " old seq: " + sequence.toString(10) + " new seq: " + (swap.getSequence() ?? 0n).toString(10));
66
- await this.storageManager.removeData(hash, sequence);
67
- await this.storageManager.saveData(swap.getIdentifierHash(), swap.getSequence(), swap);
68
- }
69
- if (this.inflightSwapStates.has(swap.state))
70
- this.inflightSwaps.add(swap.getIdentifier());
71
- }
72
- }
73
- /**
74
- * Remove swap data
75
- *
76
- * @param swap
77
- * @param ultimateState set the ultimate state of the swap before removing
78
- */
79
- async removeSwapData(swap, ultimateState) {
80
- if (this.inflightSwaps.delete(swap.getIdentifier()))
81
- this.logger.debug("removeSwapData(): Removing in-flight swap, current in-flight swaps: " + this.inflightSwaps.size);
82
- if (ultimateState != null)
83
- await swap.setState(ultimateState);
84
- if (swap != null)
85
- await PluginManager_1.PluginManager.swapRemove(swap);
86
- this.swapLogger.debug(swap, "removeSwapData(): removing swap final state: " + swap.state);
87
- await this.storageManager.removeData(swap.getIdentifierHash(), swap.getSequence());
88
- }
89
- async saveSwapData(swap) {
90
- const identifier = swap.getIdentifier();
91
- if (this.inflightSwapStates.has(swap.state)) {
92
- if (!this.inflightSwaps.has(identifier)) {
93
- this.inflightSwaps.add(identifier);
94
- this.logger.debug("saveSwapData(): Adding in-flight swap, current in-flight swaps: " + this.inflightSwaps.size);
95
- }
96
- }
97
- else {
98
- if (this.inflightSwaps.delete(identifier))
99
- this.logger.debug("saveSwapData(): Removing in-flight swap, current in-flight swaps: " + this.inflightSwaps.size);
100
- }
101
- await this.storageManager.saveData(swap.getIdentifierHash(), swap.getSequence(), swap);
102
- }
103
- /**
104
- * Pre-fetches native balance to further check if we have enough reserve in a native token
105
- *
106
- * @param chainIdentifier
107
- * @param abortController
108
- * @protected
109
- */
110
- prefetchNativeBalanceIfNeeded(chainIdentifier, abortController) {
111
- const minNativeTokenReserve = this.config.minNativeBalances?.[chainIdentifier] ?? 0n;
112
- if (minNativeTokenReserve === 0n)
113
- return null;
114
- const { chainInterface, signer } = this.getChain(chainIdentifier);
115
- return chainInterface.getBalance(signer.getAddress(), chainInterface.getNativeCurrencyAddress()).catch(e => {
116
- this.logger.error("getBalancePrefetch(): balancePrefetch error: ", e);
117
- abortController.abort(e);
118
- return null;
119
- });
120
- }
121
- /**
122
- * Checks if we have enough native balance to facilitate swaps
123
- *
124
- * @param chainIdentifier
125
- * @param balancePrefetch
126
- * @param signal
127
- * @throws {DefinedRuntimeError} will throw an error if there are not enough funds in the vault
128
- */
129
- async checkNativeBalance(chainIdentifier, balancePrefetch, signal) {
130
- if (signal != null)
131
- signal.throwIfAborted();
132
- const minNativeTokenReserve = this.config.minNativeBalances?.[chainIdentifier] ?? 0n;
133
- if (minNativeTokenReserve === 0n)
134
- return;
135
- const balance = await balancePrefetch;
136
- if (signal != null)
137
- signal.throwIfAborted();
138
- if (balance == null) {
139
- throw new Error("Failed to fetch native token balance!");
140
- }
141
- if (balance < minNativeTokenReserve) {
142
- throw {
143
- code: 20012,
144
- msg: "LP ran out of native token to cover gas fees"
145
- };
146
- }
147
- }
148
- /**
149
- * Checks whether there are too many swaps in-flight currently
150
- * @private
151
- */
152
- checkTooManyInflightSwaps() {
153
- if (this.config.maxInflightSwaps == null)
154
- return;
155
- if (this.inflightSwaps.size >= this.config.maxInflightSwaps)
156
- throw {
157
- code: 20013,
158
- msg: "LP has too many in-flight swaps, retry later!"
159
- };
160
- }
161
- /**
162
- * Checks if we have enough balance of the token in the swap vault
163
- *
164
- * @param totalInToken
165
- * @param balancePrefetch
166
- * @param signal
167
- * @throws {DefinedRuntimeError} will throw an error if there are not enough funds in the vault
168
- */
169
- async checkBalance(totalInToken, balancePrefetch, signal) {
170
- const balance = await balancePrefetch;
171
- if (signal != null)
172
- signal.throwIfAborted();
173
- if (balance == null || balance < totalInToken) {
174
- throw {
175
- code: 20002,
176
- msg: "Not enough liquidity"
177
- };
178
- }
179
- }
180
- /**
181
- * Checks if the sequence number is between 0-2^64
182
- *
183
- * @param sequence
184
- * @throws {DefinedRuntimeError} will throw an error if sequence number is out of bounds
185
- */
186
- checkSequence(sequence) {
187
- if (sequence < 0n || sequence >= 2n ** 64n) {
188
- throw {
189
- code: 20060,
190
- msg: "Invalid sequence"
191
- };
192
- }
193
- }
194
- /**
195
- * Checks whether a given token is supported on a specified chain
196
- *
197
- * @param chainId
198
- * @param token
199
- * @protected
200
- */
201
- isTokenSupported(chainId, token) {
202
- const chainTokens = this.allowedTokens[chainId];
203
- if (chainTokens == null)
204
- return false;
205
- return chainTokens.has(token);
206
- }
207
- getInfo() {
208
- const chainTokens = {};
209
- for (let chainId in this.allowedTokens) {
210
- chainTokens[chainId] = Array.from(this.allowedTokens[chainId]);
211
- }
212
- return {
213
- swapFeePPM: Number(this.config.feePPM),
214
- swapBaseFee: Number(this.config.baseFee),
215
- min: Number(this.config.min),
216
- max: Number(this.config.max),
217
- data: this.getInfoData(),
218
- chainTokens
219
- };
220
- }
221
- getInitAuthorizationTimeout(chainIdentifier) {
222
- return this.config.initAuthorizationTimeouts?.[chainIdentifier] ?? this.config.initAuthorizationTimeout;
223
- }
224
- }
225
- exports.SwapHandler = SwapHandler;
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.SwapHandler = exports.SwapHandlerType = void 0;
4
+ const PluginManager_1 = require("../plugins/PluginManager");
5
+ const Utils_1 = require("../utils/Utils");
6
+ var SwapHandlerType;
7
+ (function (SwapHandlerType) {
8
+ SwapHandlerType["TO_BTC"] = "TO_BTC";
9
+ SwapHandlerType["FROM_BTC"] = "FROM_BTC";
10
+ SwapHandlerType["TO_BTCLN"] = "TO_BTCLN";
11
+ SwapHandlerType["FROM_BTCLN"] = "FROM_BTCLN";
12
+ SwapHandlerType["FROM_BTCLN_TRUSTED"] = "FROM_BTCLN_TRUSTED";
13
+ SwapHandlerType["FROM_BTC_TRUSTED"] = "FROM_BTC_TRUSTED";
14
+ SwapHandlerType["FROM_BTC_SPV"] = "FROM_BTC_SPV";
15
+ SwapHandlerType["FROM_BTCLN_AUTO"] = "FROM_BTCLN_AUTO";
16
+ })(SwapHandlerType = exports.SwapHandlerType || (exports.SwapHandlerType = {}));
17
+ /**
18
+ * An abstract class defining a singular swap service
19
+ */
20
+ class SwapHandler {
21
+ constructor(storageDirectory, path, chainsData, swapPricing) {
22
+ this.inflightSwaps = new Set();
23
+ this.logger = (0, Utils_1.getLogger)(() => "SwapHandler(" + this.type + "): ");
24
+ this.swapLogger = {
25
+ debug: (swap, msg, ...args) => this.logger.debug(swap.getIdentifier() + ": " + msg, ...args),
26
+ info: (swap, msg, ...args) => this.logger.info(swap.getIdentifier() + ": " + msg, ...args),
27
+ warn: (swap, msg, ...args) => this.logger.warn(swap.getIdentifier() + ": " + msg, ...args),
28
+ error: (swap, msg, ...args) => this.logger.error(swap.getIdentifier() + ": " + msg, ...args)
29
+ };
30
+ this.storageManager = storageDirectory;
31
+ this.chains = chainsData;
32
+ this.path = path;
33
+ this.swapPricing = swapPricing;
34
+ this.allowedTokens = {};
35
+ for (let chainId in chainsData.chains) {
36
+ this.allowedTokens[chainId] = new Set(chainsData.chains[chainId].allowedTokens);
37
+ }
38
+ }
39
+ getChain(identifier) {
40
+ if (this.chains.chains[identifier] == null)
41
+ throw {
42
+ code: 20200,
43
+ msg: "Invalid chain specified!"
44
+ };
45
+ return this.chains.chains[identifier];
46
+ }
47
+ /**
48
+ * Starts the watchdog checking past swaps for expiry or claim eligibility.
49
+ */
50
+ async startWatchdog() {
51
+ let rerun;
52
+ rerun = async () => {
53
+ await this.processPastSwaps().catch(e => this.logger.error("startWatchdog(): Error when processing past swaps: ", e));
54
+ setTimeout(rerun, this.config.swapCheckInterval);
55
+ };
56
+ await rerun();
57
+ }
58
+ async loadData(ctor) {
59
+ await this.storageManager.loadData(ctor);
60
+ //Check if all swaps contain a valid amount
61
+ for (let { obj: swap, hash, sequence } of await this.storageManager.query([])) {
62
+ if (hash !== swap.getIdentifierHash() || sequence !== (swap.getSequence() ?? 0n)) {
63
+ this.swapLogger.info(swap, "loadData(): Swap storage key or sequence mismatch, fixing," +
64
+ " old hash: " + hash + " new hash: " + swap.getIdentifierHash() +
65
+ " old seq: " + sequence.toString(10) + " new seq: " + (swap.getSequence() ?? 0n).toString(10));
66
+ await this.storageManager.removeData(hash, sequence);
67
+ await this.storageManager.saveData(swap.getIdentifierHash(), swap.getSequence(), swap);
68
+ }
69
+ if (this.inflightSwapStates.has(swap.state))
70
+ this.inflightSwaps.add(swap.getIdentifier());
71
+ }
72
+ }
73
+ /**
74
+ * Remove swap data
75
+ *
76
+ * @param swap
77
+ * @param ultimateState set the ultimate state of the swap before removing
78
+ */
79
+ async removeSwapData(swap, ultimateState) {
80
+ if (this.inflightSwaps.delete(swap.getIdentifier()))
81
+ this.logger.debug("removeSwapData(): Removing in-flight swap, current in-flight swaps: " + this.inflightSwaps.size);
82
+ if (ultimateState != null)
83
+ await swap.setState(ultimateState);
84
+ if (swap != null)
85
+ await PluginManager_1.PluginManager.swapRemove(swap);
86
+ this.swapLogger.debug(swap, "removeSwapData(): removing swap final state: " + swap.state);
87
+ await this.storageManager.removeData(swap.getIdentifierHash(), swap.getSequence());
88
+ }
89
+ async saveSwapData(swap) {
90
+ const identifier = swap.getIdentifier();
91
+ if (this.inflightSwapStates.has(swap.state)) {
92
+ if (!this.inflightSwaps.has(identifier)) {
93
+ this.inflightSwaps.add(identifier);
94
+ this.logger.debug("saveSwapData(): Adding in-flight swap, current in-flight swaps: " + this.inflightSwaps.size);
95
+ }
96
+ }
97
+ else {
98
+ if (this.inflightSwaps.delete(identifier))
99
+ this.logger.debug("saveSwapData(): Removing in-flight swap, current in-flight swaps: " + this.inflightSwaps.size);
100
+ }
101
+ await this.storageManager.saveData(swap.getIdentifierHash(), swap.getSequence(), swap);
102
+ }
103
+ /**
104
+ * Pre-fetches native balance to further check if we have enough reserve in a native token
105
+ *
106
+ * @param chainIdentifier
107
+ * @param abortController
108
+ * @protected
109
+ */
110
+ prefetchNativeBalanceIfNeeded(chainIdentifier, abortController) {
111
+ const minNativeTokenReserve = this.config.minNativeBalances?.[chainIdentifier] ?? 0n;
112
+ if (minNativeTokenReserve === 0n)
113
+ return null;
114
+ const { chainInterface, signer } = this.getChain(chainIdentifier);
115
+ return chainInterface.getBalance(signer.getAddress(), chainInterface.getNativeCurrencyAddress()).catch(e => {
116
+ this.logger.error("getBalancePrefetch(): balancePrefetch error: ", e);
117
+ abortController.abort(e);
118
+ return null;
119
+ });
120
+ }
121
+ /**
122
+ * Checks if we have enough native balance to facilitate swaps
123
+ *
124
+ * @param chainIdentifier
125
+ * @param balancePrefetch
126
+ * @param signal
127
+ * @throws {DefinedRuntimeError} will throw an error if there are not enough funds in the vault
128
+ */
129
+ async checkNativeBalance(chainIdentifier, balancePrefetch, signal) {
130
+ if (signal != null)
131
+ signal.throwIfAborted();
132
+ const minNativeTokenReserve = this.config.minNativeBalances?.[chainIdentifier] ?? 0n;
133
+ if (minNativeTokenReserve === 0n)
134
+ return;
135
+ const balance = await balancePrefetch;
136
+ if (signal != null)
137
+ signal.throwIfAborted();
138
+ if (balance == null) {
139
+ throw new Error("Failed to fetch native token balance!");
140
+ }
141
+ if (balance < minNativeTokenReserve) {
142
+ throw {
143
+ code: 20012,
144
+ msg: "LP ran out of native token to cover gas fees"
145
+ };
146
+ }
147
+ }
148
+ /**
149
+ * Checks whether there are too many swaps in-flight currently
150
+ * @private
151
+ */
152
+ checkTooManyInflightSwaps() {
153
+ if (this.config.maxInflightSwaps == null)
154
+ return;
155
+ if (this.inflightSwaps.size >= this.config.maxInflightSwaps)
156
+ throw {
157
+ code: 20013,
158
+ msg: "LP has too many in-flight swaps, retry later!"
159
+ };
160
+ }
161
+ /**
162
+ * Checks if we have enough balance of the token in the swap vault
163
+ *
164
+ * @param totalInToken
165
+ * @param balancePrefetch
166
+ * @param signal
167
+ * @throws {DefinedRuntimeError} will throw an error if there are not enough funds in the vault
168
+ */
169
+ async checkBalance(totalInToken, balancePrefetch, signal) {
170
+ const balance = await balancePrefetch;
171
+ if (signal != null)
172
+ signal.throwIfAborted();
173
+ if (balance == null || balance < totalInToken) {
174
+ throw {
175
+ code: 20002,
176
+ msg: "Not enough liquidity"
177
+ };
178
+ }
179
+ }
180
+ /**
181
+ * Checks if the sequence number is between 0-2^64
182
+ *
183
+ * @param sequence
184
+ * @throws {DefinedRuntimeError} will throw an error if sequence number is out of bounds
185
+ */
186
+ checkSequence(sequence) {
187
+ if (sequence < 0n || sequence >= 2n ** 64n) {
188
+ throw {
189
+ code: 20060,
190
+ msg: "Invalid sequence"
191
+ };
192
+ }
193
+ }
194
+ /**
195
+ * Checks whether a given token is supported on a specified chain
196
+ *
197
+ * @param chainId
198
+ * @param token
199
+ * @protected
200
+ */
201
+ isTokenSupported(chainId, token) {
202
+ const chainTokens = this.allowedTokens[chainId];
203
+ if (chainTokens == null)
204
+ return false;
205
+ return chainTokens.has(token);
206
+ }
207
+ getInfo() {
208
+ const chainTokens = {};
209
+ for (let chainId in this.allowedTokens) {
210
+ chainTokens[chainId] = Array.from(this.allowedTokens[chainId]);
211
+ }
212
+ return {
213
+ swapFeePPM: Number(this.config.feePPM),
214
+ swapBaseFee: Number(this.config.baseFee),
215
+ min: Number(this.config.min),
216
+ max: Number(this.config.max),
217
+ data: this.getInfoData(),
218
+ chainTokens
219
+ };
220
+ }
221
+ getInitAuthorizationTimeout(chainIdentifier) {
222
+ return this.config.initAuthorizationTimeouts?.[chainIdentifier] ?? this.config.initAuthorizationTimeout;
223
+ }
224
+ }
225
+ exports.SwapHandler = SwapHandler;
@@ -1,80 +1,80 @@
1
- import { Lockable, StorageObject } from "@atomiqlabs/base";
2
- import { SwapHandlerType } from "./SwapHandler";
3
- export declare abstract class SwapHandlerSwap<S = any> extends Lockable implements StorageObject {
4
- type: SwapHandlerType;
5
- chainIdentifier: string;
6
- state: S;
7
- metadata: {
8
- request: any;
9
- times: {
10
- [key: string]: number;
11
- };
12
- [key: string]: any;
13
- };
14
- txIds: {
15
- [key: string]: string;
16
- };
17
- readonly swapFee: bigint;
18
- readonly swapFeeInToken: bigint;
19
- protected constructor(chainIdentifier: string, swapFee: bigint, swapFeeInToken: bigint);
20
- protected constructor(obj: any);
21
- serialize(): any;
22
- /**
23
- * Sets the state of the swap and also calls swap change listener on plugins
24
- *
25
- * @param newState
26
- */
27
- setState(newState: S): Promise<void>;
28
- /**
29
- * Returns the identification hash of the swap, usually claim data hash, but can be overriden, e.g. for
30
- * lightning swaps the identifier hash is used instead of claim data hash
31
- */
32
- abstract getIdentifierHash(): string;
33
- abstract getSequence(): bigint | null;
34
- /**
35
- * Returns unique identifier of the swap in the form <hash>_<sequence> or just <hash> if the swap type doesn't
36
- * use sequence number
37
- */
38
- getIdentifier(): string;
39
- /**
40
- * Returns the smart chain token used for the swap
41
- */
42
- abstract getToken(): string;
43
- /**
44
- * Checks whether the swap is finished, such that it is final and either successful or failed
45
- */
46
- isFinished(): boolean;
47
- /**
48
- * Checks whether the swap was initiated by the user
49
- */
50
- abstract isInitiated(): boolean;
51
- /**
52
- * Checks whether the swap was finished and was successful
53
- */
54
- abstract isSuccess(): boolean;
55
- /**
56
- * Checks whether the swap was finished and was failed
57
- */
58
- abstract isFailed(): boolean;
59
- /**
60
- * Returns the input amount paid by the user (excluding fees)
61
- */
62
- getInputAmount(): bigint;
63
- /**
64
- * Returns the total input amount paid by the user (including all fees)
65
- */
66
- abstract getTotalInputAmount(): bigint;
67
- /**
68
- * Returns the actual output amount paid out to the user
69
- */
70
- abstract getOutputAmount(): bigint;
71
- /**
72
- * Returns swap fee, denominated in input & output tokens (the fee is paid only once, it is just represented here in
73
- * both denomination for ease of use)
74
- */
75
- abstract getSwapFee(): {
76
- inInputToken: bigint;
77
- inOutputToken: bigint;
78
- };
79
- abstract getDestinationAddress(): string;
80
- }
1
+ import { Lockable, StorageObject } from "@atomiqlabs/base";
2
+ import { SwapHandlerType } from "./SwapHandler";
3
+ export declare abstract class SwapHandlerSwap<S = any> extends Lockable implements StorageObject {
4
+ type: SwapHandlerType;
5
+ chainIdentifier: string;
6
+ state: S;
7
+ metadata: {
8
+ request: any;
9
+ times: {
10
+ [key: string]: number;
11
+ };
12
+ [key: string]: any;
13
+ };
14
+ txIds: {
15
+ [key: string]: string;
16
+ };
17
+ readonly swapFee: bigint;
18
+ readonly swapFeeInToken: bigint;
19
+ protected constructor(chainIdentifier: string, swapFee: bigint, swapFeeInToken: bigint);
20
+ protected constructor(obj: any);
21
+ serialize(): any;
22
+ /**
23
+ * Sets the state of the swap and also calls swap change listener on plugins
24
+ *
25
+ * @param newState
26
+ */
27
+ setState(newState: S): Promise<void>;
28
+ /**
29
+ * Returns the identification hash of the swap, usually claim data hash, but can be overriden, e.g. for
30
+ * lightning swaps the identifier hash is used instead of claim data hash
31
+ */
32
+ abstract getIdentifierHash(): string;
33
+ abstract getSequence(): bigint | null;
34
+ /**
35
+ * Returns unique identifier of the swap in the form <hash>_<sequence> or just <hash> if the swap type doesn't
36
+ * use sequence number
37
+ */
38
+ getIdentifier(): string;
39
+ /**
40
+ * Returns the smart chain token used for the swap
41
+ */
42
+ abstract getToken(): string;
43
+ /**
44
+ * Checks whether the swap is finished, such that it is final and either successful or failed
45
+ */
46
+ isFinished(): boolean;
47
+ /**
48
+ * Checks whether the swap was initiated by the user
49
+ */
50
+ abstract isInitiated(): boolean;
51
+ /**
52
+ * Checks whether the swap was finished and was successful
53
+ */
54
+ abstract isSuccess(): boolean;
55
+ /**
56
+ * Checks whether the swap was finished and was failed
57
+ */
58
+ abstract isFailed(): boolean;
59
+ /**
60
+ * Returns the input amount paid by the user (excluding fees)
61
+ */
62
+ getInputAmount(): bigint;
63
+ /**
64
+ * Returns the total input amount paid by the user (including all fees)
65
+ */
66
+ abstract getTotalInputAmount(): bigint;
67
+ /**
68
+ * Returns the actual output amount paid out to the user
69
+ */
70
+ abstract getOutputAmount(): bigint;
71
+ /**
72
+ * Returns swap fee, denominated in input & output tokens (the fee is paid only once, it is just represented here in
73
+ * both denomination for ease of use)
74
+ */
75
+ abstract getSwapFee(): {
76
+ inInputToken: bigint;
77
+ inOutputToken: bigint;
78
+ };
79
+ abstract getDestinationAddress(): string;
80
+ }