@atomiqlabs/lp-lib 14.0.0-dev.11 → 14.0.0-dev.13

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 (164) 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 +42 -42
  5. package/dist/index.js +58 -58
  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 +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 +153 -153
  27. package/dist/swaps/SwapHandler.js +160 -160
  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 +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 +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 +675 -648
  56. package/dist/swaps/escrow/frombtcln_abstract/FromBtcLnSwapAbs.d.ts +33 -33
  57. package/dist/swaps/escrow/frombtcln_abstract/FromBtcLnSwapAbs.js +91 -91
  58. package/dist/swaps/escrow/frombtcln_autoinit/FromBtcLnAuto.d.ts +104 -104
  59. package/dist/swaps/escrow/frombtcln_autoinit/FromBtcLnAuto.js +659 -629
  60. package/dist/swaps/escrow/frombtcln_autoinit/FromBtcLnAutoSwap.d.ts +55 -55
  61. package/dist/swaps/escrow/frombtcln_autoinit/FromBtcLnAutoSwap.js +120 -120
  62. package/dist/swaps/escrow/tobtc_abstract/ToBtcAbs.d.ts +171 -171
  63. package/dist/swaps/escrow/tobtc_abstract/ToBtcAbs.js +706 -706
  64. package/dist/swaps/escrow/tobtc_abstract/ToBtcSwapAbs.d.ts +26 -26
  65. package/dist/swaps/escrow/tobtc_abstract/ToBtcSwapAbs.js +62 -62
  66. package/dist/swaps/escrow/tobtcln_abstract/ToBtcLnAbs.d.ts +177 -177
  67. package/dist/swaps/escrow/tobtcln_abstract/ToBtcLnAbs.js +861 -861
  68. package/dist/swaps/escrow/tobtcln_abstract/ToBtcLnSwapAbs.d.ts +23 -23
  69. package/dist/swaps/escrow/tobtcln_abstract/ToBtcLnSwapAbs.js +56 -56
  70. package/dist/swaps/spv_vault_swap/SpvVault.d.ts +41 -41
  71. package/dist/swaps/spv_vault_swap/SpvVault.js +111 -111
  72. package/dist/swaps/spv_vault_swap/SpvVaultSwap.d.ts +67 -67
  73. package/dist/swaps/spv_vault_swap/SpvVaultSwap.js +158 -158
  74. package/dist/swaps/spv_vault_swap/SpvVaultSwapHandler.d.ts +68 -68
  75. package/dist/swaps/spv_vault_swap/SpvVaultSwapHandler.js +491 -490
  76. package/dist/swaps/spv_vault_swap/SpvVaults.d.ts +52 -52
  77. package/dist/swaps/spv_vault_swap/SpvVaults.js +364 -364
  78. package/dist/swaps/trusted/frombtc_trusted/FromBtcTrusted.d.ts +51 -51
  79. package/dist/swaps/trusted/frombtc_trusted/FromBtcTrusted.js +650 -650
  80. package/dist/swaps/trusted/frombtc_trusted/FromBtcTrustedSwap.d.ts +52 -52
  81. package/dist/swaps/trusted/frombtc_trusted/FromBtcTrustedSwap.js +118 -118
  82. package/dist/swaps/trusted/frombtcln_trusted/FromBtcLnTrusted.d.ts +76 -76
  83. package/dist/swaps/trusted/frombtcln_trusted/FromBtcLnTrusted.js +494 -494
  84. package/dist/swaps/trusted/frombtcln_trusted/FromBtcLnTrustedSwap.d.ts +34 -34
  85. package/dist/swaps/trusted/frombtcln_trusted/FromBtcLnTrustedSwap.js +81 -81
  86. package/dist/utils/Utils.d.ts +29 -29
  87. package/dist/utils/Utils.js +89 -89
  88. package/dist/utils/paramcoders/IParamReader.d.ts +5 -5
  89. package/dist/utils/paramcoders/IParamReader.js +2 -2
  90. package/dist/utils/paramcoders/IParamWriter.d.ts +4 -4
  91. package/dist/utils/paramcoders/IParamWriter.js +2 -2
  92. package/dist/utils/paramcoders/LegacyParamEncoder.d.ts +10 -10
  93. package/dist/utils/paramcoders/LegacyParamEncoder.js +22 -22
  94. package/dist/utils/paramcoders/ParamDecoder.d.ts +25 -25
  95. package/dist/utils/paramcoders/ParamDecoder.js +222 -222
  96. package/dist/utils/paramcoders/ParamEncoder.d.ts +9 -9
  97. package/dist/utils/paramcoders/ParamEncoder.js +22 -22
  98. package/dist/utils/paramcoders/SchemaVerifier.d.ts +21 -21
  99. package/dist/utils/paramcoders/SchemaVerifier.js +84 -84
  100. package/dist/utils/paramcoders/server/ServerParamDecoder.d.ts +8 -8
  101. package/dist/utils/paramcoders/server/ServerParamDecoder.js +107 -107
  102. package/dist/utils/paramcoders/server/ServerParamEncoder.d.ts +11 -11
  103. package/dist/utils/paramcoders/server/ServerParamEncoder.js +65 -65
  104. package/dist/wallets/IBitcoinWallet.d.ts +67 -67
  105. package/dist/wallets/IBitcoinWallet.js +2 -2
  106. package/dist/wallets/ILightningWallet.d.ts +117 -117
  107. package/dist/wallets/ILightningWallet.js +37 -37
  108. package/dist/wallets/ISpvVaultSigner.d.ts +7 -7
  109. package/dist/wallets/ISpvVaultSigner.js +2 -2
  110. package/package.json +36 -36
  111. package/src/fees/IBtcFeeEstimator.ts +6 -6
  112. package/src/index.ts +53 -53
  113. package/src/info/InfoHandler.ts +106 -106
  114. package/src/plugins/IPlugin.ts +168 -168
  115. package/src/plugins/PluginManager.ts +336 -336
  116. package/src/prices/BinanceSwapPrice.ts +113 -113
  117. package/src/prices/CoinGeckoSwapPrice.ts +87 -87
  118. package/src/prices/ISwapPrice.ts +88 -88
  119. package/src/prices/OKXSwapPrice.ts +113 -113
  120. package/src/storage/IIntermediaryStorage.ts +19 -19
  121. package/src/storagemanager/IntermediaryStorageManager.ts +118 -118
  122. package/src/storagemanager/StorageManager.ts +78 -78
  123. package/src/swaps/SwapHandler.ts +277 -277
  124. package/src/swaps/SwapHandlerSwap.ts +141 -141
  125. package/src/swaps/assertions/AmountAssertions.ts +76 -76
  126. package/src/swaps/assertions/FromBtcAmountAssertions.ts +238 -238
  127. package/src/swaps/assertions/LightningAssertions.ts +103 -103
  128. package/src/swaps/assertions/ToBtcAmountAssertions.ts +203 -203
  129. package/src/swaps/escrow/EscrowHandler.ts +179 -179
  130. package/src/swaps/escrow/EscrowHandlerSwap.ts +86 -86
  131. package/src/swaps/escrow/FromBtcBaseSwap.ts +38 -38
  132. package/src/swaps/escrow/FromBtcBaseSwapHandler.ts +286 -286
  133. package/src/swaps/escrow/ToBtcBaseSwap.ts +85 -85
  134. package/src/swaps/escrow/ToBtcBaseSwapHandler.ts +129 -129
  135. package/src/swaps/escrow/frombtc_abstract/FromBtcAbs.ts +452 -452
  136. package/src/swaps/escrow/frombtc_abstract/FromBtcSwapAbs.ts +61 -61
  137. package/src/swaps/escrow/frombtcln_abstract/FromBtcLnAbs.ts +856 -828
  138. package/src/swaps/escrow/frombtcln_abstract/FromBtcLnSwapAbs.ts +141 -141
  139. package/src/swaps/escrow/frombtcln_autoinit/FromBtcLnAuto.ts +822 -789
  140. package/src/swaps/escrow/frombtcln_autoinit/FromBtcLnAutoSwap.ts +196 -196
  141. package/src/swaps/escrow/tobtc_abstract/ToBtcAbs.ts +879 -879
  142. package/src/swaps/escrow/tobtc_abstract/ToBtcSwapAbs.ts +102 -102
  143. package/src/swaps/escrow/tobtcln_abstract/ToBtcLnAbs.ts +1110 -1110
  144. package/src/swaps/escrow/tobtcln_abstract/ToBtcLnSwapAbs.ts +77 -77
  145. package/src/swaps/spv_vault_swap/SpvVault.ts +143 -143
  146. package/src/swaps/spv_vault_swap/SpvVaultSwap.ts +225 -225
  147. package/src/swaps/spv_vault_swap/SpvVaultSwapHandler.ts +627 -626
  148. package/src/swaps/spv_vault_swap/SpvVaults.ts +435 -435
  149. package/src/swaps/trusted/frombtc_trusted/FromBtcTrusted.ts +747 -747
  150. package/src/swaps/trusted/frombtc_trusted/FromBtcTrustedSwap.ts +185 -185
  151. package/src/swaps/trusted/frombtcln_trusted/FromBtcLnTrusted.ts +590 -590
  152. package/src/swaps/trusted/frombtcln_trusted/FromBtcLnTrustedSwap.ts +121 -121
  153. package/src/utils/Utils.ts +104 -104
  154. package/src/utils/paramcoders/IParamReader.ts +7 -7
  155. package/src/utils/paramcoders/IParamWriter.ts +8 -8
  156. package/src/utils/paramcoders/LegacyParamEncoder.ts +27 -27
  157. package/src/utils/paramcoders/ParamDecoder.ts +218 -218
  158. package/src/utils/paramcoders/ParamEncoder.ts +29 -29
  159. package/src/utils/paramcoders/SchemaVerifier.ts +96 -96
  160. package/src/utils/paramcoders/server/ServerParamDecoder.ts +118 -118
  161. package/src/utils/paramcoders/server/ServerParamEncoder.ts +75 -75
  162. package/src/wallets/IBitcoinWallet.ts +68 -68
  163. package/src/wallets/ILightningWallet.ts +178 -178
  164. package/src/wallets/ISpvVaultSigner.ts +10 -10
@@ -1,490 +1,491 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.SpvVaultSwapHandler = void 0;
4
- const SwapHandler_1 = require("../SwapHandler");
5
- const base_1 = require("@atomiqlabs/base");
6
- const SpvVaultSwap_1 = require("./SpvVaultSwap");
7
- const PluginManager_1 = require("../../plugins/PluginManager");
8
- const ServerParamDecoder_1 = require("../../utils/paramcoders/server/ServerParamDecoder");
9
- const Utils_1 = require("../../utils/Utils");
10
- const SchemaVerifier_1 = require("../../utils/paramcoders/SchemaVerifier");
11
- const FromBtcAmountAssertions_1 = require("../assertions/FromBtcAmountAssertions");
12
- const crypto_1 = require("crypto");
13
- const btc_signer_1 = require("@scure/btc-signer");
14
- const SpvVaults_1 = require("./SpvVaults");
15
- const TX_MAX_VSIZE = 16 * 1024;
16
- class SpvVaultSwapHandler extends SwapHandler_1.SwapHandler {
17
- constructor(storageDirectory, vaultStorage, path, chainsData, swapPricing, bitcoin, bitcoinRpc, spvVaultSigner, config) {
18
- super(storageDirectory, path, chainsData, swapPricing);
19
- this.type = SwapHandler_1.SwapHandlerType.FROM_BTC_SPV;
20
- this.btcTxIdIndex = new Map();
21
- this.bitcoinRpc = bitcoinRpc;
22
- this.bitcoin = bitcoin;
23
- this.vaultSigner = spvVaultSigner;
24
- this.config = config;
25
- this.AmountAssertions = new FromBtcAmountAssertions_1.FromBtcAmountAssertions(config, swapPricing);
26
- this.Vaults = new SpvVaults_1.SpvVaults(vaultStorage, bitcoin, spvVaultSigner, bitcoinRpc, this.getChain.bind(this), config);
27
- }
28
- async processClaimEvent(swap, event) {
29
- if (swap == null)
30
- return;
31
- //Update swap
32
- swap.txIds.claim = event.meta?.txId;
33
- await this.removeSwapData(swap, SpvVaultSwap_1.SpvVaultSwapState.CLAIMED);
34
- }
35
- /**
36
- * Chain event processor
37
- *
38
- * @param chainIdentifier
39
- * @param eventData
40
- */
41
- async processEvent(chainIdentifier, eventData) {
42
- for (let event of eventData) {
43
- if (!(event instanceof base_1.SpvVaultEvent))
44
- continue;
45
- const vault = await this.Vaults.getVault(chainIdentifier, event.owner, event.vaultId);
46
- if (vault == null)
47
- continue;
48
- if (event instanceof base_1.SpvVaultOpenEvent) {
49
- await this.Vaults.processOpenEvent(vault, event);
50
- }
51
- else if (event instanceof base_1.SpvVaultCloseEvent) {
52
- await this.Vaults.processCloseEvent(vault, event);
53
- }
54
- else if (event instanceof base_1.SpvVaultClaimEvent) {
55
- const swap = this.btcTxIdIndex.get(event.btcTxId);
56
- if (swap != null) {
57
- swap.txIds.claim = event.meta?.txId;
58
- if (swap.metadata != null)
59
- swap.metadata.times.claimTxReceived = Date.now();
60
- }
61
- await this.Vaults.processClaimEvent(vault, swap, event);
62
- await this.processClaimEvent(swap, event);
63
- }
64
- else if (event instanceof base_1.SpvVaultDepositEvent) {
65
- await this.Vaults.processDepositEvent(vault, event);
66
- }
67
- }
68
- return true;
69
- }
70
- /**
71
- * Initializes chain events subscription
72
- */
73
- subscribeToEvents() {
74
- for (let key in this.chains.chains) {
75
- this.chains.chains[key].chainEvents.registerListener((events) => this.processEvent(key, events));
76
- }
77
- this.logger.info("SC: Events: subscribed to smartchain events");
78
- }
79
- async startWatchdog() {
80
- await super.startWatchdog();
81
- await this.Vaults.startVaultsWatchdog();
82
- }
83
- async init() {
84
- await this.storageManager.loadData(SpvVaultSwap_1.SpvVaultSwap);
85
- for (let { obj: swap, hash, sequence } of await this.storageManager.query([])) {
86
- if (swap.btcTxId != null)
87
- this.btcTxIdIndex.set(swap.btcTxId, swap);
88
- }
89
- await this.Vaults.init();
90
- this.subscribeToEvents();
91
- await PluginManager_1.PluginManager.serviceInitialize(this);
92
- }
93
- async processPastSwap(swap) {
94
- if (swap.state === SpvVaultSwap_1.SpvVaultSwapState.CREATED) {
95
- if (swap.expiry < Date.now() / 1000) {
96
- await this.removeSwapData(swap, SpvVaultSwap_1.SpvVaultSwapState.EXPIRED);
97
- await this.bitcoin.addUnusedAddress(swap.btcAddress);
98
- }
99
- }
100
- if (swap.state === SpvVaultSwap_1.SpvVaultSwapState.SIGNED) {
101
- //Check if sent
102
- const tx = await this.bitcoinRpc.getTransaction(swap.btcTxId);
103
- if (tx == null) {
104
- await this.removeSwapData(swap, SpvVaultSwap_1.SpvVaultSwapState.FAILED);
105
- return;
106
- }
107
- else if (tx.confirmations === 0) {
108
- await swap.setState(SpvVaultSwap_1.SpvVaultSwapState.SENT);
109
- await this.saveSwapData(swap);
110
- return;
111
- }
112
- else {
113
- await swap.setState(SpvVaultSwap_1.SpvVaultSwapState.BTC_CONFIRMED);
114
- await this.saveSwapData(swap);
115
- }
116
- }
117
- if (swap.state === SpvVaultSwap_1.SpvVaultSwapState.SENT) {
118
- //Check if confirmed or double-spent
119
- const tx = await this.bitcoinRpc.getTransaction(swap.btcTxId);
120
- if (tx == null) {
121
- await this.removeSwapData(swap, SpvVaultSwap_1.SpvVaultSwapState.DOUBLE_SPENT);
122
- return;
123
- }
124
- else if (tx.confirmations > 0) {
125
- await swap.setState(SpvVaultSwap_1.SpvVaultSwapState.BTC_CONFIRMED);
126
- await this.saveSwapData(swap);
127
- }
128
- }
129
- }
130
- async processPastSwaps() {
131
- const swaps = await this.storageManager.query([
132
- {
133
- key: "state",
134
- value: [
135
- SpvVaultSwap_1.SpvVaultSwapState.CREATED,
136
- SpvVaultSwap_1.SpvVaultSwapState.SIGNED,
137
- SpvVaultSwap_1.SpvVaultSwapState.SENT //Check if confirmed or double-spent
138
- ]
139
- }
140
- ]);
141
- for (let { obj: swap } of swaps) {
142
- await this.processPastSwap(swap);
143
- }
144
- }
145
- getPricePrefetches(chainIdentifier, token, gasToken, abortController) {
146
- const pricePrefetchPromise = this.swapPricing.preFetchPrice(token, chainIdentifier).catch(e => {
147
- this.logger.error("getPricePrefetches(): pricePrefetchPromise error: ", e);
148
- abortController.abort(e);
149
- return null;
150
- });
151
- const gasTokenPricePrefetchPromise = token === gasToken ?
152
- pricePrefetchPromise :
153
- this.swapPricing.preFetchPrice(gasToken, chainIdentifier).catch(e => {
154
- this.logger.error("getPricePrefetches(): gasTokenPricePrefetchPromise error: ", e);
155
- abortController.abort(e);
156
- return null;
157
- });
158
- return { pricePrefetchPromise, gasTokenPricePrefetchPromise };
159
- }
160
- startRestServer(restServer) {
161
- restServer.use(this.path + "/getQuote", (0, ServerParamDecoder_1.serverParamDecoder)(10 * 1000));
162
- restServer.post(this.path + "/getQuote", (0, Utils_1.expressHandlerWrapper)(async (req, res) => {
163
- const metadata = { request: {}, times: {} };
164
- const chainIdentifier = req.query.chain ?? this.chains.default;
165
- const { signer, chainInterface, spvVaultContract } = this.getChain(chainIdentifier);
166
- metadata.times.requestReceived = Date.now();
167
- /**
168
- * address: string smart chain address of the recipient
169
- * amount: string amount (in sats)
170
- * token: string Desired token to use
171
- * gasAmount: string Desired amount in gas token to also get
172
- * gasToken: string
173
- * exactOut: boolean Whether the swap should be an exact out instead of exact in swap
174
- * callerFeeRate: string Caller/watchtower fee (in output token) to assign to the swap
175
- * frontingFeeRate: string Fronting fee (in output token) to assign to the swap
176
- */
177
- const parsedBody = await req.paramReader.getParams({
178
- address: (val) => val != null &&
179
- typeof (val) === "string" &&
180
- chainInterface.isValidAddress(val) ? val : null,
181
- amount: SchemaVerifier_1.FieldTypeEnum.BigInt,
182
- token: (val) => val != null &&
183
- typeof (val) === "string" &&
184
- this.isTokenSupported(chainIdentifier, val) ? val : null,
185
- gasAmount: SchemaVerifier_1.FieldTypeEnum.BigInt,
186
- gasToken: (val) => val != null &&
187
- typeof (val) === "string" &&
188
- chainInterface.isValidToken(val) ? val : null,
189
- exactOut: SchemaVerifier_1.FieldTypeEnum.BooleanOptional,
190
- callerFeeRate: SchemaVerifier_1.FieldTypeEnum.BigInt,
191
- frontingFeeRate: SchemaVerifier_1.FieldTypeEnum.BigInt,
192
- });
193
- if (parsedBody == null)
194
- throw {
195
- code: 20100,
196
- msg: "Invalid request body"
197
- };
198
- metadata.request = parsedBody;
199
- if (parsedBody.gasToken !== chainInterface.getNativeCurrencyAddress())
200
- throw {
201
- code: 20190,
202
- msg: "Unsupported gas token"
203
- };
204
- if (parsedBody.callerFeeRate < 0n || parsedBody.callerFeeRate >= 2n ** 20n)
205
- throw {
206
- code: 20191,
207
- msg: "Invalid caller fee rate"
208
- };
209
- if (parsedBody.frontingFeeRate < 0n || parsedBody.frontingFeeRate >= 2n ** 20n)
210
- throw {
211
- code: 20192,
212
- msg: "Invalid fronting fee rate"
213
- };
214
- const requestedAmount = {
215
- input: !parsedBody.exactOut,
216
- amount: parsedBody.exactOut ?
217
- (parsedBody.amount * (100000n + parsedBody.callerFeeRate + parsedBody.frontingFeeRate) / 100000n) :
218
- parsedBody.amount,
219
- token: parsedBody.token
220
- };
221
- const gasTokenAmount = {
222
- input: false,
223
- amount: parsedBody.gasAmount * (100000n + parsedBody.callerFeeRate + parsedBody.frontingFeeRate) / 100000n,
224
- token: parsedBody.gasToken
225
- };
226
- const request = {
227
- chainIdentifier,
228
- raw: req,
229
- parsed: parsedBody,
230
- metadata
231
- };
232
- const useToken = parsedBody.token;
233
- const gasToken = parsedBody.gasToken;
234
- //Check request params
235
- const fees = await this.AmountAssertions.preCheckFromBtcAmounts(this.type, request, requestedAmount, gasTokenAmount);
236
- metadata.times.requestChecked = Date.now();
237
- //Create abortController for parallel prefetches
238
- const responseStream = res.responseStream;
239
- const abortController = (0, Utils_1.getAbortController)(responseStream);
240
- //Pre-fetch data
241
- const { pricePrefetchPromise, gasTokenPricePrefetchPromise } = this.getPricePrefetches(chainIdentifier, useToken, gasToken, abortController);
242
- //Check valid amount specified (min/max)
243
- let { amountBD, swapFee, swapFeeInToken, totalInToken, amountBDgas, gasSwapFee, gasSwapFeeInToken, totalInGasToken } = await this.AmountAssertions.checkFromBtcAmount(this.type, request, { ...requestedAmount, pricePrefetch: pricePrefetchPromise }, fees, abortController.signal, { ...gasTokenAmount, pricePrefetch: gasTokenPricePrefetchPromise });
244
- metadata.times.priceCalculated = Date.now();
245
- const totalBtcOutput = amountBD + amountBDgas;
246
- //Check if we have enough funds to honor the request
247
- const vault = await this.Vaults.findVaultForSwap(chainIdentifier, totalBtcOutput, useToken, totalInToken, gasToken, totalInGasToken);
248
- metadata.times.vaultPicked = Date.now();
249
- //Create swap receive bitcoin address
250
- const btcFeeRate = await this.bitcoin.getFeeRate();
251
- const receiveAddress = await this.bitcoin.getAddress();
252
- abortController.signal.throwIfAborted();
253
- metadata.times.addressCreated = Date.now();
254
- //Adjust the amounts based on passed fees
255
- if (parsedBody.exactOut) {
256
- totalInToken = parsedBody.amount;
257
- }
258
- else {
259
- totalInToken = (totalInToken * 100000n / (100000n + parsedBody.callerFeeRate + parsedBody.frontingFeeRate));
260
- }
261
- totalInGasToken = (totalInGasToken * 100000n / (100000n + parsedBody.callerFeeRate + parsedBody.frontingFeeRate));
262
- //Calculate raw amounts
263
- const [rawTokenAmount, rawGasTokenAmount] = vault.toRawAmounts([totalInToken, totalInGasToken]);
264
- [totalInToken, totalInGasToken] = vault.fromRawAmounts([rawTokenAmount, rawGasTokenAmount]);
265
- const expiry = Math.floor(Date.now() / 1000) + this.getInitAuthorizationTimeout(chainIdentifier);
266
- //Get PSBT data
267
- const callerFeeShare = parsedBody.callerFeeRate;
268
- const frontingFeeShare = parsedBody.frontingFeeRate;
269
- const executionFeeShare = 0n;
270
- const utxo = vault.getLatestUtxo();
271
- const quoteId = (0, crypto_1.randomBytes)(32).toString("hex");
272
- const swap = new SpvVaultSwap_1.SpvVaultSwap(chainIdentifier, quoteId, expiry, vault, utxo, receiveAddress, btcFeeRate, parsedBody.address, totalBtcOutput, totalInToken, totalInGasToken, swapFee, swapFeeInToken, gasSwapFee, gasSwapFeeInToken, callerFeeShare, frontingFeeShare, executionFeeShare, useToken, gasToken);
273
- swap.metadata = metadata;
274
- await PluginManager_1.PluginManager.swapCreate(swap);
275
- await this.saveSwapData(swap);
276
- this.swapLogger.info(swap, "REST: /getQuote: Created swap address: " + receiveAddress + " amount: " + totalBtcOutput.toString(10));
277
- await responseStream.writeParamsAndEnd({
278
- code: 20000,
279
- msg: "Success",
280
- data: {
281
- quoteId,
282
- expiry,
283
- address: signer.getAddress(),
284
- vaultId: vault.data.getVaultId().toString(10),
285
- vaultBtcAddress: vault.btcAddress,
286
- btcAddress: receiveAddress,
287
- btcUtxo: utxo,
288
- btcFeeRate,
289
- btcAmount: totalBtcOutput.toString(10),
290
- btcAmountSwap: amountBD.toString(10),
291
- btcAmountGas: amountBDgas.toString(10),
292
- total: totalInToken.toString(10),
293
- totalGas: totalInGasToken.toString(10),
294
- totalFeeBtc: (swapFee + gasSwapFee).toString(10),
295
- swapFeeBtc: swapFee.toString(10),
296
- swapFee: swapFeeInToken.toString(10),
297
- gasSwapFeeBtc: gasSwapFee.toString(10),
298
- gasSwapFee: gasSwapFeeInToken.toString(10),
299
- callerFeeShare: callerFeeShare.toString(10),
300
- frontingFeeShare: frontingFeeShare.toString(10),
301
- executionFeeShare: executionFeeShare.toString(10)
302
- }
303
- });
304
- }));
305
- restServer.use(this.path + "/postQuote", (0, ServerParamDecoder_1.serverParamDecoder)(10 * 1000));
306
- restServer.post(this.path + "/postQuote", (0, Utils_1.expressHandlerWrapper)(async (req, res) => {
307
- let requestReceived = Date.now();
308
- const parsedBody = await req.paramReader.getParams({
309
- quoteId: SchemaVerifier_1.FieldTypeEnum.String,
310
- psbtHex: (val) => val != null &&
311
- typeof (val) === "string" &&
312
- Utils_1.HEX_REGEX.test(val) ? val : null
313
- });
314
- const swap = await this.storageManager.getData(parsedBody.quoteId, 0n);
315
- if (swap == null || swap.state !== SpvVaultSwap_1.SpvVaultSwapState.CREATED || swap.expiry < Date.now() / 1000)
316
- throw {
317
- code: 20505,
318
- msg: "Invalid quote ID, not found or expired!"
319
- };
320
- const metadata = swap.metadata;
321
- metadata.times ?? (metadata.times = {});
322
- metadata.times.requestReceived = requestReceived;
323
- const vault = await this.Vaults.getVault(swap.chainIdentifier, swap.vaultOwner, swap.vaultId);
324
- if (vault == null || !vault.isReady()) {
325
- throw {
326
- code: 20506,
327
- msg: "Used vault not found!"
328
- };
329
- }
330
- //Try parse psbt
331
- let transaction;
332
- try {
333
- transaction = btc_signer_1.Transaction.fromPSBT(Buffer.from(parsedBody.psbtHex, "hex"));
334
- }
335
- catch (e) {
336
- this.swapLogger.error(swap, "REST: /postQuote: failed to parse provided PSBT: ", e);
337
- throw {
338
- code: 20507,
339
- msg: "Error parsing PSBT, hex format required!"
340
- };
341
- }
342
- //Check correct psbt
343
- for (let i = 1; i < transaction.inputsLength; i++) { //Skip first vault input
344
- const txIn = transaction.getInput(i);
345
- if ((0, btc_signer_1.getInputType)(txIn).txType === "legacy")
346
- throw {
347
- code: 20514,
348
- msg: "Legacy (pre-segwit) inputs in tx are not allowed!"
349
- };
350
- //Check UTXOs exist and are unspent
351
- if (await this.bitcoinRpc.isSpent(Buffer.from(txIn.txid).toString("hex") + ":" + txIn.index.toString(10)))
352
- throw {
353
- code: 20515,
354
- msg: "Spent UTXO in inputs!"
355
- };
356
- }
357
- const { spvVaultContract } = this.getChain(swap.chainIdentifier);
358
- let data;
359
- try {
360
- data = await spvVaultContract.getWithdrawalData(await this.bitcoin.parsePsbt(transaction));
361
- }
362
- catch (e) {
363
- this.swapLogger.error(swap, "REST: /postQuote: failed to parse PSBT to withdrawal tx data: ", e);
364
- throw {
365
- code: 20508,
366
- msg: "PSBT transaction cannot be parsed!"
367
- };
368
- }
369
- if (!data.isRecipient(swap.recipient) ||
370
- data.callerFeeRate !== swap.callerFeeShare ||
371
- data.frontingFeeRate !== swap.frontingFeeShare ||
372
- data.executionFeeRate !== swap.executionFeeShare ||
373
- data.rawAmounts[0] !== swap.rawAmountToken ||
374
- data.rawAmounts[1] !== swap.rawAmountGasToken ||
375
- data.getSpentVaultUtxo() !== swap.vaultUtxo ||
376
- data.btcTx.outs[0].value !== SpvVaults_1.VAULT_DUST_AMOUNT ||
377
- !Buffer.from(data.btcTx.outs[0].scriptPubKey.hex, "hex").equals(this.bitcoin.toOutputScript(swap.vaultAddress)) ||
378
- BigInt(data.btcTx.outs[2].value) !== swap.amountBtc ||
379
- !Buffer.from(data.btcTx.outs[2].scriptPubKey.hex, "hex").equals(this.bitcoin.toOutputScript(swap.btcAddress)) ||
380
- (data.btcTx.locktime > 0 && data.btcTx.locktime < 500000000) ||
381
- data.btcTx.locktime > Math.floor(Date.now() / 1000) - 1000000) {
382
- this.swapLogger.error(swap, "REST: /postQuote: Invalid psbt data submitted, raw psbt hex: ", parsedBody.psbtHex);
383
- throw {
384
- code: 20509,
385
- msg: "Invalid PSBT provided!"
386
- };
387
- }
388
- if (swap.vaultUtxo !== vault.getLatestUtxo()) {
389
- throw {
390
- code: 20510,
391
- msg: "Vault UTXO already spent, please try again!"
392
- };
393
- }
394
- //Create abortController for parallel prefetches
395
- const responseStream = res.responseStream;
396
- const signedTx = await this.vaultSigner.signPsbt(swap.chainIdentifier, swap.vaultId, transaction, [0]);
397
- if (!signedTx.isFinal)
398
- throw {
399
- code: 20513,
400
- msg: "One or more PSBT inputs not finalized!"
401
- };
402
- const effectiveFeeRate = await this.bitcoinRpc.getEffectiveFeeRate(await this.bitcoin.parsePsbt(signedTx));
403
- if (effectiveFeeRate.feeRate < swap.btcFeeRate)
404
- throw {
405
- code: 20511,
406
- msg: "Bitcoin transaction fee too low, expected minimum: " + swap.btcFeeRate + " adjusted effective fee rate: " + effectiveFeeRate.feeRate
407
- };
408
- const txVsize = signedTx.vsize;
409
- if (txVsize > TX_MAX_VSIZE)
410
- throw {
411
- code: 20516,
412
- msg: "Bitcoin transaction size too large, maximum: " + TX_MAX_VSIZE + " actual: " + txVsize
413
- };
414
- if (swap.vaultUtxo !== vault.getLatestUtxo()) {
415
- throw {
416
- code: 20510,
417
- msg: "Vault UTXO already spent, please try again!"
418
- };
419
- }
420
- vault.addWithdrawal(data);
421
- await this.Vaults.saveVault(vault);
422
- //Double-check the state to prevent race condition
423
- if (swap.state !== SpvVaultSwap_1.SpvVaultSwapState.CREATED)
424
- throw {
425
- code: 20505,
426
- msg: "Invalid quote ID, not found or expired!"
427
- };
428
- swap.btcTxId = signedTx.id;
429
- swap.state = SpvVaultSwap_1.SpvVaultSwapState.SIGNED;
430
- await this.saveSwapData(swap);
431
- this.swapLogger.info(swap, "REST: /postQuote: BTC transaction signed, txId: " + swap.btcTxId);
432
- try {
433
- await this.bitcoin.sendRawTransaction(Buffer.from(signedTx.toBytes(true, true)).toString("hex"));
434
- await swap.setState(SpvVaultSwap_1.SpvVaultSwapState.SENT);
435
- }
436
- catch (e) {
437
- this.swapLogger.error(swap, "REST: /postQuote: Failed to send BTC transaction: ", e);
438
- vault.removeWithdrawal(data);
439
- await this.Vaults.saveVault(vault);
440
- await this.removeSwapData(swap, SpvVaultSwap_1.SpvVaultSwapState.FAILED);
441
- throw {
442
- code: 20512,
443
- msg: "Error broadcasting bitcoin transaction!"
444
- };
445
- }
446
- await responseStream.writeParamsAndEnd({
447
- code: 20000,
448
- msg: "Success",
449
- data: {
450
- txId: swap.btcTxId
451
- }
452
- });
453
- }));
454
- }
455
- getInfoData() {
456
- const mappedDict = {};
457
- for (let chainId in this.config.gasTokenMax) {
458
- mappedDict[chainId] = {
459
- gasToken: this.getChain(chainId).chainInterface.getNativeCurrencyAddress(),
460
- max: this.config.gasTokenMax[chainId].toString(10)
461
- };
462
- }
463
- return {
464
- gasTokens: mappedDict
465
- };
466
- }
467
- async saveSwapData(swap) {
468
- if (swap.btcTxId != null)
469
- this.btcTxIdIndex.set(swap.btcTxId, swap);
470
- return super.saveSwapData(swap);
471
- }
472
- async removeSwapData(hashOrSwap, sequenceOrUltimateState) {
473
- let swap;
474
- let state;
475
- if (typeof (hashOrSwap) === "string") {
476
- if (typeof (sequenceOrUltimateState) !== "bigint")
477
- throw new Error("Sequence must be a BN instance!");
478
- swap = await this.storageManager.getData(hashOrSwap, sequenceOrUltimateState);
479
- }
480
- else {
481
- swap = hashOrSwap;
482
- if (sequenceOrUltimateState != null && typeof (sequenceOrUltimateState) !== "bigint")
483
- state = sequenceOrUltimateState;
484
- }
485
- if (swap.btcTxId != null)
486
- this.btcTxIdIndex.delete(swap.btcTxId);
487
- return super.removeSwapData(swap, state);
488
- }
489
- }
490
- exports.SpvVaultSwapHandler = SpvVaultSwapHandler;
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.SpvVaultSwapHandler = void 0;
4
+ const SwapHandler_1 = require("../SwapHandler");
5
+ const base_1 = require("@atomiqlabs/base");
6
+ const SpvVaultSwap_1 = require("./SpvVaultSwap");
7
+ const PluginManager_1 = require("../../plugins/PluginManager");
8
+ const ServerParamDecoder_1 = require("../../utils/paramcoders/server/ServerParamDecoder");
9
+ const Utils_1 = require("../../utils/Utils");
10
+ const SchemaVerifier_1 = require("../../utils/paramcoders/SchemaVerifier");
11
+ const FromBtcAmountAssertions_1 = require("../assertions/FromBtcAmountAssertions");
12
+ const crypto_1 = require("crypto");
13
+ const btc_signer_1 = require("@scure/btc-signer");
14
+ const SpvVaults_1 = require("./SpvVaults");
15
+ const TX_MAX_VSIZE = 16 * 1024;
16
+ class SpvVaultSwapHandler extends SwapHandler_1.SwapHandler {
17
+ constructor(storageDirectory, vaultStorage, path, chainsData, swapPricing, bitcoin, bitcoinRpc, spvVaultSigner, config) {
18
+ super(storageDirectory, path, chainsData, swapPricing);
19
+ this.type = SwapHandler_1.SwapHandlerType.FROM_BTC_SPV;
20
+ this.btcTxIdIndex = new Map();
21
+ this.bitcoinRpc = bitcoinRpc;
22
+ this.bitcoin = bitcoin;
23
+ this.vaultSigner = spvVaultSigner;
24
+ this.config = config;
25
+ this.AmountAssertions = new FromBtcAmountAssertions_1.FromBtcAmountAssertions(config, swapPricing);
26
+ this.Vaults = new SpvVaults_1.SpvVaults(vaultStorage, bitcoin, spvVaultSigner, bitcoinRpc, this.getChain.bind(this), config);
27
+ }
28
+ async processClaimEvent(swap, event) {
29
+ if (swap == null)
30
+ return;
31
+ //Update swap
32
+ swap.txIds.claim = event.meta?.txId;
33
+ await this.removeSwapData(swap, SpvVaultSwap_1.SpvVaultSwapState.CLAIMED);
34
+ }
35
+ /**
36
+ * Chain event processor
37
+ *
38
+ * @param chainIdentifier
39
+ * @param eventData
40
+ */
41
+ async processEvent(chainIdentifier, eventData) {
42
+ for (let event of eventData) {
43
+ if (!(event instanceof base_1.SpvVaultEvent))
44
+ continue;
45
+ const vault = await this.Vaults.getVault(chainIdentifier, event.owner, event.vaultId);
46
+ if (vault == null)
47
+ continue;
48
+ if (event instanceof base_1.SpvVaultOpenEvent) {
49
+ await this.Vaults.processOpenEvent(vault, event);
50
+ }
51
+ else if (event instanceof base_1.SpvVaultCloseEvent) {
52
+ await this.Vaults.processCloseEvent(vault, event);
53
+ }
54
+ else if (event instanceof base_1.SpvVaultClaimEvent) {
55
+ const swap = this.btcTxIdIndex.get(event.btcTxId);
56
+ if (swap != null) {
57
+ swap.txIds.claim = event.meta?.txId;
58
+ if (swap.metadata != null)
59
+ swap.metadata.times.claimTxReceived = Date.now();
60
+ }
61
+ await this.Vaults.processClaimEvent(vault, swap, event);
62
+ await this.processClaimEvent(swap, event);
63
+ }
64
+ else if (event instanceof base_1.SpvVaultDepositEvent) {
65
+ await this.Vaults.processDepositEvent(vault, event);
66
+ }
67
+ }
68
+ return true;
69
+ }
70
+ /**
71
+ * Initializes chain events subscription
72
+ */
73
+ subscribeToEvents() {
74
+ for (let key in this.chains.chains) {
75
+ this.chains.chains[key].chainEvents.registerListener((events) => this.processEvent(key, events));
76
+ }
77
+ this.logger.info("SC: Events: subscribed to smartchain events");
78
+ }
79
+ async startWatchdog() {
80
+ await super.startWatchdog();
81
+ await this.Vaults.startVaultsWatchdog();
82
+ }
83
+ async init() {
84
+ await this.storageManager.loadData(SpvVaultSwap_1.SpvVaultSwap);
85
+ for (let { obj: swap, hash, sequence } of await this.storageManager.query([])) {
86
+ if (swap.btcTxId != null)
87
+ this.btcTxIdIndex.set(swap.btcTxId, swap);
88
+ }
89
+ await this.Vaults.init();
90
+ this.subscribeToEvents();
91
+ await PluginManager_1.PluginManager.serviceInitialize(this);
92
+ }
93
+ async processPastSwap(swap) {
94
+ if (swap.state === SpvVaultSwap_1.SpvVaultSwapState.CREATED) {
95
+ if (swap.expiry < Date.now() / 1000) {
96
+ await this.removeSwapData(swap, SpvVaultSwap_1.SpvVaultSwapState.EXPIRED);
97
+ await this.bitcoin.addUnusedAddress(swap.btcAddress);
98
+ }
99
+ }
100
+ if (swap.state === SpvVaultSwap_1.SpvVaultSwapState.SIGNED) {
101
+ //Check if sent
102
+ const tx = await this.bitcoinRpc.getTransaction(swap.btcTxId);
103
+ if (tx == null) {
104
+ await this.removeSwapData(swap, SpvVaultSwap_1.SpvVaultSwapState.FAILED);
105
+ return;
106
+ }
107
+ else if (tx.confirmations === 0) {
108
+ await swap.setState(SpvVaultSwap_1.SpvVaultSwapState.SENT);
109
+ await this.saveSwapData(swap);
110
+ return;
111
+ }
112
+ else {
113
+ await swap.setState(SpvVaultSwap_1.SpvVaultSwapState.BTC_CONFIRMED);
114
+ await this.saveSwapData(swap);
115
+ }
116
+ }
117
+ if (swap.state === SpvVaultSwap_1.SpvVaultSwapState.SENT) {
118
+ //Check if confirmed or double-spent
119
+ const tx = await this.bitcoinRpc.getTransaction(swap.btcTxId);
120
+ if (tx == null) {
121
+ await this.removeSwapData(swap, SpvVaultSwap_1.SpvVaultSwapState.DOUBLE_SPENT);
122
+ return;
123
+ }
124
+ else if (tx.confirmations > 0) {
125
+ await swap.setState(SpvVaultSwap_1.SpvVaultSwapState.BTC_CONFIRMED);
126
+ await this.saveSwapData(swap);
127
+ }
128
+ }
129
+ }
130
+ async processPastSwaps() {
131
+ const swaps = await this.storageManager.query([
132
+ {
133
+ key: "state",
134
+ value: [
135
+ SpvVaultSwap_1.SpvVaultSwapState.CREATED,
136
+ SpvVaultSwap_1.SpvVaultSwapState.SIGNED,
137
+ SpvVaultSwap_1.SpvVaultSwapState.SENT //Check if confirmed or double-spent
138
+ ]
139
+ }
140
+ ]);
141
+ for (let { obj: swap } of swaps) {
142
+ await this.processPastSwap(swap);
143
+ }
144
+ }
145
+ getPricePrefetches(chainIdentifier, token, gasToken, abortController) {
146
+ const pricePrefetchPromise = this.swapPricing.preFetchPrice(token, chainIdentifier).catch(e => {
147
+ this.logger.error("getPricePrefetches(): pricePrefetchPromise error: ", e);
148
+ abortController.abort(e);
149
+ return null;
150
+ });
151
+ const gasTokenPricePrefetchPromise = token === gasToken ?
152
+ pricePrefetchPromise :
153
+ this.swapPricing.preFetchPrice(gasToken, chainIdentifier).catch(e => {
154
+ this.logger.error("getPricePrefetches(): gasTokenPricePrefetchPromise error: ", e);
155
+ abortController.abort(e);
156
+ return null;
157
+ });
158
+ return { pricePrefetchPromise, gasTokenPricePrefetchPromise };
159
+ }
160
+ startRestServer(restServer) {
161
+ restServer.use(this.path + "/getQuote", (0, ServerParamDecoder_1.serverParamDecoder)(10 * 1000));
162
+ restServer.post(this.path + "/getQuote", (0, Utils_1.expressHandlerWrapper)(async (req, res) => {
163
+ const metadata = { request: {}, times: {} };
164
+ const chainIdentifier = req.query.chain ?? this.chains.default;
165
+ const { signer, chainInterface, spvVaultContract } = this.getChain(chainIdentifier);
166
+ metadata.times.requestReceived = Date.now();
167
+ /**
168
+ * address: string smart chain address of the recipient
169
+ * amount: string amount (in sats)
170
+ * token: string Desired token to use
171
+ * gasAmount: string Desired amount in gas token to also get
172
+ * gasToken: string
173
+ * exactOut: boolean Whether the swap should be an exact out instead of exact in swap
174
+ * callerFeeRate: string Caller/watchtower fee (in output token) to assign to the swap
175
+ * frontingFeeRate: string Fronting fee (in output token) to assign to the swap
176
+ */
177
+ const parsedBody = await req.paramReader.getParams({
178
+ address: (val) => val != null &&
179
+ typeof (val) === "string" &&
180
+ chainInterface.isValidAddress(val) ? val : null,
181
+ amount: SchemaVerifier_1.FieldTypeEnum.BigInt,
182
+ token: (val) => val != null &&
183
+ typeof (val) === "string" &&
184
+ this.isTokenSupported(chainIdentifier, val) ? val : null,
185
+ gasAmount: SchemaVerifier_1.FieldTypeEnum.BigInt,
186
+ gasToken: (val) => val != null &&
187
+ typeof (val) === "string" &&
188
+ chainInterface.isValidToken(val) ? val : null,
189
+ exactOut: SchemaVerifier_1.FieldTypeEnum.BooleanOptional,
190
+ callerFeeRate: SchemaVerifier_1.FieldTypeEnum.BigInt,
191
+ frontingFeeRate: SchemaVerifier_1.FieldTypeEnum.BigInt,
192
+ });
193
+ if (parsedBody == null)
194
+ throw {
195
+ code: 20100,
196
+ msg: "Invalid request body"
197
+ };
198
+ metadata.request = parsedBody;
199
+ if (parsedBody.gasToken !== chainInterface.getNativeCurrencyAddress())
200
+ throw {
201
+ code: 20190,
202
+ msg: "Unsupported gas token"
203
+ };
204
+ if (parsedBody.callerFeeRate < 0n || parsedBody.callerFeeRate >= 2n ** 20n)
205
+ throw {
206
+ code: 20191,
207
+ msg: "Invalid caller fee rate"
208
+ };
209
+ if (parsedBody.frontingFeeRate < 0n || parsedBody.frontingFeeRate >= 2n ** 20n)
210
+ throw {
211
+ code: 20192,
212
+ msg: "Invalid fronting fee rate"
213
+ };
214
+ const requestedAmount = {
215
+ input: !parsedBody.exactOut,
216
+ amount: parsedBody.exactOut ?
217
+ (parsedBody.amount * (100000n + parsedBody.callerFeeRate + parsedBody.frontingFeeRate) / 100000n) :
218
+ parsedBody.amount,
219
+ token: parsedBody.token
220
+ };
221
+ const gasTokenAmount = {
222
+ input: false,
223
+ amount: parsedBody.gasAmount * (100000n + parsedBody.callerFeeRate + parsedBody.frontingFeeRate) / 100000n,
224
+ token: parsedBody.gasToken
225
+ };
226
+ const request = {
227
+ chainIdentifier,
228
+ raw: req,
229
+ parsed: parsedBody,
230
+ metadata
231
+ };
232
+ const useToken = parsedBody.token;
233
+ const gasToken = parsedBody.gasToken;
234
+ //Check request params
235
+ const fees = await this.AmountAssertions.preCheckFromBtcAmounts(this.type, request, requestedAmount, gasTokenAmount);
236
+ metadata.times.requestChecked = Date.now();
237
+ //Create abortController for parallel prefetches
238
+ const responseStream = res.responseStream;
239
+ const abortController = (0, Utils_1.getAbortController)(responseStream);
240
+ //Pre-fetch data
241
+ const { pricePrefetchPromise, gasTokenPricePrefetchPromise } = this.getPricePrefetches(chainIdentifier, useToken, gasToken, abortController);
242
+ //Check valid amount specified (min/max)
243
+ let { amountBD, swapFee, swapFeeInToken, totalInToken, amountBDgas, gasSwapFee, gasSwapFeeInToken, totalInGasToken } = await this.AmountAssertions.checkFromBtcAmount(this.type, request, { ...requestedAmount, pricePrefetch: pricePrefetchPromise }, fees, abortController.signal, { ...gasTokenAmount, pricePrefetch: gasTokenPricePrefetchPromise });
244
+ metadata.times.priceCalculated = Date.now();
245
+ const totalBtcOutput = amountBD + amountBDgas;
246
+ //Check if we have enough funds to honor the request
247
+ const vault = await this.Vaults.findVaultForSwap(chainIdentifier, totalBtcOutput, useToken, totalInToken, gasToken, totalInGasToken);
248
+ metadata.times.vaultPicked = Date.now();
249
+ //Create swap receive bitcoin address
250
+ const btcFeeRate = await this.bitcoin.getFeeRate();
251
+ const receiveAddress = await this.bitcoin.getAddress();
252
+ abortController.signal.throwIfAborted();
253
+ metadata.times.addressCreated = Date.now();
254
+ //Adjust the amounts based on passed fees
255
+ if (parsedBody.exactOut) {
256
+ totalInToken = parsedBody.amount;
257
+ }
258
+ else {
259
+ totalInToken = (totalInToken * 100000n / (100000n + parsedBody.callerFeeRate + parsedBody.frontingFeeRate));
260
+ }
261
+ totalInGasToken = (totalInGasToken * 100000n / (100000n + parsedBody.callerFeeRate + parsedBody.frontingFeeRate));
262
+ //Calculate raw amounts
263
+ const [rawTokenAmount, rawGasTokenAmount] = vault.toRawAmounts([totalInToken, totalInGasToken]);
264
+ [totalInToken, totalInGasToken] = vault.fromRawAmounts([rawTokenAmount, rawGasTokenAmount]);
265
+ const expiry = Math.floor(Date.now() / 1000) + this.getInitAuthorizationTimeout(chainIdentifier);
266
+ //Get PSBT data
267
+ const callerFeeShare = parsedBody.callerFeeRate;
268
+ const frontingFeeShare = parsedBody.frontingFeeRate;
269
+ const executionFeeShare = 0n;
270
+ const utxo = vault.getLatestUtxo();
271
+ const quoteId = (0, crypto_1.randomBytes)(32).toString("hex");
272
+ const swap = new SpvVaultSwap_1.SpvVaultSwap(chainIdentifier, quoteId, expiry, vault, utxo, receiveAddress, btcFeeRate, parsedBody.address, totalBtcOutput, totalInToken, totalInGasToken, swapFee, swapFeeInToken, gasSwapFee, gasSwapFeeInToken, callerFeeShare, frontingFeeShare, executionFeeShare, useToken, gasToken);
273
+ swap.metadata = metadata;
274
+ await PluginManager_1.PluginManager.swapCreate(swap);
275
+ await this.saveSwapData(swap);
276
+ this.swapLogger.info(swap, "REST: /getQuote: Created swap address: " + receiveAddress + " amount: " + totalBtcOutput.toString(10));
277
+ await responseStream.writeParamsAndEnd({
278
+ code: 20000,
279
+ msg: "Success",
280
+ data: {
281
+ quoteId,
282
+ expiry,
283
+ address: signer.getAddress(),
284
+ vaultId: vault.data.getVaultId().toString(10),
285
+ vaultBtcAddress: vault.btcAddress,
286
+ btcAddress: receiveAddress,
287
+ btcUtxo: utxo,
288
+ btcFeeRate,
289
+ btcAmount: totalBtcOutput.toString(10),
290
+ btcAmountSwap: amountBD.toString(10),
291
+ btcAmountGas: amountBDgas.toString(10),
292
+ total: totalInToken.toString(10),
293
+ totalGas: totalInGasToken.toString(10),
294
+ totalFeeBtc: (swapFee + gasSwapFee).toString(10),
295
+ swapFeeBtc: swapFee.toString(10),
296
+ swapFee: swapFeeInToken.toString(10),
297
+ gasSwapFeeBtc: gasSwapFee.toString(10),
298
+ gasSwapFee: gasSwapFeeInToken.toString(10),
299
+ callerFeeShare: callerFeeShare.toString(10),
300
+ frontingFeeShare: frontingFeeShare.toString(10),
301
+ executionFeeShare: executionFeeShare.toString(10)
302
+ }
303
+ });
304
+ }));
305
+ restServer.use(this.path + "/postQuote", (0, ServerParamDecoder_1.serverParamDecoder)(10 * 1000));
306
+ restServer.post(this.path + "/postQuote", (0, Utils_1.expressHandlerWrapper)(async (req, res) => {
307
+ let requestReceived = Date.now();
308
+ const parsedBody = await req.paramReader.getParams({
309
+ quoteId: SchemaVerifier_1.FieldTypeEnum.String,
310
+ psbtHex: (val) => val != null &&
311
+ typeof (val) === "string" &&
312
+ Utils_1.HEX_REGEX.test(val) ? val : null
313
+ });
314
+ const swap = await this.storageManager.getData(parsedBody.quoteId, 0n);
315
+ if (swap == null || swap.state !== SpvVaultSwap_1.SpvVaultSwapState.CREATED || swap.expiry < Date.now() / 1000)
316
+ throw {
317
+ code: 20505,
318
+ msg: "Invalid quote ID, not found or expired!"
319
+ };
320
+ const metadata = swap.metadata;
321
+ metadata.times ?? (metadata.times = {});
322
+ metadata.times.requestReceived = requestReceived;
323
+ const vault = await this.Vaults.getVault(swap.chainIdentifier, swap.vaultOwner, swap.vaultId);
324
+ if (vault == null || !vault.isReady()) {
325
+ throw {
326
+ code: 20506,
327
+ msg: "Used vault not found!"
328
+ };
329
+ }
330
+ //Try parse psbt
331
+ let transaction;
332
+ try {
333
+ transaction = btc_signer_1.Transaction.fromPSBT(Buffer.from(parsedBody.psbtHex, "hex"));
334
+ }
335
+ catch (e) {
336
+ this.swapLogger.error(swap, "REST: /postQuote: failed to parse provided PSBT: ", e);
337
+ throw {
338
+ code: 20507,
339
+ msg: "Error parsing PSBT, hex format required!"
340
+ };
341
+ }
342
+ //Check correct psbt
343
+ for (let i = 1; i < transaction.inputsLength; i++) { //Skip first vault input
344
+ const txIn = transaction.getInput(i);
345
+ if ((0, btc_signer_1.getInputType)(txIn).txType === "legacy")
346
+ throw {
347
+ code: 20514,
348
+ msg: "Legacy (pre-segwit) inputs in tx are not allowed!"
349
+ };
350
+ //Check UTXOs exist and are unspent
351
+ if (await this.bitcoinRpc.isSpent(Buffer.from(txIn.txid).toString("hex") + ":" + txIn.index.toString(10)))
352
+ throw {
353
+ code: 20515,
354
+ msg: "Spent UTXO in inputs!"
355
+ };
356
+ }
357
+ const { spvVaultContract } = this.getChain(swap.chainIdentifier);
358
+ let data;
359
+ try {
360
+ data = await spvVaultContract.getWithdrawalData(await this.bitcoin.parsePsbt(transaction));
361
+ }
362
+ catch (e) {
363
+ this.swapLogger.error(swap, "REST: /postQuote: failed to parse PSBT to withdrawal tx data: ", e);
364
+ throw {
365
+ code: 20508,
366
+ msg: "PSBT transaction cannot be parsed!"
367
+ };
368
+ }
369
+ if (!data.isRecipient(swap.recipient) ||
370
+ data.callerFeeRate !== swap.callerFeeShare ||
371
+ data.frontingFeeRate !== swap.frontingFeeShare ||
372
+ data.executionFeeRate !== swap.executionFeeShare ||
373
+ data.rawAmounts[0] !== swap.rawAmountToken ||
374
+ data.rawAmounts[1] !== swap.rawAmountGasToken ||
375
+ data.getExecutionData() != null ||
376
+ data.getSpentVaultUtxo() !== swap.vaultUtxo ||
377
+ data.btcTx.outs[0].value !== SpvVaults_1.VAULT_DUST_AMOUNT ||
378
+ !Buffer.from(data.btcTx.outs[0].scriptPubKey.hex, "hex").equals(this.bitcoin.toOutputScript(swap.vaultAddress)) ||
379
+ BigInt(data.btcTx.outs[2].value) !== swap.amountBtc ||
380
+ !Buffer.from(data.btcTx.outs[2].scriptPubKey.hex, "hex").equals(this.bitcoin.toOutputScript(swap.btcAddress)) ||
381
+ (data.btcTx.locktime > 0 && data.btcTx.locktime < 500000000) ||
382
+ data.btcTx.locktime > Math.floor(Date.now() / 1000) - 1000000) {
383
+ this.swapLogger.error(swap, "REST: /postQuote: Invalid psbt data submitted, raw psbt hex: ", parsedBody.psbtHex);
384
+ throw {
385
+ code: 20509,
386
+ msg: "Invalid PSBT provided!"
387
+ };
388
+ }
389
+ if (swap.vaultUtxo !== vault.getLatestUtxo()) {
390
+ throw {
391
+ code: 20510,
392
+ msg: "Vault UTXO already spent, please try again!"
393
+ };
394
+ }
395
+ //Create abortController for parallel prefetches
396
+ const responseStream = res.responseStream;
397
+ const signedTx = await this.vaultSigner.signPsbt(swap.chainIdentifier, swap.vaultId, transaction, [0]);
398
+ if (!signedTx.isFinal)
399
+ throw {
400
+ code: 20513,
401
+ msg: "One or more PSBT inputs not finalized!"
402
+ };
403
+ const effectiveFeeRate = await this.bitcoinRpc.getEffectiveFeeRate(await this.bitcoin.parsePsbt(signedTx));
404
+ if (effectiveFeeRate.feeRate < swap.btcFeeRate)
405
+ throw {
406
+ code: 20511,
407
+ msg: "Bitcoin transaction fee too low, expected minimum: " + swap.btcFeeRate + " adjusted effective fee rate: " + effectiveFeeRate.feeRate
408
+ };
409
+ const txVsize = signedTx.vsize;
410
+ if (txVsize > TX_MAX_VSIZE)
411
+ throw {
412
+ code: 20516,
413
+ msg: "Bitcoin transaction size too large, maximum: " + TX_MAX_VSIZE + " actual: " + txVsize
414
+ };
415
+ if (swap.vaultUtxo !== vault.getLatestUtxo()) {
416
+ throw {
417
+ code: 20510,
418
+ msg: "Vault UTXO already spent, please try again!"
419
+ };
420
+ }
421
+ vault.addWithdrawal(data);
422
+ await this.Vaults.saveVault(vault);
423
+ //Double-check the state to prevent race condition
424
+ if (swap.state !== SpvVaultSwap_1.SpvVaultSwapState.CREATED)
425
+ throw {
426
+ code: 20505,
427
+ msg: "Invalid quote ID, not found or expired!"
428
+ };
429
+ swap.btcTxId = signedTx.id;
430
+ swap.state = SpvVaultSwap_1.SpvVaultSwapState.SIGNED;
431
+ await this.saveSwapData(swap);
432
+ this.swapLogger.info(swap, "REST: /postQuote: BTC transaction signed, txId: " + swap.btcTxId);
433
+ try {
434
+ await this.bitcoin.sendRawTransaction(Buffer.from(signedTx.toBytes(true, true)).toString("hex"));
435
+ await swap.setState(SpvVaultSwap_1.SpvVaultSwapState.SENT);
436
+ }
437
+ catch (e) {
438
+ this.swapLogger.error(swap, "REST: /postQuote: Failed to send BTC transaction: ", e);
439
+ vault.removeWithdrawal(data);
440
+ await this.Vaults.saveVault(vault);
441
+ await this.removeSwapData(swap, SpvVaultSwap_1.SpvVaultSwapState.FAILED);
442
+ throw {
443
+ code: 20512,
444
+ msg: "Error broadcasting bitcoin transaction!"
445
+ };
446
+ }
447
+ await responseStream.writeParamsAndEnd({
448
+ code: 20000,
449
+ msg: "Success",
450
+ data: {
451
+ txId: swap.btcTxId
452
+ }
453
+ });
454
+ }));
455
+ }
456
+ getInfoData() {
457
+ const mappedDict = {};
458
+ for (let chainId in this.config.gasTokenMax) {
459
+ mappedDict[chainId] = {
460
+ gasToken: this.getChain(chainId).chainInterface.getNativeCurrencyAddress(),
461
+ max: this.config.gasTokenMax[chainId].toString(10)
462
+ };
463
+ }
464
+ return {
465
+ gasTokens: mappedDict
466
+ };
467
+ }
468
+ async saveSwapData(swap) {
469
+ if (swap.btcTxId != null)
470
+ this.btcTxIdIndex.set(swap.btcTxId, swap);
471
+ return super.saveSwapData(swap);
472
+ }
473
+ async removeSwapData(hashOrSwap, sequenceOrUltimateState) {
474
+ let swap;
475
+ let state;
476
+ if (typeof (hashOrSwap) === "string") {
477
+ if (typeof (sequenceOrUltimateState) !== "bigint")
478
+ throw new Error("Sequence must be a BN instance!");
479
+ swap = await this.storageManager.getData(hashOrSwap, sequenceOrUltimateState);
480
+ }
481
+ else {
482
+ swap = hashOrSwap;
483
+ if (sequenceOrUltimateState != null && typeof (sequenceOrUltimateState) !== "bigint")
484
+ state = sequenceOrUltimateState;
485
+ }
486
+ if (swap.btcTxId != null)
487
+ this.btcTxIdIndex.delete(swap.btcTxId);
488
+ return super.removeSwapData(swap, state);
489
+ }
490
+ }
491
+ exports.SpvVaultSwapHandler = SpvVaultSwapHandler;