@atomiqlabs/lp-lib 14.0.0-dev.11 → 14.0.0-dev.13

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