-
Notifications
You must be signed in to change notification settings - Fork 43
/
FeeProvider.ts
433 lines (377 loc) · 11.4 KB
/
FeeProvider.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
import Logger from '../Logger';
import {
getChainCurrency,
getPairId,
getReceivingChain,
getSendingChain,
mapToObject,
splitPairId,
stringify,
} from '../Utils';
import ElementsClient from '../chain/ElementsClient';
import { etherDecimals, gweiDecimals } from '../consts/Consts';
import {
BaseFeeType,
CurrencyType,
OrderSide,
PercentageFeeType,
SwapType,
SwapVersion,
swapTypeToString,
} from '../consts/Enums';
import { PairConfig } from '../consts/Types';
import WalletManager from '../wallet/WalletManager';
import { Ethereum, Rsk } from '../wallet/ethereum/EvmNetworks';
import DataAggregator from './data/DataAggregator';
type TransactionSizesForVersion = {
normalClaim: number;
reverseLockup: number;
reverseClaim: number;
};
type TransactionSizes = {
[SwapVersion.Legacy]: TransactionSizesForVersion;
[SwapVersion.Taproot]: TransactionSizesForVersion;
};
type PercentageFees = {
[SwapType.Chain]: {
[OrderSide.BUY]: number;
[OrderSide.SELL]: number;
};
[SwapType.Submarine]: number;
[SwapType.ReverseSubmarine]: number;
};
type ReverseMinerFees = {
lockup: number;
claim: number;
};
type MinerFeesForVersion = {
normal: number;
reverse: ReverseMinerFees;
};
type ChainSwapMinerFees = {
server: number;
user: ReverseMinerFees;
};
type MinerFees = {
[SwapVersion.Legacy]: MinerFeesForVersion;
[SwapVersion.Taproot]: MinerFeesForVersion;
};
class FeeProvider {
public static transactionSizes: {
[CurrencyType.BitcoinLike]: TransactionSizes;
[CurrencyType.Liquid]: TransactionSizes;
} = {
[CurrencyType.BitcoinLike]: {
[SwapVersion.Taproot]: {
normalClaim: 151,
reverseLockup: 154,
reverseClaim: 111,
},
[SwapVersion.Legacy]: {
// The claim transaction which spends a nested SegWit swap output and sends it to a P2WPKH address has about 170 vbytes
normalClaim: 170,
// We cannot know what kind of address the user will claim to, so we just assume the worst case: P2PKH
// Claiming a P2WSH to a P2PKH address is about 138 bytes
reverseClaim: 138,
// The lockup transaction which spends a P2WPKH output (possibly more, but we assume a best case scenario here),
// locks up funds in a P2WSH swap and sends the change back to a P2WKH output has about 153 vbytes
reverseLockup: 153,
},
},
[CurrencyType.Liquid]: {
[SwapVersion.Taproot]: {
normalClaim: 1337,
reverseLockup: 2503,
reverseClaim: 1309,
},
[SwapVersion.Legacy]: {
normalClaim: 1333,
reverseLockup: 2503,
reverseClaim: 1378,
},
},
};
// TODO: query those estimations from the provider
public static gasUsage = {
EtherSwap: {
lockup: 46460,
claim: 24924,
refund: 23372,
},
ERC20Swap: {
lockup: 86980,
claim: 24522,
refund: 23724,
},
};
private static readonly defaultFee = 1;
// A map between the symbols of the pairs and their percentage fees
public percentageFees = new Map<string, PercentageFees>();
public minerFees = new Map<string, MinerFees>();
constructor(
private logger: Logger,
private walletManager: WalletManager,
private dataAggregator: DataAggregator,
private getFeeEstimation: (symbol: string) => Promise<Map<string, number>>,
) {}
public init = (pairs: PairConfig[]): void => {
pairs.forEach((pair) => {
const pairId = getPairId(pair);
// Set the configured fee or fallback to 1% if it is not defined
let percentage = pair.fee;
if (percentage === undefined) {
percentage = FeeProvider.defaultFee;
this.logger.warn(
`Setting default fee of ${percentage}% for pair ${pairId} because none was specified`,
);
}
const prepareFee = (fee?: number) => fee || percentage;
this.percentageFees.set(pairId, {
[SwapType.Submarine]: prepareFee(pair.swapInFee),
[SwapType.ReverseSubmarine]: prepareFee(percentage),
[SwapType.Chain]: {
[OrderSide.BUY]: prepareFee(pair.chainSwap?.buyFee),
[OrderSide.SELL]: prepareFee(pair.chainSwap?.sellFee),
},
});
});
this.logger.debug(
`Using fees: ${stringify(
mapToObject(
new Map<string, any>(
Array.from(this.percentageFees.entries()).map(([pair, fees]) => {
const chainFees = fees[SwapType.Chain];
return [
pair,
{
[swapTypeToString(SwapType.Submarine)]:
fees[SwapType.Submarine],
[swapTypeToString(SwapType.ReverseSubmarine)]:
fees[SwapType.ReverseSubmarine],
[swapTypeToString(SwapType.Chain)]: {
buy: chainFees[OrderSide.BUY],
sell: chainFees[OrderSide.SELL],
},
},
];
}),
),
),
)}`,
);
};
public getPercentageFee = (
pair: string,
orderSide: OrderSide,
type: SwapType,
feeType: PercentageFeeType = PercentageFeeType.Calculation,
): number => {
const percentages = this.percentageFees.get(pair);
if (percentages === undefined) {
return 0;
}
const percentageType = percentages[type];
const percentage =
typeof percentageType === 'number'
? percentageType
: percentageType[orderSide];
return feeType === PercentageFeeType.Calculation
? percentage / 100
: percentage;
};
public getFees = (
pair: string,
swapVersion: SwapVersion,
rate: number,
orderSide: OrderSide,
amount: number,
type: SwapType,
feeType: BaseFeeType,
): {
baseFee: number;
percentageFee: number;
} => {
let percentageFee = this.getPercentageFee(
pair,
orderSide,
type,
PercentageFeeType.Calculation,
);
if (percentageFee !== 0) {
percentageFee = percentageFee * amount * rate;
}
const { base, quote } = splitPairId(pair);
const chainCurrency = getChainCurrency(
base,
quote,
orderSide,
type === SwapType.ReverseSubmarine,
);
return {
percentageFee: Math.ceil(percentageFee),
baseFee: this.getBaseFee(chainCurrency, swapVersion, feeType),
};
};
public getBaseFee = (
chainCurrency: string,
swapVersion: SwapVersion,
type: BaseFeeType,
): number => {
const minerFees = this.minerFees.get(chainCurrency)![swapVersion];
switch (type) {
case BaseFeeType.NormalClaim:
return minerFees.normal;
case BaseFeeType.ReverseClaim:
return minerFees.reverse.claim;
case BaseFeeType.ReverseLockup:
return minerFees.reverse.lockup;
}
};
public getSwapBaseFees = <
T extends number | ReverseMinerFees | ChainSwapMinerFees,
>(
pairId: string,
orderSide: OrderSide,
type: SwapType,
version: SwapVersion,
): T => {
const { base, quote } = splitPairId(pairId);
if (type === SwapType.Chain) {
if (version !== SwapVersion.Taproot) {
throw 'Chain Swaps only support version Taproot';
}
const sendingMinerfees = this.minerFees.get(
getSendingChain(base, quote, orderSide),
)![SwapVersion.Taproot];
const receivingMinerFees = this.minerFees.get(
getReceivingChain(base, quote, orderSide),
)![SwapVersion.Taproot];
return {
server: sendingMinerfees.reverse.lockup + receivingMinerFees.normal,
user: {
claim: sendingMinerfees.reverse.claim,
lockup: receivingMinerFees.reverse.lockup,
},
} as ChainSwapMinerFees as T;
} else {
const isReverse = type === SwapType.ReverseSubmarine;
const minerFeesObj = this.minerFees.get(
getChainCurrency(base, quote, orderSide, isReverse),
)![version];
return (isReverse ? minerFeesObj.reverse : minerFeesObj.normal) as T;
}
};
public updateMinerFees = async (chainCurrency: string): Promise<void> => {
const feeMap = await this.getFeeEstimation(chainCurrency);
// TODO: avoid hard coding symbols
switch (chainCurrency) {
case 'BTC':
case 'LTC':
case ElementsClient.symbol: {
const relativeFee = feeMap.get(chainCurrency)!;
const calculateMinerFeesForVersion = (
sizes: TransactionSizesForVersion,
): MinerFeesForVersion => ({
normal: Math.ceil(relativeFee * sizes.normalClaim),
reverse: {
claim: Math.ceil(relativeFee * sizes.reverseClaim),
lockup: Math.ceil(relativeFee * sizes.reverseLockup),
},
});
const sizes =
chainCurrency === ElementsClient.symbol
? FeeProvider.transactionSizes[CurrencyType.Liquid]
: FeeProvider.transactionSizes[CurrencyType.BitcoinLike];
this.minerFees.set(chainCurrency, {
[SwapVersion.Taproot]: calculateMinerFeesForVersion(
sizes[SwapVersion.Taproot],
),
[SwapVersion.Legacy]: calculateMinerFeesForVersion(
sizes[SwapVersion.Legacy],
),
});
break;
}
case Ethereum.symbol:
case Rsk.symbol: {
const relativeFee = feeMap.get(chainCurrency)!;
const claimCost = FeeProvider.calculateEtherGasCost(
relativeFee,
FeeProvider.gasUsage.EtherSwap.claim,
);
const fees = {
normal: claimCost,
reverse: {
claim: claimCost,
lockup: FeeProvider.calculateEtherGasCost(
relativeFee,
FeeProvider.gasUsage.EtherSwap.lockup,
),
},
};
this.minerFees.set(chainCurrency, {
[SwapVersion.Legacy]: fees,
[SwapVersion.Taproot]: fees,
});
break;
}
// If it is not BTC, LTC or ETH, it is an ERC20 token
default: {
const networkSymbol = this.walletManager.ethereumManagers.find(
(manager) => manager.hasSymbol(chainCurrency),
)!.networkDetails.symbol;
const relativeFee = feeMap.get(networkSymbol)!;
const rate = this.dataAggregator.latestRates.get(
getPairId({ base: networkSymbol, quote: chainCurrency }),
)!;
const claimCost = FeeProvider.calculateTokenGasCosts(
rate,
relativeFee,
FeeProvider.gasUsage.ERC20Swap.claim,
);
const fees = {
normal: claimCost,
reverse: {
claim: claimCost,
lockup: FeeProvider.calculateTokenGasCosts(
rate,
relativeFee,
FeeProvider.gasUsage.ERC20Swap.lockup,
),
},
};
this.minerFees.set(chainCurrency, {
[SwapVersion.Legacy]: fees,
[SwapVersion.Taproot]: fees,
});
break;
}
}
};
private static calculateTokenGasCosts = (
rate: number,
gasPrice: number,
gasUsage: number,
) => {
return Math.ceil(
rate * FeeProvider.calculateEtherGasCost(gasPrice, gasUsage),
);
};
private static calculateEtherGasCost = (
gasPrice: number,
gasUsage: number,
) => {
return Number(
(BigInt(Math.round(gasPrice * Number(gweiDecimals))) * BigInt(gasUsage)) /
etherDecimals,
);
};
}
export default FeeProvider;
export {
MinerFees,
PercentageFees,
ReverseMinerFees,
ChainSwapMinerFees,
MinerFeesForVersion,
};