-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathController.sol
595 lines (504 loc) · 18.5 KB
/
Controller.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
// SPDX-License-Identifier: MIT
pragma solidity >=0.4.23 ^0.8.0;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "./utils/ABDKMath64x64.sol";
import "./interfaces/IUniswapV2Router02.sol";
import "./interfaces/IUSDZ.sol";
import "hardhat/console.sol";
// TODO features
// - Admin functions for withdrawing protocol USDZ/xSUSHI
// TODO fixes
// - add nonReentrant
// - remove fees/rates in contructor - setter only for safety
// - check best practices for ABDKMath64x64
// - standardize revert msgs
// - use smaller uints for fees and rates
// - natspec comments for functions
contract Controller is Ownable {
struct Position {
uint256 collateral;
uint256 debt;
uint256 lastInterest;
}
mapping(address => Position) private positions;
// to store protocol and user liquidation fees (in xSUSHI)
mapping(address => uint256) private liquidationFees;
// protocol debt and interest revenue
uint256 public protocolDebt; // in xSUSHI
uint256 public protocolIntRev; // in USDZ
address public usdcAddress;
address public usdzAddress;
address public xSushiAddress;
address public sushiRouterAddress;
address[] public xSushiToUsdcPath;
uint256 public liqFeeProtocol;
uint256 public liqFeeSender;
uint256 public interestRate;
uint256 public borrowThreshold;
uint256 public liqThreshold;
uint256 public constant SCALING_FACTOR = 10000;
int128 public SECONDS_IN_YEAR; // int128 for compound interest math
// ---------------------------------------------------------------------
// EVENTS
// ---------------------------------------------------------------------
event Deposit(address indexed account, uint256 amount);
event Withdraw(address indexed account, uint256 amount);
event Borrow(
address indexed account,
uint256 amountBorrowed,
uint256 totalDebt,
uint256 collateralAmount
);
event Repay(
address indexed account,
uint256 debtRepaid,
uint256 debtRemaining,
uint256 collateralAmount
);
event Liquidation(
address indexed account,
address indexed liquidator,
uint256 collateralLiquidated,
uint256 lastCollateralRatio,
uint256 lastDebtOutstanding,
uint256 protocolDebtCreated // if liquidating at < 100% col rat -> protocol takes on debt
);
// ---------------------------------------------------------------------
// CONSTRUCTOR
// ---------------------------------------------------------------------
constructor(
address _usdzAddress,
address _usdcAddress,
address _xSushiAddress,
address _routerAddress,
address[] memory _swapPath,
uint256 _liqFeeProtocol,
uint256 _liqFeeSender,
uint256 _interestRate,
uint256 _borrowThreshold,
uint256 _liqThreshold
) {
usdzAddress = _usdzAddress;
usdcAddress = _usdcAddress;
xSushiAddress = _xSushiAddress;
sushiRouterAddress = _routerAddress;
// fees and rates use SCALING_FACTOR (default 10 000)
liqFeeProtocol = _liqFeeProtocol;
liqFeeSender = _liqFeeSender;
interestRate = _interestRate;
borrowThreshold = _borrowThreshold;
liqThreshold = _liqThreshold;
// building xSUSHI-USDC SushiSwap pricing path
xSushiToUsdcPath = _swapPath;
// set SECONDS_IN_YEAR for interest calculations
SECONDS_IN_YEAR = ABDKMath64x64.fromUInt(31556952);
// infinite approve Sushi pool for token liquidation swaps
require(
IERC20(xSushiAddress).approve(
address(sushiRouterAddress),
type(uint256).max
),
"xsushi approve failed"
);
}
// ---------------------------------------------------------------------
// PUBLIC STATE-MODIFYING FUNCTIONS
// ---------------------------------------------------------------------
// User deposits xSUSHI as collateral
function deposit(uint256 _amount) public {
// IERC20 xSUSHI = IERC20(xSushiAddress);
require(
IERC20(xSushiAddress).transferFrom(
msg.sender,
address(this),
_amount
),
"deposit failed"
);
// Adding deposited collateral to position
positions[msg.sender].collateral += _amount;
emit Deposit(msg.sender, _amount);
}
// User withdraws xSUSHI collateral if safety ratio stays > 200%
function withdraw(uint256 _amount) public {
Position storage pos = positions[msg.sender];
require(pos.collateral >= _amount, "not enough collateral in account");
uint256 interest_ = calcInterest(msg.sender);
pos.debt += interest_;
pos.lastInterest = block.timestamp;
uint256 colRatio = getCurrentCollateralRatio(msg.sender);
require(
colRatio > borrowThreshold,
"account already below safety ratio"
);
uint256 withdrawable_;
if (pos.debt == 0) {
withdrawable_ = pos.collateral;
} else {
withdrawable_ =
(pos.collateral / colRatio) *
(colRatio - borrowThreshold);
}
require(withdrawable_ >= _amount, "amount unsafe to withdraw");
pos.collateral -= _amount;
require(
IERC20(xSushiAddress).transfer(msg.sender, _amount),
"withdraw transfer failed"
);
emit Withdraw(msg.sender, _amount);
}
// User mints and borrows USDZ against collateral
function borrow(uint256 _amount) public {
require(_amount > 0, "can't borrow 0");
Position storage pos = positions[msg.sender];
uint256 interest_ = calcInterest(msg.sender);
// Check forward col. ratio >= safe col. ratio limit
require(
getForwardCollateralRatio(
msg.sender,
pos.debt + interest_ + _amount
) >= borrowThreshold,
"not enough collateral to borrow that much"
);
// add interest and new debt to position
pos.debt += (_amount + interest_);
pos.lastInterest = block.timestamp;
IUSDZ(usdzAddress).mint(msg.sender, _amount);
emit Borrow(msg.sender, _amount, pos.debt, pos.collateral);
}
// User repays any interest, then debt in USDZ
// Interest revenue is acounted for in protocolIntRev
function repay(uint256 _amount) public {
require(_amount > 0, "can't repay 0");
Position storage pos = positions[msg.sender];
uint256 interestDue = calcInterest(msg.sender);
// account for protocol interest revenue
if (_amount >= interestDue + pos.debt) {
// repays all interest and debt
require(
IUSDZ(usdzAddress).transferFrom(
msg.sender,
address(this),
pos.debt + interestDue
),
"repay transfer failed"
);
protocolIntRev += interestDue;
pos.debt = 0;
} else if (_amount >= interestDue) {
// repays all interest, starts repaying debt
require(
IUSDZ(usdzAddress).transferFrom(
msg.sender,
address(this),
_amount
),
"repay transfer failed"
);
protocolIntRev += _amount;
pos.debt -= (_amount - interestDue);
} else {
// repay partial interest, no debt repayment
require(
IUSDZ(usdzAddress).transferFrom(
msg.sender,
address(this),
_amount
),
"repay transfer failed"
);
protocolIntRev += _amount;
pos.debt += (interestDue - _amount);
}
// restart interest compounding from here
pos.lastInterest = block.timestamp;
emit Repay(msg.sender, _amount, pos.debt, pos.collateral);
}
// Liquidates account if collateral ratio below safety threshold
// Accounts for protocol shortfal as debt (in xSUSHI)
// No protocol interest revenue taken on liquidations,
// as a protocol liquidation fee is taken instead
function liquidate(address _account) public {
Position storage pos = positions[_account];
require(pos.collateral > 0, "account has no collateral");
uint256 interest_ = calcInterest(_account);
uint256 totalCollateral = pos.collateral; //needed for reporting in event
uint256 collateralRatio = getForwardCollateralRatio(
_account,
pos.debt + interest_
);
// Check debt + interest puts account below liquidation col ratio
require(
collateralRatio < liqThreshold,
"account not below liq threshold"
);
// calc fees to protocol and liquidator
uint256 protocolShare = ((pos.collateral * liqFeeProtocol) /
SCALING_FACTOR);
uint256 liquidatorShare = ((pos.collateral * liqFeeSender) /
SCALING_FACTOR);
require(
protocolShare + liquidatorShare <= pos.collateral,
"liq fees incorrectly set"
);
// taking protocol fees in xSUSHI
liquidationFees[address(this)] += protocolShare;
// paying liquidator fees in xSUSHI
liquidationFees[msg.sender] += liquidatorShare;
uint256 amountIn = pos.collateral - (protocolShare + liquidatorShare);
// sell remaining xSUSHI collateral for USDC
IUniswapV2Router02(sushiRouterAddress).swapExactTokensForTokens(
amountIn,
0,
xSushiToUsdcPath,
address(this),
block.timestamp
);
// Accounting for protocol shortfall by taking on debt
pos.collateral = totalCollateral - (protocolShare + liquidatorShare);
uint256 colRatioAfterFees = getForwardCollateralRatio(
_account,
pos.debt + interest_
);
uint256 protocolDebtCreated;
if (colRatioAfterFees < SCALING_FACTOR) {
// if liquidating at col ratio < 100% + fees
protocolDebtCreated =
(SCALING_FACTOR - colRatioAfterFees) *
pos.collateral;
}
protocolDebt += protocolDebtCreated;
emit Liquidation(
_account,
msg.sender,
totalCollateral,
collateralRatio,
pos.debt,
protocolDebtCreated
);
pos.collateral = 0;
pos.debt = 0;
}
// ---------------------------------------------------------------------
// SWAPPER AND CLAIM FUNCTIONS
// ---------------------------------------------------------------------
// Deposit USDC to mint USDZ 1:1
function swapUSDCforUSDZ(uint256 _usdcAmount) public {
require(_usdcAmount > 0, "can't mint zero USDZ");
require(
IERC20(usdcAddress).transferFrom(
msg.sender,
address(this),
_usdcAmount
),
"USDC transfer failed"
);
IUSDZ(usdzAddress).mint(msg.sender, _usdcAmount);
}
// Burn USDZ to withdraw USDC 1:1
// TODO make nonReentrant
function swapUSDZforUSDC(uint256 _usdzAmount) public {
uint256 usdcBalance = IERC20(usdcAddress).balanceOf(address(this));
require(usdcBalance >= _usdzAmount, "USDC reserve too low");
IUSDZ(usdzAddress).burn(msg.sender, _usdzAmount);
IERC20(usdcAddress).transfer(msg.sender, _usdzAmount);
}
function claimLiquidationFees(uint256 _amount) public {
require(
liquidationFees[msg.sender] >= _amount,
"amount higher than balance"
);
liquidationFees[msg.sender] -= _amount;
IERC20(xSushiAddress).transfer(msg.sender, _amount);
}
// ---------------------------------------------------------------------
// PUBLIC VIEW FUNCTIONS
// ---------------------------------------------------------------------
function getPosition(address _account)
public
view
returns (
uint256,
uint256,
uint256,
uint256
)
{
calcInterest(_account);
return (
positions[_account].collateral, // collateral
positions[_account].debt, // debt
calcInterest(_account), // interest
positions[_account].lastInterest // interestCalcStartTime
);
}
function getLiquidationFees(address _account)
public
view
returns (uint256)
{
return liquidationFees[_account];
}
// Returns account's current col rat incl. index
// Returns true if account is liquidatable
function isLiquidatable(address _account)
public
view
returns (uint256, bool)
{
uint256 colRat;
uint256 debt;
uint256 interest;
(, debt, interest, ) = getPosition(_account);
colRat = getForwardCollateralRatio(_account, debt + interest);
return (colRat, colRat < liqThreshold);
}
// ---------------------------------------------------------------------
// HELPER FUNCTIONS
// ---------------------------------------------------------------------
// Calculates forward collateral ratio of an account, using custom debt amount
function getForwardCollateralRatio(address _account, uint256 _totalDebt)
public
view
returns (uint256)
{
return _getCollateralRatio(_account, _totalDebt);
}
// Calculates current collateral ratio of an account.
// NOTE: EXCLUDES INTEREST
function getCurrentCollateralRatio(address _account)
public
view
returns (uint256)
{
return _getCollateralRatio(_account, positions[_account].debt);
}
// Internal getColRatio logic
// Assumes totalDebt is in USDZ, and 1 USDZ = 1 USDC, and collateral is in xSUSHI
function _getCollateralRatio(address _account, uint256 _totalDebt)
internal
view
returns (uint256)
{
uint256 collateral_ = positions[_account].collateral;
if (collateral_ == 0) {
// if collateral is 0, col ratio is 0 and no borrowing possible
return 0;
} else if (_totalDebt == 0) {
// if debt is 0, col ratio is infinite
return type(uint256).max;
}
IUniswapV2Router02 router = IUniswapV2Router02(sushiRouterAddress);
uint256 collateralValue_ = router.getAmountsOut(
collateral_,
xSushiToUsdcPath
)[2];
// col. ratio = collateral USDC value / debt USDC value
// E.g. 2:1 will return 20 000 (20 000/10 000=2) for 200%
return (collateralValue_ * SCALING_FACTOR) / (_totalDebt);
}
// Calculates interest on position of given address
// WARNING: contains fancy math
function calcInterest(address _account)
public
view
returns (uint256 interest)
{
if (
positions[_account].debt == 0 ||
positions[_account].lastInterest == 0 ||
interestRate == 0 ||
block.timestamp == positions[_account].lastInterest
) {
return 0;
}
uint256 secondsSinceLastInterest_ = block.timestamp -
positions[_account].lastInterest;
int128 yearsBorrowed_ = ABDKMath64x64.div(
ABDKMath64x64.fromUInt(secondsSinceLastInterest_),
SECONDS_IN_YEAR
);
int128 interestRate_ = ABDKMath64x64.div(
ABDKMath64x64.fromUInt(interestRate),
ABDKMath64x64.fromUInt(SCALING_FACTOR)
);
int128 debt_ = ABDKMath64x64.fromUInt(positions[_account].debt);
// continous compound interest = P*e^(i*t)
// this figure includes principal + interest
uint64 interest_ = ABDKMath64x64.toUInt(
ABDKMath64x64.mul(
debt_,
ABDKMath64x64.exp(
ABDKMath64x64.mul(interestRate_, yearsBorrowed_)
)
)
);
// returns only the interest, not the principal
return uint256(interest_) - positions[_account].debt;
}
// ---------------------------------------------------------------------
// ONLY OWNER FUNCTIONS
// ---------------------------------------------------------------------
function setFeesAndRates(
uint256 _liqFeeProtocol,
uint256 _liqFeeSender,
uint256 _interestRate
) external onlyOwner {
// Liquidation fees
require(
_liqFeeProtocol + _liqFeeSender <= SCALING_FACTOR,
"liq fees out of range"
);
liqFeeProtocol = _liqFeeProtocol;
liqFeeSender = _liqFeeSender;
// Interest rates - capped at 100% APR
require(_interestRate <= SCALING_FACTOR, "interestRate out of range");
interestRate = _interestRate;
}
function setThresholds(uint256 _borrowThreshold, uint256 _liqThreshold)
external
onlyOwner
{
// both thresholds should be > scaling factor
// e.g. 20 000 / 10 000 = 200%
require(
_borrowThreshold >= SCALING_FACTOR,
"borrow threshold must be > scaling factor"
);
require(
_liqThreshold >= SCALING_FACTOR,
"liq threshold must be > scaling factor"
);
borrowThreshold = _borrowThreshold;
liqThreshold = _liqThreshold;
}
function setTokenAddresses(
address _usdz,
address _usdc,
address _xsushi
) external onlyOwner {
require(
_usdz != address(0) && _usdc != address(0) && _xsushi != address(0),
"zero address not allowed"
);
usdzAddress = _usdz;
usdcAddress = _usdc;
xSushiAddress = _xsushi;
}
// Sets any SushiSwap protocol contract addresses
function setSushiAddresses(address _sushiRouter) external onlyOwner {
require(_sushiRouter != address(0), "zero address not allowed");
sushiRouterAddress = _sushiRouter;
}
}
contract TestController is Controller {
function echindna_testpass() public view returns (bool) {
return true;
}
}
contract TestController is Controller {
function echindna_testpass() public view returns (bool) {
return true;
}
}