@atomiqlabs/lp-lib 14.0.0-dev.3 → 14.0.0-dev.30

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