@atomiqlabs/lp-lib 16.1.0 → 16.1.2
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.
- package/LICENSE +201 -201
- package/dist/fees/IBtcFeeEstimator.d.ts +3 -3
- package/dist/fees/IBtcFeeEstimator.js +2 -2
- package/dist/index.d.ts +42 -42
- package/dist/index.js +58 -58
- package/dist/info/InfoHandler.d.ts +17 -17
- package/dist/info/InfoHandler.js +60 -60
- package/dist/plugins/IPlugin.d.ts +144 -144
- package/dist/plugins/IPlugin.js +34 -34
- package/dist/plugins/PluginManager.d.ts +113 -113
- package/dist/plugins/PluginManager.js +274 -274
- package/dist/prices/BinanceSwapPrice.d.ts +29 -29
- package/dist/prices/BinanceSwapPrice.js +79 -79
- package/dist/prices/CoinGeckoSwapPrice.d.ts +33 -33
- package/dist/prices/CoinGeckoSwapPrice.js +51 -51
- package/dist/prices/ISwapPrice.d.ts +43 -43
- package/dist/prices/ISwapPrice.js +55 -55
- package/dist/prices/OKXSwapPrice.d.ts +29 -29
- package/dist/prices/OKXSwapPrice.js +79 -79
- package/dist/storage/IIntermediaryStorage.d.ts +18 -18
- package/dist/storage/IIntermediaryStorage.js +2 -2
- package/dist/storagemanager/IntermediaryStorageManager.d.ts +19 -19
- package/dist/storagemanager/IntermediaryStorageManager.js +111 -111
- package/dist/storagemanager/StorageManager.d.ts +13 -13
- package/dist/storagemanager/StorageManager.js +64 -64
- package/dist/swaps/SwapHandler.d.ts +171 -171
- package/dist/swaps/SwapHandler.js +217 -217
- package/dist/swaps/SwapHandlerSwap.d.ts +79 -79
- package/dist/swaps/SwapHandlerSwap.js +78 -78
- package/dist/swaps/assertions/AmountAssertions.d.ts +28 -28
- package/dist/swaps/assertions/AmountAssertions.js +74 -74
- package/dist/swaps/assertions/FromBtcAmountAssertions.d.ts +76 -76
- package/dist/swaps/assertions/FromBtcAmountAssertions.js +185 -185
- package/dist/swaps/assertions/LightningAssertions.d.ts +44 -44
- package/dist/swaps/assertions/LightningAssertions.js +86 -86
- package/dist/swaps/assertions/ToBtcAmountAssertions.d.ts +53 -53
- package/dist/swaps/assertions/ToBtcAmountAssertions.js +150 -150
- package/dist/swaps/escrow/EscrowHandler.d.ts +50 -50
- package/dist/swaps/escrow/EscrowHandler.js +151 -151
- package/dist/swaps/escrow/EscrowHandlerSwap.d.ts +35 -35
- package/dist/swaps/escrow/EscrowHandlerSwap.js +69 -69
- package/dist/swaps/escrow/FromBtcBaseSwap.d.ts +14 -14
- package/dist/swaps/escrow/FromBtcBaseSwap.js +32 -32
- package/dist/swaps/escrow/FromBtcBaseSwapHandler.d.ts +102 -102
- package/dist/swaps/escrow/FromBtcBaseSwapHandler.js +210 -210
- package/dist/swaps/escrow/ToBtcBaseSwap.d.ts +36 -36
- package/dist/swaps/escrow/ToBtcBaseSwap.js +67 -67
- package/dist/swaps/escrow/ToBtcBaseSwapHandler.d.ts +53 -53
- package/dist/swaps/escrow/ToBtcBaseSwapHandler.js +81 -81
- package/dist/swaps/escrow/frombtc_abstract/FromBtcAbs.d.ts +84 -84
- package/dist/swaps/escrow/frombtc_abstract/FromBtcAbs.js +322 -322
- package/dist/swaps/escrow/frombtc_abstract/FromBtcSwapAbs.d.ts +21 -21
- package/dist/swaps/escrow/frombtc_abstract/FromBtcSwapAbs.js +50 -50
- package/dist/swaps/escrow/frombtcln_abstract/FromBtcLnAbs.d.ts +108 -108
- package/dist/swaps/escrow/frombtcln_abstract/FromBtcLnAbs.js +695 -695
- package/dist/swaps/escrow/frombtcln_abstract/FromBtcLnSwapAbs.d.ts +33 -33
- package/dist/swaps/escrow/frombtcln_abstract/FromBtcLnSwapAbs.js +91 -91
- package/dist/swaps/escrow/frombtcln_autoinit/FromBtcLnAuto.d.ts +112 -112
- package/dist/swaps/escrow/frombtcln_autoinit/FromBtcLnAuto.js +708 -708
- package/dist/swaps/escrow/frombtcln_autoinit/FromBtcLnAutoSwap.d.ts +55 -55
- package/dist/swaps/escrow/frombtcln_autoinit/FromBtcLnAutoSwap.js +120 -120
- package/dist/swaps/escrow/tobtc_abstract/ToBtcAbs.d.ts +170 -170
- package/dist/swaps/escrow/tobtc_abstract/ToBtcAbs.js +745 -745
- package/dist/swaps/escrow/tobtc_abstract/ToBtcSwapAbs.d.ts +28 -28
- package/dist/swaps/escrow/tobtc_abstract/ToBtcSwapAbs.js +64 -64
- package/dist/swaps/escrow/tobtcln_abstract/ToBtcLnAbs.d.ts +178 -178
- package/dist/swaps/escrow/tobtcln_abstract/ToBtcLnAbs.js +899 -899
- package/dist/swaps/escrow/tobtcln_abstract/ToBtcLnSwapAbs.d.ts +24 -24
- package/dist/swaps/escrow/tobtcln_abstract/ToBtcLnSwapAbs.js +58 -58
- package/dist/swaps/spv_vault_swap/SpvVault.d.ts +44 -44
- package/dist/swaps/spv_vault_swap/SpvVault.js +145 -145
- package/dist/swaps/spv_vault_swap/SpvVaultSwap.d.ts +68 -68
- package/dist/swaps/spv_vault_swap/SpvVaultSwap.js +158 -158
- package/dist/swaps/spv_vault_swap/SpvVaultSwapHandler.d.ts +68 -68
- package/dist/swaps/spv_vault_swap/SpvVaultSwapHandler.js +561 -561
- package/dist/swaps/spv_vault_swap/SpvVaults.d.ts +63 -63
- package/dist/swaps/spv_vault_swap/SpvVaults.js +491 -491
- package/dist/swaps/trusted/frombtc_trusted/FromBtcTrusted.d.ts +52 -52
- package/dist/swaps/trusted/frombtc_trusted/FromBtcTrusted.js +662 -662
- package/dist/swaps/trusted/frombtc_trusted/FromBtcTrustedSwap.d.ts +52 -52
- package/dist/swaps/trusted/frombtc_trusted/FromBtcTrustedSwap.js +118 -118
- package/dist/swaps/trusted/frombtcln_trusted/FromBtcLnTrusted.d.ts +77 -77
- package/dist/swaps/trusted/frombtcln_trusted/FromBtcLnTrusted.js +504 -504
- package/dist/swaps/trusted/frombtcln_trusted/FromBtcLnTrustedSwap.d.ts +34 -34
- package/dist/swaps/trusted/frombtcln_trusted/FromBtcLnTrustedSwap.js +81 -81
- package/dist/utils/BitcoinUtils.d.ts +4 -4
- package/dist/utils/BitcoinUtils.js +61 -61
- package/dist/utils/Utils.d.ts +29 -29
- package/dist/utils/Utils.js +89 -89
- package/dist/utils/paramcoders/IParamReader.d.ts +5 -5
- package/dist/utils/paramcoders/IParamReader.js +2 -2
- package/dist/utils/paramcoders/IParamWriter.d.ts +4 -4
- package/dist/utils/paramcoders/IParamWriter.js +2 -2
- package/dist/utils/paramcoders/LegacyParamEncoder.d.ts +10 -10
- package/dist/utils/paramcoders/LegacyParamEncoder.js +22 -22
- package/dist/utils/paramcoders/ParamDecoder.d.ts +25 -25
- package/dist/utils/paramcoders/ParamDecoder.js +222 -222
- package/dist/utils/paramcoders/ParamEncoder.d.ts +9 -9
- package/dist/utils/paramcoders/ParamEncoder.js +22 -22
- package/dist/utils/paramcoders/SchemaVerifier.d.ts +21 -21
- package/dist/utils/paramcoders/SchemaVerifier.js +84 -84
- package/dist/utils/paramcoders/server/ServerParamDecoder.d.ts +8 -8
- package/dist/utils/paramcoders/server/ServerParamDecoder.js +107 -107
- package/dist/utils/paramcoders/server/ServerParamEncoder.d.ts +11 -11
- package/dist/utils/paramcoders/server/ServerParamEncoder.js +65 -65
- package/dist/wallets/IBitcoinWallet.d.ts +74 -74
- package/dist/wallets/IBitcoinWallet.js +2 -2
- package/dist/wallets/ILightningWallet.d.ts +136 -117
- package/dist/wallets/ILightningWallet.js +37 -37
- package/dist/wallets/ISpvVaultSigner.d.ts +7 -7
- package/dist/wallets/ISpvVaultSigner.js +2 -2
- package/package.json +36 -36
- package/src/fees/IBtcFeeEstimator.ts +6 -6
- package/src/index.ts +53 -53
- package/src/info/InfoHandler.ts +103 -103
- package/src/plugins/IPlugin.ts +174 -174
- package/src/plugins/PluginManager.ts +354 -354
- package/src/prices/BinanceSwapPrice.ts +101 -101
- package/src/prices/CoinGeckoSwapPrice.ts +75 -75
- package/src/prices/ISwapPrice.ts +88 -88
- package/src/prices/OKXSwapPrice.ts +101 -101
- package/src/storage/IIntermediaryStorage.ts +19 -19
- package/src/storagemanager/IntermediaryStorageManager.ts +118 -118
- package/src/storagemanager/StorageManager.ts +78 -78
- package/src/swaps/SwapHandler.ts +323 -323
- package/src/swaps/SwapHandlerSwap.ts +141 -141
- package/src/swaps/assertions/AmountAssertions.ts +77 -77
- package/src/swaps/assertions/FromBtcAmountAssertions.ts +251 -251
- package/src/swaps/assertions/LightningAssertions.ts +103 -103
- package/src/swaps/assertions/ToBtcAmountAssertions.ts +203 -203
- package/src/swaps/escrow/EscrowHandler.ts +172 -172
- package/src/swaps/escrow/EscrowHandlerSwap.ts +86 -86
- package/src/swaps/escrow/FromBtcBaseSwap.ts +38 -38
- package/src/swaps/escrow/FromBtcBaseSwapHandler.ts +286 -286
- package/src/swaps/escrow/ToBtcBaseSwap.ts +85 -85
- package/src/swaps/escrow/ToBtcBaseSwapHandler.ts +129 -129
- package/src/swaps/escrow/frombtc_abstract/FromBtcAbs.ts +457 -457
- package/src/swaps/escrow/frombtc_abstract/FromBtcSwapAbs.ts +61 -61
- package/src/swaps/escrow/frombtcln_abstract/FromBtcLnAbs.ts +873 -873
- package/src/swaps/escrow/frombtcln_abstract/FromBtcLnSwapAbs.ts +141 -141
- package/src/swaps/escrow/frombtcln_autoinit/FromBtcLnAuto.ts +866 -866
- package/src/swaps/escrow/frombtcln_autoinit/FromBtcLnAutoSwap.ts +196 -196
- package/src/swaps/escrow/tobtc_abstract/ToBtcAbs.ts +920 -920
- package/src/swaps/escrow/tobtc_abstract/ToBtcSwapAbs.ts +108 -108
- package/src/swaps/escrow/tobtcln_abstract/ToBtcLnAbs.ts +1149 -1149
- package/src/swaps/escrow/tobtcln_abstract/ToBtcLnSwapAbs.ts +80 -80
- package/src/swaps/spv_vault_swap/SpvVault.ts +178 -178
- package/src/swaps/spv_vault_swap/SpvVaultSwap.ts +228 -228
- package/src/swaps/spv_vault_swap/SpvVaultSwapHandler.ts +712 -712
- package/src/swaps/spv_vault_swap/SpvVaults.ts +567 -567
- package/src/swaps/trusted/frombtc_trusted/FromBtcTrusted.ts +762 -762
- package/src/swaps/trusted/frombtc_trusted/FromBtcTrustedSwap.ts +185 -185
- package/src/swaps/trusted/frombtcln_trusted/FromBtcLnTrusted.ts +603 -603
- package/src/swaps/trusted/frombtcln_trusted/FromBtcLnTrustedSwap.ts +121 -121
- package/src/utils/BitcoinUtils.ts +59 -59
- package/src/utils/Utils.ts +104 -104
- package/src/utils/paramcoders/IParamReader.ts +7 -7
- package/src/utils/paramcoders/IParamWriter.ts +8 -8
- package/src/utils/paramcoders/LegacyParamEncoder.ts +27 -27
- package/src/utils/paramcoders/ParamDecoder.ts +218 -218
- package/src/utils/paramcoders/ParamEncoder.ts +29 -29
- package/src/utils/paramcoders/SchemaVerifier.ts +96 -96
- package/src/utils/paramcoders/server/ServerParamDecoder.ts +118 -118
- package/src/utils/paramcoders/server/ServerParamEncoder.ts +75 -75
- package/src/wallets/IBitcoinWallet.ts +76 -76
- package/src/wallets/ILightningWallet.ts +200 -178
- package/src/wallets/ISpvVaultSigner.ts +10 -10
|
@@ -1,712 +1,712 @@
|
|
|
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,
|
|
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, isDefinedRuntimeError} 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
|
-
readonly type = SwapHandlerType.FROM_BTC_SPV;
|
|
61
|
-
readonly inflightSwapStates = new Set([SpvVaultSwapState.SIGNED, SpvVaultSwapState.SENT, SpvVaultSwapState.BTC_CONFIRMED]);
|
|
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
|
-
/**
|
|
256
|
-
* token: string Desired token to use
|
|
257
|
-
* gasToken: string
|
|
258
|
-
*/
|
|
259
|
-
const preFetchParsedBody = await req.paramReader.getParams({
|
|
260
|
-
token: (val: string) => val!=null &&
|
|
261
|
-
typeof(val)==="string" &&
|
|
262
|
-
this.isTokenSupported(chainIdentifier, val) ? val : null,
|
|
263
|
-
gasToken: (val: string) => val!=null &&
|
|
264
|
-
typeof(val)==="string" &&
|
|
265
|
-
chainInterface.isValidToken(val) ? val : null
|
|
266
|
-
});
|
|
267
|
-
if(preFetchParsedBody==null) throw {
|
|
268
|
-
code: 20100,
|
|
269
|
-
msg: "Invalid request body"
|
|
270
|
-
};
|
|
271
|
-
|
|
272
|
-
//Create abortController for parallel prefetches
|
|
273
|
-
const responseStream = res.responseStream;
|
|
274
|
-
const abortController = getAbortController(responseStream);
|
|
275
|
-
|
|
276
|
-
//Pre-fetch data
|
|
277
|
-
const {
|
|
278
|
-
pricePrefetchPromise,
|
|
279
|
-
gasTokenPricePrefetchPromise
|
|
280
|
-
} = this.getPricePrefetches(chainIdentifier, preFetchParsedBody.token, preFetchParsedBody.gasToken, abortController);
|
|
281
|
-
const nativeBalancePrefetch = this.prefetchNativeBalanceIfNeeded(chainIdentifier, abortController);
|
|
282
|
-
const btcFeeRatePrefetch = this.bitcoin.getFeeRate().catch(e => {
|
|
283
|
-
abortController.abort(e);
|
|
284
|
-
return null;
|
|
285
|
-
});
|
|
286
|
-
|
|
287
|
-
//Listener that re-adds the returned bitcoin address to the unused address list if request fails or closes
|
|
288
|
-
let abortAddUnusedAddressListener: () => void;
|
|
289
|
-
const bitcoinAddressPrefetch = this.bitcoin.getAddress().then(value => {
|
|
290
|
-
//Already aborted
|
|
291
|
-
if(abortController.signal.aborted) {
|
|
292
|
-
this.bitcoin.addUnusedAddress(value);
|
|
293
|
-
return null;
|
|
294
|
-
}
|
|
295
|
-
//Not aborted yet, add an event listener to re-add the address to the unused list
|
|
296
|
-
abortController.signal.addEventListener("abort", abortAddUnusedAddressListener = () => {
|
|
297
|
-
this.bitcoin.addUnusedAddress(value);
|
|
298
|
-
});
|
|
299
|
-
return value;
|
|
300
|
-
}).catch(e => {
|
|
301
|
-
abortController.abort(e);
|
|
302
|
-
return null;
|
|
303
|
-
});
|
|
304
|
-
|
|
305
|
-
/**
|
|
306
|
-
* address: string smart chain address of the recipient
|
|
307
|
-
* amount: string amount (in sats)
|
|
308
|
-
* gasAmount: string Desired amount in gas token to also get
|
|
309
|
-
* exactOut: boolean Whether the swap should be an exact out instead of exact in swap
|
|
310
|
-
* callerFeeRate: string Caller/watchtower fee (in output token) to assign to the swap
|
|
311
|
-
* frontingFeeRate: string Fronting fee (in output token) to assign to the swap
|
|
312
|
-
*/
|
|
313
|
-
const actualParsedBody = await req.paramReader.getParams({
|
|
314
|
-
address: (val: string) => val!=null &&
|
|
315
|
-
typeof(val)==="string" &&
|
|
316
|
-
chainInterface.isValidAddress(val, true) ? val : null,
|
|
317
|
-
amount: FieldTypeEnum.BigInt,
|
|
318
|
-
gasAmount: FieldTypeEnum.BigInt,
|
|
319
|
-
exactOut: FieldTypeEnum.BooleanOptional,
|
|
320
|
-
callerFeeRate: FieldTypeEnum.BigInt,
|
|
321
|
-
frontingFeeRate: FieldTypeEnum.BigInt,
|
|
322
|
-
});
|
|
323
|
-
abortController.signal.throwIfAborted();
|
|
324
|
-
if(actualParsedBody==null) throw {
|
|
325
|
-
code: 20100,
|
|
326
|
-
msg: "Invalid request body"
|
|
327
|
-
};
|
|
328
|
-
|
|
329
|
-
const parsedBody: SpvVaultSwapRequestType = {...preFetchParsedBody, ...actualParsedBody};
|
|
330
|
-
metadata.request = parsedBody;
|
|
331
|
-
|
|
332
|
-
if(parsedBody.gasToken!==chainInterface.getNativeCurrencyAddress()) throw {
|
|
333
|
-
code: 20190,
|
|
334
|
-
msg: "Unsupported gas token"
|
|
335
|
-
};
|
|
336
|
-
|
|
337
|
-
if(parsedBody.callerFeeRate < 0n || parsedBody.callerFeeRate >= 2n**20n) throw {
|
|
338
|
-
code: 20191,
|
|
339
|
-
msg: "Invalid caller fee rate"
|
|
340
|
-
};
|
|
341
|
-
if(parsedBody.frontingFeeRate < 0n || parsedBody.frontingFeeRate >= 2n**20n) throw {
|
|
342
|
-
code: 20192,
|
|
343
|
-
msg: "Invalid fronting fee rate"
|
|
344
|
-
};
|
|
345
|
-
|
|
346
|
-
const requestedAmount = {
|
|
347
|
-
input: !parsedBody.exactOut,
|
|
348
|
-
amount: parsedBody.exactOut ?
|
|
349
|
-
(parsedBody.amount * (100_000n + parsedBody.callerFeeRate + parsedBody.frontingFeeRate) / 100_000n) :
|
|
350
|
-
parsedBody.amount,
|
|
351
|
-
token: parsedBody.token
|
|
352
|
-
};
|
|
353
|
-
const gasTokenAmount = {
|
|
354
|
-
input: false,
|
|
355
|
-
amount: parsedBody.gasAmount * (100_000n + parsedBody.callerFeeRate + parsedBody.frontingFeeRate) / 100_000n,
|
|
356
|
-
token: parsedBody.gasToken
|
|
357
|
-
} as const;
|
|
358
|
-
const request = {
|
|
359
|
-
chainIdentifier,
|
|
360
|
-
raw: req,
|
|
361
|
-
parsed: parsedBody,
|
|
362
|
-
metadata
|
|
363
|
-
};
|
|
364
|
-
const useToken = parsedBody.token;
|
|
365
|
-
const gasToken = parsedBody.gasToken;
|
|
366
|
-
|
|
367
|
-
this.checkTooManyInflightSwaps();
|
|
368
|
-
|
|
369
|
-
//Check request params
|
|
370
|
-
const fees = await this.AmountAssertions.preCheckFromBtcAmounts(this.type, request, requestedAmount, gasTokenAmount);
|
|
371
|
-
metadata.times.requestChecked = Date.now();
|
|
372
|
-
|
|
373
|
-
await this.checkNativeBalance(chainIdentifier, nativeBalancePrefetch, abortController.signal);
|
|
374
|
-
|
|
375
|
-
//Check valid amount specified (min/max)
|
|
376
|
-
let {
|
|
377
|
-
amountBD,
|
|
378
|
-
swapFee,
|
|
379
|
-
swapFeeInToken,
|
|
380
|
-
totalInToken,
|
|
381
|
-
amountBDgas,
|
|
382
|
-
gasSwapFee,
|
|
383
|
-
gasSwapFeeInToken,
|
|
384
|
-
totalInGasToken
|
|
385
|
-
} = await this.AmountAssertions.checkFromBtcAmount(
|
|
386
|
-
this.type,
|
|
387
|
-
request,
|
|
388
|
-
{...requestedAmount, pricePrefetch: pricePrefetchPromise},
|
|
389
|
-
fees,
|
|
390
|
-
abortController.signal,
|
|
391
|
-
{...gasTokenAmount, pricePrefetch: gasTokenPricePrefetchPromise}
|
|
392
|
-
);
|
|
393
|
-
metadata.times.priceCalculated = Date.now();
|
|
394
|
-
|
|
395
|
-
const totalBtcOutput = amountBD + amountBDgas;
|
|
396
|
-
|
|
397
|
-
//Check if we have enough funds to honor the request
|
|
398
|
-
let vault: SpvVault;
|
|
399
|
-
do {
|
|
400
|
-
vault = await this.Vaults.findVaultForSwap(chainIdentifier, totalBtcOutput, useToken, totalInToken, gasToken, totalInGasToken);
|
|
401
|
-
} while (await this.Vaults.checkVaultReplacedTransactions(vault, true));
|
|
402
|
-
abortController.signal.throwIfAborted();
|
|
403
|
-
metadata.times.vaultPicked = Date.now();
|
|
404
|
-
|
|
405
|
-
//Create swap receive bitcoin address
|
|
406
|
-
const btcFeeRate = await btcFeeRatePrefetch;
|
|
407
|
-
const receiveAddress = await bitcoinAddressPrefetch;
|
|
408
|
-
abortController.signal.throwIfAborted();
|
|
409
|
-
metadata.times.addressCreated = Date.now();
|
|
410
|
-
|
|
411
|
-
//Adjust the amounts based on passed fees
|
|
412
|
-
if(parsedBody.exactOut) {
|
|
413
|
-
totalInToken = parsedBody.amount;
|
|
414
|
-
} else {
|
|
415
|
-
totalInToken = (totalInToken * 100_000n / (100_000n + parsedBody.callerFeeRate + parsedBody.frontingFeeRate));
|
|
416
|
-
}
|
|
417
|
-
totalInGasToken = (totalInGasToken * 100_000n / (100_000n + parsedBody.callerFeeRate + parsedBody.frontingFeeRate));
|
|
418
|
-
|
|
419
|
-
//Calculate raw amounts
|
|
420
|
-
const [rawTokenAmount, rawGasTokenAmount] = vault.toRawAmounts([totalInToken, totalInGasToken]);
|
|
421
|
-
[totalInToken, totalInGasToken] = vault.fromRawAmounts([rawTokenAmount, rawGasTokenAmount]);
|
|
422
|
-
|
|
423
|
-
const expiry = Math.floor(Date.now() / 1000) + this.getInitAuthorizationTimeout(chainIdentifier);
|
|
424
|
-
|
|
425
|
-
//Get PSBT data
|
|
426
|
-
const callerFeeShare = parsedBody.callerFeeRate;
|
|
427
|
-
const frontingFeeShare = parsedBody.frontingFeeRate;
|
|
428
|
-
const executionFeeShare = 0n;
|
|
429
|
-
const utxo = vault.getLatestUtxo();
|
|
430
|
-
|
|
431
|
-
const quoteId = randomBytes(32).toString("hex");
|
|
432
|
-
const swap = new SpvVaultSwap(
|
|
433
|
-
chainIdentifier, quoteId, expiry,
|
|
434
|
-
vault, utxo,
|
|
435
|
-
receiveAddress, btcFeeRate, parsedBody.address, totalBtcOutput, totalInToken, totalInGasToken,
|
|
436
|
-
swapFee, swapFeeInToken, gasSwapFee, gasSwapFeeInToken,
|
|
437
|
-
callerFeeShare, frontingFeeShare, executionFeeShare,
|
|
438
|
-
useToken, gasToken
|
|
439
|
-
);
|
|
440
|
-
swap.metadata = metadata;
|
|
441
|
-
|
|
442
|
-
//We can remove the listener to add unused address now, as we are about to save the swap
|
|
443
|
-
abortController.signal.removeEventListener("abort", abortAddUnusedAddressListener);
|
|
444
|
-
await PluginManager.swapCreate(swap);
|
|
445
|
-
await this.saveSwapData(swap);
|
|
446
|
-
|
|
447
|
-
this.swapLogger.info(swap, "REST: /getQuote: Created swap address: "+receiveAddress+" amount: "+totalBtcOutput.toString(10));
|
|
448
|
-
|
|
449
|
-
await responseStream.writeParamsAndEnd({
|
|
450
|
-
code: 20000,
|
|
451
|
-
msg: "Success",
|
|
452
|
-
data: {
|
|
453
|
-
quoteId,
|
|
454
|
-
expiry,
|
|
455
|
-
|
|
456
|
-
address: signer.getAddress(),
|
|
457
|
-
vaultId: vault.data.getVaultId().toString(10),
|
|
458
|
-
|
|
459
|
-
vaultBtcAddress: vault.btcAddress,
|
|
460
|
-
btcAddress: receiveAddress,
|
|
461
|
-
btcUtxo: utxo,
|
|
462
|
-
btcFeeRate,
|
|
463
|
-
|
|
464
|
-
btcAmount: totalBtcOutput.toString(10),
|
|
465
|
-
btcAmountSwap: amountBD.toString(10),
|
|
466
|
-
btcAmountGas: amountBDgas.toString(10),
|
|
467
|
-
|
|
468
|
-
total: totalInToken.toString(10),
|
|
469
|
-
totalGas: totalInGasToken.toString(10),
|
|
470
|
-
|
|
471
|
-
totalFeeBtc: (swapFee + gasSwapFee).toString(10),
|
|
472
|
-
|
|
473
|
-
swapFeeBtc: swapFee.toString(10),
|
|
474
|
-
swapFee: swapFeeInToken.toString(10),
|
|
475
|
-
|
|
476
|
-
gasSwapFeeBtc: gasSwapFee.toString(10),
|
|
477
|
-
gasSwapFee: gasSwapFeeInToken.toString(10),
|
|
478
|
-
|
|
479
|
-
callerFeeShare: callerFeeShare.toString(10),
|
|
480
|
-
frontingFeeShare: frontingFeeShare.toString(10),
|
|
481
|
-
executionFeeShare: executionFeeShare.toString(10)
|
|
482
|
-
}
|
|
483
|
-
});
|
|
484
|
-
}));
|
|
485
|
-
|
|
486
|
-
restServer.use(this.path+"/postQuote", serverParamDecoder(10*1000));
|
|
487
|
-
restServer.post(this.path+"/postQuote", expressHandlerWrapper(async (req: Request & {paramReader: IParamReader}, res: Response & {responseStream: ServerParamEncoder}) => {
|
|
488
|
-
let requestReceived = Date.now();
|
|
489
|
-
|
|
490
|
-
const parsedBody: SpvVaultPostQuote = await req.paramReader.getParams({
|
|
491
|
-
quoteId: FieldTypeEnum.String,
|
|
492
|
-
psbtHex: (val: string) => val!=null &&
|
|
493
|
-
typeof(val)==="string" &&
|
|
494
|
-
HEX_REGEX.test(val) ? val : null
|
|
495
|
-
});
|
|
496
|
-
|
|
497
|
-
const swap = await this.storageManager.getData(parsedBody.quoteId, 0n);
|
|
498
|
-
if(swap==null || swap.state!==SpvVaultSwapState.CREATED || swap.expiry < Date.now()/1000) throw {
|
|
499
|
-
code: 20505,
|
|
500
|
-
msg: "Invalid quote ID, not found or expired!"
|
|
501
|
-
};
|
|
502
|
-
|
|
503
|
-
const metadata: {
|
|
504
|
-
times: {[key: string]: number},
|
|
505
|
-
error?: any
|
|
506
|
-
} = swap.metadata;
|
|
507
|
-
metadata.times ??= {};
|
|
508
|
-
metadata.times.requestReceived = requestReceived;
|
|
509
|
-
|
|
510
|
-
this.checkTooManyInflightSwaps();
|
|
511
|
-
|
|
512
|
-
const vault = await this.Vaults.getVault(swap.chainIdentifier, swap.vaultOwner, swap.vaultId);
|
|
513
|
-
if(vault==null || !vault.isReady()) {
|
|
514
|
-
throw {
|
|
515
|
-
code: 20506,
|
|
516
|
-
msg: "Used vault not found!"
|
|
517
|
-
};
|
|
518
|
-
}
|
|
519
|
-
|
|
520
|
-
//Try parse psbt
|
|
521
|
-
let transaction: Transaction;
|
|
522
|
-
try {
|
|
523
|
-
transaction = Transaction.fromPSBT(Buffer.from(parsedBody.psbtHex, "hex"));
|
|
524
|
-
} catch (e) {
|
|
525
|
-
this.swapLogger.error(swap, "REST: /postQuote: failed to parse provided PSBT: ", e);
|
|
526
|
-
throw {
|
|
527
|
-
code: 20507,
|
|
528
|
-
msg: "Error parsing PSBT, hex format required!"
|
|
529
|
-
};
|
|
530
|
-
}
|
|
531
|
-
|
|
532
|
-
for(let i=1;i<transaction.inputsLength;i++) { //Skip first vault input
|
|
533
|
-
const txIn = transaction.getInput(i);
|
|
534
|
-
if (isLegacyInput(txIn)) throw {
|
|
535
|
-
code: 20514,
|
|
536
|
-
msg: "Legacy (pre-segwit) inputs in tx are not allowed!"
|
|
537
|
-
};
|
|
538
|
-
}
|
|
539
|
-
|
|
540
|
-
//Check the posted quote with the plugins
|
|
541
|
-
AmountAssertions.handlePluginErrorResponses(await PluginManager.onHandlePostedFromBtcQuote(
|
|
542
|
-
this.type,
|
|
543
|
-
{chainIdentifier: swap.chainIdentifier, raw: req, parsed: parsedBody, metadata},
|
|
544
|
-
swap
|
|
545
|
-
));
|
|
546
|
-
|
|
547
|
-
//Check correct psbt
|
|
548
|
-
for(let i=1;i<transaction.inputsLength;i++) { //Skip first vault input
|
|
549
|
-
const txIn = transaction.getInput(i);
|
|
550
|
-
//Check UTXOs exist and are unspent
|
|
551
|
-
if(await this.bitcoinRpc.isSpent(Buffer.from(txIn.txid).toString("hex")+":"+txIn.index.toString(10))) throw {
|
|
552
|
-
code: 20515,
|
|
553
|
-
msg: "Spent UTXO in inputs!"
|
|
554
|
-
};
|
|
555
|
-
}
|
|
556
|
-
|
|
557
|
-
const {spvVaultContract} = this.getChain(swap.chainIdentifier);
|
|
558
|
-
|
|
559
|
-
let data: SpvWithdrawalTransactionData;
|
|
560
|
-
try {
|
|
561
|
-
data = await spvVaultContract.getWithdrawalData(await this.bitcoin.parsePsbt(transaction));
|
|
562
|
-
} catch (e) {
|
|
563
|
-
this.swapLogger.error(swap, "REST: /postQuote: failed to parse PSBT to withdrawal tx data: ", e);
|
|
564
|
-
throw {
|
|
565
|
-
code: 20508,
|
|
566
|
-
msg: "PSBT transaction cannot be parsed!"
|
|
567
|
-
};
|
|
568
|
-
}
|
|
569
|
-
|
|
570
|
-
if(
|
|
571
|
-
!data.isRecipient(swap.recipient) ||
|
|
572
|
-
data.callerFeeRate!==swap.callerFeeShare ||
|
|
573
|
-
data.frontingFeeRate!==swap.frontingFeeShare ||
|
|
574
|
-
data.executionFeeRate!==swap.executionFeeShare ||
|
|
575
|
-
data.rawAmounts[0]!==swap.rawAmountToken ||
|
|
576
|
-
data.rawAmounts[1]!==swap.rawAmountGasToken ||
|
|
577
|
-
data.getExecutionData()!=null ||
|
|
578
|
-
data.getSpentVaultUtxo()!==swap.vaultUtxo ||
|
|
579
|
-
data.btcTx.outs[0].value!==VAULT_DUST_AMOUNT ||
|
|
580
|
-
!Buffer.from(data.btcTx.outs[0].scriptPubKey.hex, "hex").equals(this.bitcoin.toOutputScript(swap.vaultAddress)) ||
|
|
581
|
-
BigInt(data.btcTx.outs[2].value)!==swap.amountBtc ||
|
|
582
|
-
!Buffer.from(data.btcTx.outs[2].scriptPubKey.hex, "hex").equals(this.bitcoin.toOutputScript(swap.btcAddress)) ||
|
|
583
|
-
(data.btcTx.locktime > 0 && data.btcTx.locktime < 500_000_000) ||
|
|
584
|
-
data.btcTx.locktime > Math.floor(Date.now()/1000) - 1_000_000
|
|
585
|
-
) {
|
|
586
|
-
this.swapLogger.error(swap, "REST: /postQuote: Invalid psbt data submitted, raw psbt hex: ", parsedBody.psbtHex);
|
|
587
|
-
throw {
|
|
588
|
-
code: 20509,
|
|
589
|
-
msg: "Invalid PSBT provided!"
|
|
590
|
-
};
|
|
591
|
-
}
|
|
592
|
-
|
|
593
|
-
if(swap.vaultUtxo!==vault.getLatestUtxo()) {
|
|
594
|
-
throw {
|
|
595
|
-
code: 20510,
|
|
596
|
-
msg: "Vault UTXO already spent, please try again!"
|
|
597
|
-
};
|
|
598
|
-
}
|
|
599
|
-
|
|
600
|
-
//Create abortController for parallel prefetches
|
|
601
|
-
const responseStream = res.responseStream;
|
|
602
|
-
|
|
603
|
-
const signedTx = await this.vaultSigner.signPsbt(swap.chainIdentifier, swap.vaultId, transaction, [0]);
|
|
604
|
-
if(!signedTx.isFinal) throw {
|
|
605
|
-
code: 20513,
|
|
606
|
-
msg: "One or more PSBT inputs not finalized!"
|
|
607
|
-
};
|
|
608
|
-
|
|
609
|
-
const effectiveFeeRate = await this.bitcoinRpc.getEffectiveFeeRate(await this.bitcoin.parsePsbt(signedTx));
|
|
610
|
-
if(effectiveFeeRate.feeRate < 1 || Math.round(effectiveFeeRate.feeRate) < swap.btcFeeRate) throw {
|
|
611
|
-
code: 20511,
|
|
612
|
-
msg: "Bitcoin transaction fee too low, expected minimum: "+swap.btcFeeRate+" adjusted effective fee rate: "+effectiveFeeRate.feeRate
|
|
613
|
-
}
|
|
614
|
-
|
|
615
|
-
const txVsize = signedTx.vsize;
|
|
616
|
-
if(txVsize>TX_MAX_VSIZE) throw {
|
|
617
|
-
code: 20516,
|
|
618
|
-
msg: "Bitcoin transaction size too large, maximum: "+TX_MAX_VSIZE+" actual: "+txVsize
|
|
619
|
-
};
|
|
620
|
-
|
|
621
|
-
await this.Vaults.checkVaultReplacedTransactions(vault, true);
|
|
622
|
-
if(swap.vaultUtxo!==vault.getLatestUtxo()) {
|
|
623
|
-
throw {
|
|
624
|
-
code: 20510,
|
|
625
|
-
msg: "Vault UTXO already spent, please try again!"
|
|
626
|
-
};
|
|
627
|
-
}
|
|
628
|
-
|
|
629
|
-
try {
|
|
630
|
-
const btcRawTx = Buffer.from(signedTx.toBytes(true, true)).toString("hex");
|
|
631
|
-
|
|
632
|
-
//Double-check the state to prevent race condition
|
|
633
|
-
if(swap.state!==SpvVaultSwapState.CREATED) {
|
|
634
|
-
throw {
|
|
635
|
-
code: 20505,
|
|
636
|
-
msg: "Invalid quote ID, not found or expired!"
|
|
637
|
-
};
|
|
638
|
-
}
|
|
639
|
-
|
|
640
|
-
//Double check in-flight swap count
|
|
641
|
-
this.checkTooManyInflightSwaps();
|
|
642
|
-
|
|
643
|
-
swap.btcTxId = signedTx.id;
|
|
644
|
-
swap.state = SpvVaultSwapState.SIGNED;
|
|
645
|
-
swap.sending = true;
|
|
646
|
-
await this.saveSwapData(swap);
|
|
647
|
-
|
|
648
|
-
data.btcTx.raw = btcRawTx;
|
|
649
|
-
(data as any).sending = true;
|
|
650
|
-
vault.addWithdrawal(data);
|
|
651
|
-
await this.Vaults.saveVault(vault);
|
|
652
|
-
|
|
653
|
-
this.swapLogger.info(swap, "REST: /postQuote: BTC transaction signed, txId: "+swap.btcTxId);
|
|
654
|
-
|
|
655
|
-
try {
|
|
656
|
-
await this.bitcoin.sendRawTransaction(btcRawTx);
|
|
657
|
-
await swap.setState(SpvVaultSwapState.SENT);
|
|
658
|
-
(data as any).sending = false;
|
|
659
|
-
swap.sending = false;
|
|
660
|
-
} catch (e) {
|
|
661
|
-
this.swapLogger.error(swap, "REST: /postQuote: Failed to send BTC transaction: ", e);
|
|
662
|
-
throw {
|
|
663
|
-
code: 20512,
|
|
664
|
-
msg: "Error broadcasting bitcoin transaction!"
|
|
665
|
-
};
|
|
666
|
-
}
|
|
667
|
-
} catch (e) {
|
|
668
|
-
(data as any).sending = false;
|
|
669
|
-
swap.sending = false;
|
|
670
|
-
vault.removeWithdrawal(data);
|
|
671
|
-
await this.Vaults.saveVault(vault);
|
|
672
|
-
|
|
673
|
-
if(isDefinedRuntimeError(e) && swap.metadata!=null) swap.metadata.postQuoteError = e;
|
|
674
|
-
await this.removeSwapData(swap, SpvVaultSwapState.FAILED);
|
|
675
|
-
|
|
676
|
-
throw e;
|
|
677
|
-
}
|
|
678
|
-
|
|
679
|
-
await responseStream.writeParamsAndEnd({
|
|
680
|
-
code: 20000,
|
|
681
|
-
msg: "Success",
|
|
682
|
-
data: {
|
|
683
|
-
txId: swap.btcTxId
|
|
684
|
-
}
|
|
685
|
-
});
|
|
686
|
-
}));
|
|
687
|
-
}
|
|
688
|
-
|
|
689
|
-
getInfoData(): any {
|
|
690
|
-
const mappedDict = {};
|
|
691
|
-
for(let chainId in this.config.gasTokenMax) {
|
|
692
|
-
mappedDict[chainId] = {
|
|
693
|
-
gasToken: this.getChain(chainId).chainInterface.getNativeCurrencyAddress(),
|
|
694
|
-
max: this.config.gasTokenMax[chainId].toString(10)
|
|
695
|
-
};
|
|
696
|
-
}
|
|
697
|
-
return {
|
|
698
|
-
gasTokens: mappedDict
|
|
699
|
-
};
|
|
700
|
-
}
|
|
701
|
-
|
|
702
|
-
protected async saveSwapData(swap: SpvVaultSwap): Promise<void> {
|
|
703
|
-
if(swap.btcTxId!=null) this.btcTxIdIndex.set(swap.btcTxId, swap);
|
|
704
|
-
return super.saveSwapData(swap);
|
|
705
|
-
}
|
|
706
|
-
|
|
707
|
-
protected async removeSwapData(swap: SpvVaultSwap, ultimateState?: SpvVaultSwapState): Promise<void> {
|
|
708
|
-
if(swap.btcTxId!=null) this.btcTxIdIndex.delete(swap.btcTxId);
|
|
709
|
-
return super.removeSwapData(swap, ultimateState);
|
|
710
|
-
}
|
|
711
|
-
|
|
712
|
-
}
|
|
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,
|
|
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, isDefinedRuntimeError} 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
|
+
readonly type = SwapHandlerType.FROM_BTC_SPV;
|
|
61
|
+
readonly inflightSwapStates = new Set([SpvVaultSwapState.SIGNED, SpvVaultSwapState.SENT, SpvVaultSwapState.BTC_CONFIRMED]);
|
|
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
|
+
/**
|
|
256
|
+
* token: string Desired token to use
|
|
257
|
+
* gasToken: string
|
|
258
|
+
*/
|
|
259
|
+
const preFetchParsedBody = await req.paramReader.getParams({
|
|
260
|
+
token: (val: string) => val!=null &&
|
|
261
|
+
typeof(val)==="string" &&
|
|
262
|
+
this.isTokenSupported(chainIdentifier, val) ? val : null,
|
|
263
|
+
gasToken: (val: string) => val!=null &&
|
|
264
|
+
typeof(val)==="string" &&
|
|
265
|
+
chainInterface.isValidToken(val) ? val : null
|
|
266
|
+
});
|
|
267
|
+
if(preFetchParsedBody==null) throw {
|
|
268
|
+
code: 20100,
|
|
269
|
+
msg: "Invalid request body"
|
|
270
|
+
};
|
|
271
|
+
|
|
272
|
+
//Create abortController for parallel prefetches
|
|
273
|
+
const responseStream = res.responseStream;
|
|
274
|
+
const abortController = getAbortController(responseStream);
|
|
275
|
+
|
|
276
|
+
//Pre-fetch data
|
|
277
|
+
const {
|
|
278
|
+
pricePrefetchPromise,
|
|
279
|
+
gasTokenPricePrefetchPromise
|
|
280
|
+
} = this.getPricePrefetches(chainIdentifier, preFetchParsedBody.token, preFetchParsedBody.gasToken, abortController);
|
|
281
|
+
const nativeBalancePrefetch = this.prefetchNativeBalanceIfNeeded(chainIdentifier, abortController);
|
|
282
|
+
const btcFeeRatePrefetch = this.bitcoin.getFeeRate().catch(e => {
|
|
283
|
+
abortController.abort(e);
|
|
284
|
+
return null;
|
|
285
|
+
});
|
|
286
|
+
|
|
287
|
+
//Listener that re-adds the returned bitcoin address to the unused address list if request fails or closes
|
|
288
|
+
let abortAddUnusedAddressListener: () => void;
|
|
289
|
+
const bitcoinAddressPrefetch = this.bitcoin.getAddress().then(value => {
|
|
290
|
+
//Already aborted
|
|
291
|
+
if(abortController.signal.aborted) {
|
|
292
|
+
this.bitcoin.addUnusedAddress(value);
|
|
293
|
+
return null;
|
|
294
|
+
}
|
|
295
|
+
//Not aborted yet, add an event listener to re-add the address to the unused list
|
|
296
|
+
abortController.signal.addEventListener("abort", abortAddUnusedAddressListener = () => {
|
|
297
|
+
this.bitcoin.addUnusedAddress(value);
|
|
298
|
+
});
|
|
299
|
+
return value;
|
|
300
|
+
}).catch(e => {
|
|
301
|
+
abortController.abort(e);
|
|
302
|
+
return null;
|
|
303
|
+
});
|
|
304
|
+
|
|
305
|
+
/**
|
|
306
|
+
* address: string smart chain address of the recipient
|
|
307
|
+
* amount: string amount (in sats)
|
|
308
|
+
* gasAmount: string Desired amount in gas token to also get
|
|
309
|
+
* exactOut: boolean Whether the swap should be an exact out instead of exact in swap
|
|
310
|
+
* callerFeeRate: string Caller/watchtower fee (in output token) to assign to the swap
|
|
311
|
+
* frontingFeeRate: string Fronting fee (in output token) to assign to the swap
|
|
312
|
+
*/
|
|
313
|
+
const actualParsedBody = await req.paramReader.getParams({
|
|
314
|
+
address: (val: string) => val!=null &&
|
|
315
|
+
typeof(val)==="string" &&
|
|
316
|
+
chainInterface.isValidAddress(val, true) ? val : null,
|
|
317
|
+
amount: FieldTypeEnum.BigInt,
|
|
318
|
+
gasAmount: FieldTypeEnum.BigInt,
|
|
319
|
+
exactOut: FieldTypeEnum.BooleanOptional,
|
|
320
|
+
callerFeeRate: FieldTypeEnum.BigInt,
|
|
321
|
+
frontingFeeRate: FieldTypeEnum.BigInt,
|
|
322
|
+
});
|
|
323
|
+
abortController.signal.throwIfAborted();
|
|
324
|
+
if(actualParsedBody==null) throw {
|
|
325
|
+
code: 20100,
|
|
326
|
+
msg: "Invalid request body"
|
|
327
|
+
};
|
|
328
|
+
|
|
329
|
+
const parsedBody: SpvVaultSwapRequestType = {...preFetchParsedBody, ...actualParsedBody};
|
|
330
|
+
metadata.request = parsedBody;
|
|
331
|
+
|
|
332
|
+
if(parsedBody.gasToken!==chainInterface.getNativeCurrencyAddress()) throw {
|
|
333
|
+
code: 20190,
|
|
334
|
+
msg: "Unsupported gas token"
|
|
335
|
+
};
|
|
336
|
+
|
|
337
|
+
if(parsedBody.callerFeeRate < 0n || parsedBody.callerFeeRate >= 2n**20n) throw {
|
|
338
|
+
code: 20191,
|
|
339
|
+
msg: "Invalid caller fee rate"
|
|
340
|
+
};
|
|
341
|
+
if(parsedBody.frontingFeeRate < 0n || parsedBody.frontingFeeRate >= 2n**20n) throw {
|
|
342
|
+
code: 20192,
|
|
343
|
+
msg: "Invalid fronting fee rate"
|
|
344
|
+
};
|
|
345
|
+
|
|
346
|
+
const requestedAmount = {
|
|
347
|
+
input: !parsedBody.exactOut,
|
|
348
|
+
amount: parsedBody.exactOut ?
|
|
349
|
+
(parsedBody.amount * (100_000n + parsedBody.callerFeeRate + parsedBody.frontingFeeRate) / 100_000n) :
|
|
350
|
+
parsedBody.amount,
|
|
351
|
+
token: parsedBody.token
|
|
352
|
+
};
|
|
353
|
+
const gasTokenAmount = {
|
|
354
|
+
input: false,
|
|
355
|
+
amount: parsedBody.gasAmount * (100_000n + parsedBody.callerFeeRate + parsedBody.frontingFeeRate) / 100_000n,
|
|
356
|
+
token: parsedBody.gasToken
|
|
357
|
+
} as const;
|
|
358
|
+
const request = {
|
|
359
|
+
chainIdentifier,
|
|
360
|
+
raw: req,
|
|
361
|
+
parsed: parsedBody,
|
|
362
|
+
metadata
|
|
363
|
+
};
|
|
364
|
+
const useToken = parsedBody.token;
|
|
365
|
+
const gasToken = parsedBody.gasToken;
|
|
366
|
+
|
|
367
|
+
this.checkTooManyInflightSwaps();
|
|
368
|
+
|
|
369
|
+
//Check request params
|
|
370
|
+
const fees = await this.AmountAssertions.preCheckFromBtcAmounts(this.type, request, requestedAmount, gasTokenAmount);
|
|
371
|
+
metadata.times.requestChecked = Date.now();
|
|
372
|
+
|
|
373
|
+
await this.checkNativeBalance(chainIdentifier, nativeBalancePrefetch, abortController.signal);
|
|
374
|
+
|
|
375
|
+
//Check valid amount specified (min/max)
|
|
376
|
+
let {
|
|
377
|
+
amountBD,
|
|
378
|
+
swapFee,
|
|
379
|
+
swapFeeInToken,
|
|
380
|
+
totalInToken,
|
|
381
|
+
amountBDgas,
|
|
382
|
+
gasSwapFee,
|
|
383
|
+
gasSwapFeeInToken,
|
|
384
|
+
totalInGasToken
|
|
385
|
+
} = await this.AmountAssertions.checkFromBtcAmount(
|
|
386
|
+
this.type,
|
|
387
|
+
request,
|
|
388
|
+
{...requestedAmount, pricePrefetch: pricePrefetchPromise},
|
|
389
|
+
fees,
|
|
390
|
+
abortController.signal,
|
|
391
|
+
{...gasTokenAmount, pricePrefetch: gasTokenPricePrefetchPromise}
|
|
392
|
+
);
|
|
393
|
+
metadata.times.priceCalculated = Date.now();
|
|
394
|
+
|
|
395
|
+
const totalBtcOutput = amountBD + amountBDgas;
|
|
396
|
+
|
|
397
|
+
//Check if we have enough funds to honor the request
|
|
398
|
+
let vault: SpvVault;
|
|
399
|
+
do {
|
|
400
|
+
vault = await this.Vaults.findVaultForSwap(chainIdentifier, totalBtcOutput, useToken, totalInToken, gasToken, totalInGasToken);
|
|
401
|
+
} while (await this.Vaults.checkVaultReplacedTransactions(vault, true));
|
|
402
|
+
abortController.signal.throwIfAborted();
|
|
403
|
+
metadata.times.vaultPicked = Date.now();
|
|
404
|
+
|
|
405
|
+
//Create swap receive bitcoin address
|
|
406
|
+
const btcFeeRate = await btcFeeRatePrefetch;
|
|
407
|
+
const receiveAddress = await bitcoinAddressPrefetch;
|
|
408
|
+
abortController.signal.throwIfAborted();
|
|
409
|
+
metadata.times.addressCreated = Date.now();
|
|
410
|
+
|
|
411
|
+
//Adjust the amounts based on passed fees
|
|
412
|
+
if(parsedBody.exactOut) {
|
|
413
|
+
totalInToken = parsedBody.amount;
|
|
414
|
+
} else {
|
|
415
|
+
totalInToken = (totalInToken * 100_000n / (100_000n + parsedBody.callerFeeRate + parsedBody.frontingFeeRate));
|
|
416
|
+
}
|
|
417
|
+
totalInGasToken = (totalInGasToken * 100_000n / (100_000n + parsedBody.callerFeeRate + parsedBody.frontingFeeRate));
|
|
418
|
+
|
|
419
|
+
//Calculate raw amounts
|
|
420
|
+
const [rawTokenAmount, rawGasTokenAmount] = vault.toRawAmounts([totalInToken, totalInGasToken]);
|
|
421
|
+
[totalInToken, totalInGasToken] = vault.fromRawAmounts([rawTokenAmount, rawGasTokenAmount]);
|
|
422
|
+
|
|
423
|
+
const expiry = Math.floor(Date.now() / 1000) + this.getInitAuthorizationTimeout(chainIdentifier);
|
|
424
|
+
|
|
425
|
+
//Get PSBT data
|
|
426
|
+
const callerFeeShare = parsedBody.callerFeeRate;
|
|
427
|
+
const frontingFeeShare = parsedBody.frontingFeeRate;
|
|
428
|
+
const executionFeeShare = 0n;
|
|
429
|
+
const utxo = vault.getLatestUtxo();
|
|
430
|
+
|
|
431
|
+
const quoteId = randomBytes(32).toString("hex");
|
|
432
|
+
const swap = new SpvVaultSwap(
|
|
433
|
+
chainIdentifier, quoteId, expiry,
|
|
434
|
+
vault, utxo,
|
|
435
|
+
receiveAddress, btcFeeRate, parsedBody.address, totalBtcOutput, totalInToken, totalInGasToken,
|
|
436
|
+
swapFee, swapFeeInToken, gasSwapFee, gasSwapFeeInToken,
|
|
437
|
+
callerFeeShare, frontingFeeShare, executionFeeShare,
|
|
438
|
+
useToken, gasToken
|
|
439
|
+
);
|
|
440
|
+
swap.metadata = metadata;
|
|
441
|
+
|
|
442
|
+
//We can remove the listener to add unused address now, as we are about to save the swap
|
|
443
|
+
abortController.signal.removeEventListener("abort", abortAddUnusedAddressListener);
|
|
444
|
+
await PluginManager.swapCreate(swap);
|
|
445
|
+
await this.saveSwapData(swap);
|
|
446
|
+
|
|
447
|
+
this.swapLogger.info(swap, "REST: /getQuote: Created swap address: "+receiveAddress+" amount: "+totalBtcOutput.toString(10));
|
|
448
|
+
|
|
449
|
+
await responseStream.writeParamsAndEnd({
|
|
450
|
+
code: 20000,
|
|
451
|
+
msg: "Success",
|
|
452
|
+
data: {
|
|
453
|
+
quoteId,
|
|
454
|
+
expiry,
|
|
455
|
+
|
|
456
|
+
address: signer.getAddress(),
|
|
457
|
+
vaultId: vault.data.getVaultId().toString(10),
|
|
458
|
+
|
|
459
|
+
vaultBtcAddress: vault.btcAddress,
|
|
460
|
+
btcAddress: receiveAddress,
|
|
461
|
+
btcUtxo: utxo,
|
|
462
|
+
btcFeeRate,
|
|
463
|
+
|
|
464
|
+
btcAmount: totalBtcOutput.toString(10),
|
|
465
|
+
btcAmountSwap: amountBD.toString(10),
|
|
466
|
+
btcAmountGas: amountBDgas.toString(10),
|
|
467
|
+
|
|
468
|
+
total: totalInToken.toString(10),
|
|
469
|
+
totalGas: totalInGasToken.toString(10),
|
|
470
|
+
|
|
471
|
+
totalFeeBtc: (swapFee + gasSwapFee).toString(10),
|
|
472
|
+
|
|
473
|
+
swapFeeBtc: swapFee.toString(10),
|
|
474
|
+
swapFee: swapFeeInToken.toString(10),
|
|
475
|
+
|
|
476
|
+
gasSwapFeeBtc: gasSwapFee.toString(10),
|
|
477
|
+
gasSwapFee: gasSwapFeeInToken.toString(10),
|
|
478
|
+
|
|
479
|
+
callerFeeShare: callerFeeShare.toString(10),
|
|
480
|
+
frontingFeeShare: frontingFeeShare.toString(10),
|
|
481
|
+
executionFeeShare: executionFeeShare.toString(10)
|
|
482
|
+
}
|
|
483
|
+
});
|
|
484
|
+
}));
|
|
485
|
+
|
|
486
|
+
restServer.use(this.path+"/postQuote", serverParamDecoder(10*1000));
|
|
487
|
+
restServer.post(this.path+"/postQuote", expressHandlerWrapper(async (req: Request & {paramReader: IParamReader}, res: Response & {responseStream: ServerParamEncoder}) => {
|
|
488
|
+
let requestReceived = Date.now();
|
|
489
|
+
|
|
490
|
+
const parsedBody: SpvVaultPostQuote = await req.paramReader.getParams({
|
|
491
|
+
quoteId: FieldTypeEnum.String,
|
|
492
|
+
psbtHex: (val: string) => val!=null &&
|
|
493
|
+
typeof(val)==="string" &&
|
|
494
|
+
HEX_REGEX.test(val) ? val : null
|
|
495
|
+
});
|
|
496
|
+
|
|
497
|
+
const swap = await this.storageManager.getData(parsedBody.quoteId, 0n);
|
|
498
|
+
if(swap==null || swap.state!==SpvVaultSwapState.CREATED || swap.expiry < Date.now()/1000) throw {
|
|
499
|
+
code: 20505,
|
|
500
|
+
msg: "Invalid quote ID, not found or expired!"
|
|
501
|
+
};
|
|
502
|
+
|
|
503
|
+
const metadata: {
|
|
504
|
+
times: {[key: string]: number},
|
|
505
|
+
error?: any
|
|
506
|
+
} = swap.metadata;
|
|
507
|
+
metadata.times ??= {};
|
|
508
|
+
metadata.times.requestReceived = requestReceived;
|
|
509
|
+
|
|
510
|
+
this.checkTooManyInflightSwaps();
|
|
511
|
+
|
|
512
|
+
const vault = await this.Vaults.getVault(swap.chainIdentifier, swap.vaultOwner, swap.vaultId);
|
|
513
|
+
if(vault==null || !vault.isReady()) {
|
|
514
|
+
throw {
|
|
515
|
+
code: 20506,
|
|
516
|
+
msg: "Used vault not found!"
|
|
517
|
+
};
|
|
518
|
+
}
|
|
519
|
+
|
|
520
|
+
//Try parse psbt
|
|
521
|
+
let transaction: Transaction;
|
|
522
|
+
try {
|
|
523
|
+
transaction = Transaction.fromPSBT(Buffer.from(parsedBody.psbtHex, "hex"));
|
|
524
|
+
} catch (e) {
|
|
525
|
+
this.swapLogger.error(swap, "REST: /postQuote: failed to parse provided PSBT: ", e);
|
|
526
|
+
throw {
|
|
527
|
+
code: 20507,
|
|
528
|
+
msg: "Error parsing PSBT, hex format required!"
|
|
529
|
+
};
|
|
530
|
+
}
|
|
531
|
+
|
|
532
|
+
for(let i=1;i<transaction.inputsLength;i++) { //Skip first vault input
|
|
533
|
+
const txIn = transaction.getInput(i);
|
|
534
|
+
if (isLegacyInput(txIn)) throw {
|
|
535
|
+
code: 20514,
|
|
536
|
+
msg: "Legacy (pre-segwit) inputs in tx are not allowed!"
|
|
537
|
+
};
|
|
538
|
+
}
|
|
539
|
+
|
|
540
|
+
//Check the posted quote with the plugins
|
|
541
|
+
AmountAssertions.handlePluginErrorResponses(await PluginManager.onHandlePostedFromBtcQuote(
|
|
542
|
+
this.type,
|
|
543
|
+
{chainIdentifier: swap.chainIdentifier, raw: req, parsed: parsedBody, metadata},
|
|
544
|
+
swap
|
|
545
|
+
));
|
|
546
|
+
|
|
547
|
+
//Check correct psbt
|
|
548
|
+
for(let i=1;i<transaction.inputsLength;i++) { //Skip first vault input
|
|
549
|
+
const txIn = transaction.getInput(i);
|
|
550
|
+
//Check UTXOs exist and are unspent
|
|
551
|
+
if(await this.bitcoinRpc.isSpent(Buffer.from(txIn.txid).toString("hex")+":"+txIn.index.toString(10))) throw {
|
|
552
|
+
code: 20515,
|
|
553
|
+
msg: "Spent UTXO in inputs!"
|
|
554
|
+
};
|
|
555
|
+
}
|
|
556
|
+
|
|
557
|
+
const {spvVaultContract} = this.getChain(swap.chainIdentifier);
|
|
558
|
+
|
|
559
|
+
let data: SpvWithdrawalTransactionData;
|
|
560
|
+
try {
|
|
561
|
+
data = await spvVaultContract.getWithdrawalData(await this.bitcoin.parsePsbt(transaction));
|
|
562
|
+
} catch (e) {
|
|
563
|
+
this.swapLogger.error(swap, "REST: /postQuote: failed to parse PSBT to withdrawal tx data: ", e);
|
|
564
|
+
throw {
|
|
565
|
+
code: 20508,
|
|
566
|
+
msg: "PSBT transaction cannot be parsed!"
|
|
567
|
+
};
|
|
568
|
+
}
|
|
569
|
+
|
|
570
|
+
if(
|
|
571
|
+
!data.isRecipient(swap.recipient) ||
|
|
572
|
+
data.callerFeeRate!==swap.callerFeeShare ||
|
|
573
|
+
data.frontingFeeRate!==swap.frontingFeeShare ||
|
|
574
|
+
data.executionFeeRate!==swap.executionFeeShare ||
|
|
575
|
+
data.rawAmounts[0]!==swap.rawAmountToken ||
|
|
576
|
+
data.rawAmounts[1]!==swap.rawAmountGasToken ||
|
|
577
|
+
data.getExecutionData()!=null ||
|
|
578
|
+
data.getSpentVaultUtxo()!==swap.vaultUtxo ||
|
|
579
|
+
data.btcTx.outs[0].value!==VAULT_DUST_AMOUNT ||
|
|
580
|
+
!Buffer.from(data.btcTx.outs[0].scriptPubKey.hex, "hex").equals(this.bitcoin.toOutputScript(swap.vaultAddress)) ||
|
|
581
|
+
BigInt(data.btcTx.outs[2].value)!==swap.amountBtc ||
|
|
582
|
+
!Buffer.from(data.btcTx.outs[2].scriptPubKey.hex, "hex").equals(this.bitcoin.toOutputScript(swap.btcAddress)) ||
|
|
583
|
+
(data.btcTx.locktime > 0 && data.btcTx.locktime < 500_000_000) ||
|
|
584
|
+
data.btcTx.locktime > Math.floor(Date.now()/1000) - 1_000_000
|
|
585
|
+
) {
|
|
586
|
+
this.swapLogger.error(swap, "REST: /postQuote: Invalid psbt data submitted, raw psbt hex: ", parsedBody.psbtHex);
|
|
587
|
+
throw {
|
|
588
|
+
code: 20509,
|
|
589
|
+
msg: "Invalid PSBT provided!"
|
|
590
|
+
};
|
|
591
|
+
}
|
|
592
|
+
|
|
593
|
+
if(swap.vaultUtxo!==vault.getLatestUtxo()) {
|
|
594
|
+
throw {
|
|
595
|
+
code: 20510,
|
|
596
|
+
msg: "Vault UTXO already spent, please try again!"
|
|
597
|
+
};
|
|
598
|
+
}
|
|
599
|
+
|
|
600
|
+
//Create abortController for parallel prefetches
|
|
601
|
+
const responseStream = res.responseStream;
|
|
602
|
+
|
|
603
|
+
const signedTx = await this.vaultSigner.signPsbt(swap.chainIdentifier, swap.vaultId, transaction, [0]);
|
|
604
|
+
if(!signedTx.isFinal) throw {
|
|
605
|
+
code: 20513,
|
|
606
|
+
msg: "One or more PSBT inputs not finalized!"
|
|
607
|
+
};
|
|
608
|
+
|
|
609
|
+
const effectiveFeeRate = await this.bitcoinRpc.getEffectiveFeeRate(await this.bitcoin.parsePsbt(signedTx));
|
|
610
|
+
if(effectiveFeeRate.feeRate < 1 || Math.round(effectiveFeeRate.feeRate) < swap.btcFeeRate) throw {
|
|
611
|
+
code: 20511,
|
|
612
|
+
msg: "Bitcoin transaction fee too low, expected minimum: "+swap.btcFeeRate+" adjusted effective fee rate: "+effectiveFeeRate.feeRate
|
|
613
|
+
}
|
|
614
|
+
|
|
615
|
+
const txVsize = signedTx.vsize;
|
|
616
|
+
if(txVsize>TX_MAX_VSIZE) throw {
|
|
617
|
+
code: 20516,
|
|
618
|
+
msg: "Bitcoin transaction size too large, maximum: "+TX_MAX_VSIZE+" actual: "+txVsize
|
|
619
|
+
};
|
|
620
|
+
|
|
621
|
+
await this.Vaults.checkVaultReplacedTransactions(vault, true);
|
|
622
|
+
if(swap.vaultUtxo!==vault.getLatestUtxo()) {
|
|
623
|
+
throw {
|
|
624
|
+
code: 20510,
|
|
625
|
+
msg: "Vault UTXO already spent, please try again!"
|
|
626
|
+
};
|
|
627
|
+
}
|
|
628
|
+
|
|
629
|
+
try {
|
|
630
|
+
const btcRawTx = Buffer.from(signedTx.toBytes(true, true)).toString("hex");
|
|
631
|
+
|
|
632
|
+
//Double-check the state to prevent race condition
|
|
633
|
+
if(swap.state!==SpvVaultSwapState.CREATED) {
|
|
634
|
+
throw {
|
|
635
|
+
code: 20505,
|
|
636
|
+
msg: "Invalid quote ID, not found or expired!"
|
|
637
|
+
};
|
|
638
|
+
}
|
|
639
|
+
|
|
640
|
+
//Double check in-flight swap count
|
|
641
|
+
this.checkTooManyInflightSwaps();
|
|
642
|
+
|
|
643
|
+
swap.btcTxId = signedTx.id;
|
|
644
|
+
swap.state = SpvVaultSwapState.SIGNED;
|
|
645
|
+
swap.sending = true;
|
|
646
|
+
await this.saveSwapData(swap);
|
|
647
|
+
|
|
648
|
+
data.btcTx.raw = btcRawTx;
|
|
649
|
+
(data as any).sending = true;
|
|
650
|
+
vault.addWithdrawal(data);
|
|
651
|
+
await this.Vaults.saveVault(vault);
|
|
652
|
+
|
|
653
|
+
this.swapLogger.info(swap, "REST: /postQuote: BTC transaction signed, txId: "+swap.btcTxId);
|
|
654
|
+
|
|
655
|
+
try {
|
|
656
|
+
await this.bitcoin.sendRawTransaction(btcRawTx);
|
|
657
|
+
await swap.setState(SpvVaultSwapState.SENT);
|
|
658
|
+
(data as any).sending = false;
|
|
659
|
+
swap.sending = false;
|
|
660
|
+
} catch (e) {
|
|
661
|
+
this.swapLogger.error(swap, "REST: /postQuote: Failed to send BTC transaction: ", e);
|
|
662
|
+
throw {
|
|
663
|
+
code: 20512,
|
|
664
|
+
msg: "Error broadcasting bitcoin transaction!"
|
|
665
|
+
};
|
|
666
|
+
}
|
|
667
|
+
} catch (e) {
|
|
668
|
+
(data as any).sending = false;
|
|
669
|
+
swap.sending = false;
|
|
670
|
+
vault.removeWithdrawal(data);
|
|
671
|
+
await this.Vaults.saveVault(vault);
|
|
672
|
+
|
|
673
|
+
if(isDefinedRuntimeError(e) && swap.metadata!=null) swap.metadata.postQuoteError = e;
|
|
674
|
+
await this.removeSwapData(swap, SpvVaultSwapState.FAILED);
|
|
675
|
+
|
|
676
|
+
throw e;
|
|
677
|
+
}
|
|
678
|
+
|
|
679
|
+
await responseStream.writeParamsAndEnd({
|
|
680
|
+
code: 20000,
|
|
681
|
+
msg: "Success",
|
|
682
|
+
data: {
|
|
683
|
+
txId: swap.btcTxId
|
|
684
|
+
}
|
|
685
|
+
});
|
|
686
|
+
}));
|
|
687
|
+
}
|
|
688
|
+
|
|
689
|
+
getInfoData(): any {
|
|
690
|
+
const mappedDict = {};
|
|
691
|
+
for(let chainId in this.config.gasTokenMax) {
|
|
692
|
+
mappedDict[chainId] = {
|
|
693
|
+
gasToken: this.getChain(chainId).chainInterface.getNativeCurrencyAddress(),
|
|
694
|
+
max: this.config.gasTokenMax[chainId].toString(10)
|
|
695
|
+
};
|
|
696
|
+
}
|
|
697
|
+
return {
|
|
698
|
+
gasTokens: mappedDict
|
|
699
|
+
};
|
|
700
|
+
}
|
|
701
|
+
|
|
702
|
+
protected async saveSwapData(swap: SpvVaultSwap): Promise<void> {
|
|
703
|
+
if(swap.btcTxId!=null) this.btcTxIdIndex.set(swap.btcTxId, swap);
|
|
704
|
+
return super.saveSwapData(swap);
|
|
705
|
+
}
|
|
706
|
+
|
|
707
|
+
protected async removeSwapData(swap: SpvVaultSwap, ultimateState?: SpvVaultSwapState): Promise<void> {
|
|
708
|
+
if(swap.btcTxId!=null) this.btcTxIdIndex.delete(swap.btcTxId);
|
|
709
|
+
return super.removeSwapData(swap, ultimateState);
|
|
710
|
+
}
|
|
711
|
+
|
|
712
|
+
}
|