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

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