@atomiqlabs/lp-lib 15.0.12 → 15.0.14

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (163) hide show
  1. package/LICENSE +201 -201
  2. package/dist/fees/IBtcFeeEstimator.d.ts +3 -3
  3. package/dist/fees/IBtcFeeEstimator.js +2 -2
  4. package/dist/index.d.ts +40 -40
  5. package/dist/index.js +56 -56
  6. package/dist/info/InfoHandler.d.ts +17 -17
  7. package/dist/info/InfoHandler.js +58 -61
  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 +18 -18
  23. package/dist/storagemanager/IntermediaryStorageManager.js +104 -104
  24. package/dist/storagemanager/StorageManager.d.ts +12 -12
  25. package/dist/storagemanager/StorageManager.js +57 -57
  26. package/dist/swaps/SwapHandler.d.ts +153 -156
  27. package/dist/swaps/SwapHandler.js +157 -163
  28. package/dist/swaps/SwapHandlerSwap.d.ts +79 -79
  29. package/dist/swaps/SwapHandlerSwap.js +78 -78
  30. package/dist/swaps/assertions/AmountAssertions.d.ts +28 -28
  31. package/dist/swaps/assertions/AmountAssertions.js +74 -72
  32. package/dist/swaps/assertions/FromBtcAmountAssertions.d.ts +76 -76
  33. package/dist/swaps/assertions/FromBtcAmountAssertions.js +172 -172
  34. package/dist/swaps/assertions/LightningAssertions.d.ts +44 -44
  35. package/dist/swaps/assertions/LightningAssertions.js +86 -86
  36. package/dist/swaps/assertions/ToBtcAmountAssertions.d.ts +53 -53
  37. package/dist/swaps/assertions/ToBtcAmountAssertions.js +150 -150
  38. package/dist/swaps/escrow/EscrowHandler.d.ts +51 -51
  39. package/dist/swaps/escrow/EscrowHandler.js +158 -158
  40. package/dist/swaps/escrow/EscrowHandlerSwap.d.ts +35 -35
  41. package/dist/swaps/escrow/EscrowHandlerSwap.js +69 -69
  42. package/dist/swaps/escrow/FromBtcBaseSwap.d.ts +14 -14
  43. package/dist/swaps/escrow/FromBtcBaseSwap.js +32 -32
  44. package/dist/swaps/escrow/FromBtcBaseSwapHandler.d.ts +101 -101
  45. package/dist/swaps/escrow/FromBtcBaseSwapHandler.js +207 -207
  46. package/dist/swaps/escrow/ToBtcBaseSwap.d.ts +36 -36
  47. package/dist/swaps/escrow/ToBtcBaseSwap.js +67 -67
  48. package/dist/swaps/escrow/ToBtcBaseSwapHandler.d.ts +53 -53
  49. package/dist/swaps/escrow/ToBtcBaseSwapHandler.js +81 -81
  50. package/dist/swaps/escrow/frombtc_abstract/FromBtcAbs.d.ts +83 -83
  51. package/dist/swaps/escrow/frombtc_abstract/FromBtcAbs.js +318 -318
  52. package/dist/swaps/escrow/frombtc_abstract/FromBtcSwapAbs.d.ts +21 -21
  53. package/dist/swaps/escrow/frombtc_abstract/FromBtcSwapAbs.js +50 -50
  54. package/dist/swaps/escrow/frombtcln_abstract/FromBtcLnAbs.d.ts +107 -107
  55. package/dist/swaps/escrow/frombtcln_abstract/FromBtcLnAbs.js +673 -675
  56. package/dist/swaps/escrow/frombtcln_abstract/FromBtcLnSwapAbs.d.ts +32 -32
  57. package/dist/swaps/escrow/frombtcln_abstract/FromBtcLnSwapAbs.js +88 -88
  58. package/dist/swaps/escrow/tobtc_abstract/ToBtcAbs.d.ts +171 -171
  59. package/dist/swaps/escrow/tobtc_abstract/ToBtcAbs.js +718 -718
  60. package/dist/swaps/escrow/tobtc_abstract/ToBtcSwapAbs.d.ts +28 -28
  61. package/dist/swaps/escrow/tobtc_abstract/ToBtcSwapAbs.js +64 -64
  62. package/dist/swaps/escrow/tobtcln_abstract/ToBtcLnAbs.d.ts +177 -177
  63. package/dist/swaps/escrow/tobtcln_abstract/ToBtcLnAbs.js +863 -863
  64. package/dist/swaps/escrow/tobtcln_abstract/ToBtcLnSwapAbs.d.ts +24 -24
  65. package/dist/swaps/escrow/tobtcln_abstract/ToBtcLnSwapAbs.js +58 -58
  66. package/dist/swaps/spv_vault_swap/SpvVault.d.ts +45 -45
  67. package/dist/swaps/spv_vault_swap/SpvVault.js +145 -145
  68. package/dist/swaps/spv_vault_swap/SpvVaultSwap.d.ts +68 -68
  69. package/dist/swaps/spv_vault_swap/SpvVaultSwap.js +158 -158
  70. package/dist/swaps/spv_vault_swap/SpvVaultSwapHandler.d.ts +68 -68
  71. package/dist/swaps/spv_vault_swap/SpvVaultSwapHandler.js +528 -528
  72. package/dist/swaps/spv_vault_swap/SpvVaults.d.ts +68 -68
  73. package/dist/swaps/spv_vault_swap/SpvVaults.js +454 -454
  74. package/dist/swaps/trusted/frombtc_trusted/FromBtcTrusted.d.ts +51 -51
  75. package/dist/swaps/trusted/frombtc_trusted/FromBtcTrusted.js +650 -650
  76. package/dist/swaps/trusted/frombtc_trusted/FromBtcTrustedSwap.d.ts +52 -52
  77. package/dist/swaps/trusted/frombtc_trusted/FromBtcTrustedSwap.js +118 -118
  78. package/dist/swaps/trusted/frombtcln_trusted/FromBtcLnTrusted.d.ts +76 -76
  79. package/dist/swaps/trusted/frombtcln_trusted/FromBtcLnTrusted.js +493 -495
  80. package/dist/swaps/trusted/frombtcln_trusted/FromBtcLnTrustedSwap.d.ts +34 -34
  81. package/dist/swaps/trusted/frombtcln_trusted/FromBtcLnTrustedSwap.js +81 -81
  82. package/dist/utils/BitcoinUtils.d.ts +4 -4
  83. package/dist/utils/BitcoinUtils.js +61 -61
  84. package/dist/utils/Utils.d.ts +29 -29
  85. package/dist/utils/Utils.js +88 -88
  86. package/dist/utils/paramcoders/IParamReader.d.ts +5 -5
  87. package/dist/utils/paramcoders/IParamReader.js +2 -2
  88. package/dist/utils/paramcoders/IParamWriter.d.ts +4 -4
  89. package/dist/utils/paramcoders/IParamWriter.js +2 -2
  90. package/dist/utils/paramcoders/LegacyParamEncoder.d.ts +10 -10
  91. package/dist/utils/paramcoders/LegacyParamEncoder.js +22 -22
  92. package/dist/utils/paramcoders/ParamDecoder.d.ts +25 -25
  93. package/dist/utils/paramcoders/ParamDecoder.js +222 -222
  94. package/dist/utils/paramcoders/ParamEncoder.d.ts +9 -9
  95. package/dist/utils/paramcoders/ParamEncoder.js +22 -22
  96. package/dist/utils/paramcoders/SchemaVerifier.d.ts +21 -21
  97. package/dist/utils/paramcoders/SchemaVerifier.js +84 -84
  98. package/dist/utils/paramcoders/server/ServerParamDecoder.d.ts +8 -8
  99. package/dist/utils/paramcoders/server/ServerParamDecoder.js +105 -105
  100. package/dist/utils/paramcoders/server/ServerParamEncoder.d.ts +11 -11
  101. package/dist/utils/paramcoders/server/ServerParamEncoder.js +65 -65
  102. package/dist/wallets/IBitcoinWallet.d.ts +67 -67
  103. package/dist/wallets/IBitcoinWallet.js +2 -2
  104. package/dist/wallets/ILightningWallet.d.ts +117 -117
  105. package/dist/wallets/ILightningWallet.js +37 -37
  106. package/dist/wallets/ISpvVaultSigner.d.ts +7 -7
  107. package/dist/wallets/ISpvVaultSigner.js +2 -2
  108. package/dist/wallets/ISpvVaultWallet.d.ts +42 -42
  109. package/dist/wallets/ISpvVaultWallet.js +2 -2
  110. package/package.json +36 -36
  111. package/src/fees/IBtcFeeEstimator.ts +6 -6
  112. package/src/index.ts +51 -51
  113. package/src/info/InfoHandler.ts +100 -106
  114. package/src/plugins/IPlugin.ts +174 -174
  115. package/src/plugins/PluginManager.ts +354 -354
  116. package/src/prices/BinanceSwapPrice.ts +113 -113
  117. package/src/prices/CoinGeckoSwapPrice.ts +87 -87
  118. package/src/prices/ISwapPrice.ts +88 -88
  119. package/src/prices/OKXSwapPrice.ts +113 -113
  120. package/src/storage/IIntermediaryStorage.ts +19 -19
  121. package/src/storagemanager/IntermediaryStorageManager.ts +109 -109
  122. package/src/storagemanager/StorageManager.ts +68 -68
  123. package/src/swaps/SwapHandler.ts +272 -280
  124. package/src/swaps/SwapHandlerSwap.ts +141 -141
  125. package/src/swaps/assertions/AmountAssertions.ts +77 -76
  126. package/src/swaps/assertions/FromBtcAmountAssertions.ts +238 -238
  127. package/src/swaps/assertions/LightningAssertions.ts +103 -103
  128. package/src/swaps/assertions/ToBtcAmountAssertions.ts +203 -203
  129. package/src/swaps/escrow/EscrowHandler.ts +179 -179
  130. package/src/swaps/escrow/EscrowHandlerSwap.ts +86 -86
  131. package/src/swaps/escrow/FromBtcBaseSwap.ts +38 -38
  132. package/src/swaps/escrow/FromBtcBaseSwapHandler.ts +283 -283
  133. package/src/swaps/escrow/ToBtcBaseSwap.ts +85 -85
  134. package/src/swaps/escrow/ToBtcBaseSwapHandler.ts +129 -129
  135. package/src/swaps/escrow/frombtc_abstract/FromBtcAbs.ts +452 -452
  136. package/src/swaps/escrow/frombtc_abstract/FromBtcSwapAbs.ts +61 -61
  137. package/src/swaps/escrow/frombtcln_abstract/FromBtcLnAbs.ts +855 -856
  138. package/src/swaps/escrow/frombtcln_abstract/FromBtcLnSwapAbs.ts +137 -137
  139. package/src/swaps/escrow/tobtc_abstract/ToBtcAbs.ts +890 -890
  140. package/src/swaps/escrow/tobtc_abstract/ToBtcSwapAbs.ts +108 -108
  141. package/src/swaps/escrow/tobtcln_abstract/ToBtcLnAbs.ts +1112 -1112
  142. package/src/swaps/escrow/tobtcln_abstract/ToBtcLnSwapAbs.ts +80 -80
  143. package/src/swaps/spv_vault_swap/SpvVault.ts +178 -178
  144. package/src/swaps/spv_vault_swap/SpvVaultSwap.ts +228 -228
  145. package/src/swaps/spv_vault_swap/SpvVaultSwapHandler.ts +671 -671
  146. package/src/swaps/spv_vault_swap/SpvVaults.ts +526 -526
  147. package/src/swaps/trusted/frombtc_trusted/FromBtcTrusted.ts +747 -747
  148. package/src/swaps/trusted/frombtc_trusted/FromBtcTrustedSwap.ts +185 -185
  149. package/src/swaps/trusted/frombtcln_trusted/FromBtcLnTrusted.ts +591 -592
  150. package/src/swaps/trusted/frombtcln_trusted/FromBtcLnTrustedSwap.ts +121 -121
  151. package/src/utils/BitcoinUtils.ts +59 -59
  152. package/src/utils/Utils.ts +102 -102
  153. package/src/utils/paramcoders/IParamReader.ts +7 -7
  154. package/src/utils/paramcoders/IParamWriter.ts +8 -8
  155. package/src/utils/paramcoders/LegacyParamEncoder.ts +27 -27
  156. package/src/utils/paramcoders/ParamDecoder.ts +218 -218
  157. package/src/utils/paramcoders/ParamEncoder.ts +29 -29
  158. package/src/utils/paramcoders/SchemaVerifier.ts +96 -96
  159. package/src/utils/paramcoders/server/ServerParamDecoder.ts +115 -115
  160. package/src/utils/paramcoders/server/ServerParamEncoder.ts +75 -75
  161. package/src/wallets/IBitcoinWallet.ts +68 -68
  162. package/src/wallets/ILightningWallet.ts +178 -178
  163. package/src/wallets/ISpvVaultSigner.ts +10 -10
@@ -1,671 +1,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.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 ?? this.chains.default;
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.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
+ }