-
Notifications
You must be signed in to change notification settings - Fork 2
/
WBTCUSDTSwap.sol
637 lines (589 loc) · 21.1 KB
/
WBTCUSDTSwap.sol
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
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.7;
import '@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol';
import './abstract/MetalSwapAbstract.sol';
contract WBTCUSDTSwap is MetalSwapAbstract {
using SafeERC20 for ERC20;
constructor(
ERC20 _erc20Asset,
MetalSwapPoolAbstract _poolAsset,
uint256 _nrOfAssetDecimals,
ERC20 _erc20Currency,
MetalSwapPoolAbstract _poolCurrency,
uint256 _nrOfCurrencyDecimals,
IPriceProvider pp,
ERC20 _governanceToken,
address governanceAddr,
address _financialSwapManager
)
MetalSwapAbstract(
_erc20Asset,
_poolAsset,
_nrOfAssetDecimals,
_erc20Currency,
_poolCurrency,
_nrOfCurrencyDecimals,
pp,
_governanceToken,
governanceAddr,
_financialSwapManager
)
{}
function createSwap(
uint256 period,
uint256 targetSize,
uint16 coverX100,
SwapType swapType
)
external
payable
override
nonReentrant
checkSCUnpaused
returns (uint256 swapID)
{
require(
coverX100 >= coverX100Min &&
((swapType == SwapType(0) &&
targetSize >= targetSizeMinAsset) ||
(swapType == SwapType(1) &&
targetSize >= targetSizeMinCurrency)) &&
period >= minTimeSwap,
'Error on createSwap: cannot create the requested swap because period, cover% or targetSize are out of range'
);
require(
verifySwapPermission(targetSize, swapType),
'Error on createSwap: cannot create the requested swap because out of safety margins!'
);
if (swapType == SwapType(0)) {
targetSize = formatAmount(targetSize, assetDecimals, 18);
} else {
targetSize = formatAmount(targetSize, currencyDecimals, 18);
}
(uint256 settlementFee, uint256 periodFee) = FinancialSwapManager(
financialSwapManager
).calcFees(period, targetSize);
uint256 threshold;
uint256 cover = (targetSize * coverX100) / 100;
uint256 currentPrice = getPrice();
if (swapType == SwapType(0)) {
//swapType==SwapType(0) is the swapType WBTC->usd
threshold =
currentPrice +
(currentPrice * (coverX100 - safetyMarginX100)) /
100;
ERC20(erc20Asset).safeTransferFrom(
msg.sender,
address(premiumAddress),
formatAmount(periodFee, 18, assetDecimals)
);
ERC20(erc20Asset).safeTransferFrom(
msg.sender,
address(settlementFeeContainer),
formatAmount(settlementFee, 18, assetDecimals)
);
swapAvgAsset += (targetSize * currentPrice) / PRICE_DECIMALS; //update of the avgSwap value
} else {
//the ELSE refers to the swapType USD->eth
threshold =
currentPrice -
(currentPrice * (coverX100 - safetyMarginX100)) /
100;
ERC20(erc20Currency).safeTransferFrom(
msg.sender,
address(premiumAddress),
formatAmount(periodFee, 18, currencyDecimals)
);
ERC20(erc20Currency).safeTransferFrom(
msg.sender,
address(settlementFeeContainer),
formatAmount(settlementFee, 18, currencyDecimals)
);
swapAvgCurrency += targetSize; //update of the avgSwap value
}
uint256 rewardAmount = getReward(periodFee, swapType);
uint256 executionTime = block.timestamp + period;
swapID = swaps.length;
swaps.push(
Swap(
swapType,
State.Active,
payable(msg.sender),
coverX100,
currentPrice,
targetSize,
threshold,
periodFee,
block.timestamp,
executionTime,
rewardAmount
)
);
lockFunds(swapType, cover, payable(msg.sender));
emit CreatedSwap(
swapID,
msg.sender,
swapType,
threshold,
executionTime,
block.number
);
return swapID;
}
function closeSwap(uint256 swapID)
external
override
nonReentrant
checkSCUnpaused
{
Swap storage swap = swaps[swapID];
require(
swap.holder == msg.sender,
'Error on closeSwap: msg.sender is not swap holder'
);
require(
swap.state == State.Active,
'Error on closeSwap: swap position is not active'
);
uint256 cover = (swap.targetSize * swap.coverX100) / 100;
uint256 currentPrice = getPrice();
require(
((swap.swapType == SwapType(0)) && swap.threshold > currentPrice) ||
((swap.swapType == SwapType(1)) &&
swap.threshold < currentPrice),
'Error on closeSwap: swap in margin call'
);
require(
block.timestamp < swap.executionTime,
'Error on closeSwap: execution time already reached'
);
(uint256 profitCalc, uint256 loss) = calcProfitLoss(
swap.swapType,
currentPrice,
swap.initPrice,
swap.targetSize
);
uint256 penalties = FinancialSwapManager(financialSwapManager)
.calcPenalties(
swap.swapType,
swap.targetSize,
profitCalc,
loss,
cover,
swap.executionTime,
currentPrice
);
require(
cover > penalties,
'Error on closeSwap: penalties are bigger than cover'
);
swap.state = State.Closed;
uint256 rewardPenalties = calcRewardPenalties(
swap.rewardAmount,
swap.initTime,
swap.executionTime
);
require(
swap.rewardAmount >= rewardPenalties,
'Error on closeSwap: error during assign reward'
);
(uint256 profit, uint256 remainingCoverReturn) = payProfit(
swap,
penalties,
currentPrice,
swap.rewardAmount - rewardPenalties
);
uint256 settlementFee = FinancialSwapManager(financialSwapManager)
.getSettlementFee(swap.targetSize);
if (swap.swapType == SwapType(0)) {
settlementFeeContainer.payLiquidationFee(
payable(msg.sender),
formatAmount(settlementFee, 18, assetDecimals),
address(erc20Asset)
);
emit ClosedSwap(
swapID,
swap.holder,
formatAmount(profit, 18, currencyDecimals),
formatAmount(remainingCoverReturn, 18, assetDecimals),
block.timestamp,
currentPrice
);
} else {
settlementFeeContainer.payLiquidationFee(
payable(msg.sender),
formatAmount(settlementFee, 18, currencyDecimals),
address(erc20Currency)
);
emit ClosedSwap(
swapID,
swap.holder,
formatAmount(profit, 18, assetDecimals),
formatAmount(remainingCoverReturn, 18, currencyDecimals),
block.timestamp,
currentPrice
);
}
}
function executeSwap(uint256 swapID)
external
override
nonReentrant
checkSCUnpaused
{
Swap storage swap = swaps[swapID];
require(
swap.state == State.Active,
'Error on executeSwap: swap position is not active'
);
require(
swap.executionTime <= block.timestamp,
'Error on executeSwap: execution time not yet reached'
);
uint256 currentPrice = getPrice();
require(
((swap.swapType == SwapType(0)) && swap.threshold > currentPrice) ||
((swap.swapType == SwapType(1)) &&
swap.threshold < currentPrice),
'Error on executeSwap: swap in margin call'
);
swap.state = State.Executed;
(uint256 profit, uint256 remainingCoverReturn) = payProfit(
swap,
0,
currentPrice,
swap.rewardAmount
);
uint256 settlementFee = FinancialSwapManager(financialSwapManager)
.getSettlementFee(swap.targetSize);
if (swap.swapType == SwapType(0)) {
settlementFeeContainer.payLiquidationFee(
payable(msg.sender),
formatAmount(settlementFee, 18, assetDecimals),
address(erc20Asset)
);
emit ExecutedSwap(
swapID,
swap.holder,
msg.sender,
formatAmount(profit, 18, currencyDecimals),
formatAmount(remainingCoverReturn, 18, assetDecimals),
currentPrice
);
} else {
settlementFeeContainer.payLiquidationFee(
payable(msg.sender),
formatAmount(settlementFee, 18, currencyDecimals),
address(erc20Currency)
);
emit ExecutedSwap(
swapID,
swap.holder,
msg.sender,
formatAmount(profit, 18, assetDecimals),
formatAmount(remainingCoverReturn, 18, currencyDecimals),
currentPrice
);
}
}
function marginCall(uint256 swapID)
external
override
nonReentrant
checkSCUnpaused
{
Swap storage swap = swaps[swapID];
require(
swap.state == State.Active,
'Error on marginCall: swap position is not active'
);
uint256 currentPrice = getPrice();
require(
((swap.swapType == SwapType(0)) && swap.threshold < currentPrice) ||
((swap.swapType == SwapType(1)) &&
swap.threshold > currentPrice),
'Error on marginCall: the swap is not in margin call conditions!'
); //swapType==SwapType(0) is the swapType ETH->usd
uint256 cover = (swap.targetSize * swap.coverX100) / 100;
swap.state = State.Liquidated;
unlockFunds(swap.swapType, cover);
uint256 rewardPenalties = calcRewardPenalties(
swap.rewardAmount,
swap.initTime,
swap.executionTime
);
require(
swap.rewardAmount >= rewardPenalties,
'Error on marginCall: error during assign reward'
);
uint256 rewardToSend = swap.rewardAmount - rewardPenalties;
if (rewardToSend > 0) {
if (
governanceToken.balanceOf(governanceTokenRewardTreasury) >=
rewardToSend
) {
require(
governanceToken.transferFrom(
governanceTokenRewardTreasury,
swap.holder,
rewardToSend
),
'Error on marginCall: failure during XMT reward token transfer'
);
}
}
if (swap.swapType == SwapType(0)) {
swapAvgAsset -= (swap.targetSize * swap.initPrice) / PRICE_DECIMALS;
settlementFeeContainer.payLiquidationFee(
payable(msg.sender),
formatAmount(
FinancialSwapManager(financialSwapManager).getSettlementFee(
swap.targetSize
),
18,
assetDecimals
),
address(erc20Asset)
);
} else {
swapAvgCurrency -= swap.targetSize;
settlementFeeContainer.payLiquidationFee(
payable(msg.sender),
formatAmount(
FinancialSwapManager(financialSwapManager).getSettlementFee(
swap.targetSize
),
18,
currencyDecimals
),
address(erc20Currency)
);
}
emit LiquidatedSwap(swapID, swap.holder, msg.sender, block.timestamp);
}
function addCover(uint256 swapID, uint16 newCoverX100)
external
payable
override
nonReentrant
checkSCUnpaused
{
Swap storage swap = swaps[swapID];
require(
swap.holder == msg.sender,
'Error on addCover: msg.sender is not swap holder'
);
require(
newCoverX100 > swap.coverX100,
'Error on addCover: new cover % too low!'
);
require(
swap.state == State.Active,
'Error on addCover: swap position is not active'
);
uint256 currentPrice = getPrice();
require(
((swap.swapType == SwapType(0)) && swap.threshold > currentPrice) ||
((swap.swapType == SwapType(1)) &&
swap.threshold < currentPrice),
'Error on addCover: swap in margin call'
); //swapType==SwapType(0) is the swapType ETH->usd
uint256 coverToAdd = calcCoverToAdd(
swap.targetSize,
swap.coverX100,
newCoverX100
);
if ((swap.swapType == SwapType(0))) {
//swapType==SwapType(0) is the swapType ETH->usd
erc20Asset.safeTransferFrom(
swap.holder,
address(poolAsset),
formatAmount(coverToAdd, 18, assetDecimals)
);
poolAsset.lock(formatAmount(coverToAdd, 18, assetDecimals));
swap.threshold =
swap.initPrice +
(swap.initPrice * (newCoverX100 - safetyMarginX100)) /
100; //calc and set the new threshold of the swap
} else {
//swapType==SwapType(1) is the swapType USD->eth
erc20Currency.safeTransferFrom(
swap.holder,
address(poolCurrency),
formatAmount(coverToAdd, 18, currencyDecimals)
);
poolCurrency.lock(formatAmount(coverToAdd, 18, currencyDecimals));
swap.threshold =
swap.initPrice -
(swap.initPrice * (newCoverX100 - safetyMarginX100)) /
100; //calc and set the new threshold of the swap
}
swap.coverX100 = newCoverX100;
emit AddedCoverToSwap(
swapID,
msg.sender,
swap.coverX100,
swap.threshold,
block.timestamp
);
}
function payProfit(
Swap memory swap,
uint256 penalties,
uint256 currentPrice,
uint256 rewardAmount
) internal override returns (uint256 profit, uint256 remainingCoverReturn) {
//governance token reward assignment based on the period fees
if (rewardAmount > 0) {
if (
governanceToken.balanceOf(governanceTokenRewardTreasury) >=
rewardAmount
) {
require(
governanceToken.transferFrom(
governanceTokenRewardTreasury,
swap.holder,
rewardAmount
),
'Error on payProfit: failure during XMT reward token transfer'
);
}
}
//profit calculations
profit = 0;
int256 priceDifference = int256(currentPrice) - int256(swap.initPrice);
uint256 cover = (swap.targetSize * swap.coverX100) / 100;
/* eth */
if (swap.swapType == SwapType(0)) {
//swapType==SwapType(0) is the swapType ETH->usd
swapAvgAsset -= (swap.targetSize * swap.initPrice) / PRICE_DECIMALS;
if (priceDifference >= 0) {
uint256 remainingCover = cover -
((swap.targetSize * uint256(priceDifference)) /
currentPrice);
int256 remainingCoverPenalties = int256(remainingCover) -
int256(penalties);
if (remainingCoverPenalties > 0) {
poolAsset.send(
swap.holder,
formatAmount(
uint256(remainingCoverPenalties),
18,
assetDecimals
)
);
unlockFunds(swap.swapType, cover);
return (profit, uint256(remainingCoverPenalties));
} else {
unlockFunds(swap.swapType, cover);
return (profit, 0);
}
} else {
profit =
(uint256(-priceDifference) * swap.targetSize) /
PRICE_DECIMALS;
poolCurrency.sendProfit(
swap.holder,
formatAmount(profit, 18, currencyDecimals)
);
poolAsset.send(
swap.holder,
formatAmount(cover - penalties, 18, assetDecimals)
);
unlockFunds(swap.swapType, cover);
return (profit, uint256(cover - penalties));
}
}
/* usd */
if (swap.swapType == SwapType(1)) {
//swapType==SwapType(1) is the swapType USD->eth
swapAvgCurrency -= swap.targetSize;
if (priceDifference <= 0) {
uint256 remainingCover = cover -
((swap.targetSize * uint256(-priceDifference)) /
swap.initPrice);
int256 remainingCoverPenalties = int256(remainingCover) -
int256(penalties);
if (remainingCoverPenalties > 0) {
poolCurrency.send(
swap.holder,
formatAmount(
uint256(remainingCoverPenalties),
18,
currencyDecimals
)
);
unlockFunds(swap.swapType, cover);
return (profit, uint256(remainingCoverPenalties));
} else {
unlockFunds(swap.swapType, cover);
return (profit, 0);
}
} else {
profit =
(uint256(priceDifference) *
swap.targetSize *
PRICE_DECIMALS) /
(currentPrice * swap.initPrice);
poolAsset.sendProfit(
swap.holder,
formatAmount(profit, 18, assetDecimals)
);
poolCurrency.send(
swap.holder,
formatAmount(cover - penalties, 18, currencyDecimals)
);
unlockFunds(swap.swapType, cover);
return (profit, uint256(cover - penalties));
}
}
}
function lockFunds(
SwapType _swapType,
uint256 _cover,
address payable _swapHolder
) internal override {
if (_swapType == SwapType(0)) {
ERC20(erc20Asset).safeTransferFrom(
_swapHolder,
address(poolAsset),
formatAmount(_cover, 18, assetDecimals)
);
poolAsset.lock(formatAmount(_cover, 18, assetDecimals));
} else {
ERC20(erc20Currency).safeTransferFrom(
_swapHolder,
address(poolCurrency),
formatAmount(_cover, 18, currencyDecimals)
);
poolCurrency.lock(formatAmount(_cover, 18, currencyDecimals));
}
}
function unlockFunds(SwapType _swapType, uint256 _cover) internal override {
if (_swapType == SwapType(0)) {
poolAsset.unlock(formatAmount(_cover, 18, assetDecimals));
} else {
poolCurrency.unlock(formatAmount(_cover, 18, currencyDecimals));
}
}
function setOperatingAllowance() public override onlyGovernance {
erc20Currency.safeApprove(address(poolCurrency), type(uint256).max);
erc20Currency.safeApprove(
address(settlementFeeContainer),
type(uint256).max
);
erc20Currency.safeApprove(address(premiumAddress), type(uint256).max);
erc20Asset.safeApprove(address(poolAsset), type(uint256).max);
erc20Asset.safeApprove(
address(settlementFeeContainer),
type(uint256).max
);
erc20Asset.safeApprove(address(premiumAddress), type(uint256).max);
emit SetOperatingAllowance(
address(poolCurrency),
address(poolAsset),
address(settlementFeeContainer),
premiumAddress
);
}
}