@atomiqlabs/lp-lib 15.0.14 → 16.0.0

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