@atomiqlabs/lp-lib 14.0.0-dev.21 → 14.0.0-dev.24

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