-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathNumaVault.sol
1321 lines (1150 loc) · 42.3 KB
/
NumaVault.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
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//SPDX-License-Identifier: MIT
pragma solidity 0.8.20;
import "@openzeppelin/contracts_5.0.2/access/Ownable2Step.sol";
import {ReentrancyGuard} from "@openzeppelin/contracts_5.0.2/utils/ReentrancyGuard.sol";
import "@openzeppelin/contracts_5.0.2/utils/Pausable.sol";
import "@openzeppelin/contracts_5.0.2/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts_5.0.2/utils/structs/EnumerableSet.sol";
import "@uniswap/v3-core/contracts/libraries/FullMath.sol";
import "../Numa.sol";
import "../interfaces/IVaultOracleSingle.sol";
import "../interfaces/IVaultManager.sol";
import "../interfaces/INumaVault.sol";
import "./NumaMinter.sol";
import "../lending/CNumaToken.sol";
import "@openzeppelin/contracts_5.0.2/utils/structs/EnumerableSet.sol";
import "../utils/constants.sol";
/// @title Numa vault to mint/burn Numa to lst token
contract NumaVault is Ownable2Step, ReentrancyGuard, Pausable, INumaVault {
using EnumerableSet for EnumerableSet.AddressSet;
// address that receives fees
address payable private fee_address;
// address that receives REWARDS (extracted from lst token rebase)
address payable private rwd_address;
bool private isFeeReceiver;
bool private isRwdReceiver;
// fee that is sent to fee_address
// percentage of buy/sell fee in base 1000
uint16 public fees = 200; //20%
// amount percentage limit sent to fee_address
uint16 public feesMaxAmountPct = 50; //5%
mapping(address => bool) feeWhitelisted;
uint16 public max_percent = 100; //10%
// threshold for reward extraction
uint public rwd_threshold = 0;
//
NUMA public immutable numa;
NumaMinter public immutable minterContract;
IERC20 public immutable lstToken;
IVaultOracleSingle public oracle;
IVaultManager public vaultManager;
// reward extraction variables
uint256 public last_extracttimestamp;
uint256 public last_lsttokenvalueWei;
// constants
// minimum input amount for buy/sell
uint256 public constant MIN = 1000;
// decimals of lst token
uint256 public immutable decimals;
bool isWithdrawRevoked = false;
// lending parameters
uint public maxBorrow;
uint public cf_liquid_warning = 2000; // 200%
uint debt;
uint public rewardsFromDebt;
uint maxLstProfitForLiquidations;
bool buyPaused = false;
bool isLiquidityLocked;
uint lstLockedBalance;
uint lstLockedBalanceRaw;
CNumaToken public cLstToken;
CNumaToken public cNuma;
uint leverageDebt;
// for reth borrowers only
uint public minBorrowAmountAllowPartialLiquidation = 10 ether;
// Events
event SetOracle(address oracle);
event SetVaultManager(address vaultManager);
event Buy(uint256 received, uint256 sent, address receiver);
event Sell(uint256 sent, uint256 received, address receiver);
event Fee(uint256 fee, address feeReceiver);
event FeeUpdated(uint16 Fee, uint16 MaxPctAmount);
event MaxPercentUpdated(uint16 NewValue);
event ThresholdUpdated(uint256 newThreshold);
event FeeAddressUpdated(address feeAddress);
event RwdAddressUpdated(address rwdAddress);
event AddedToRemovedSupply(address _address);
event RemovedFromRemoveSupply(address _address);
event RewardsExtracted(uint _rwd, uint _currentvalueWei);
event RewardsDebtExtracted(uint _rwd);
event SetCTokens(address cNuma, address crEth);
event SetMaxBorrow(uint _maxBorrow);
event BorrowedVault(uint _amount);
event RepaidVault(uint _amount);
event SetMaxProfit(uint _maxProfit);
event SetCFLiquidWarning(uint _cfLiquidWarning);
event Whitelisted(address _addy, bool _wl);
// AUDITV2FIX: added in liquidation functions
modifier notBorrower(address _borrower) {
require(msg.sender != _borrower, "cant liquidate your own position");
_;
}
constructor(
address _numaAddress,
address _tokenAddress,
uint256 _decimals,
address _oracleAddress,
address _minterAddress,
uint _existingDebt, // in case of migration
uint _existingRwdFromDebt // in case of migration
) Ownable(msg.sender) {
minterContract = NumaMinter(_minterAddress);
numa = NUMA(_numaAddress);
oracle = IVaultOracleSingle(_oracleAddress);
lstToken = IERC20(_tokenAddress);
decimals = _decimals;
// lst rewards
last_extracttimestamp = block.timestamp;
last_lsttokenvalueWei = oracle.getTokenPrice(decimals);
// debt for migration
debt = _existingDebt;
rewardsFromDebt = _existingRwdFromDebt;
// paused by default because might be empty
_pause();
}
/**
* @dev pause vault
*/
function pause() external onlyOwner {
_pause();
}
/**
* @dev unpause vault
*/
function unpause() external onlyOwner {
_unpause();
}
// buys can be paused if we want to force people to buy from other vaults
/**
* @dev unpause buying and selling from vault
*/
function pauseBuy(bool _buyPaused) external onlyOwner {
buyPaused = _buyPaused;
}
/**
* @dev adds an address as fee whitelisted
*/
function setFeeWhitelist(
address _addy,
bool _whitelisted
) external onlyOwner {
feeWhitelisted[_addy] = _whitelisted;
emit Whitelisted(_addy, _whitelisted);
}
/**
* @dev minimum reth borrow balance needed to allow partial liquidations
*/
function setMinBorrowAmountAllowPartialLiquidation(
uint _minBorrowAmountAllowPartialLiquidation
) external onlyOwner {
minBorrowAmountAllowPartialLiquidation = _minBorrowAmountAllowPartialLiquidation;
}
/**
* @dev set the IVaultOracle address (used to compute token price in Eth)
*/
function setCTokens(address _cNuma, address _clstToken) external onlyOwner {
cNuma = CNumaToken(_cNuma);
cLstToken = CNumaToken(_clstToken);
emit SetCTokens(_cNuma, _clstToken);
}
function getcNumaAddress() external view returns (address) {
return address(cNuma);
}
function getcLstAddress() external view returns (address) {
return address(cLstToken);
}
/**
* @dev set the cf_liquid_warning
*/
function setCFLiquidWarning(uint _cFLiquidWarning) external onlyOwner {
// CF will change so we need to update interest rates
updateVault();
cf_liquid_warning = _cFLiquidWarning;
emit SetCFLiquidWarning(_cFLiquidWarning);
}
/**
* @dev set the max borrow amount from vault
*/
function setMaxBorrow(uint _maxBorrow) external onlyOwner {
// CF will change so we need to update interest rates
updateVault();
maxBorrow = _maxBorrow;
emit SetMaxBorrow(_maxBorrow);
}
/**
* @dev max profit (in reth) for liquidators
*/
function setMaxLiquidationsProfit(uint _maxProfit) external onlyOwner {
maxLstProfitForLiquidations = _maxProfit;
emit SetMaxProfit(_maxProfit);
}
/**
* @dev set the IVaultOracle address (used to compute token price in Eth)
*/
function setOracle(address _oracle) external onlyOwner {
require(_oracle != address(0x0), "zero address");
oracle = IVaultOracleSingle(_oracle);
emit SetOracle(address(_oracle));
}
/**
* @dev set the IVaultManager address (used to total Eth balance of all vaults)
*/
function setVaultManager(address _vaultManager) external onlyOwner {
require(_vaultManager != address(0x0), "zero address");
vaultManager = IVaultManager(_vaultManager);
// vault have to be registered before
require(vaultManager.isVault(address(this)), "not a registered vault");
emit SetVaultManager(_vaultManager);
}
/**
* @dev Set Rwd address
*/
function setRwdAddress(
address _address,
bool _isRwdReceiver
) external onlyOwner {
rwd_address = payable(_address);
isRwdReceiver = _isRwdReceiver;
emit RwdAddressUpdated(_address);
}
/**
* @dev Set Fee address
*/
function setFeeAddress(
address _address,
bool _isFeeReceiver
) external onlyOwner {
fee_address = payable(_address);
isFeeReceiver = _isFeeReceiver;
emit FeeAddressUpdated(_address);
}
/**
* @dev Set Fee percentage (exemple: 1% fee --> fee = 10)
*/
function setFee(uint16 _fees, uint16 _feesMaxAmountPct) external onlyOwner {
require(_fees <= BASE_1000, "above 1000");
require(_feesMaxAmountPct <= BASE_1000, "above 1000");
fees = _fees;
feesMaxAmountPct = _feesMaxAmountPct;
emit FeeUpdated(_fees, _feesMaxAmountPct);
}
/**
* @dev max buy amount in percentage of vault's balance
*/
function setMaxPercent(uint16 _maxPercent) external onlyOwner {
require(max_percent <= BASE_1000, "Percent above 100");
max_percent = _maxPercent;
emit MaxPercentUpdated(_maxPercent);
}
/**
* @dev Set rewards threshold
*/
function setRewardsThreshold(uint256 _threshold) external onlyOwner {
rwd_threshold = _threshold;
emit ThresholdUpdated(_threshold);
}
/**
* @dev vault balance including debt from lending protocol
*/
function getVaultBalance() internal view returns (uint) {
if (isLiquidityLocked) {
return lstLockedBalance;
} else {
uint balance = lstToken.balanceOf(address(this));
balance += (debt - rewardsFromDebt); // debt is owned by us but rewards will be sent so not ours anymore
return balance;
}
}
/**
* @dev vault balance excluding debt from lending protocol
*/
function getVaultBalanceNoDebt() internal view returns (uint) {
if (isLiquidityLocked) {
return lstLockedBalanceRaw;
} else {
return lstToken.balanceOf(address(this));
}
}
/**
* @dev returns the estimated rewards value of lst token
*/
function rewardsValue() public view returns (uint256, uint256, uint256) {
require(address(oracle) != address(0), "oracle not set");
uint currentvalueWei = oracle.getTokenPrice(decimals);
if (currentvalueWei <= last_lsttokenvalueWei) {
return (0, currentvalueWei, 0);
}
uint diff = (currentvalueWei - last_lsttokenvalueWei);
uint balance = getVaultBalanceNoDebt();
uint rwd = FullMath.mulDiv(balance, diff, currentvalueWei);
// extract from debt. Substract rewardsFromDebt as it's not supposed to be in the vault anymore
uint debtRwd = FullMath.mulDiv(
(debt - rewardsFromDebt),
diff,
currentvalueWei
);
return (rwd, currentvalueWei, debtRwd);
}
/**
* @dev lst rewards extraction
*/
function extractInternal(
uint rwd,
uint currentvalueWei,
uint rwdDebt
) internal {
last_extracttimestamp = block.timestamp;
last_lsttokenvalueWei = currentvalueWei;
// rewards from debt are not sent, they are accumulated to be sent when there's a repay
rewardsFromDebt += rwdDebt;
if (rwd_address != address(0)) {
SafeERC20.safeTransfer(IERC20(lstToken), rwd_address, rwd);
if (isContract(rwd_address) && isRwdReceiver) {
// we don't check result as contract might not implement the deposit function (if multi sig for example)
rwd_address.call(
abi.encodeWithSignature("DepositFromVault(uint256)", rwd)
);
}
}
emit RewardsExtracted(rwd, currentvalueWei);
}
/**
* @dev transfers rewards to rwd_address and updates reference price
* @notice no require as it will be called from buy/sell function and we only want to skip this step if
* conditions are not filled
*/
function extractRewardsNoRequire() internal {
if (block.timestamp >= (last_extracttimestamp + 24 hours)) {
(
uint256 rwd,
uint256 currentvalueWei,
uint256 rwdDebt
) = rewardsValue();
if (rwd > rwd_threshold) {
extractInternal(rwd, currentvalueWei, rwdDebt);
}
}
}
/**
* @dev vaults' balance in Eth including debt
*/
function getEthBalance() external view returns (uint256) {
require(address(oracle) != address(0), "oracle not set");
uint balanceLst = getVaultBalance();
// we use last reference value for balance computation
uint resultEth = FullMath.mulDiv(
last_lsttokenvalueWei,
balanceLst,
decimals
);
return resultEth;
}
/**
* @dev vaults' balance in Eth excluding debt
*/
function getEthBalanceNoDebt() public view returns (uint256) {
require(address(oracle) != address(0), "oracle not set");
uint balanceLst = getVaultBalanceNoDebt();
// we use last reference value for balance computation
uint resultEth = FullMath.mulDiv(
last_lsttokenvalueWei,
balanceLst,
decimals
);
return resultEth;
}
/**
* @dev Buy numa from token (token approval needed)
*/
function buy(
uint _inputAmount,
uint _minNumaAmount,
address _receiver
) external whenNotPaused returns (uint _numaOut) {
// CF will change so we need to update interest rates
// Note that we call that function from vault and not vaultManager, because in multi vault case, we don't need to accrue interest on
// other vaults as we use a "local CF"
// rEth balance will change so we need to update debasing factors
(
,
uint criticalScaleForNumaPriceAndSellFee,
) = updateVaultAndUpdateDebasing();
uint256 vaultsBalance = getVaultBalance();
uint256 MAX = (max_percent * vaultsBalance) / BASE_1000;
require(_inputAmount <= MAX, "must trade under max");
_numaOut = buyNoMax(
_inputAmount,
_minNumaAmount,
_receiver,
criticalScaleForNumaPriceAndSellFee,
true
);
}
/**
* @dev Buy numa from token (token approval needed), no max check
*/
function buyNoMax(
uint _inputAmount,
uint _minNumaAmount,
address _receiver,
uint _criticalScaleForNumaPriceAndSellFee,
bool _transferREth
) internal nonReentrant whenNotPaused returns (uint _numaOut) {
// SAME CODE AS buy() but no max amount (used for liquidations)
// buys can be paused if we want to force people to buy from other vaults
require(!buyPaused, "buy paused");
require(_inputAmount > MIN, "must trade over min");
// execute buy
uint256 numaAmount = vaultManager.tokenToNuma(
_inputAmount,
last_lsttokenvalueWei,
decimals,
_criticalScaleForNumaPriceAndSellFee
);
require(numaAmount > 0, "amount of numa is <= 0");
if (_transferREth) {
SafeERC20.safeTransferFrom(
lstToken,
msg.sender,
address(this),
_inputAmount
);
}
uint fee = vaultManager.getBuyFee();
if (feeWhitelisted[msg.sender]) {
fee = 1 ether; // max percent (= no fee)
}
_numaOut = (numaAmount * fee) / 1 ether;
require(_numaOut >= _minNumaAmount, "Min NUMA");
// mint numa
minterContract.mint(_receiver, _numaOut);
emit Buy(_numaOut, _inputAmount, _receiver);
// fee
if (fee_address != address(0x0)) {
// fee to be transfered is a percentage of buy/sell fee
uint feeTransferNum = uint(fees) * (1 ether - fee);
uint feeTransferDen = uint(BASE_1000) * 1 ether;
uint256 feeAmount = (feeTransferNum * _inputAmount) /
(feeTransferDen);
// clip sent fees
uint256 feeAmountMax = (feesMaxAmountPct * _inputAmount) /
BASE_1000;
if (feeAmount > feeAmountMax) feeAmount = feeAmountMax;
SafeERC20.safeTransfer(lstToken, fee_address, feeAmount);
if (isContract(fee_address) && isFeeReceiver) {
// we don't check result as contract might not implement the deposit function (if multi sig for example)
fee_address.call(
abi.encodeWithSignature(
"DepositFromVault(uint256)",
feeAmount
)
);
}
emit Fee(feeAmount, fee_address);
}
vaultManager.updateBuyFeePID(numaAmount, true);
}
/**
* @dev extract rewards and accruInterests on lst ctoken
*/
function updateVault() public {
// extract rewards if any
extractRewardsNoRequire();
// accrue interest
if (address(cLstToken) != address(0)) cLstToken.accrueInterest();
}
/**
* @dev update vault and debasings (synth scaling, sell fee pid, scale applied in numa price when critical_cf is reached)
*/
function updateVaultAndUpdateDebasing()
public
returns (
uint scale,
uint criticalScaleForNumaPriceAndSellFee,
uint sell_fee_result
)
{
// accrue interest
updateVault();
// update scaling and sell_fee
(
scale,
criticalScaleForNumaPriceAndSellFee,
sell_fee_result
) = vaultManager.updateDebasings();
}
/**
* @dev Sell numa (burn) to token (numa approval needed)
*/
function sell(
uint256 _numaAmount,
uint256 _minTokenAmount,
address _receiver
) external nonReentrant whenNotPaused returns (uint _tokenOut) {
require(_numaAmount > MIN, "must trade over min");
// CF will change so we need to update interest rates
// Note that we call that function from vault and not vaultManager, because in multi vault case, we don't need to accrue interest on
// other vaults as we use a "local CF"
// rEth balance will change so we need to update debasing factors
(
,
uint criticalScaleForNumaPriceAndSellFee,
uint fee
) = updateVaultAndUpdateDebasing();
// execute sell
// Total Eth to be sent
uint256 tokenAmount = vaultManager.numaToToken(
_numaAmount,
last_lsttokenvalueWei,
decimals,
criticalScaleForNumaPriceAndSellFee
);
require(tokenAmount > 0, "amount of token is <=0");
require(
lstToken.balanceOf(address(this)) >= tokenAmount,
"not enough liquidity in vault"
);
if (feeWhitelisted[msg.sender]) {
fee = 1 ether;
}
_tokenOut = (tokenAmount * fee) / 1 ether;
require(_tokenOut >= _minTokenAmount, "Min Token");
// burning numa tokens
if (msg.sender != address(this)) {
numa.burnFrom(msg.sender, _numaAmount);
} else {
numa.burn(_numaAmount);
}
// don't transfer to ourselves
if (msg.sender != address(this)) {
// transfer lst tokens to receiver
SafeERC20.safeTransfer(lstToken, _receiver, _tokenOut);
}
emit Sell(_numaAmount, _tokenOut, _receiver);
// fee
if (fee_address != address(0x0)) {
// fee to be transfered is a percentage of buy/sell fee
uint feeTransferNum = fees * (1 ether - fee);
uint feeTransferDen = uint(BASE_1000) * 1 ether;
uint256 feeAmount = (feeTransferNum * tokenAmount) /
(feeTransferDen);
// clip sent fees
uint256 feeAmountMax = (feesMaxAmountPct * tokenAmount) / BASE_1000;
if (feeAmount > feeAmountMax) feeAmount = feeAmountMax;
SafeERC20.safeTransfer(IERC20(lstToken), fee_address, feeAmount);
if (isContract(fee_address) && isFeeReceiver) {
// we don't check result as contract might not implement the deposit function (if multi sig for example)
fee_address.call(
abi.encodeWithSignature(
"DepositFromVault(uint256)",
feeAmount
)
);
}
emit Fee(feeAmount, fee_address);
}
vaultManager.updateBuyFeePID(_numaAmount, false);
}
/**
* @dev Estimate number of tokens needed to get an amount of numa
* no need to simulate rwd extraction as extractrewards is called when borrowing from vault
*/
function getBuyNumaAmountIn(uint256 _amount) public view returns (uint256) {
// how many numa from 1 lstToken
(, , uint criticalScaleForNumaPriceAndSellFee, ) = vaultManager
.getSynthScaling();
uint256 numaAmount = vaultManager.tokenToNuma(
decimals,
last_lsttokenvalueWei,
decimals,
criticalScaleForNumaPriceAndSellFee
);
numaAmount = (numaAmount * vaultManager.getBuyFee()) / 1 ether;
// using 1 ether here because numa token has 18 decimals
uint result = FullMath.mulDivRoundingUp(_amount, 1 ether, numaAmount);
return result;
}
/**
* @dev Estimate number of numas needed to get an amount of token
* no need to simulate rwd extraction as extractrewards is called when borrowing from vault
*/
function getSellNumaAmountIn(
uint256 _amount
) public view returns (uint256) {
(, , uint criticalScaleForNumaPriceAndSellFee, ) = vaultManager
.getSynthScaling();
// how many tokens for 1 numa
// using 1 ether here because numa token has 18 decimals
uint256 tokenAmount = vaultManager.numaToToken(
1 ether,
last_lsttokenvalueWei,
decimals,
criticalScaleForNumaPriceAndSellFee
);
(uint sellFee, , ) = vaultManager.getSellFeeScaling();
tokenAmount = (tokenAmount * sellFee) / 1 ether;
uint result = FullMath.mulDivRoundingUp(_amount, decimals, tokenAmount);
return result;
}
/**
* @dev Estimate number of Numas from an amount of token with extraction simulation
*/
function lstToNuma(uint256 _amount) external view returns (uint256) {
(, , uint criticalScaleForNumaPriceAndSellFee, ) = vaultManager
.getSynthScaling();
uint256 refValue = last_lsttokenvalueWei;
(uint256 rwd, uint256 currentvalueWei, ) = rewardsValue();
if (rwd > rwd_threshold) {
refValue = currentvalueWei;
}
uint256 numaAmount = vaultManager.tokenToNuma(
_amount,
refValue,
decimals,
criticalScaleForNumaPriceAndSellFee
);
return (numaAmount * vaultManager.getBuyFee()) / 1 ether;
}
/**
* @dev Estimate number of tokens from an amount of numa with extraction simulation
*/
function numaToLst(uint256 _amount) external view returns (uint256) {
(, , uint criticalScaleForNumaPriceAndSellFee, ) = vaultManager
.getSynthScaling();
uint256 refValue = last_lsttokenvalueWei;
(uint256 rwd, uint256 currentvalueWei, ) = rewardsValue();
if (rwd > rwd_threshold) {
refValue = currentvalueWei;
}
uint256 tokenAmount = vaultManager.numaToToken(
_amount,
refValue,
decimals,
criticalScaleForNumaPriceAndSellFee
);
(uint sellFee, , ) = vaultManager.getSellFeeScaling();
return (tokenAmount * sellFee) / 1 ether;
}
/**
* @dev max borrowable amount from vault, will also impact utilization rate of lending protocol
*/
function getMaxBorrow() public view returns (uint256) {
uint synthValueInEth = vaultManager.getTotalSynthValueEth();
// single vault balance
uint EthBalance = getEthBalanceNoDebt();
uint synthValueWithCF = FullMath.mulDiv(
synthValueInEth,
cf_liquid_warning,
BASE_1000
);
if (EthBalance < synthValueWithCF) return 0;
else {
uint resultEth = EthBalance - synthValueWithCF;
uint resultToken = FullMath.mulDiv(
resultEth,
decimals,
last_lsttokenvalueWei
);
// clamp it with our parameter
uint maxBorrowLeft = 0;
if (maxBorrow > debt)
maxBorrowLeft = maxBorrow - debt;
if (resultToken > maxBorrowLeft) resultToken = maxBorrowLeft;
return resultToken;
}
}
/**
* @dev lending protocol debt
*/
function getDebt() external view returns (uint) {
return debt;
}
/**
* @dev repay from lending protocol
*/
function repay(uint _amount) external {
require(msg.sender == address(cLstToken));
require(_amount > 0, "amount <= 0");
require(_amount <= debt, "repay more than debt");
updateVaultAndUpdateDebasing();
// repay
SafeERC20.safeTransferFrom(
lstToken,
msg.sender,
address(this),
_amount
);
// we will use some repaid amount as rewards from our accumulated virtual rewards from debt
uint extractedRwdFromDebt = FullMath.mulDiv(
rewardsFromDebt,
_amount,
debt
);
if ((extractedRwdFromDebt > 0) && (rwd_address != address(0))) {
rewardsFromDebt -= extractedRwdFromDebt;
SafeERC20.safeTransfer(
IERC20(lstToken),
rwd_address,
extractedRwdFromDebt
);
if (isContract(rwd_address) && isRwdReceiver) {
// we don't check result as contract might not implement the deposit function (if multi sig for example)
rwd_address.call(
abi.encodeWithSignature(
"DepositFromVault(uint256)",
extractedRwdFromDebt
)
);
}
emit RewardsDebtExtracted(extractedRwdFromDebt);
}
debt = debt - _amount;
emit RepaidVault(_amount);
}
/**
* @dev borrow from lending protocol
*/
function borrow(uint _amount) external {
require(msg.sender == address(cLstToken));
updateVaultAndUpdateDebasing();
uint maxAmount = getMaxBorrow();
require(_amount <= maxAmount, "max borrow");
debt = debt + _amount;
SafeERC20.safeTransfer(lstToken, msg.sender, _amount);
emit BorrowedVault(_amount);
}
/**
* @notice locks numa supply so that price stays the same during a flashloan
* @param _lock true or false
*/
function lockNumaSupply(bool _lock) internal {
vaultManager.lockSupplyFlashloan(_lock);
}
/**
* @notice locks lst balance so that price stays the same during a flashloan
* @param _lock true or false
*/
function lockLstBalance(bool _lock) internal {
if (_lock) {
lstLockedBalance = getVaultBalance();
lstLockedBalanceRaw = getVaultBalanceNoDebt();
}
isLiquidityLocked = _lock;
}
function startLiquidation()
internal
returns (uint criticalScaleForNumaPriceAndSellFee)
{
(
,
criticalScaleForNumaPriceAndSellFee,
) = updateVaultAndUpdateDebasing();
// lock numa supply
lockNumaSupply(true);
// lock lst balance for pricing
lockLstBalance(true);
}
function endLiquidation() internal {
// unlock numa supply
lockNumaSupply(false);
// unlock use real balance for price
lockLstBalance(false);
}
/**
* @notice bad debt liquidation
* @param _borrower borrower address
* @param _percentagePosition1000 prcentage of position to be liquidated
* @param collateralToken collateral token
*/
function liquidateBadDebt(
address _borrower,
uint _percentagePosition1000,
CNumaToken collateralToken
) external whenNotPaused notBorrower(_borrower) {
require(
(_percentagePosition1000 > 0 && _percentagePosition1000 <= 1000),
"percentage"
);
require(
(address(collateralToken) == address(cNuma)) ||
(address(collateralToken) == address(cLstToken)),
"bad token"
);
startLiquidation();
IERC20 underlyingCollateral;
IERC20 underlyingBorrow;
CNumaToken borrowToken;
if (address(collateralToken) == address(cLstToken)) {
underlyingCollateral = IERC20(lstToken);
underlyingBorrow = IERC20(address(numa));
borrowToken = cNuma;
} else {
underlyingCollateral = IERC20(address(numa));
underlyingBorrow = IERC20(lstToken);
borrowToken = cLstToken;
}
// AUDITV2FIX using borrowBalanceCurrent to get an up to date debt
//uint borrowAmountFull = borrowToken.borrowBalanceStored(_borrower);
uint borrowAmountFull = borrowToken.borrowBalanceCurrent(_borrower);
require(borrowAmountFull > 0, "no borrow");
uint repayAmount = (borrowAmountFull * _percentagePosition1000) / 1000;
// user supplied funds
SafeERC20.safeTransferFrom(
underlyingBorrow,
msg.sender,
address(this),
repayAmount
);
// liquidate
underlyingBorrow.approve(address(borrowToken), repayAmount);
borrowToken.liquidateBadDebt(
_borrower,
repayAmount,
_percentagePosition1000,
CTokenInterface(address(collateralToken))
);
// redeem
uint balcToken = IERC20(address(collateralToken)).balanceOf(
address(this)
);
uint balBefore = IERC20(underlyingCollateral).balanceOf(address(this));
collateralToken.redeem(balcToken);
uint balAfter = IERC20(underlyingCollateral).balanceOf(address(this));
uint received = balAfter - balBefore;
// send to liquidator
SafeERC20.safeTransfer(
IERC20(address(underlyingCollateral)),
msg.sender,
received
);
endLiquidation();
}
/**
* @notice numa borrower liquidation
* @param _borrower borrower address
* @param _numaAmount amount to use for liquidation
* @param _swapToInput boolean, do we swap seized tokens to numa
* @param _flashloan boolean do we use a flashloan or do we provide the liquidity
*/
function liquidateNumaBorrower(
address _borrower,
uint _numaAmount,
bool _swapToInput,
bool _flashloan
) external whenNotPaused notBorrower(_borrower) {
// if using flashloan, you have to swap collateral seized to repay flashloan
require(
((_flashloan && _swapToInput) || (!_flashloan)),
"invalid param"
);
uint criticalScaleForNumaPriceAndSellFee = startLiquidation();
uint numaAmount = _numaAmount;
// minimum liquidation amount
uint borrowAmount = cNuma.borrowBalanceCurrent(_borrower);
// AUDITV2FIX: handle max liquidations
if (_numaAmount == type(uint256).max) {
numaAmount = borrowAmount;
} else {
// min liquidation amount
// convert minimum amount for partial liquidations in numa
uint minBorrowAmountAllowPartialLiquidationNuma = vaultManager
.tokenToNuma(
minBorrowAmountAllowPartialLiquidation,
last_lsttokenvalueWei,
decimals,
criticalScaleForNumaPriceAndSellFee
);
uint minAmount = minBorrowAmountAllowPartialLiquidationNuma;
if (borrowAmount < minAmount) minAmount = borrowAmount;
require(numaAmount >= minAmount, "min liquidation");