@atomiqlabs/lp-lib 15.0.12 → 15.0.14

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