@atomiqlabs/lp-lib 14.0.0-dev.21 → 14.0.0-dev.24

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