@atomiqlabs/lp-lib 15.0.5 → 15.0.6

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