@atomiqlabs/lp-lib 15.0.14 → 16.0.0

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