@atomiqlabs/lp-lib 14.0.0-dev.13 → 14.0.0-dev.16
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 +61 -61
- package/dist/plugins/IPlugin.d.ts +143 -143
- package/dist/plugins/IPlugin.js +34 -34
- package/dist/plugins/PluginManager.d.ts +112 -112
- package/dist/plugins/PluginManager.js +259 -259
- package/dist/prices/BinanceSwapPrice.d.ts +26 -26
- package/dist/prices/BinanceSwapPrice.js +92 -92
- package/dist/prices/CoinGeckoSwapPrice.d.ts +30 -30
- package/dist/prices/CoinGeckoSwapPrice.js +64 -64
- package/dist/prices/ISwapPrice.d.ts +43 -43
- package/dist/prices/ISwapPrice.js +55 -55
- package/dist/prices/OKXSwapPrice.d.ts +26 -26
- package/dist/prices/OKXSwapPrice.js +92 -92
- 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 +153 -153
- package/dist/swaps/SwapHandler.js +160 -160
- 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 +72 -72
- package/dist/swaps/assertions/FromBtcAmountAssertions.d.ts +76 -76
- package/dist/swaps/assertions/FromBtcAmountAssertions.js +180 -172
- 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 +51 -51
- package/dist/swaps/escrow/EscrowHandler.js +158 -158
- 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 +83 -83
- package/dist/swaps/escrow/frombtc_abstract/FromBtcAbs.js +318 -318
- 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 +107 -107
- package/dist/swaps/escrow/frombtcln_abstract/FromBtcLnAbs.js +675 -675
- 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 +104 -104
- package/dist/swaps/escrow/frombtcln_autoinit/FromBtcLnAuto.js +659 -659
- 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 +171 -171
- package/dist/swaps/escrow/tobtc_abstract/ToBtcAbs.js +706 -706
- package/dist/swaps/escrow/tobtc_abstract/ToBtcSwapAbs.d.ts +26 -26
- package/dist/swaps/escrow/tobtc_abstract/ToBtcSwapAbs.js +62 -62
- package/dist/swaps/escrow/tobtcln_abstract/ToBtcLnAbs.d.ts +177 -177
- package/dist/swaps/escrow/tobtcln_abstract/ToBtcLnAbs.js +861 -861
- package/dist/swaps/escrow/tobtcln_abstract/ToBtcLnSwapAbs.d.ts +23 -23
- package/dist/swaps/escrow/tobtcln_abstract/ToBtcLnSwapAbs.js +56 -56
- package/dist/swaps/spv_vault_swap/SpvVault.d.ts +41 -41
- package/dist/swaps/spv_vault_swap/SpvVault.js +111 -111
- package/dist/swaps/spv_vault_swap/SpvVaultSwap.d.ts +67 -67
- 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 +491 -491
- package/dist/swaps/spv_vault_swap/SpvVaults.d.ts +52 -52
- package/dist/swaps/spv_vault_swap/SpvVaults.js +364 -364
- package/dist/swaps/trusted/frombtc_trusted/FromBtcTrusted.d.ts +51 -51
- package/dist/swaps/trusted/frombtc_trusted/FromBtcTrusted.js +650 -650
- 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 +76 -76
- package/dist/swaps/trusted/frombtcln_trusted/FromBtcLnTrusted.js +494 -494
- package/dist/swaps/trusted/frombtcln_trusted/FromBtcLnTrustedSwap.d.ts +34 -34
- package/dist/swaps/trusted/frombtcln_trusted/FromBtcLnTrustedSwap.js +81 -81
- 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 +67 -67
- package/dist/wallets/IBitcoinWallet.js +2 -2
- package/dist/wallets/ILightningWallet.d.ts +117 -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 +106 -106
- package/src/plugins/IPlugin.ts +168 -168
- package/src/plugins/PluginManager.ts +336 -336
- package/src/prices/BinanceSwapPrice.ts +113 -113
- package/src/prices/CoinGeckoSwapPrice.ts +87 -87
- package/src/prices/ISwapPrice.ts +88 -88
- package/src/prices/OKXSwapPrice.ts +113 -113
- 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 +277 -277
- package/src/swaps/SwapHandlerSwap.ts +141 -141
- package/src/swaps/assertions/AmountAssertions.ts +76 -76
- package/src/swaps/assertions/FromBtcAmountAssertions.ts +246 -238
- package/src/swaps/assertions/LightningAssertions.ts +103 -103
- package/src/swaps/assertions/ToBtcAmountAssertions.ts +203 -203
- package/src/swaps/escrow/EscrowHandler.ts +179 -179
- 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 +452 -452
- package/src/swaps/escrow/frombtc_abstract/FromBtcSwapAbs.ts +61 -61
- package/src/swaps/escrow/frombtcln_abstract/FromBtcLnAbs.ts +856 -856
- package/src/swaps/escrow/frombtcln_abstract/FromBtcLnSwapAbs.ts +141 -141
- package/src/swaps/escrow/frombtcln_autoinit/FromBtcLnAuto.ts +822 -822
- package/src/swaps/escrow/frombtcln_autoinit/FromBtcLnAutoSwap.ts +196 -196
- package/src/swaps/escrow/tobtc_abstract/ToBtcAbs.ts +879 -879
- package/src/swaps/escrow/tobtc_abstract/ToBtcSwapAbs.ts +102 -102
- package/src/swaps/escrow/tobtcln_abstract/ToBtcLnAbs.ts +1110 -1110
- package/src/swaps/escrow/tobtcln_abstract/ToBtcLnSwapAbs.ts +77 -77
- package/src/swaps/spv_vault_swap/SpvVault.ts +143 -143
- package/src/swaps/spv_vault_swap/SpvVaultSwap.ts +225 -225
- package/src/swaps/spv_vault_swap/SpvVaultSwapHandler.ts +627 -627
- package/src/swaps/spv_vault_swap/SpvVaults.ts +435 -435
- package/src/swaps/trusted/frombtc_trusted/FromBtcTrusted.ts +747 -747
- package/src/swaps/trusted/frombtc_trusted/FromBtcTrustedSwap.ts +185 -185
- package/src/swaps/trusted/frombtcln_trusted/FromBtcLnTrusted.ts +590 -590
- package/src/swaps/trusted/frombtcln_trusted/FromBtcLnTrustedSwap.ts +121 -121
- 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 +68 -68
- package/src/wallets/ILightningWallet.ts +178 -178
- package/src/wallets/ISpvVaultSigner.ts +10 -10
|
@@ -1,452 +1,452 @@
|
|
|
1
|
-
import {Express, Request, Response} from "express";
|
|
2
|
-
import {FromBtcSwapAbs, FromBtcSwapState} from "./FromBtcSwapAbs";
|
|
3
|
-
import {MultichainData, SwapHandlerType} from "../../SwapHandler";
|
|
4
|
-
import {ISwapPrice} from "../../../prices/ISwapPrice";
|
|
5
|
-
import {
|
|
6
|
-
BigIntBufferUtils,
|
|
7
|
-
ChainSwapType,
|
|
8
|
-
ClaimEvent,
|
|
9
|
-
InitializeEvent,
|
|
10
|
-
RefundEvent,
|
|
11
|
-
SwapData
|
|
12
|
-
} from "@atomiqlabs/base";
|
|
13
|
-
import {randomBytes} from "crypto";
|
|
14
|
-
import {expressHandlerWrapper, getAbortController} from "../../../utils/Utils";
|
|
15
|
-
import {PluginManager} from "../../../plugins/PluginManager";
|
|
16
|
-
import {IIntermediaryStorage} from "../../../storage/IIntermediaryStorage";
|
|
17
|
-
import {FieldTypeEnum} from "../../../utils/paramcoders/SchemaVerifier";
|
|
18
|
-
import {serverParamDecoder} from "../../../utils/paramcoders/server/ServerParamDecoder";
|
|
19
|
-
import {IParamReader} from "../../../utils/paramcoders/IParamReader";
|
|
20
|
-
import {ServerParamEncoder} from "../../../utils/paramcoders/server/ServerParamEncoder";
|
|
21
|
-
import {FromBtcBaseConfig, FromBtcBaseSwapHandler} from "../FromBtcBaseSwapHandler";
|
|
22
|
-
import {IBitcoinWallet} from "../../../wallets/IBitcoinWallet";
|
|
23
|
-
|
|
24
|
-
export type FromBtcConfig = FromBtcBaseConfig & {
|
|
25
|
-
confirmations: number,
|
|
26
|
-
swapCsvDelta: number
|
|
27
|
-
};
|
|
28
|
-
|
|
29
|
-
export type FromBtcRequestType = {
|
|
30
|
-
address: string,
|
|
31
|
-
amount: bigint,
|
|
32
|
-
token: string,
|
|
33
|
-
sequence: bigint,
|
|
34
|
-
exactOut?: boolean
|
|
35
|
-
};
|
|
36
|
-
|
|
37
|
-
/**
|
|
38
|
-
* Swap handler handling from BTC swaps using PTLCs (proof-time locked contracts) and btc relay (on-chain bitcoin SPV)
|
|
39
|
-
*/
|
|
40
|
-
export class FromBtcAbs extends FromBtcBaseSwapHandler<FromBtcSwapAbs, FromBtcSwapState> {
|
|
41
|
-
readonly type = SwapHandlerType.FROM_BTC;
|
|
42
|
-
readonly swapType = ChainSwapType.CHAIN;
|
|
43
|
-
|
|
44
|
-
readonly config: FromBtcConfig & {swapTsCsvDelta: bigint};
|
|
45
|
-
|
|
46
|
-
readonly bitcoin: IBitcoinWallet;
|
|
47
|
-
|
|
48
|
-
constructor(
|
|
49
|
-
storageDirectory: IIntermediaryStorage<FromBtcSwapAbs>,
|
|
50
|
-
path: string,
|
|
51
|
-
chains: MultichainData,
|
|
52
|
-
bitcoin: IBitcoinWallet,
|
|
53
|
-
swapPricing: ISwapPrice,
|
|
54
|
-
config: FromBtcConfig
|
|
55
|
-
) {
|
|
56
|
-
super(storageDirectory, path, chains, swapPricing, config);
|
|
57
|
-
this.bitcoin = bitcoin;
|
|
58
|
-
this.config = {
|
|
59
|
-
...config,
|
|
60
|
-
swapTsCsvDelta: BigInt(config.swapCsvDelta) * (config.bitcoinBlocktime / config.safetyFactor)
|
|
61
|
-
};
|
|
62
|
-
}
|
|
63
|
-
|
|
64
|
-
/**
|
|
65
|
-
* Returns the payment hash of the swap, takes swap nonce into account. Payment hash is chain-specific.
|
|
66
|
-
*
|
|
67
|
-
* @param chainIdentifier
|
|
68
|
-
* @param address
|
|
69
|
-
* @param amount
|
|
70
|
-
*/
|
|
71
|
-
private getHash(chainIdentifier: string, address: string, amount: bigint): Buffer {
|
|
72
|
-
const parsedOutputScript = this.bitcoin.toOutputScript(address);
|
|
73
|
-
const {swapContract} = this.getChain(chainIdentifier);
|
|
74
|
-
return swapContract.getHashForOnchain(parsedOutputScript, amount, this.config.confirmations, 0n);
|
|
75
|
-
}
|
|
76
|
-
|
|
77
|
-
/**
|
|
78
|
-
* Processes past swap
|
|
79
|
-
*
|
|
80
|
-
* @param swap
|
|
81
|
-
* @protected
|
|
82
|
-
* @returns true if the swap should be refunded, false if nothing should be done
|
|
83
|
-
*/
|
|
84
|
-
protected async processPastSwap(swap: FromBtcSwapAbs): Promise<boolean> {
|
|
85
|
-
const {swapContract, signer} = this.getChain(swap.chainIdentifier);
|
|
86
|
-
|
|
87
|
-
//Once authorization expires in CREATED state, the user can no more commit it on-chain
|
|
88
|
-
if(swap.state===FromBtcSwapState.CREATED) {
|
|
89
|
-
if(!await swapContract.isInitAuthorizationExpired(swap.data, swap)) return false;
|
|
90
|
-
|
|
91
|
-
const isCommited = await swapContract.isCommited(swap.data);
|
|
92
|
-
if(isCommited) {
|
|
93
|
-
this.swapLogger.info(swap, "processPastSwap(state=CREATED): swap was commited, but processed from watchdog, address: "+swap.address);
|
|
94
|
-
await swap.setState(FromBtcSwapState.COMMITED);
|
|
95
|
-
await this.saveSwapData(swap);
|
|
96
|
-
return false;
|
|
97
|
-
}
|
|
98
|
-
|
|
99
|
-
this.swapLogger.info(swap, "processPastSwap(state=CREATED): removing past swap due to authorization expiry, address: "+swap.address);
|
|
100
|
-
await this.removeSwapData(swap, FromBtcSwapState.CANCELED);
|
|
101
|
-
await this.bitcoin.addUnusedAddress(swap.address);
|
|
102
|
-
return false;
|
|
103
|
-
}
|
|
104
|
-
|
|
105
|
-
//Check if commited swap expired by now
|
|
106
|
-
if(swap.state===FromBtcSwapState.COMMITED) {
|
|
107
|
-
if(!await swapContract.isExpired(signer.getAddress(), swap.data)) return false;
|
|
108
|
-
|
|
109
|
-
const isCommited = await swapContract.isCommited(swap.data);
|
|
110
|
-
if(isCommited) {
|
|
111
|
-
this.swapLogger.info(swap, "processPastSwap(state=COMMITED): swap expired, will refund, address: "+swap.address);
|
|
112
|
-
return true;
|
|
113
|
-
}
|
|
114
|
-
|
|
115
|
-
this.swapLogger.warn(swap, "processPastSwap(state=COMMITED): commited swap expired and not committed anymore (already refunded?), address: "+swap.address);
|
|
116
|
-
await this.removeSwapData(swap, FromBtcSwapState.CANCELED);
|
|
117
|
-
return false;
|
|
118
|
-
}
|
|
119
|
-
}
|
|
120
|
-
|
|
121
|
-
/**
|
|
122
|
-
* Checks past swaps, refunds and deletes ones that are already expired.
|
|
123
|
-
*/
|
|
124
|
-
protected async processPastSwaps() {
|
|
125
|
-
|
|
126
|
-
const queriedData = await this.storageManager.query([
|
|
127
|
-
{
|
|
128
|
-
key: "state",
|
|
129
|
-
value: [
|
|
130
|
-
FromBtcSwapState.CREATED,
|
|
131
|
-
FromBtcSwapState.COMMITED
|
|
132
|
-
]
|
|
133
|
-
}
|
|
134
|
-
]);
|
|
135
|
-
|
|
136
|
-
const refundSwaps: FromBtcSwapAbs[] = [];
|
|
137
|
-
|
|
138
|
-
for(let {obj: swap} of queriedData) {
|
|
139
|
-
if(await this.processPastSwap(swap)) refundSwaps.push(swap);
|
|
140
|
-
}
|
|
141
|
-
|
|
142
|
-
await this.refundSwaps(refundSwaps);
|
|
143
|
-
}
|
|
144
|
-
|
|
145
|
-
/**
|
|
146
|
-
* Refunds all swaps (calls SC on-chain refund function)
|
|
147
|
-
*
|
|
148
|
-
* @param refundSwaps
|
|
149
|
-
* @protected
|
|
150
|
-
*/
|
|
151
|
-
protected async refundSwaps(refundSwaps: FromBtcSwapAbs[]) {
|
|
152
|
-
for(let refundSwap of refundSwaps) {
|
|
153
|
-
const {swapContract, signer} = this.getChain(refundSwap.chainIdentifier);
|
|
154
|
-
const unlock = refundSwap.lock(swapContract.refundTimeout);
|
|
155
|
-
if(unlock==null) continue;
|
|
156
|
-
this.swapLogger.debug(refundSwap, "refundSwaps(): initiate refund of swap");
|
|
157
|
-
await swapContract.refund(signer, refundSwap.data, true, false, {waitForConfirmation: true});
|
|
158
|
-
this.swapLogger.info(refundSwap, "refundSwaps(): swap refunded, address: "+refundSwap.address);
|
|
159
|
-
//The swap should be removed by the event handler
|
|
160
|
-
await refundSwap.setState(FromBtcSwapState.REFUNDED);
|
|
161
|
-
unlock();
|
|
162
|
-
}
|
|
163
|
-
}
|
|
164
|
-
|
|
165
|
-
protected async processInitializeEvent(chainIdentifier: string, savedSwap: FromBtcSwapAbs, event: InitializeEvent<SwapData>) {
|
|
166
|
-
this.swapLogger.info(savedSwap, "SC: InitializeEvent: swap initialized by the client, address: "+savedSwap.address);
|
|
167
|
-
|
|
168
|
-
if(savedSwap.state===FromBtcSwapState.CREATED) {
|
|
169
|
-
await savedSwap.setState(FromBtcSwapState.COMMITED);
|
|
170
|
-
await this.saveSwapData(savedSwap);
|
|
171
|
-
}
|
|
172
|
-
}
|
|
173
|
-
|
|
174
|
-
protected async processClaimEvent(chainIdentifier: string, savedSwap: FromBtcSwapAbs, event: ClaimEvent<SwapData>): Promise<void> {
|
|
175
|
-
savedSwap.txId = Buffer.from(event.result, "hex").reverse().toString("hex");
|
|
176
|
-
|
|
177
|
-
this.swapLogger.info(savedSwap, "SC: ClaimEvent: swap successfully claimed by the client, address: "+savedSwap.address);
|
|
178
|
-
await this.removeSwapData(savedSwap, FromBtcSwapState.CLAIMED);
|
|
179
|
-
}
|
|
180
|
-
|
|
181
|
-
protected async processRefundEvent(chainIdentifier: string, savedSwap: FromBtcSwapAbs, event: RefundEvent<SwapData>) {
|
|
182
|
-
savedSwap.txIds.refund = (event as any).meta?.txId;
|
|
183
|
-
|
|
184
|
-
this.swapLogger.info(event, "SC: RefundEvent: swap refunded, address: "+savedSwap.address);
|
|
185
|
-
await this.removeSwapData(savedSwap, FromBtcSwapState.REFUNDED);
|
|
186
|
-
await this.bitcoin.addUnusedAddress(savedSwap.address);
|
|
187
|
-
}
|
|
188
|
-
|
|
189
|
-
/**
|
|
190
|
-
* Calculates the requested claimer bounty, based on client's request
|
|
191
|
-
*
|
|
192
|
-
* @param req
|
|
193
|
-
* @param expiry
|
|
194
|
-
* @param signal
|
|
195
|
-
* @throws {DefinedRuntimeError} will throw an error if the plugin cancelled the request
|
|
196
|
-
* @returns {Promise<BN>} resulting claimer bounty to be used with the swap
|
|
197
|
-
*/
|
|
198
|
-
private async getClaimerBounty(req: Request & {paramReader: IParamReader}, expiry: bigint, signal: AbortSignal): Promise<bigint> {
|
|
199
|
-
const parsedClaimerBounty = await req.paramReader.getParams({
|
|
200
|
-
claimerBounty: {
|
|
201
|
-
feePerBlock: FieldTypeEnum.BigInt,
|
|
202
|
-
safetyFactor: FieldTypeEnum.BigInt,
|
|
203
|
-
startTimestamp: FieldTypeEnum.BigInt,
|
|
204
|
-
addBlock: FieldTypeEnum.BigInt,
|
|
205
|
-
addFee: FieldTypeEnum.BigInt,
|
|
206
|
-
},
|
|
207
|
-
}).catch(e => null);
|
|
208
|
-
|
|
209
|
-
signal.throwIfAborted();
|
|
210
|
-
|
|
211
|
-
if(parsedClaimerBounty==null || parsedClaimerBounty.claimerBounty==null) {
|
|
212
|
-
throw {
|
|
213
|
-
code: 20043,
|
|
214
|
-
msg: "Invalid claimerBounty"
|
|
215
|
-
};
|
|
216
|
-
}
|
|
217
|
-
|
|
218
|
-
const tsDelta: bigint = expiry - parsedClaimerBounty.claimerBounty.startTimestamp;
|
|
219
|
-
const blocksDelta: bigint = tsDelta / this.config.bitcoinBlocktime * parsedClaimerBounty.claimerBounty.safetyFactor;
|
|
220
|
-
const totalBlock: bigint = blocksDelta + parsedClaimerBounty.claimerBounty.addBlock;
|
|
221
|
-
return parsedClaimerBounty.claimerBounty.addFee + (totalBlock * parsedClaimerBounty.claimerBounty.feePerBlock);
|
|
222
|
-
}
|
|
223
|
-
|
|
224
|
-
private getDummySwapData(chainIdentifier: string, useToken: string, address: string): Promise<SwapData> {
|
|
225
|
-
const {swapContract, signer} = this.getChain(chainIdentifier);
|
|
226
|
-
const dummyAmount = BigInt(Math.floor(Math.random() * 0x1000000));
|
|
227
|
-
return swapContract.createSwapData(
|
|
228
|
-
ChainSwapType.CHAIN,
|
|
229
|
-
signer.getAddress(),
|
|
230
|
-
address,
|
|
231
|
-
useToken,
|
|
232
|
-
dummyAmount,
|
|
233
|
-
swapContract.getHashForOnchain(randomBytes(32), dummyAmount, 3, null).toString("hex"),
|
|
234
|
-
BigIntBufferUtils.fromBuffer(randomBytes(8)),
|
|
235
|
-
BigInt(Math.floor(Date.now()/1000)) + this.config.swapTsCsvDelta,
|
|
236
|
-
false,
|
|
237
|
-
true,
|
|
238
|
-
BigInt(Math.floor(Math.random() * 0x10000)),
|
|
239
|
-
BigInt(Math.floor(Math.random() * 0x10000))
|
|
240
|
-
);
|
|
241
|
-
}
|
|
242
|
-
|
|
243
|
-
/**
|
|
244
|
-
* Sets up required listeners for the REST server
|
|
245
|
-
*
|
|
246
|
-
* @param restServer
|
|
247
|
-
*/
|
|
248
|
-
startRestServer(restServer: Express) {
|
|
249
|
-
|
|
250
|
-
restServer.use(this.path+"/getAddress", serverParamDecoder(10*1000));
|
|
251
|
-
restServer.post(this.path+"/getAddress", expressHandlerWrapper(async (req: Request & {paramReader: IParamReader}, res: Response & {responseStream: ServerParamEncoder}) => {
|
|
252
|
-
const metadata: {
|
|
253
|
-
request: any,
|
|
254
|
-
times: {[key: string]: number},
|
|
255
|
-
} = {request: {}, times: {}};
|
|
256
|
-
|
|
257
|
-
const chainIdentifier = req.query.chain as string ?? this.chains.default;
|
|
258
|
-
const {swapContract, signer, chainInterface} = this.getChain(chainIdentifier);
|
|
259
|
-
const depositToken = req.query.depositToken as string ?? chainInterface.getNativeCurrencyAddress();
|
|
260
|
-
this.checkAllowedDepositToken(chainIdentifier, depositToken);
|
|
261
|
-
|
|
262
|
-
metadata.times.requestReceived = Date.now();
|
|
263
|
-
/**
|
|
264
|
-
* address: string solana address of the recipient
|
|
265
|
-
* amount: string amount (in sats) of the invoice
|
|
266
|
-
* token: string Desired token to use
|
|
267
|
-
* exactOut: boolean Whether the swap should be an exact out instead of exact in swap
|
|
268
|
-
* sequence: BN Unique sequence number for the swap
|
|
269
|
-
*
|
|
270
|
-
*Sent later
|
|
271
|
-
* claimerBounty: object Data for calculating claimer bounty
|
|
272
|
-
* - feePerBlock: string Fee per block to be synchronized with btc relay
|
|
273
|
-
* - safetyFactor: number Safety factor to multiply required blocks (when using 10 min block time)
|
|
274
|
-
* - startTimestamp: string UNIX seconds used for timestamp delta calc
|
|
275
|
-
* - addBlock: number Additional blocks to add to the calculation
|
|
276
|
-
* - addFee: string Additional fee to add to the final claimer bounty
|
|
277
|
-
* feeRate: string Fee rate to be used for init signature
|
|
278
|
-
*/
|
|
279
|
-
const parsedBody: FromBtcRequestType = await req.paramReader.getParams({
|
|
280
|
-
address: (val: string) => val!=null &&
|
|
281
|
-
typeof(val)==="string" &&
|
|
282
|
-
chainInterface.isValidAddress(val) ? val : null,
|
|
283
|
-
amount: FieldTypeEnum.BigInt,
|
|
284
|
-
token: (val: string) => val!=null &&
|
|
285
|
-
typeof(val)==="string" &&
|
|
286
|
-
this.isTokenSupported(chainIdentifier, val) ? val : null,
|
|
287
|
-
sequence: FieldTypeEnum.BigInt,
|
|
288
|
-
exactOut: FieldTypeEnum.BooleanOptional
|
|
289
|
-
});
|
|
290
|
-
if(parsedBody==null) throw {
|
|
291
|
-
code: 20100,
|
|
292
|
-
msg: "Invalid request body"
|
|
293
|
-
};
|
|
294
|
-
metadata.request = parsedBody;
|
|
295
|
-
|
|
296
|
-
const requestedAmount = {input: !parsedBody.exactOut, amount: parsedBody.amount, token: parsedBody.token};
|
|
297
|
-
const request = {
|
|
298
|
-
chainIdentifier,
|
|
299
|
-
raw: req,
|
|
300
|
-
parsed: parsedBody,
|
|
301
|
-
metadata
|
|
302
|
-
};
|
|
303
|
-
const useToken = parsedBody.token;
|
|
304
|
-
|
|
305
|
-
//Check request params
|
|
306
|
-
this.checkSequence(parsedBody.sequence);
|
|
307
|
-
const fees = await this.AmountAssertions.preCheckFromBtcAmounts(this.type, request, requestedAmount);
|
|
308
|
-
metadata.times.requestChecked = Date.now();
|
|
309
|
-
|
|
310
|
-
//Create abortController for parallel prefetches
|
|
311
|
-
const responseStream = res.responseStream;
|
|
312
|
-
const abortController = getAbortController(responseStream);
|
|
313
|
-
|
|
314
|
-
//Pre-fetch data
|
|
315
|
-
const {
|
|
316
|
-
pricePrefetchPromise,
|
|
317
|
-
gasTokenPricePrefetchPromise,
|
|
318
|
-
depositTokenPricePrefetchPromise
|
|
319
|
-
} = this.getFromBtcPricePrefetches(chainIdentifier, useToken, depositToken, abortController);
|
|
320
|
-
const balancePrefetch: Promise<bigint> = this.getBalancePrefetch(chainIdentifier, useToken, abortController);
|
|
321
|
-
const signDataPrefetchPromise: Promise<any> = this.getSignDataPrefetch(chainIdentifier, abortController, responseStream);
|
|
322
|
-
|
|
323
|
-
const dummySwapData = await this.getDummySwapData(chainIdentifier, useToken, parsedBody.address);
|
|
324
|
-
abortController.signal.throwIfAborted();
|
|
325
|
-
const baseSDPromise: Promise<bigint> = this.getBaseSecurityDepositPrefetch(
|
|
326
|
-
chainIdentifier, dummySwapData, depositToken,
|
|
327
|
-
gasTokenPricePrefetchPromise, depositTokenPricePrefetchPromise,
|
|
328
|
-
abortController
|
|
329
|
-
);
|
|
330
|
-
|
|
331
|
-
//Check valid amount specified (min/max)
|
|
332
|
-
const {
|
|
333
|
-
amountBD,
|
|
334
|
-
swapFee,
|
|
335
|
-
swapFeeInToken,
|
|
336
|
-
totalInToken,
|
|
337
|
-
securityDepositApyPPM,
|
|
338
|
-
securityDepositBaseMultiplierPPM
|
|
339
|
-
} = await this.AmountAssertions.checkFromBtcAmount(this.type, request, {...requestedAmount, pricePrefetch: pricePrefetchPromise}, fees, abortController.signal);
|
|
340
|
-
metadata.times.priceCalculated = Date.now();
|
|
341
|
-
|
|
342
|
-
if(securityDepositApyPPM!=null) fees.securityDepositApyPPM = securityDepositApyPPM;
|
|
343
|
-
if(securityDepositBaseMultiplierPPM!=null) fees.securityDepositBaseMultiplierPPM = securityDepositBaseMultiplierPPM;
|
|
344
|
-
|
|
345
|
-
//Check if we have enough funds to honor the request
|
|
346
|
-
await this.checkBalance(totalInToken, balancePrefetch, abortController.signal);
|
|
347
|
-
metadata.times.balanceChecked = Date.now();
|
|
348
|
-
|
|
349
|
-
//Create swap receive bitcoin address
|
|
350
|
-
const receiveAddress = await this.bitcoin.getAddress();
|
|
351
|
-
abortController.signal.throwIfAborted();
|
|
352
|
-
metadata.times.addressCreated = Date.now();
|
|
353
|
-
|
|
354
|
-
const paymentHash = this.getHash(chainIdentifier, receiveAddress, amountBD);
|
|
355
|
-
const currentTimestamp = BigInt(Math.floor(Date.now()/1000));
|
|
356
|
-
const expiryTimeout = this.config.swapTsCsvDelta;
|
|
357
|
-
const expiry = currentTimestamp + expiryTimeout;
|
|
358
|
-
|
|
359
|
-
//Calculate security deposit
|
|
360
|
-
const totalSecurityDeposit = await this.getSecurityDeposit(
|
|
361
|
-
chainIdentifier, amountBD, swapFee, expiryTimeout,
|
|
362
|
-
baseSDPromise, depositToken, depositTokenPricePrefetchPromise, fees,
|
|
363
|
-
abortController.signal, metadata
|
|
364
|
-
);
|
|
365
|
-
metadata.times.securityDepositCalculated = Date.now();
|
|
366
|
-
|
|
367
|
-
//Calculate claimer bounty
|
|
368
|
-
const totalClaimerBounty = await this.getClaimerBounty(req, expiry, abortController.signal);
|
|
369
|
-
metadata.times.claimerBountyCalculated = Date.now();
|
|
370
|
-
|
|
371
|
-
//Create swap data
|
|
372
|
-
const data: SwapData = await swapContract.createSwapData(
|
|
373
|
-
ChainSwapType.CHAIN,
|
|
374
|
-
signer.getAddress(),
|
|
375
|
-
parsedBody.address,
|
|
376
|
-
useToken,
|
|
377
|
-
totalInToken,
|
|
378
|
-
paymentHash.toString("hex"),
|
|
379
|
-
parsedBody.sequence,
|
|
380
|
-
expiry,
|
|
381
|
-
false,
|
|
382
|
-
true,
|
|
383
|
-
totalSecurityDeposit,
|
|
384
|
-
totalClaimerBounty,
|
|
385
|
-
depositToken
|
|
386
|
-
);
|
|
387
|
-
data.setExtraData(swapContract.getExtraData(
|
|
388
|
-
this.bitcoin.toOutputScript(receiveAddress),
|
|
389
|
-
amountBD,
|
|
390
|
-
this.config.confirmations
|
|
391
|
-
).toString("hex"));
|
|
392
|
-
abortController.signal.throwIfAborted();
|
|
393
|
-
metadata.times.swapCreated = Date.now();
|
|
394
|
-
|
|
395
|
-
//Sign the swap
|
|
396
|
-
const sigData = await this.getFromBtcSignatureData(chainIdentifier, data, req, abortController.signal, signDataPrefetchPromise);
|
|
397
|
-
metadata.times.swapSigned = Date.now();
|
|
398
|
-
|
|
399
|
-
const createdSwap: FromBtcSwapAbs = new FromBtcSwapAbs(chainIdentifier, receiveAddress, this.config.confirmations, amountBD, swapFee, swapFeeInToken);
|
|
400
|
-
createdSwap.data = data;
|
|
401
|
-
createdSwap.metadata = metadata;
|
|
402
|
-
createdSwap.prefix = sigData.prefix;
|
|
403
|
-
createdSwap.timeout = sigData.timeout;
|
|
404
|
-
createdSwap.signature = sigData.signature;
|
|
405
|
-
createdSwap.feeRate = sigData.feeRate;
|
|
406
|
-
|
|
407
|
-
await PluginManager.swapCreate(createdSwap);
|
|
408
|
-
await this.saveSwapData(createdSwap);
|
|
409
|
-
|
|
410
|
-
this.swapLogger.info(createdSwap, "REST: /getAddress: Created swap address: "+receiveAddress+" amount: "+amountBD.toString(10));
|
|
411
|
-
|
|
412
|
-
await responseStream.writeParamsAndEnd({
|
|
413
|
-
code: 20000,
|
|
414
|
-
msg: "Success",
|
|
415
|
-
data: {
|
|
416
|
-
amount: amountBD.toString(10),
|
|
417
|
-
btcAddress: receiveAddress,
|
|
418
|
-
address: signer.getAddress(),
|
|
419
|
-
swapFee: swapFeeInToken.toString(10),
|
|
420
|
-
total: totalInToken.toString(10),
|
|
421
|
-
confirmations: this.config.confirmations,
|
|
422
|
-
data: data.serialize(),
|
|
423
|
-
prefix: sigData.prefix,
|
|
424
|
-
timeout: sigData.timeout,
|
|
425
|
-
signature: sigData.signature
|
|
426
|
-
}
|
|
427
|
-
});
|
|
428
|
-
|
|
429
|
-
}));
|
|
430
|
-
|
|
431
|
-
this.logger.info("REST: Started at path: ", this.path);
|
|
432
|
-
}
|
|
433
|
-
|
|
434
|
-
/**
|
|
435
|
-
* Initializes swap handler, loads data and subscribes to chain events
|
|
436
|
-
*/
|
|
437
|
-
async init() {
|
|
438
|
-
await this.loadData(FromBtcSwapAbs);
|
|
439
|
-
this.subscribeToEvents();
|
|
440
|
-
await PluginManager.serviceInitialize(this);
|
|
441
|
-
}
|
|
442
|
-
|
|
443
|
-
getInfoData(): any {
|
|
444
|
-
return {
|
|
445
|
-
confirmations: this.config.confirmations,
|
|
446
|
-
|
|
447
|
-
cltv: this.config.swapCsvDelta,
|
|
448
|
-
timestampCltv: Number(this.config.swapTsCsvDelta)
|
|
449
|
-
};
|
|
450
|
-
}
|
|
451
|
-
|
|
452
|
-
}
|
|
1
|
+
import {Express, Request, Response} from "express";
|
|
2
|
+
import {FromBtcSwapAbs, FromBtcSwapState} from "./FromBtcSwapAbs";
|
|
3
|
+
import {MultichainData, SwapHandlerType} from "../../SwapHandler";
|
|
4
|
+
import {ISwapPrice} from "../../../prices/ISwapPrice";
|
|
5
|
+
import {
|
|
6
|
+
BigIntBufferUtils,
|
|
7
|
+
ChainSwapType,
|
|
8
|
+
ClaimEvent,
|
|
9
|
+
InitializeEvent,
|
|
10
|
+
RefundEvent,
|
|
11
|
+
SwapData
|
|
12
|
+
} from "@atomiqlabs/base";
|
|
13
|
+
import {randomBytes} from "crypto";
|
|
14
|
+
import {expressHandlerWrapper, getAbortController} from "../../../utils/Utils";
|
|
15
|
+
import {PluginManager} from "../../../plugins/PluginManager";
|
|
16
|
+
import {IIntermediaryStorage} from "../../../storage/IIntermediaryStorage";
|
|
17
|
+
import {FieldTypeEnum} from "../../../utils/paramcoders/SchemaVerifier";
|
|
18
|
+
import {serverParamDecoder} from "../../../utils/paramcoders/server/ServerParamDecoder";
|
|
19
|
+
import {IParamReader} from "../../../utils/paramcoders/IParamReader";
|
|
20
|
+
import {ServerParamEncoder} from "../../../utils/paramcoders/server/ServerParamEncoder";
|
|
21
|
+
import {FromBtcBaseConfig, FromBtcBaseSwapHandler} from "../FromBtcBaseSwapHandler";
|
|
22
|
+
import {IBitcoinWallet} from "../../../wallets/IBitcoinWallet";
|
|
23
|
+
|
|
24
|
+
export type FromBtcConfig = FromBtcBaseConfig & {
|
|
25
|
+
confirmations: number,
|
|
26
|
+
swapCsvDelta: number
|
|
27
|
+
};
|
|
28
|
+
|
|
29
|
+
export type FromBtcRequestType = {
|
|
30
|
+
address: string,
|
|
31
|
+
amount: bigint,
|
|
32
|
+
token: string,
|
|
33
|
+
sequence: bigint,
|
|
34
|
+
exactOut?: boolean
|
|
35
|
+
};
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* Swap handler handling from BTC swaps using PTLCs (proof-time locked contracts) and btc relay (on-chain bitcoin SPV)
|
|
39
|
+
*/
|
|
40
|
+
export class FromBtcAbs extends FromBtcBaseSwapHandler<FromBtcSwapAbs, FromBtcSwapState> {
|
|
41
|
+
readonly type = SwapHandlerType.FROM_BTC;
|
|
42
|
+
readonly swapType = ChainSwapType.CHAIN;
|
|
43
|
+
|
|
44
|
+
readonly config: FromBtcConfig & {swapTsCsvDelta: bigint};
|
|
45
|
+
|
|
46
|
+
readonly bitcoin: IBitcoinWallet;
|
|
47
|
+
|
|
48
|
+
constructor(
|
|
49
|
+
storageDirectory: IIntermediaryStorage<FromBtcSwapAbs>,
|
|
50
|
+
path: string,
|
|
51
|
+
chains: MultichainData,
|
|
52
|
+
bitcoin: IBitcoinWallet,
|
|
53
|
+
swapPricing: ISwapPrice,
|
|
54
|
+
config: FromBtcConfig
|
|
55
|
+
) {
|
|
56
|
+
super(storageDirectory, path, chains, swapPricing, config);
|
|
57
|
+
this.bitcoin = bitcoin;
|
|
58
|
+
this.config = {
|
|
59
|
+
...config,
|
|
60
|
+
swapTsCsvDelta: BigInt(config.swapCsvDelta) * (config.bitcoinBlocktime / config.safetyFactor)
|
|
61
|
+
};
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* Returns the payment hash of the swap, takes swap nonce into account. Payment hash is chain-specific.
|
|
66
|
+
*
|
|
67
|
+
* @param chainIdentifier
|
|
68
|
+
* @param address
|
|
69
|
+
* @param amount
|
|
70
|
+
*/
|
|
71
|
+
private getHash(chainIdentifier: string, address: string, amount: bigint): Buffer {
|
|
72
|
+
const parsedOutputScript = this.bitcoin.toOutputScript(address);
|
|
73
|
+
const {swapContract} = this.getChain(chainIdentifier);
|
|
74
|
+
return swapContract.getHashForOnchain(parsedOutputScript, amount, this.config.confirmations, 0n);
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* Processes past swap
|
|
79
|
+
*
|
|
80
|
+
* @param swap
|
|
81
|
+
* @protected
|
|
82
|
+
* @returns true if the swap should be refunded, false if nothing should be done
|
|
83
|
+
*/
|
|
84
|
+
protected async processPastSwap(swap: FromBtcSwapAbs): Promise<boolean> {
|
|
85
|
+
const {swapContract, signer} = this.getChain(swap.chainIdentifier);
|
|
86
|
+
|
|
87
|
+
//Once authorization expires in CREATED state, the user can no more commit it on-chain
|
|
88
|
+
if(swap.state===FromBtcSwapState.CREATED) {
|
|
89
|
+
if(!await swapContract.isInitAuthorizationExpired(swap.data, swap)) return false;
|
|
90
|
+
|
|
91
|
+
const isCommited = await swapContract.isCommited(swap.data);
|
|
92
|
+
if(isCommited) {
|
|
93
|
+
this.swapLogger.info(swap, "processPastSwap(state=CREATED): swap was commited, but processed from watchdog, address: "+swap.address);
|
|
94
|
+
await swap.setState(FromBtcSwapState.COMMITED);
|
|
95
|
+
await this.saveSwapData(swap);
|
|
96
|
+
return false;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
this.swapLogger.info(swap, "processPastSwap(state=CREATED): removing past swap due to authorization expiry, address: "+swap.address);
|
|
100
|
+
await this.removeSwapData(swap, FromBtcSwapState.CANCELED);
|
|
101
|
+
await this.bitcoin.addUnusedAddress(swap.address);
|
|
102
|
+
return false;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
//Check if commited swap expired by now
|
|
106
|
+
if(swap.state===FromBtcSwapState.COMMITED) {
|
|
107
|
+
if(!await swapContract.isExpired(signer.getAddress(), swap.data)) return false;
|
|
108
|
+
|
|
109
|
+
const isCommited = await swapContract.isCommited(swap.data);
|
|
110
|
+
if(isCommited) {
|
|
111
|
+
this.swapLogger.info(swap, "processPastSwap(state=COMMITED): swap expired, will refund, address: "+swap.address);
|
|
112
|
+
return true;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
this.swapLogger.warn(swap, "processPastSwap(state=COMMITED): commited swap expired and not committed anymore (already refunded?), address: "+swap.address);
|
|
116
|
+
await this.removeSwapData(swap, FromBtcSwapState.CANCELED);
|
|
117
|
+
return false;
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/**
|
|
122
|
+
* Checks past swaps, refunds and deletes ones that are already expired.
|
|
123
|
+
*/
|
|
124
|
+
protected async processPastSwaps() {
|
|
125
|
+
|
|
126
|
+
const queriedData = await this.storageManager.query([
|
|
127
|
+
{
|
|
128
|
+
key: "state",
|
|
129
|
+
value: [
|
|
130
|
+
FromBtcSwapState.CREATED,
|
|
131
|
+
FromBtcSwapState.COMMITED
|
|
132
|
+
]
|
|
133
|
+
}
|
|
134
|
+
]);
|
|
135
|
+
|
|
136
|
+
const refundSwaps: FromBtcSwapAbs[] = [];
|
|
137
|
+
|
|
138
|
+
for(let {obj: swap} of queriedData) {
|
|
139
|
+
if(await this.processPastSwap(swap)) refundSwaps.push(swap);
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
await this.refundSwaps(refundSwaps);
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/**
|
|
146
|
+
* Refunds all swaps (calls SC on-chain refund function)
|
|
147
|
+
*
|
|
148
|
+
* @param refundSwaps
|
|
149
|
+
* @protected
|
|
150
|
+
*/
|
|
151
|
+
protected async refundSwaps(refundSwaps: FromBtcSwapAbs[]) {
|
|
152
|
+
for(let refundSwap of refundSwaps) {
|
|
153
|
+
const {swapContract, signer} = this.getChain(refundSwap.chainIdentifier);
|
|
154
|
+
const unlock = refundSwap.lock(swapContract.refundTimeout);
|
|
155
|
+
if(unlock==null) continue;
|
|
156
|
+
this.swapLogger.debug(refundSwap, "refundSwaps(): initiate refund of swap");
|
|
157
|
+
await swapContract.refund(signer, refundSwap.data, true, false, {waitForConfirmation: true});
|
|
158
|
+
this.swapLogger.info(refundSwap, "refundSwaps(): swap refunded, address: "+refundSwap.address);
|
|
159
|
+
//The swap should be removed by the event handler
|
|
160
|
+
await refundSwap.setState(FromBtcSwapState.REFUNDED);
|
|
161
|
+
unlock();
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
protected async processInitializeEvent(chainIdentifier: string, savedSwap: FromBtcSwapAbs, event: InitializeEvent<SwapData>) {
|
|
166
|
+
this.swapLogger.info(savedSwap, "SC: InitializeEvent: swap initialized by the client, address: "+savedSwap.address);
|
|
167
|
+
|
|
168
|
+
if(savedSwap.state===FromBtcSwapState.CREATED) {
|
|
169
|
+
await savedSwap.setState(FromBtcSwapState.COMMITED);
|
|
170
|
+
await this.saveSwapData(savedSwap);
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
protected async processClaimEvent(chainIdentifier: string, savedSwap: FromBtcSwapAbs, event: ClaimEvent<SwapData>): Promise<void> {
|
|
175
|
+
savedSwap.txId = Buffer.from(event.result, "hex").reverse().toString("hex");
|
|
176
|
+
|
|
177
|
+
this.swapLogger.info(savedSwap, "SC: ClaimEvent: swap successfully claimed by the client, address: "+savedSwap.address);
|
|
178
|
+
await this.removeSwapData(savedSwap, FromBtcSwapState.CLAIMED);
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
protected async processRefundEvent(chainIdentifier: string, savedSwap: FromBtcSwapAbs, event: RefundEvent<SwapData>) {
|
|
182
|
+
savedSwap.txIds.refund = (event as any).meta?.txId;
|
|
183
|
+
|
|
184
|
+
this.swapLogger.info(event, "SC: RefundEvent: swap refunded, address: "+savedSwap.address);
|
|
185
|
+
await this.removeSwapData(savedSwap, FromBtcSwapState.REFUNDED);
|
|
186
|
+
await this.bitcoin.addUnusedAddress(savedSwap.address);
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
/**
|
|
190
|
+
* Calculates the requested claimer bounty, based on client's request
|
|
191
|
+
*
|
|
192
|
+
* @param req
|
|
193
|
+
* @param expiry
|
|
194
|
+
* @param signal
|
|
195
|
+
* @throws {DefinedRuntimeError} will throw an error if the plugin cancelled the request
|
|
196
|
+
* @returns {Promise<BN>} resulting claimer bounty to be used with the swap
|
|
197
|
+
*/
|
|
198
|
+
private async getClaimerBounty(req: Request & {paramReader: IParamReader}, expiry: bigint, signal: AbortSignal): Promise<bigint> {
|
|
199
|
+
const parsedClaimerBounty = await req.paramReader.getParams({
|
|
200
|
+
claimerBounty: {
|
|
201
|
+
feePerBlock: FieldTypeEnum.BigInt,
|
|
202
|
+
safetyFactor: FieldTypeEnum.BigInt,
|
|
203
|
+
startTimestamp: FieldTypeEnum.BigInt,
|
|
204
|
+
addBlock: FieldTypeEnum.BigInt,
|
|
205
|
+
addFee: FieldTypeEnum.BigInt,
|
|
206
|
+
},
|
|
207
|
+
}).catch(e => null);
|
|
208
|
+
|
|
209
|
+
signal.throwIfAborted();
|
|
210
|
+
|
|
211
|
+
if(parsedClaimerBounty==null || parsedClaimerBounty.claimerBounty==null) {
|
|
212
|
+
throw {
|
|
213
|
+
code: 20043,
|
|
214
|
+
msg: "Invalid claimerBounty"
|
|
215
|
+
};
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
const tsDelta: bigint = expiry - parsedClaimerBounty.claimerBounty.startTimestamp;
|
|
219
|
+
const blocksDelta: bigint = tsDelta / this.config.bitcoinBlocktime * parsedClaimerBounty.claimerBounty.safetyFactor;
|
|
220
|
+
const totalBlock: bigint = blocksDelta + parsedClaimerBounty.claimerBounty.addBlock;
|
|
221
|
+
return parsedClaimerBounty.claimerBounty.addFee + (totalBlock * parsedClaimerBounty.claimerBounty.feePerBlock);
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
private getDummySwapData(chainIdentifier: string, useToken: string, address: string): Promise<SwapData> {
|
|
225
|
+
const {swapContract, signer} = this.getChain(chainIdentifier);
|
|
226
|
+
const dummyAmount = BigInt(Math.floor(Math.random() * 0x1000000));
|
|
227
|
+
return swapContract.createSwapData(
|
|
228
|
+
ChainSwapType.CHAIN,
|
|
229
|
+
signer.getAddress(),
|
|
230
|
+
address,
|
|
231
|
+
useToken,
|
|
232
|
+
dummyAmount,
|
|
233
|
+
swapContract.getHashForOnchain(randomBytes(32), dummyAmount, 3, null).toString("hex"),
|
|
234
|
+
BigIntBufferUtils.fromBuffer(randomBytes(8)),
|
|
235
|
+
BigInt(Math.floor(Date.now()/1000)) + this.config.swapTsCsvDelta,
|
|
236
|
+
false,
|
|
237
|
+
true,
|
|
238
|
+
BigInt(Math.floor(Math.random() * 0x10000)),
|
|
239
|
+
BigInt(Math.floor(Math.random() * 0x10000))
|
|
240
|
+
);
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
/**
|
|
244
|
+
* Sets up required listeners for the REST server
|
|
245
|
+
*
|
|
246
|
+
* @param restServer
|
|
247
|
+
*/
|
|
248
|
+
startRestServer(restServer: Express) {
|
|
249
|
+
|
|
250
|
+
restServer.use(this.path+"/getAddress", serverParamDecoder(10*1000));
|
|
251
|
+
restServer.post(this.path+"/getAddress", expressHandlerWrapper(async (req: Request & {paramReader: IParamReader}, res: Response & {responseStream: ServerParamEncoder}) => {
|
|
252
|
+
const metadata: {
|
|
253
|
+
request: any,
|
|
254
|
+
times: {[key: string]: number},
|
|
255
|
+
} = {request: {}, times: {}};
|
|
256
|
+
|
|
257
|
+
const chainIdentifier = req.query.chain as string ?? this.chains.default;
|
|
258
|
+
const {swapContract, signer, chainInterface} = this.getChain(chainIdentifier);
|
|
259
|
+
const depositToken = req.query.depositToken as string ?? chainInterface.getNativeCurrencyAddress();
|
|
260
|
+
this.checkAllowedDepositToken(chainIdentifier, depositToken);
|
|
261
|
+
|
|
262
|
+
metadata.times.requestReceived = Date.now();
|
|
263
|
+
/**
|
|
264
|
+
* address: string solana address of the recipient
|
|
265
|
+
* amount: string amount (in sats) of the invoice
|
|
266
|
+
* token: string Desired token to use
|
|
267
|
+
* exactOut: boolean Whether the swap should be an exact out instead of exact in swap
|
|
268
|
+
* sequence: BN Unique sequence number for the swap
|
|
269
|
+
*
|
|
270
|
+
*Sent later
|
|
271
|
+
* claimerBounty: object Data for calculating claimer bounty
|
|
272
|
+
* - feePerBlock: string Fee per block to be synchronized with btc relay
|
|
273
|
+
* - safetyFactor: number Safety factor to multiply required blocks (when using 10 min block time)
|
|
274
|
+
* - startTimestamp: string UNIX seconds used for timestamp delta calc
|
|
275
|
+
* - addBlock: number Additional blocks to add to the calculation
|
|
276
|
+
* - addFee: string Additional fee to add to the final claimer bounty
|
|
277
|
+
* feeRate: string Fee rate to be used for init signature
|
|
278
|
+
*/
|
|
279
|
+
const parsedBody: FromBtcRequestType = await req.paramReader.getParams({
|
|
280
|
+
address: (val: string) => val!=null &&
|
|
281
|
+
typeof(val)==="string" &&
|
|
282
|
+
chainInterface.isValidAddress(val) ? val : null,
|
|
283
|
+
amount: FieldTypeEnum.BigInt,
|
|
284
|
+
token: (val: string) => val!=null &&
|
|
285
|
+
typeof(val)==="string" &&
|
|
286
|
+
this.isTokenSupported(chainIdentifier, val) ? val : null,
|
|
287
|
+
sequence: FieldTypeEnum.BigInt,
|
|
288
|
+
exactOut: FieldTypeEnum.BooleanOptional
|
|
289
|
+
});
|
|
290
|
+
if(parsedBody==null) throw {
|
|
291
|
+
code: 20100,
|
|
292
|
+
msg: "Invalid request body"
|
|
293
|
+
};
|
|
294
|
+
metadata.request = parsedBody;
|
|
295
|
+
|
|
296
|
+
const requestedAmount = {input: !parsedBody.exactOut, amount: parsedBody.amount, token: parsedBody.token};
|
|
297
|
+
const request = {
|
|
298
|
+
chainIdentifier,
|
|
299
|
+
raw: req,
|
|
300
|
+
parsed: parsedBody,
|
|
301
|
+
metadata
|
|
302
|
+
};
|
|
303
|
+
const useToken = parsedBody.token;
|
|
304
|
+
|
|
305
|
+
//Check request params
|
|
306
|
+
this.checkSequence(parsedBody.sequence);
|
|
307
|
+
const fees = await this.AmountAssertions.preCheckFromBtcAmounts(this.type, request, requestedAmount);
|
|
308
|
+
metadata.times.requestChecked = Date.now();
|
|
309
|
+
|
|
310
|
+
//Create abortController for parallel prefetches
|
|
311
|
+
const responseStream = res.responseStream;
|
|
312
|
+
const abortController = getAbortController(responseStream);
|
|
313
|
+
|
|
314
|
+
//Pre-fetch data
|
|
315
|
+
const {
|
|
316
|
+
pricePrefetchPromise,
|
|
317
|
+
gasTokenPricePrefetchPromise,
|
|
318
|
+
depositTokenPricePrefetchPromise
|
|
319
|
+
} = this.getFromBtcPricePrefetches(chainIdentifier, useToken, depositToken, abortController);
|
|
320
|
+
const balancePrefetch: Promise<bigint> = this.getBalancePrefetch(chainIdentifier, useToken, abortController);
|
|
321
|
+
const signDataPrefetchPromise: Promise<any> = this.getSignDataPrefetch(chainIdentifier, abortController, responseStream);
|
|
322
|
+
|
|
323
|
+
const dummySwapData = await this.getDummySwapData(chainIdentifier, useToken, parsedBody.address);
|
|
324
|
+
abortController.signal.throwIfAborted();
|
|
325
|
+
const baseSDPromise: Promise<bigint> = this.getBaseSecurityDepositPrefetch(
|
|
326
|
+
chainIdentifier, dummySwapData, depositToken,
|
|
327
|
+
gasTokenPricePrefetchPromise, depositTokenPricePrefetchPromise,
|
|
328
|
+
abortController
|
|
329
|
+
);
|
|
330
|
+
|
|
331
|
+
//Check valid amount specified (min/max)
|
|
332
|
+
const {
|
|
333
|
+
amountBD,
|
|
334
|
+
swapFee,
|
|
335
|
+
swapFeeInToken,
|
|
336
|
+
totalInToken,
|
|
337
|
+
securityDepositApyPPM,
|
|
338
|
+
securityDepositBaseMultiplierPPM
|
|
339
|
+
} = await this.AmountAssertions.checkFromBtcAmount(this.type, request, {...requestedAmount, pricePrefetch: pricePrefetchPromise}, fees, abortController.signal);
|
|
340
|
+
metadata.times.priceCalculated = Date.now();
|
|
341
|
+
|
|
342
|
+
if(securityDepositApyPPM!=null) fees.securityDepositApyPPM = securityDepositApyPPM;
|
|
343
|
+
if(securityDepositBaseMultiplierPPM!=null) fees.securityDepositBaseMultiplierPPM = securityDepositBaseMultiplierPPM;
|
|
344
|
+
|
|
345
|
+
//Check if we have enough funds to honor the request
|
|
346
|
+
await this.checkBalance(totalInToken, balancePrefetch, abortController.signal);
|
|
347
|
+
metadata.times.balanceChecked = Date.now();
|
|
348
|
+
|
|
349
|
+
//Create swap receive bitcoin address
|
|
350
|
+
const receiveAddress = await this.bitcoin.getAddress();
|
|
351
|
+
abortController.signal.throwIfAborted();
|
|
352
|
+
metadata.times.addressCreated = Date.now();
|
|
353
|
+
|
|
354
|
+
const paymentHash = this.getHash(chainIdentifier, receiveAddress, amountBD);
|
|
355
|
+
const currentTimestamp = BigInt(Math.floor(Date.now()/1000));
|
|
356
|
+
const expiryTimeout = this.config.swapTsCsvDelta;
|
|
357
|
+
const expiry = currentTimestamp + expiryTimeout;
|
|
358
|
+
|
|
359
|
+
//Calculate security deposit
|
|
360
|
+
const totalSecurityDeposit = await this.getSecurityDeposit(
|
|
361
|
+
chainIdentifier, amountBD, swapFee, expiryTimeout,
|
|
362
|
+
baseSDPromise, depositToken, depositTokenPricePrefetchPromise, fees,
|
|
363
|
+
abortController.signal, metadata
|
|
364
|
+
);
|
|
365
|
+
metadata.times.securityDepositCalculated = Date.now();
|
|
366
|
+
|
|
367
|
+
//Calculate claimer bounty
|
|
368
|
+
const totalClaimerBounty = await this.getClaimerBounty(req, expiry, abortController.signal);
|
|
369
|
+
metadata.times.claimerBountyCalculated = Date.now();
|
|
370
|
+
|
|
371
|
+
//Create swap data
|
|
372
|
+
const data: SwapData = await swapContract.createSwapData(
|
|
373
|
+
ChainSwapType.CHAIN,
|
|
374
|
+
signer.getAddress(),
|
|
375
|
+
parsedBody.address,
|
|
376
|
+
useToken,
|
|
377
|
+
totalInToken,
|
|
378
|
+
paymentHash.toString("hex"),
|
|
379
|
+
parsedBody.sequence,
|
|
380
|
+
expiry,
|
|
381
|
+
false,
|
|
382
|
+
true,
|
|
383
|
+
totalSecurityDeposit,
|
|
384
|
+
totalClaimerBounty,
|
|
385
|
+
depositToken
|
|
386
|
+
);
|
|
387
|
+
data.setExtraData(swapContract.getExtraData(
|
|
388
|
+
this.bitcoin.toOutputScript(receiveAddress),
|
|
389
|
+
amountBD,
|
|
390
|
+
this.config.confirmations
|
|
391
|
+
).toString("hex"));
|
|
392
|
+
abortController.signal.throwIfAborted();
|
|
393
|
+
metadata.times.swapCreated = Date.now();
|
|
394
|
+
|
|
395
|
+
//Sign the swap
|
|
396
|
+
const sigData = await this.getFromBtcSignatureData(chainIdentifier, data, req, abortController.signal, signDataPrefetchPromise);
|
|
397
|
+
metadata.times.swapSigned = Date.now();
|
|
398
|
+
|
|
399
|
+
const createdSwap: FromBtcSwapAbs = new FromBtcSwapAbs(chainIdentifier, receiveAddress, this.config.confirmations, amountBD, swapFee, swapFeeInToken);
|
|
400
|
+
createdSwap.data = data;
|
|
401
|
+
createdSwap.metadata = metadata;
|
|
402
|
+
createdSwap.prefix = sigData.prefix;
|
|
403
|
+
createdSwap.timeout = sigData.timeout;
|
|
404
|
+
createdSwap.signature = sigData.signature;
|
|
405
|
+
createdSwap.feeRate = sigData.feeRate;
|
|
406
|
+
|
|
407
|
+
await PluginManager.swapCreate(createdSwap);
|
|
408
|
+
await this.saveSwapData(createdSwap);
|
|
409
|
+
|
|
410
|
+
this.swapLogger.info(createdSwap, "REST: /getAddress: Created swap address: "+receiveAddress+" amount: "+amountBD.toString(10));
|
|
411
|
+
|
|
412
|
+
await responseStream.writeParamsAndEnd({
|
|
413
|
+
code: 20000,
|
|
414
|
+
msg: "Success",
|
|
415
|
+
data: {
|
|
416
|
+
amount: amountBD.toString(10),
|
|
417
|
+
btcAddress: receiveAddress,
|
|
418
|
+
address: signer.getAddress(),
|
|
419
|
+
swapFee: swapFeeInToken.toString(10),
|
|
420
|
+
total: totalInToken.toString(10),
|
|
421
|
+
confirmations: this.config.confirmations,
|
|
422
|
+
data: data.serialize(),
|
|
423
|
+
prefix: sigData.prefix,
|
|
424
|
+
timeout: sigData.timeout,
|
|
425
|
+
signature: sigData.signature
|
|
426
|
+
}
|
|
427
|
+
});
|
|
428
|
+
|
|
429
|
+
}));
|
|
430
|
+
|
|
431
|
+
this.logger.info("REST: Started at path: ", this.path);
|
|
432
|
+
}
|
|
433
|
+
|
|
434
|
+
/**
|
|
435
|
+
* Initializes swap handler, loads data and subscribes to chain events
|
|
436
|
+
*/
|
|
437
|
+
async init() {
|
|
438
|
+
await this.loadData(FromBtcSwapAbs);
|
|
439
|
+
this.subscribeToEvents();
|
|
440
|
+
await PluginManager.serviceInitialize(this);
|
|
441
|
+
}
|
|
442
|
+
|
|
443
|
+
getInfoData(): any {
|
|
444
|
+
return {
|
|
445
|
+
confirmations: this.config.confirmations,
|
|
446
|
+
|
|
447
|
+
cltv: this.config.swapCsvDelta,
|
|
448
|
+
timestampCltv: Number(this.config.swapTsCsvDelta)
|
|
449
|
+
};
|
|
450
|
+
}
|
|
451
|
+
|
|
452
|
+
}
|