@atomiqlabs/lp-lib 13.0.0-beta.9 → 13.0.0

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 (160) 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 +40 -40
  5. package/dist/index.js +56 -56
  6. package/dist/info/InfoHandler.d.ts +17 -17
  7. package/dist/info/InfoHandler.js +61 -61
  8. package/dist/plugins/IPlugin.d.ts +143 -143
  9. package/dist/plugins/IPlugin.js +34 -34
  10. package/dist/plugins/PluginManager.d.ts +112 -112
  11. package/dist/plugins/PluginManager.js +259 -259
  12. package/dist/prices/BinanceSwapPrice.d.ts +26 -26
  13. package/dist/prices/BinanceSwapPrice.js +92 -92
  14. package/dist/prices/CoinGeckoSwapPrice.d.ts +30 -30
  15. package/dist/prices/CoinGeckoSwapPrice.js +64 -64
  16. package/dist/prices/ISwapPrice.d.ts +43 -43
  17. package/dist/prices/ISwapPrice.js +55 -55
  18. package/dist/prices/OKXSwapPrice.d.ts +26 -26
  19. package/dist/prices/OKXSwapPrice.js +92 -92
  20. package/dist/storage/IIntermediaryStorage.d.ts +18 -18
  21. package/dist/storage/IIntermediaryStorage.js +2 -2
  22. package/dist/storagemanager/IntermediaryStorageManager.d.ts +18 -18
  23. package/dist/storagemanager/IntermediaryStorageManager.js +104 -104
  24. package/dist/storagemanager/StorageManager.d.ts +12 -12
  25. package/dist/storagemanager/StorageManager.js +57 -57
  26. package/dist/swaps/SwapHandler.d.ts +156 -156
  27. package/dist/swaps/SwapHandler.js +163 -163
  28. package/dist/swaps/SwapHandlerSwap.d.ts +79 -79
  29. package/dist/swaps/SwapHandlerSwap.js +78 -78
  30. package/dist/swaps/assertions/AmountAssertions.d.ts +28 -28
  31. package/dist/swaps/assertions/AmountAssertions.js +72 -72
  32. package/dist/swaps/assertions/FromBtcAmountAssertions.d.ts +76 -76
  33. package/dist/swaps/assertions/FromBtcAmountAssertions.js +172 -172
  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 +150 -150
  38. package/dist/swaps/escrow/EscrowHandler.d.ts +51 -51
  39. package/dist/swaps/escrow/EscrowHandler.js +158 -158
  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 +101 -101
  45. package/dist/swaps/escrow/FromBtcBaseSwapHandler.js +207 -207
  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 +83 -83
  51. package/dist/swaps/escrow/frombtc_abstract/FromBtcAbs.js +318 -318
  52. package/dist/swaps/escrow/frombtc_abstract/FromBtcSwapAbs.d.ts +21 -21
  53. package/dist/swaps/escrow/frombtc_abstract/FromBtcSwapAbs.js +50 -50
  54. package/dist/swaps/escrow/frombtcln_abstract/FromBtcLnAbs.d.ts +107 -107
  55. package/dist/swaps/escrow/frombtcln_abstract/FromBtcLnAbs.js +648 -648
  56. package/dist/swaps/escrow/frombtcln_abstract/FromBtcLnSwapAbs.d.ts +32 -32
  57. package/dist/swaps/escrow/frombtcln_abstract/FromBtcLnSwapAbs.js +88 -88
  58. package/dist/swaps/escrow/tobtc_abstract/ToBtcAbs.d.ts +171 -171
  59. package/dist/swaps/escrow/tobtc_abstract/ToBtcAbs.js +702 -702
  60. package/dist/swaps/escrow/tobtc_abstract/ToBtcSwapAbs.d.ts +26 -26
  61. package/dist/swaps/escrow/tobtc_abstract/ToBtcSwapAbs.js +62 -62
  62. package/dist/swaps/escrow/tobtcln_abstract/ToBtcLnAbs.d.ts +177 -177
  63. package/dist/swaps/escrow/tobtcln_abstract/ToBtcLnAbs.js +857 -857
  64. package/dist/swaps/escrow/tobtcln_abstract/ToBtcLnSwapAbs.d.ts +23 -23
  65. package/dist/swaps/escrow/tobtcln_abstract/ToBtcLnSwapAbs.js +56 -56
  66. package/dist/swaps/spv_vault_swap/SpvVault.d.ts +41 -41
  67. package/dist/swaps/spv_vault_swap/SpvVault.js +111 -111
  68. package/dist/swaps/spv_vault_swap/SpvVaultSwap.d.ts +67 -67
  69. package/dist/swaps/spv_vault_swap/SpvVaultSwap.js +158 -158
  70. package/dist/swaps/spv_vault_swap/SpvVaultSwapHandler.d.ts +68 -68
  71. package/dist/swaps/spv_vault_swap/SpvVaultSwapHandler.js +488 -478
  72. package/dist/swaps/spv_vault_swap/SpvVaults.d.ts +57 -57
  73. package/dist/swaps/spv_vault_swap/SpvVaults.js +369 -369
  74. package/dist/swaps/trusted/frombtc_trusted/FromBtcTrusted.d.ts +51 -51
  75. package/dist/swaps/trusted/frombtc_trusted/FromBtcTrusted.js +650 -650
  76. package/dist/swaps/trusted/frombtc_trusted/FromBtcTrustedSwap.d.ts +52 -52
  77. package/dist/swaps/trusted/frombtc_trusted/FromBtcTrustedSwap.js +118 -118
  78. package/dist/swaps/trusted/frombtcln_trusted/FromBtcLnTrusted.d.ts +76 -76
  79. package/dist/swaps/trusted/frombtcln_trusted/FromBtcLnTrusted.js +495 -495
  80. package/dist/swaps/trusted/frombtcln_trusted/FromBtcLnTrustedSwap.d.ts +34 -34
  81. package/dist/swaps/trusted/frombtcln_trusted/FromBtcLnTrustedSwap.js +81 -81
  82. package/dist/utils/Utils.d.ts +29 -29
  83. package/dist/utils/Utils.js +88 -88
  84. package/dist/utils/paramcoders/IParamReader.d.ts +5 -5
  85. package/dist/utils/paramcoders/IParamReader.js +2 -2
  86. package/dist/utils/paramcoders/IParamWriter.d.ts +4 -4
  87. package/dist/utils/paramcoders/IParamWriter.js +2 -2
  88. package/dist/utils/paramcoders/LegacyParamEncoder.d.ts +10 -10
  89. package/dist/utils/paramcoders/LegacyParamEncoder.js +22 -22
  90. package/dist/utils/paramcoders/ParamDecoder.d.ts +25 -25
  91. package/dist/utils/paramcoders/ParamDecoder.js +222 -222
  92. package/dist/utils/paramcoders/ParamEncoder.d.ts +9 -9
  93. package/dist/utils/paramcoders/ParamEncoder.js +22 -22
  94. package/dist/utils/paramcoders/SchemaVerifier.d.ts +21 -21
  95. package/dist/utils/paramcoders/SchemaVerifier.js +84 -84
  96. package/dist/utils/paramcoders/server/ServerParamDecoder.d.ts +8 -8
  97. package/dist/utils/paramcoders/server/ServerParamDecoder.js +105 -105
  98. package/dist/utils/paramcoders/server/ServerParamEncoder.d.ts +11 -11
  99. package/dist/utils/paramcoders/server/ServerParamEncoder.js +65 -65
  100. package/dist/wallets/IBitcoinWallet.d.ts +67 -67
  101. package/dist/wallets/IBitcoinWallet.js +2 -2
  102. package/dist/wallets/ILightningWallet.d.ts +117 -117
  103. package/dist/wallets/ILightningWallet.js +37 -37
  104. package/dist/wallets/ISpvVaultSigner.d.ts +7 -7
  105. package/dist/wallets/ISpvVaultSigner.js +2 -2
  106. package/dist/wallets/ISpvVaultWallet.d.ts +42 -42
  107. package/dist/wallets/ISpvVaultWallet.js +2 -2
  108. package/package.json +36 -36
  109. package/src/fees/IBtcFeeEstimator.ts +6 -6
  110. package/src/index.ts +51 -51
  111. package/src/info/InfoHandler.ts +106 -106
  112. package/src/plugins/IPlugin.ts +168 -168
  113. package/src/plugins/PluginManager.ts +336 -336
  114. package/src/prices/BinanceSwapPrice.ts +113 -113
  115. package/src/prices/CoinGeckoSwapPrice.ts +87 -87
  116. package/src/prices/ISwapPrice.ts +88 -88
  117. package/src/prices/OKXSwapPrice.ts +113 -113
  118. package/src/storage/IIntermediaryStorage.ts +19 -19
  119. package/src/storagemanager/IntermediaryStorageManager.ts +109 -109
  120. package/src/storagemanager/StorageManager.ts +68 -68
  121. package/src/swaps/SwapHandler.ts +280 -280
  122. package/src/swaps/SwapHandlerSwap.ts +141 -141
  123. package/src/swaps/assertions/AmountAssertions.ts +76 -76
  124. package/src/swaps/assertions/FromBtcAmountAssertions.ts +238 -238
  125. package/src/swaps/assertions/LightningAssertions.ts +103 -103
  126. package/src/swaps/assertions/ToBtcAmountAssertions.ts +203 -203
  127. package/src/swaps/escrow/EscrowHandler.ts +179 -179
  128. package/src/swaps/escrow/EscrowHandlerSwap.ts +86 -86
  129. package/src/swaps/escrow/FromBtcBaseSwap.ts +38 -38
  130. package/src/swaps/escrow/FromBtcBaseSwapHandler.ts +283 -283
  131. package/src/swaps/escrow/ToBtcBaseSwap.ts +85 -85
  132. package/src/swaps/escrow/ToBtcBaseSwapHandler.ts +129 -129
  133. package/src/swaps/escrow/frombtc_abstract/FromBtcAbs.ts +452 -452
  134. package/src/swaps/escrow/frombtc_abstract/FromBtcSwapAbs.ts +61 -61
  135. package/src/swaps/escrow/frombtcln_abstract/FromBtcLnAbs.ts +828 -828
  136. package/src/swaps/escrow/frombtcln_abstract/FromBtcLnSwapAbs.ts +137 -137
  137. package/src/swaps/escrow/tobtc_abstract/ToBtcAbs.ts +876 -876
  138. package/src/swaps/escrow/tobtc_abstract/ToBtcSwapAbs.ts +102 -102
  139. package/src/swaps/escrow/tobtcln_abstract/ToBtcLnAbs.ts +1107 -1107
  140. package/src/swaps/escrow/tobtcln_abstract/ToBtcLnSwapAbs.ts +77 -77
  141. package/src/swaps/spv_vault_swap/SpvVault.ts +143 -143
  142. package/src/swaps/spv_vault_swap/SpvVaultSwap.ts +225 -225
  143. package/src/swaps/spv_vault_swap/SpvVaultSwapHandler.ts +624 -613
  144. package/src/swaps/spv_vault_swap/SpvVaults.ts +440 -440
  145. package/src/swaps/trusted/frombtc_trusted/FromBtcTrusted.ts +747 -747
  146. package/src/swaps/trusted/frombtc_trusted/FromBtcTrustedSwap.ts +185 -185
  147. package/src/swaps/trusted/frombtcln_trusted/FromBtcLnTrusted.ts +592 -592
  148. package/src/swaps/trusted/frombtcln_trusted/FromBtcLnTrustedSwap.ts +121 -121
  149. package/src/utils/Utils.ts +102 -102
  150. package/src/utils/paramcoders/IParamReader.ts +7 -7
  151. package/src/utils/paramcoders/IParamWriter.ts +8 -8
  152. package/src/utils/paramcoders/LegacyParamEncoder.ts +27 -27
  153. package/src/utils/paramcoders/ParamDecoder.ts +218 -218
  154. package/src/utils/paramcoders/ParamEncoder.ts +29 -29
  155. package/src/utils/paramcoders/SchemaVerifier.ts +96 -96
  156. package/src/utils/paramcoders/server/ServerParamDecoder.ts +115 -115
  157. package/src/utils/paramcoders/server/ServerParamEncoder.ts +75 -75
  158. package/src/wallets/IBitcoinWallet.ts +68 -68
  159. package/src/wallets/ILightningWallet.ts +178 -178
  160. package/src/wallets/ISpvVaultSigner.ts +10 -10
@@ -1,284 +1,284 @@
1
- import {SwapData} from "@atomiqlabs/base";
2
- import {MultichainData, SwapBaseConfig} from "../SwapHandler";
3
- import {IParamReader} from "../../utils/paramcoders/IParamReader";
4
- import {FieldTypeEnum} from "../../utils/paramcoders/SchemaVerifier";
5
- import {Request} from "express";
6
- import {EscrowHandler} from "./EscrowHandler";
7
- import {FromBtcBaseSwap} from "./FromBtcBaseSwap";
8
- import {FromBtcAmountAssertions} from "../assertions/FromBtcAmountAssertions";
9
- import {IIntermediaryStorage} from "../../storage/IIntermediaryStorage";
10
- import {ISwapPrice} from "../../prices/ISwapPrice";
11
-
12
- const secondsInYear = BigInt(365*24*60*60);
13
-
14
- export type FromBtcBaseConfig = SwapBaseConfig & {
15
- securityDepositAPY: number
16
- };
17
-
18
- export abstract class FromBtcBaseSwapHandler<V extends FromBtcBaseSwap<SwapData, S>, S> extends EscrowHandler<V, S> {
19
-
20
- abstract config: FromBtcBaseConfig;
21
-
22
- readonly AmountAssertions: FromBtcAmountAssertions;
23
-
24
- constructor(
25
- storageDirectory: IIntermediaryStorage<V>,
26
- path: string,
27
- chainsData: MultichainData,
28
- swapPricing: ISwapPrice,
29
- config: FromBtcBaseConfig
30
- ) {
31
- super(storageDirectory, path, chainsData, swapPricing);
32
- this.AmountAssertions = new FromBtcAmountAssertions(config, swapPricing);
33
- }
34
-
35
- /**
36
- * Starts a pre-fetch for swap price & security deposit price
37
- *
38
- * @param chainIdentifier
39
- * @param useToken
40
- * @param depositToken
41
- * @param abortController
42
- */
43
- protected getFromBtcPricePrefetches(chainIdentifier: string, useToken: string, depositToken: string, abortController: AbortController): {
44
- pricePrefetchPromise: Promise<bigint>,
45
- gasTokenPricePrefetchPromise: Promise<bigint>,
46
- depositTokenPricePrefetchPromise: Promise<bigint>
47
- } {
48
- const pricePrefetchPromise: Promise<bigint> = this.swapPricing.preFetchPrice(useToken, chainIdentifier).catch(e => {
49
- this.logger.error("getFromBtcPricePrefetches(): pricePrefetch error: ", e);
50
- abortController.abort(e);
51
- return null;
52
- });
53
- const {chainInterface} = this.getChain(chainIdentifier);
54
- const gasTokenPricePrefetchPromise: Promise<bigint> = useToken.toString()===chainInterface.getNativeCurrencyAddress().toString() ?
55
- pricePrefetchPromise :
56
- this.swapPricing.preFetchPrice(chainInterface.getNativeCurrencyAddress(), chainIdentifier).catch(e => {
57
- this.logger.error("getFromBtcPricePrefetches(): gasTokenPricePrefetchPromise error: ", e);
58
- abortController.abort(e);
59
- return null;
60
- });
61
- const depositTokenPricePrefetchPromise: Promise<bigint> = depositToken===chainInterface.getNativeCurrencyAddress() ?
62
- gasTokenPricePrefetchPromise :
63
- this.swapPricing.preFetchPrice(depositToken, chainIdentifier).catch(e => {
64
- this.logger.error("getFromBtcPricePrefetches(): depositTokenPricePrefetchPromise error: ", e);
65
- abortController.abort(e);
66
- return null;
67
- });
68
- return {pricePrefetchPromise, gasTokenPricePrefetchPromise, depositTokenPricePrefetchPromise};
69
- }
70
-
71
- /**
72
- * Starts a pre-fetch for base security deposit (transaction fee for refunding transaction on our side)
73
- *
74
- * @param chainIdentifier
75
- * @param dummySwapData
76
- * @param depositToken
77
- * @param gasTokenPricePrefetchPromise
78
- * @param depositTokenPricePrefetchPromise
79
- * @param abortController
80
- */
81
- protected async getBaseSecurityDepositPrefetch(
82
- chainIdentifier: string, dummySwapData: SwapData, depositToken: string,
83
- gasTokenPricePrefetchPromise: Promise<bigint>, depositTokenPricePrefetchPromise: Promise<bigint>,
84
- abortController: AbortController
85
- ): Promise<bigint> {
86
- //Solana workaround
87
- const {swapContract, chainInterface} = this.getChain(chainIdentifier);
88
- let feeResult: bigint;
89
- const gasToken = chainInterface.getNativeCurrencyAddress();
90
- if (swapContract.getRawRefundFee != null) {
91
- try {
92
- feeResult = await swapContract.getRawRefundFee(dummySwapData);
93
- } catch (e) {
94
- this.logger.error("getBaseSecurityDepositPrefetch(): pre-fetch error: ", e);
95
- abortController.abort(e);
96
- return null;
97
- }
98
- } else {
99
- try {
100
- feeResult = await swapContract.getRefundFee(dummySwapData);
101
- } catch (e1) {
102
- this.logger.error("getBaseSecurityDepositPrefetch(): pre-fetch error: ", e1);
103
- abortController.abort(e1);
104
- return null;
105
- }
106
- }
107
- feeResult = feeResult * 2n;
108
- if(gasToken===depositToken) return feeResult;
109
- const btcValue = await this.swapPricing.getToBtcSwapAmount(feeResult, gasToken, chainIdentifier, true, gasTokenPricePrefetchPromise);
110
- return await this.swapPricing.getFromBtcSwapAmount(btcValue, depositToken, chainIdentifier, true, depositTokenPricePrefetchPromise);
111
- }
112
-
113
- /**
114
- * Starts a pre-fetch for vault balance
115
- *
116
- * @param chainIdentifier
117
- * @param useToken
118
- * @param abortController
119
- */
120
- protected async getBalancePrefetch(chainIdentifier: string, useToken: string, abortController: AbortController): Promise<bigint> {
121
- const {swapContract, signer} = this.getChain(chainIdentifier);
122
- try {
123
- return await swapContract.getBalance(signer.getAddress(), useToken, true);
124
- } catch (e) {
125
- this.logger.error("getBalancePrefetch(): balancePrefetch error: ", e);
126
- abortController.abort(e);
127
- return null;
128
- }
129
- }
130
-
131
- /**
132
- * Checks if we have enough balance of the token in the swap vault
133
- *
134
- * @param totalInToken
135
- * @param balancePrefetch
136
- * @param signal
137
- * @throws {DefinedRuntimeError} will throw an error if there are not enough funds in the vault
138
- */
139
- protected async checkBalance(totalInToken: bigint, balancePrefetch: Promise<bigint>, signal: AbortSignal | null): Promise<void> {
140
- const balance = await balancePrefetch;
141
- if(signal!=null) signal.throwIfAborted();
142
-
143
- if(balance==null || balance < totalInToken) {
144
- throw {
145
- code: 20002,
146
- msg: "Not enough liquidity"
147
- };
148
- }
149
- }
150
-
151
- /**
152
- * Checks if the specified token is allowed as a deposit token
153
- *
154
- * @param chainIdentifier
155
- * @param depositToken
156
- * @throws {DefinedRuntimeError} will throw an error if there are not enough funds in the vault
157
- */
158
- protected checkAllowedDepositToken(chainIdentifier: string, depositToken: string): void {
159
- const {chainInterface, allowedDepositTokens} = this.getChain(chainIdentifier);
160
- if(allowedDepositTokens==null) {
161
- if(depositToken!==chainInterface.getNativeCurrencyAddress()) throw {
162
- code: 20190,
163
- msg: "Unsupported deposit token"
164
- };
165
- } else {
166
- if(!allowedDepositTokens.includes(depositToken)) throw {
167
- code: 20190,
168
- msg: "Unsupported deposit token"
169
- };
170
- }
171
- }
172
-
173
- /**
174
- * Signs the created swap
175
- *
176
- * @param chainIdentifier
177
- * @param swapObject
178
- * @param req
179
- * @param abortSignal
180
- * @param signDataPrefetchPromise
181
- */
182
- protected async getFromBtcSignatureData(
183
- chainIdentifier: string,
184
- swapObject: SwapData,
185
- req: Request & {paramReader: IParamReader},
186
- abortSignal: AbortSignal,
187
- signDataPrefetchPromise?: Promise<any>
188
- ): Promise<{
189
- prefix: string,
190
- timeout: string,
191
- signature: string,
192
- feeRate: string
193
- }> {
194
- const {swapContract, signer} = this.getChain(chainIdentifier);
195
-
196
- const prefetchedSignData = signDataPrefetchPromise!=null ? await signDataPrefetchPromise : null;
197
- if(prefetchedSignData!=null) this.logger.debug("getFromBtcSignatureData(): pre-fetched signature data: ", prefetchedSignData);
198
- abortSignal.throwIfAborted();
199
-
200
- const feeRateObj = await req.paramReader.getParams({
201
- feeRate: FieldTypeEnum.String
202
- }).catch(() => null);
203
- abortSignal.throwIfAborted();
204
-
205
- const feeRate = feeRateObj?.feeRate!=null && typeof(feeRateObj.feeRate)==="string" ? feeRateObj.feeRate : null;
206
- this.logger.debug("getFromBtcSignatureData(): using fee rate from client: ", feeRate);
207
- const sigData = await swapContract.getInitSignature(
208
- signer,
209
- swapObject,
210
- this.getInitAuthorizationTimeout(chainIdentifier),
211
- prefetchedSignData,
212
- feeRate
213
- );
214
- abortSignal.throwIfAborted();
215
-
216
- return {
217
- ...sigData,
218
- feeRate
219
- };
220
- }
221
-
222
- /**
223
- * Calculates the required security deposit
224
- *
225
- * @param chainIdentifier
226
- * @param amountBD
227
- * @param swapFee
228
- * @param expiryTimeout
229
- * @param baseSecurityDepositPromise
230
- * @param depositToken
231
- * @param depositTokenPricePrefetchPromise
232
- * @param securityDepositData
233
- * @param signal
234
- * @param metadata
235
- */
236
- protected async getSecurityDeposit(
237
- chainIdentifier: string,
238
- amountBD: bigint,
239
- swapFee: bigint,
240
- expiryTimeout: bigint,
241
- baseSecurityDepositPromise: Promise<bigint>,
242
- depositToken: string,
243
- depositTokenPricePrefetchPromise: Promise<bigint>,
244
- securityDepositData: {
245
- securityDepositApyPPM?: bigint,
246
- securityDepositBaseMultiplierPPM?: bigint,
247
- },
248
- signal: AbortSignal,
249
- metadata: any
250
- ): Promise<bigint> {
251
- let baseSD: bigint = await baseSecurityDepositPromise;
252
- if(securityDepositData.securityDepositBaseMultiplierPPM!=null)
253
- baseSD = baseSD * securityDepositData.securityDepositBaseMultiplierPPM / 1_000_000n;
254
-
255
- signal.throwIfAborted();
256
-
257
- metadata.times.refundFeeFetched = Date.now();
258
-
259
- const swapValueInDepositToken = await this.swapPricing.getFromBtcSwapAmount(
260
- amountBD - swapFee,
261
- depositToken,
262
- chainIdentifier,
263
- true,
264
- depositTokenPricePrefetchPromise
265
- );
266
-
267
- signal.throwIfAborted();
268
-
269
- const apyPPM = securityDepositData.securityDepositApyPPM ?? BigInt(Math.floor(this.config.securityDepositAPY*1000000));
270
- const variableSD = swapValueInDepositToken * apyPPM * expiryTimeout / 1000000n / secondsInYear;
271
-
272
- this.logger.debug(
273
- "getSecurityDeposit(): base security deposit: "+baseSD.toString(10)+
274
- " deposit token: "+depositToken+
275
- " swap output in deposit token: "+swapValueInDepositToken.toString(10)+
276
- " apy ppm: "+apyPPM.toString(10)+
277
- " expiry timeout: "+expiryTimeout.toString(10)+
278
- " variable security deposit: "+variableSD.toString(10)
279
- );
280
-
281
- return baseSD + variableSD;
282
- }
283
-
1
+ import {SwapData} from "@atomiqlabs/base";
2
+ import {MultichainData, SwapBaseConfig} from "../SwapHandler";
3
+ import {IParamReader} from "../../utils/paramcoders/IParamReader";
4
+ import {FieldTypeEnum} from "../../utils/paramcoders/SchemaVerifier";
5
+ import {Request} from "express";
6
+ import {EscrowHandler} from "./EscrowHandler";
7
+ import {FromBtcBaseSwap} from "./FromBtcBaseSwap";
8
+ import {FromBtcAmountAssertions} from "../assertions/FromBtcAmountAssertions";
9
+ import {IIntermediaryStorage} from "../../storage/IIntermediaryStorage";
10
+ import {ISwapPrice} from "../../prices/ISwapPrice";
11
+
12
+ const secondsInYear = BigInt(365*24*60*60);
13
+
14
+ export type FromBtcBaseConfig = SwapBaseConfig & {
15
+ securityDepositAPY: number
16
+ };
17
+
18
+ export abstract class FromBtcBaseSwapHandler<V extends FromBtcBaseSwap<SwapData, S>, S> extends EscrowHandler<V, S> {
19
+
20
+ abstract config: FromBtcBaseConfig;
21
+
22
+ readonly AmountAssertions: FromBtcAmountAssertions;
23
+
24
+ constructor(
25
+ storageDirectory: IIntermediaryStorage<V>,
26
+ path: string,
27
+ chainsData: MultichainData,
28
+ swapPricing: ISwapPrice,
29
+ config: FromBtcBaseConfig
30
+ ) {
31
+ super(storageDirectory, path, chainsData, swapPricing);
32
+ this.AmountAssertions = new FromBtcAmountAssertions(config, swapPricing);
33
+ }
34
+
35
+ /**
36
+ * Starts a pre-fetch for swap price & security deposit price
37
+ *
38
+ * @param chainIdentifier
39
+ * @param useToken
40
+ * @param depositToken
41
+ * @param abortController
42
+ */
43
+ protected getFromBtcPricePrefetches(chainIdentifier: string, useToken: string, depositToken: string, abortController: AbortController): {
44
+ pricePrefetchPromise: Promise<bigint>,
45
+ gasTokenPricePrefetchPromise: Promise<bigint>,
46
+ depositTokenPricePrefetchPromise: Promise<bigint>
47
+ } {
48
+ const pricePrefetchPromise: Promise<bigint> = this.swapPricing.preFetchPrice(useToken, chainIdentifier).catch(e => {
49
+ this.logger.error("getFromBtcPricePrefetches(): pricePrefetch error: ", e);
50
+ abortController.abort(e);
51
+ return null;
52
+ });
53
+ const {chainInterface} = this.getChain(chainIdentifier);
54
+ const gasTokenPricePrefetchPromise: Promise<bigint> = useToken.toString()===chainInterface.getNativeCurrencyAddress().toString() ?
55
+ pricePrefetchPromise :
56
+ this.swapPricing.preFetchPrice(chainInterface.getNativeCurrencyAddress(), chainIdentifier).catch(e => {
57
+ this.logger.error("getFromBtcPricePrefetches(): gasTokenPricePrefetchPromise error: ", e);
58
+ abortController.abort(e);
59
+ return null;
60
+ });
61
+ const depositTokenPricePrefetchPromise: Promise<bigint> = depositToken===chainInterface.getNativeCurrencyAddress() ?
62
+ gasTokenPricePrefetchPromise :
63
+ this.swapPricing.preFetchPrice(depositToken, chainIdentifier).catch(e => {
64
+ this.logger.error("getFromBtcPricePrefetches(): depositTokenPricePrefetchPromise error: ", e);
65
+ abortController.abort(e);
66
+ return null;
67
+ });
68
+ return {pricePrefetchPromise, gasTokenPricePrefetchPromise, depositTokenPricePrefetchPromise};
69
+ }
70
+
71
+ /**
72
+ * Starts a pre-fetch for base security deposit (transaction fee for refunding transaction on our side)
73
+ *
74
+ * @param chainIdentifier
75
+ * @param dummySwapData
76
+ * @param depositToken
77
+ * @param gasTokenPricePrefetchPromise
78
+ * @param depositTokenPricePrefetchPromise
79
+ * @param abortController
80
+ */
81
+ protected async getBaseSecurityDepositPrefetch(
82
+ chainIdentifier: string, dummySwapData: SwapData, depositToken: string,
83
+ gasTokenPricePrefetchPromise: Promise<bigint>, depositTokenPricePrefetchPromise: Promise<bigint>,
84
+ abortController: AbortController
85
+ ): Promise<bigint> {
86
+ //Solana workaround
87
+ const {swapContract, chainInterface} = this.getChain(chainIdentifier);
88
+ let feeResult: bigint;
89
+ const gasToken = chainInterface.getNativeCurrencyAddress();
90
+ if (swapContract.getRawRefundFee != null) {
91
+ try {
92
+ feeResult = await swapContract.getRawRefundFee(dummySwapData);
93
+ } catch (e) {
94
+ this.logger.error("getBaseSecurityDepositPrefetch(): pre-fetch error: ", e);
95
+ abortController.abort(e);
96
+ return null;
97
+ }
98
+ } else {
99
+ try {
100
+ feeResult = await swapContract.getRefundFee(dummySwapData);
101
+ } catch (e1) {
102
+ this.logger.error("getBaseSecurityDepositPrefetch(): pre-fetch error: ", e1);
103
+ abortController.abort(e1);
104
+ return null;
105
+ }
106
+ }
107
+ feeResult = feeResult * 2n;
108
+ if(gasToken===depositToken) return feeResult;
109
+ const btcValue = await this.swapPricing.getToBtcSwapAmount(feeResult, gasToken, chainIdentifier, true, gasTokenPricePrefetchPromise);
110
+ return await this.swapPricing.getFromBtcSwapAmount(btcValue, depositToken, chainIdentifier, true, depositTokenPricePrefetchPromise);
111
+ }
112
+
113
+ /**
114
+ * Starts a pre-fetch for vault balance
115
+ *
116
+ * @param chainIdentifier
117
+ * @param useToken
118
+ * @param abortController
119
+ */
120
+ protected async getBalancePrefetch(chainIdentifier: string, useToken: string, abortController: AbortController): Promise<bigint> {
121
+ const {swapContract, signer} = this.getChain(chainIdentifier);
122
+ try {
123
+ return await swapContract.getBalance(signer.getAddress(), useToken, true);
124
+ } catch (e) {
125
+ this.logger.error("getBalancePrefetch(): balancePrefetch error: ", e);
126
+ abortController.abort(e);
127
+ return null;
128
+ }
129
+ }
130
+
131
+ /**
132
+ * Checks if we have enough balance of the token in the swap vault
133
+ *
134
+ * @param totalInToken
135
+ * @param balancePrefetch
136
+ * @param signal
137
+ * @throws {DefinedRuntimeError} will throw an error if there are not enough funds in the vault
138
+ */
139
+ protected async checkBalance(totalInToken: bigint, balancePrefetch: Promise<bigint>, signal: AbortSignal | null): Promise<void> {
140
+ const balance = await balancePrefetch;
141
+ if(signal!=null) signal.throwIfAborted();
142
+
143
+ if(balance==null || balance < totalInToken) {
144
+ throw {
145
+ code: 20002,
146
+ msg: "Not enough liquidity"
147
+ };
148
+ }
149
+ }
150
+
151
+ /**
152
+ * Checks if the specified token is allowed as a deposit token
153
+ *
154
+ * @param chainIdentifier
155
+ * @param depositToken
156
+ * @throws {DefinedRuntimeError} will throw an error if there are not enough funds in the vault
157
+ */
158
+ protected checkAllowedDepositToken(chainIdentifier: string, depositToken: string): void {
159
+ const {chainInterface, allowedDepositTokens} = this.getChain(chainIdentifier);
160
+ if(allowedDepositTokens==null) {
161
+ if(depositToken!==chainInterface.getNativeCurrencyAddress()) throw {
162
+ code: 20190,
163
+ msg: "Unsupported deposit token"
164
+ };
165
+ } else {
166
+ if(!allowedDepositTokens.includes(depositToken)) throw {
167
+ code: 20190,
168
+ msg: "Unsupported deposit token"
169
+ };
170
+ }
171
+ }
172
+
173
+ /**
174
+ * Signs the created swap
175
+ *
176
+ * @param chainIdentifier
177
+ * @param swapObject
178
+ * @param req
179
+ * @param abortSignal
180
+ * @param signDataPrefetchPromise
181
+ */
182
+ protected async getFromBtcSignatureData(
183
+ chainIdentifier: string,
184
+ swapObject: SwapData,
185
+ req: Request & {paramReader: IParamReader},
186
+ abortSignal: AbortSignal,
187
+ signDataPrefetchPromise?: Promise<any>
188
+ ): Promise<{
189
+ prefix: string,
190
+ timeout: string,
191
+ signature: string,
192
+ feeRate: string
193
+ }> {
194
+ const {swapContract, signer} = this.getChain(chainIdentifier);
195
+
196
+ const prefetchedSignData = signDataPrefetchPromise!=null ? await signDataPrefetchPromise : null;
197
+ if(prefetchedSignData!=null) this.logger.debug("getFromBtcSignatureData(): pre-fetched signature data: ", prefetchedSignData);
198
+ abortSignal.throwIfAborted();
199
+
200
+ const feeRateObj = await req.paramReader.getParams({
201
+ feeRate: FieldTypeEnum.String
202
+ }).catch(() => null);
203
+ abortSignal.throwIfAborted();
204
+
205
+ const feeRate = feeRateObj?.feeRate!=null && typeof(feeRateObj.feeRate)==="string" ? feeRateObj.feeRate : null;
206
+ this.logger.debug("getFromBtcSignatureData(): using fee rate from client: ", feeRate);
207
+ const sigData = await swapContract.getInitSignature(
208
+ signer,
209
+ swapObject,
210
+ this.getInitAuthorizationTimeout(chainIdentifier),
211
+ prefetchedSignData,
212
+ feeRate
213
+ );
214
+ abortSignal.throwIfAborted();
215
+
216
+ return {
217
+ ...sigData,
218
+ feeRate
219
+ };
220
+ }
221
+
222
+ /**
223
+ * Calculates the required security deposit
224
+ *
225
+ * @param chainIdentifier
226
+ * @param amountBD
227
+ * @param swapFee
228
+ * @param expiryTimeout
229
+ * @param baseSecurityDepositPromise
230
+ * @param depositToken
231
+ * @param depositTokenPricePrefetchPromise
232
+ * @param securityDepositData
233
+ * @param signal
234
+ * @param metadata
235
+ */
236
+ protected async getSecurityDeposit(
237
+ chainIdentifier: string,
238
+ amountBD: bigint,
239
+ swapFee: bigint,
240
+ expiryTimeout: bigint,
241
+ baseSecurityDepositPromise: Promise<bigint>,
242
+ depositToken: string,
243
+ depositTokenPricePrefetchPromise: Promise<bigint>,
244
+ securityDepositData: {
245
+ securityDepositApyPPM?: bigint,
246
+ securityDepositBaseMultiplierPPM?: bigint,
247
+ },
248
+ signal: AbortSignal,
249
+ metadata: any
250
+ ): Promise<bigint> {
251
+ let baseSD: bigint = await baseSecurityDepositPromise;
252
+ if(securityDepositData.securityDepositBaseMultiplierPPM!=null)
253
+ baseSD = baseSD * securityDepositData.securityDepositBaseMultiplierPPM / 1_000_000n;
254
+
255
+ signal.throwIfAborted();
256
+
257
+ metadata.times.refundFeeFetched = Date.now();
258
+
259
+ const swapValueInDepositToken = await this.swapPricing.getFromBtcSwapAmount(
260
+ amountBD - swapFee,
261
+ depositToken,
262
+ chainIdentifier,
263
+ true,
264
+ depositTokenPricePrefetchPromise
265
+ );
266
+
267
+ signal.throwIfAborted();
268
+
269
+ const apyPPM = securityDepositData.securityDepositApyPPM ?? BigInt(Math.floor(this.config.securityDepositAPY*1000000));
270
+ const variableSD = swapValueInDepositToken * apyPPM * expiryTimeout / 1000000n / secondsInYear;
271
+
272
+ this.logger.debug(
273
+ "getSecurityDeposit(): base security deposit: "+baseSD.toString(10)+
274
+ " deposit token: "+depositToken+
275
+ " swap output in deposit token: "+swapValueInDepositToken.toString(10)+
276
+ " apy ppm: "+apyPPM.toString(10)+
277
+ " expiry timeout: "+expiryTimeout.toString(10)+
278
+ " variable security deposit: "+variableSD.toString(10)
279
+ );
280
+
281
+ return baseSD + variableSD;
282
+ }
283
+
284
284
  }