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