-
Notifications
You must be signed in to change notification settings - Fork 30
/
TroveManager.sol
1594 lines (1324 loc) · 68.9 KB
/
TroveManager.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: BUSL-1.1
pragma solidity 0.6.11;
import "./Interfaces/ICollateralConfig.sol";
import "./Interfaces/ITroveManager.sol";
import "./Interfaces/IStabilityPool.sol";
import "./Interfaces/ICollSurplusPool.sol";
import "./Interfaces/ILUSDToken.sol";
import "./Interfaces/ISortedTroves.sol";
import "./Interfaces/ILQTYStaking.sol";
import "./Interfaces/IRedemptionHelper.sol";
import "./Dependencies/LiquityBase.sol";
// import "./Dependencies/Ownable.sol";
import "./Dependencies/CheckContract.sol";
import "./Dependencies/IERC20.sol";
contract TroveManager is LiquityBase, /*Ownable,*/ CheckContract, ITroveManager {
// string constant public NAME = "TroveManager";
address public owner;
// --- Connected contract declarations ---
address public borrowerOperationsAddress;
ICollateralConfig public collateralConfig;
IStabilityPool public override stabilityPool;
address gasPoolAddress;
ICollSurplusPool collSurplusPool;
ILUSDToken public override lusdToken;
IERC20 public override lqtyToken;
ILQTYStaking public override lqtyStaking;
// A doubly linked list of Troves, sorted by their sorted by their collateral ratios
ISortedTroves public sortedTroves;
IRedemptionHelper public override redemptionHelper;
// --- Data structures ---
uint constant public SECONDS_IN_ONE_MINUTE = 60;
/*
* Half-life of 12h. 12h = 720 min
* (1/2) = d^720 => d = (1/2)^(1/720)
*/
uint constant public MINUTE_DECAY_FACTOR = 999037758833783000;
uint constant public override REDEMPTION_FEE_FLOOR = DECIMAL_PRECISION / 1000 * 5; // 0.5%
uint constant public MAX_BORROWING_FEE = DECIMAL_PRECISION / 100 * 5; // 5%
/*
* BETA: 18 digit decimal. Parameter by which to divide the redeemed fraction, in order to calc the new base rate from a redemption.
* Corresponds to (1 / ALPHA) in the white paper.
*/
uint constant public BETA = 2;
uint public baseRate;
// The timestamp of the latest fee operation (redemption or new LUSD issuance)
uint public lastFeeOperationTime;
enum Status {
nonExistent,
active,
closedByOwner,
closedByLiquidation,
closedByRedemption
}
// Store the necessary data for a trove
struct Trove {
uint debt;
uint coll;
uint stake;
Status status;
uint128 arrayIndex;
}
// user => (collateral type => trove)
mapping (address => mapping (address => Trove)) public Troves;
mapping (address => uint) public totalStakes;
// Snapshot of the value of totalStakes for each collateral, taken immediately after the latest liquidation
mapping (address => uint) public totalStakesSnapshot;
// Snapshot of the total collateral across the ActivePool and DefaultPool, immediately after the latest liquidation.
mapping (address => uint) public totalCollateralSnapshot;
/*
* L_Collateral and L_LUSDDebt track the sums of accumulated liquidation rewards per unit staked. During its lifetime, each stake earns:
*
* A collateral gain of ( stake * [L_Collateral - L_Collateral(0)] )
* A LUSDDebt increase of ( stake * [L_LUSDDebt - L_LUSDDebt(0)] )
*
* Where L_Collateral(0) and L_LUSDDebt(0) are snapshots of L_Collateral and L_LUSDDebt for the active Trove taken at the instant the stake was made
*/
mapping (address => uint) public L_Collateral;
mapping (address => uint) public L_LUSDDebt;
// Map addresses with active troves to their RewardSnapshot
// user => (collateral type => reward snapshot))
mapping (address => mapping (address => RewardSnapshot)) public rewardSnapshots;
// Object containing the Collateral and LUSD snapshots for a given active trove
struct RewardSnapshot { uint collAmount; uint LUSDDebt;}
// Array of all active trove addresses - used to to compute an approximate hint off-chain, for the sorted list insertion
// collateral type => array of trove owners
mapping (address => address[]) public TroveOwners;
// Error trackers for the trove redistribution calculation
mapping (address => uint) public lastCollateralError_Redistribution;
mapping (address => uint) public lastLUSDDebtError_Redistribution;
/*
* --- Variable container structs for liquidations ---
*
* These structs are used to hold, return and assign variables inside the liquidation functions,
* in order to avoid the error: "CompilerError: Stack too deep".
**/
struct LocalVariables_OuterLiquidationFunction {
uint256 collDecimals;
uint256 collCCR;
uint256 collMCR;
uint price;
uint LUSDInStabPool;
bool recoveryModeAtStart;
uint liquidatedDebt;
uint liquidatedColl;
}
struct LocalVariables_InnerSingleLiquidateFunction {
uint collToLiquidate;
uint pendingDebtReward;
uint pendingCollReward;
}
struct LocalVariables_LiquidationSequence {
uint remainingLUSDInStabPool;
uint i;
uint ICR;
uint TCR;
address user;
bool backToNormalMode;
uint entireSystemDebt;
uint entireSystemColl;
uint256 collDecimals;
uint256 collCCR;
uint256 collMCR;
}
struct LiquidationValues {
uint entireTroveDebt;
uint entireTroveColl;
uint collGasCompensation;
uint LUSDGasCompensation;
uint debtToOffset;
uint collToSendToSP;
uint debtToRedistribute;
uint collToRedistribute;
uint collSurplus;
}
struct LiquidationTotals {
uint totalCollInSequence;
uint totalDebtInSequence;
uint totalCollGasCompensation;
uint totalLUSDGasCompensation;
uint totalDebtToOffset;
uint totalCollToSendToSP;
uint totalDebtToRedistribute;
uint totalCollToRedistribute;
uint totalCollSurplus;
}
// --- Events ---
event BorrowerOperationsAddressChanged(address _newBorrowerOperationsAddress);
event CollateralConfigAddressChanged(address _newCollateralConfigAddress);
event PriceFeedAddressChanged(address _newPriceFeedAddress);
event LUSDTokenAddressChanged(address _newLUSDTokenAddress);
event ActivePoolAddressChanged(address _activePoolAddress);
event DefaultPoolAddressChanged(address _defaultPoolAddress);
event StabilityPoolAddressChanged(address _stabilityPoolAddress);
event GasPoolAddressChanged(address _gasPoolAddress);
event CollSurplusPoolAddressChanged(address _collSurplusPoolAddress);
event SortedTrovesAddressChanged(address _sortedTrovesAddress);
event LQTYTokenAddressChanged(address _lqtyTokenAddress);
event LQTYStakingAddressChanged(address _lqtyStakingAddress);
event RedemptionHelperAddressChanged(address _redemptionHelperAddress);
event Liquidation(address _collateral, uint _liquidatedDebt, uint _liquidatedColl, uint _collGasCompensation, uint _LUSDGasCompensation);
event TroveUpdated(address indexed _borrower, address _collateral, uint _debt, uint _coll, uint _stake, TroveManagerOperation _operation);
event TroveLiquidated(address indexed _borrower, address _collateral, uint _debt, uint _coll, TroveManagerOperation _operation);
event BaseRateUpdated(uint _baseRate);
event LastFeeOpTimeUpdated(uint _lastFeeOpTime);
event TotalStakesUpdated(address _collateral, uint _newTotalStakes);
event SystemSnapshotsUpdated(address _collateral, uint _totalStakesSnapshot, uint _totalCollateralSnapshot);
event LTermsUpdated(address _collateral, uint _L_Collateral, uint _L_LUSDDebt);
event TroveSnapshotsUpdated(address _collateral, uint _L_Collateral, uint _L_LUSDDebt);
event TroveIndexUpdated(address _borrower, address _collateral, uint _newIndex);
event Redemption(
address _collateral,
uint _attemptedLUSDAmount,
uint _actualLUSDAmount,
uint _collSent,
uint _collFee
);
enum TroveManagerOperation {
applyPendingRewards,
liquidateInNormalMode,
liquidateInRecoveryMode,
redeemCollateral
}
constructor() public {
// makeshift ownable implementation to circumvent contract size limit
owner = msg.sender;
}
// --- Dependency setter ---
function setAddresses(
address _borrowerOperationsAddress,
address _collateralConfigAddress,
address _activePoolAddress,
address _defaultPoolAddress,
address _stabilityPoolAddress,
address _gasPoolAddress,
address _collSurplusPoolAddress,
address _priceFeedAddress,
address _lusdTokenAddress,
address _sortedTrovesAddress,
address _lqtyTokenAddress,
address _lqtyStakingAddress,
address _redemptionHelperAddress
)
external
override
{
require(msg.sender == owner);
checkContract(_borrowerOperationsAddress);
checkContract(_collateralConfigAddress);
checkContract(_activePoolAddress);
checkContract(_defaultPoolAddress);
checkContract(_stabilityPoolAddress);
checkContract(_gasPoolAddress);
checkContract(_collSurplusPoolAddress);
checkContract(_priceFeedAddress);
checkContract(_lusdTokenAddress);
checkContract(_sortedTrovesAddress);
checkContract(_lqtyTokenAddress);
checkContract(_lqtyStakingAddress);
checkContract(_redemptionHelperAddress);
borrowerOperationsAddress = _borrowerOperationsAddress;
collateralConfig = ICollateralConfig(_collateralConfigAddress);
activePool = IActivePool(_activePoolAddress);
defaultPool = IDefaultPool(_defaultPoolAddress);
stabilityPool = IStabilityPool(_stabilityPoolAddress);
gasPoolAddress = _gasPoolAddress;
collSurplusPool = ICollSurplusPool(_collSurplusPoolAddress);
priceFeed = IPriceFeed(_priceFeedAddress);
lusdToken = ILUSDToken(_lusdTokenAddress);
sortedTroves = ISortedTroves(_sortedTrovesAddress);
lqtyToken = IERC20(_lqtyTokenAddress);
lqtyStaking = ILQTYStaking(_lqtyStakingAddress);
redemptionHelper = IRedemptionHelper(_redemptionHelperAddress);
emit BorrowerOperationsAddressChanged(_borrowerOperationsAddress);
emit CollateralConfigAddressChanged(_collateralConfigAddress);
emit ActivePoolAddressChanged(_activePoolAddress);
emit DefaultPoolAddressChanged(_defaultPoolAddress);
emit StabilityPoolAddressChanged(_stabilityPoolAddress);
emit GasPoolAddressChanged(_gasPoolAddress);
emit CollSurplusPoolAddressChanged(_collSurplusPoolAddress);
emit PriceFeedAddressChanged(_priceFeedAddress);
emit LUSDTokenAddressChanged(_lusdTokenAddress);
emit SortedTrovesAddressChanged(_sortedTrovesAddress);
emit LQTYTokenAddressChanged(_lqtyTokenAddress);
emit LQTYStakingAddressChanged(_lqtyStakingAddress);
emit RedemptionHelperAddressChanged(_redemptionHelperAddress);
owner = address(0);
}
// --- Getters ---
function getTroveOwnersCount(address _collateral) external view override returns (uint) {
return TroveOwners[_collateral].length;
}
function getTroveFromTroveOwnersArray(address _collateral, uint _index) external view override returns (address) {
return TroveOwners[_collateral][_index];
}
// --- Trove Liquidation functions ---
// Single liquidation function. Closes the trove if its ICR is lower than the minimum collateral ratio.
function liquidate(address _borrower, address _collateral) external override {
_requireTroveIsActive(_borrower, _collateral);
address[] memory borrowers = new address[](1);
borrowers[0] = _borrower;
batchLiquidateTroves(_collateral, borrowers);
}
// --- Inner single liquidation functions ---
// Liquidate one trove, in Normal Mode.
function _liquidateNormalMode(
IActivePool _activePool,
IDefaultPool _defaultPool,
address _collateral,
address _borrower,
uint _LUSDInStabPool
)
internal
returns (LiquidationValues memory singleLiquidation)
{
LocalVariables_InnerSingleLiquidateFunction memory vars;
(singleLiquidation.entireTroveDebt,
singleLiquidation.entireTroveColl,
vars.pendingDebtReward,
vars.pendingCollReward) = getEntireDebtAndColl(_borrower, _collateral);
_movePendingTroveRewardsToActivePool(_activePool, _defaultPool, _collateral, vars.pendingDebtReward, vars.pendingCollReward);
_removeStake(_borrower, _collateral);
singleLiquidation.collGasCompensation = _getCollGasCompensation(singleLiquidation.entireTroveColl);
singleLiquidation.LUSDGasCompensation = LUSD_GAS_COMPENSATION;
uint collToLiquidate = singleLiquidation.entireTroveColl.sub(singleLiquidation.collGasCompensation);
(singleLiquidation.debtToOffset,
singleLiquidation.collToSendToSP,
singleLiquidation.debtToRedistribute,
singleLiquidation.collToRedistribute) = _getOffsetAndRedistributionVals(singleLiquidation.entireTroveDebt, collToLiquidate, _LUSDInStabPool);
_closeTrove(_borrower, _collateral, Status.closedByLiquidation);
emit TroveLiquidated(_borrower, _collateral, singleLiquidation.entireTroveDebt, singleLiquidation.entireTroveColl, TroveManagerOperation.liquidateInNormalMode);
emit TroveUpdated(_borrower, _collateral, 0, 0, 0, TroveManagerOperation.liquidateInNormalMode);
return singleLiquidation;
}
// Liquidate one trove, in Recovery Mode.
function _liquidateRecoveryMode(
IActivePool _activePool,
IDefaultPool _defaultPool,
address _collateral,
address _borrower,
uint _ICR,
uint _LUSDInStabPool,
uint _TCR,
uint _price,
uint256 _MCR
)
internal
returns (LiquidationValues memory singleLiquidation)
{
LocalVariables_InnerSingleLiquidateFunction memory vars;
if (TroveOwners[_collateral].length <= 1) {return singleLiquidation;} // don't liquidate if last trove
(singleLiquidation.entireTroveDebt,
singleLiquidation.entireTroveColl,
vars.pendingDebtReward,
vars.pendingCollReward) = getEntireDebtAndColl(_borrower, _collateral);
singleLiquidation.collGasCompensation = _getCollGasCompensation(singleLiquidation.entireTroveColl);
singleLiquidation.LUSDGasCompensation = LUSD_GAS_COMPENSATION;
vars.collToLiquidate = singleLiquidation.entireTroveColl.sub(singleLiquidation.collGasCompensation);
// If ICR <= 100%, purely redistribute the Trove across all active Troves
if (_ICR <= _100pct) {
_movePendingTroveRewardsToActivePool(_activePool, _defaultPool, _collateral, vars.pendingDebtReward, vars.pendingCollReward);
_removeStake(_borrower, _collateral);
singleLiquidation.debtToOffset = 0;
singleLiquidation.collToSendToSP = 0;
singleLiquidation.debtToRedistribute = singleLiquidation.entireTroveDebt;
singleLiquidation.collToRedistribute = vars.collToLiquidate;
_closeTrove(_borrower, _collateral, Status.closedByLiquidation);
emit TroveLiquidated(_borrower, _collateral, singleLiquidation.entireTroveDebt, singleLiquidation.entireTroveColl, TroveManagerOperation.liquidateInRecoveryMode);
emit TroveUpdated(_borrower, _collateral, 0, 0, 0, TroveManagerOperation.liquidateInRecoveryMode);
// If 100% < ICR < MCR, offset as much as possible, and redistribute the remainder
} else if ((_ICR > _100pct) && (_ICR < _MCR)) {
_movePendingTroveRewardsToActivePool(_activePool, _defaultPool, _collateral, vars.pendingDebtReward, vars.pendingCollReward);
_removeStake(_borrower, _collateral);
(singleLiquidation.debtToOffset,
singleLiquidation.collToSendToSP,
singleLiquidation.debtToRedistribute,
singleLiquidation.collToRedistribute) = _getOffsetAndRedistributionVals(singleLiquidation.entireTroveDebt, vars.collToLiquidate, _LUSDInStabPool);
_closeTrove(_borrower, _collateral, Status.closedByLiquidation);
emit TroveLiquidated(_borrower, _collateral, singleLiquidation.entireTroveDebt, singleLiquidation.entireTroveColl, TroveManagerOperation.liquidateInRecoveryMode);
emit TroveUpdated(_borrower, _collateral, 0, 0, 0, TroveManagerOperation.liquidateInRecoveryMode);
/*
* If MCR <= ICR < current TCR (accounting for the preceding liquidations in the current sequence)
* and there is LUSD in the Stability Pool, only offset, with no redistribution,
* but at a capped rate of MCR and only if the whole debt can be liquidated.
* The remainder due to the capped rate will be claimable as collateral surplus.
*/
} else if ((_ICR >= _MCR) && (_ICR < _TCR) && (singleLiquidation.entireTroveDebt <= _LUSDInStabPool)) {
_movePendingTroveRewardsToActivePool(_activePool, _defaultPool, _collateral, vars.pendingDebtReward, vars.pendingCollReward);
assert(_LUSDInStabPool != 0);
_removeStake(_borrower, _collateral);
uint collDecimals = collateralConfig.getCollateralDecimals(_collateral);
singleLiquidation = _getCappedOffsetVals(singleLiquidation.entireTroveDebt, singleLiquidation.entireTroveColl, _price, _MCR, collDecimals);
_closeTrove(_borrower, _collateral, Status.closedByLiquidation);
if (singleLiquidation.collSurplus > 0) {
collSurplusPool.accountSurplus(_borrower, _collateral, singleLiquidation.collSurplus);
}
emit TroveLiquidated(_borrower, _collateral, singleLiquidation.entireTroveDebt, singleLiquidation.collToSendToSP, TroveManagerOperation.liquidateInRecoveryMode);
emit TroveUpdated(_borrower, _collateral, 0, 0, 0, TroveManagerOperation.liquidateInRecoveryMode);
} else { // if (_ICR >= _MCR && ( _ICR >= _TCR || singleLiquidation.entireTroveDebt > _LUSDInStabPool))
LiquidationValues memory zeroVals;
return zeroVals;
}
return singleLiquidation;
}
/* In a full liquidation, returns the values for a trove's coll and debt to be offset, and coll and debt to be
* redistributed to active troves.
*/
function _getOffsetAndRedistributionVals
(
uint _debt,
uint _coll,
uint _LUSDInStabPool
)
internal
pure
returns (uint debtToOffset, uint collToSendToSP, uint debtToRedistribute, uint collToRedistribute)
{
if (_LUSDInStabPool > 0) {
/*
* Offset as much debt & collateral as possible against the Stability Pool, and redistribute the remainder
* between all active troves.
*
* If the trove's debt is larger than the deposited LUSD in the Stability Pool:
*
* - Offset an amount of the trove's debt equal to the LUSD in the Stability Pool
* - Send a fraction of the trove's collateral to the Stability Pool, equal to the fraction of its offset debt
*
*/
debtToOffset = LiquityMath._min(_debt, _LUSDInStabPool);
collToSendToSP = _coll.mul(debtToOffset).div(_debt);
debtToRedistribute = _debt.sub(debtToOffset);
collToRedistribute = _coll.sub(collToSendToSP);
} else {
debtToOffset = 0;
collToSendToSP = 0;
debtToRedistribute = _debt;
collToRedistribute = _coll;
}
}
/*
* Get its offset coll/debt and ETH gas comp, and close the trove.
*/
function _getCappedOffsetVals
(
uint _entireTroveDebt,
uint _entireTroveColl,
uint _price,
uint256 _MCR,
uint _collDecimals
)
internal
pure
returns (LiquidationValues memory singleLiquidation)
{
singleLiquidation.entireTroveDebt = _entireTroveDebt;
singleLiquidation.entireTroveColl = _entireTroveColl;
uint cappedCollPortion = _entireTroveDebt.mul(_MCR).div(_price);
if (_collDecimals < LiquityMath.CR_CALCULATION_DECIMALS) {
cappedCollPortion = cappedCollPortion.div(10 ** (LiquityMath.CR_CALCULATION_DECIMALS - _collDecimals));
} else if (_collDecimals > LiquityMath.CR_CALCULATION_DECIMALS) {
cappedCollPortion = cappedCollPortion.mul(10 ** (_collDecimals - LiquityMath.CR_CALCULATION_DECIMALS));
}
singleLiquidation.collGasCompensation = _getCollGasCompensation(cappedCollPortion);
singleLiquidation.LUSDGasCompensation = LUSD_GAS_COMPENSATION;
singleLiquidation.debtToOffset = _entireTroveDebt;
singleLiquidation.collToSendToSP = cappedCollPortion.sub(singleLiquidation.collGasCompensation);
singleLiquidation.collSurplus = _entireTroveColl.sub(cappedCollPortion);
singleLiquidation.debtToRedistribute = 0;
singleLiquidation.collToRedistribute = 0;
}
/*
* Liquidate a sequence of troves. Closes a maximum number of n under-collateralized Troves,
* starting from the one with the lowest collateral ratio in the system, and moving upwards
*/
function liquidateTroves(address _collateral, uint _n) external override {
IActivePool activePoolCached = activePool;
IDefaultPool defaultPoolCached = defaultPool;
IStabilityPool stabilityPoolCached = stabilityPool;
LocalVariables_OuterLiquidationFunction memory vars;
LiquidationTotals memory totals;
vars.collCCR = collateralConfig.getCollateralCCR(_collateral);
vars.collDecimals = collateralConfig.getCollateralDecimals(_collateral);
vars.collMCR = collateralConfig.getCollateralMCR(_collateral);
vars.price = priceFeed.fetchPrice(_collateral);
vars.LUSDInStabPool = stabilityPoolCached.getTotalLUSDDeposits();
vars.recoveryModeAtStart = _checkRecoveryMode(_collateral, vars.price, vars.collCCR, vars.collDecimals);
// Perform the appropriate liquidation sequence - tally the values, and obtain their totals
if (vars.recoveryModeAtStart) {
totals = _getTotalsFromLiquidateTrovesSequence_RecoveryMode(
activePoolCached,
defaultPoolCached,
sortedTroves,
_collateral,
vars.price,
vars.LUSDInStabPool,
_n
);
} else { // if !vars.recoveryModeAtStart
totals = _getTotalsFromLiquidateTrovesSequence_NormalMode(
activePoolCached,
defaultPoolCached,
_collateral,
vars.price,
vars.collMCR,
vars.LUSDInStabPool,
_n
);
}
require(totals.totalDebtInSequence > 0);
// Move liquidated collateral and LUSD to the appropriate pools
stabilityPoolCached.offset(_collateral, totals.totalDebtToOffset, totals.totalCollToSendToSP);
_redistributeDebtAndColl(
activePoolCached,
defaultPoolCached,
_collateral,
totals.totalDebtToRedistribute,
totals.totalCollToRedistribute,
vars.collDecimals
);
if (totals.totalCollSurplus > 0) {
activePoolCached.sendCollateral(_collateral, address(collSurplusPool), totals.totalCollSurplus);
}
// Update system snapshots
_updateSystemSnapshots_excludeCollRemainder(activePoolCached, _collateral, totals.totalCollGasCompensation);
vars.liquidatedDebt = totals.totalDebtInSequence;
vars.liquidatedColl = totals.totalCollInSequence.sub(totals.totalCollGasCompensation).sub(totals.totalCollSurplus);
emit Liquidation(_collateral, vars.liquidatedDebt, vars.liquidatedColl, totals.totalCollGasCompensation, totals.totalLUSDGasCompensation);
// Send gas compensation to caller
_sendGasCompensation(activePoolCached, _collateral, msg.sender, totals.totalLUSDGasCompensation, totals.totalCollGasCompensation);
}
/*
* This function is used when the liquidateTroves sequence starts during Recovery Mode. However, it
* handle the case where the system *leaves* Recovery Mode, part way through the liquidation sequence
*/
function _getTotalsFromLiquidateTrovesSequence_RecoveryMode
(
IActivePool _activePool,
IDefaultPool _defaultPool,
ISortedTroves _sortedTroves,
address _collateral,
uint _price,
uint _LUSDInStabPool,
uint _n
)
internal
returns(LiquidationTotals memory totals)
{
LocalVariables_LiquidationSequence memory vars;
vars.collDecimals = collateralConfig.getCollateralDecimals(_collateral);
vars.collCCR = collateralConfig.getCollateralCCR(_collateral);
vars.collMCR = collateralConfig.getCollateralMCR(_collateral);
LiquidationValues memory singleLiquidation;
vars.remainingLUSDInStabPool = _LUSDInStabPool;
vars.backToNormalMode = false;
vars.entireSystemDebt = getEntireSystemDebt(_collateral);
vars.entireSystemColl = getEntireSystemColl(_collateral);
vars.user = _sortedTroves.getLast(_collateral);
address firstUser = _sortedTroves.getFirst(_collateral);
for (vars.i = 0; vars.i < _n && vars.user != firstUser; vars.i++) {
// we need to cache it, because current user is likely going to be deleted
address nextUser = _sortedTroves.getPrev(_collateral, vars.user);
vars.ICR = getCurrentICR(vars.user, _collateral, _price);
if (!vars.backToNormalMode) {
// Break the loop if ICR is greater than MCR and Stability Pool is empty
if (vars.ICR >= vars.collMCR && vars.remainingLUSDInStabPool == 0) { break; }
vars.TCR = LiquityMath._computeCR(vars.entireSystemColl, vars.entireSystemDebt, _price, vars.collDecimals);
singleLiquidation = _liquidateRecoveryMode(
_activePool,
_defaultPool,
_collateral,
vars.user,
vars.ICR,
vars.remainingLUSDInStabPool,
vars.TCR,
_price,
vars.collMCR
);
// Update aggregate trackers
vars.remainingLUSDInStabPool = vars.remainingLUSDInStabPool.sub(singleLiquidation.debtToOffset);
vars.entireSystemDebt = vars.entireSystemDebt.sub(singleLiquidation.debtToOffset);
vars.entireSystemColl = vars.entireSystemColl.
sub(singleLiquidation.collToSendToSP).
sub(singleLiquidation.collGasCompensation).
sub(singleLiquidation.collSurplus);
// Add liquidation values to their respective running totals
totals = _addLiquidationValuesToTotals(totals, singleLiquidation);
vars.backToNormalMode = !_checkPotentialRecoveryMode(
vars.entireSystemColl,
vars.entireSystemDebt,
_price,
vars.collDecimals,
vars.collCCR
);
}
else if (vars.backToNormalMode && vars.ICR < vars.collMCR) {
singleLiquidation = _liquidateNormalMode(
_activePool,
_defaultPool,
_collateral,
vars.user,
vars.remainingLUSDInStabPool
);
vars.remainingLUSDInStabPool = vars.remainingLUSDInStabPool.sub(singleLiquidation.debtToOffset);
// Add liquidation values to their respective running totals
totals = _addLiquidationValuesToTotals(totals, singleLiquidation);
} else break; // break if the loop reaches a Trove with ICR >= MCR
vars.user = nextUser;
}
}
function _getTotalsFromLiquidateTrovesSequence_NormalMode
(
IActivePool _activePool,
IDefaultPool _defaultPool,
address _collateral,
uint _price,
uint256 _MCR,
uint _LUSDInStabPool,
uint _n
)
internal
returns(LiquidationTotals memory totals)
{
LocalVariables_LiquidationSequence memory vars;
LiquidationValues memory singleLiquidation;
ISortedTroves sortedTrovesCached = sortedTroves;
vars.remainingLUSDInStabPool = _LUSDInStabPool;
for (vars.i = 0; vars.i < _n; vars.i++) {
vars.user = sortedTrovesCached.getLast(_collateral);
vars.ICR = getCurrentICR(vars.user, _collateral, _price);
if (vars.ICR < _MCR) {
singleLiquidation = _liquidateNormalMode(
_activePool,
_defaultPool,
_collateral,
vars.user,
vars.remainingLUSDInStabPool
);
vars.remainingLUSDInStabPool = vars.remainingLUSDInStabPool.sub(singleLiquidation.debtToOffset);
// Add liquidation values to their respective running totals
totals = _addLiquidationValuesToTotals(totals, singleLiquidation);
} else break; // break if the loop reaches a Trove with ICR >= MCR
}
}
/*
* Attempt to liquidate a custom list of troves (for the specified collateral) provided by the caller.
*/
function batchLiquidateTroves(address _collateral, address[] memory _troveArray) public override {
require(_troveArray.length != 0);
IActivePool activePoolCached = activePool;
IDefaultPool defaultPoolCached = defaultPool;
IStabilityPool stabilityPoolCached = stabilityPool;
LocalVariables_OuterLiquidationFunction memory vars;
LiquidationTotals memory totals;
vars.collDecimals = collateralConfig.getCollateralDecimals(_collateral);
vars.collCCR = collateralConfig.getCollateralCCR(_collateral);
vars.collMCR = collateralConfig.getCollateralMCR(_collateral);
vars.price = priceFeed.fetchPrice(_collateral);
vars.LUSDInStabPool = stabilityPoolCached.getTotalLUSDDeposits();
vars.recoveryModeAtStart = _checkRecoveryMode(_collateral, vars.price, vars.collCCR, vars.collDecimals);
// Perform the appropriate liquidation sequence - tally values and obtain their totals.
if (vars.recoveryModeAtStart) {
totals = _getTotalFromBatchLiquidate_RecoveryMode(
activePoolCached,
defaultPoolCached,
_collateral,
vars.price,
vars.LUSDInStabPool,
_troveArray
);
} else { // if !vars.recoveryModeAtStart
totals = _getTotalsFromBatchLiquidate_NormalMode(
activePoolCached,
defaultPoolCached,
_collateral,
vars.price,
vars.collMCR,
vars.LUSDInStabPool,
_troveArray
);
}
require(totals.totalDebtInSequence > 0);
// Move liquidated collateral and LUSD to the appropriate pools
stabilityPoolCached.offset(_collateral, totals.totalDebtToOffset, totals.totalCollToSendToSP);
_redistributeDebtAndColl(
activePoolCached,
defaultPoolCached,
_collateral,
totals.totalDebtToRedistribute,
totals.totalCollToRedistribute,
vars.collDecimals
);
if (totals.totalCollSurplus > 0) {
activePoolCached.sendCollateral(_collateral, address(collSurplusPool), totals.totalCollSurplus);
}
// Update system snapshots
_updateSystemSnapshots_excludeCollRemainder(activePoolCached, _collateral, totals.totalCollGasCompensation);
vars.liquidatedDebt = totals.totalDebtInSequence;
vars.liquidatedColl = totals.totalCollInSequence.sub(totals.totalCollGasCompensation).sub(totals.totalCollSurplus);
emit Liquidation(_collateral, vars.liquidatedDebt, vars.liquidatedColl, totals.totalCollGasCompensation, totals.totalLUSDGasCompensation);
// Send gas compensation to caller
_sendGasCompensation(activePoolCached, _collateral, msg.sender, totals.totalLUSDGasCompensation, totals.totalCollGasCompensation);
}
/*
* This function is used when the batch liquidation sequence starts during Recovery Mode. However, it
* handle the case where the system *leaves* Recovery Mode, part way through the liquidation sequence
*/
function _getTotalFromBatchLiquidate_RecoveryMode
(
IActivePool _activePool,
IDefaultPool _defaultPool,
address _collateral,
uint _price,
uint _LUSDInStabPool,
address[] memory _troveArray
)
internal
returns(LiquidationTotals memory totals)
{
LocalVariables_LiquidationSequence memory vars;
vars.collDecimals = collateralConfig.getCollateralDecimals(_collateral);
vars.collCCR = collateralConfig.getCollateralCCR(_collateral);
vars.collMCR = collateralConfig.getCollateralMCR(_collateral);
LiquidationValues memory singleLiquidation;
vars.remainingLUSDInStabPool = _LUSDInStabPool;
vars.backToNormalMode = false;
vars.entireSystemDebt = getEntireSystemDebt(_collateral);
vars.entireSystemColl = getEntireSystemColl(_collateral);
for (vars.i = 0; vars.i < _troveArray.length; vars.i++) {
vars.user = _troveArray[vars.i];
// Skip non-active troves
if (Troves[vars.user][_collateral].status != Status.active) { continue; }
vars.ICR = getCurrentICR(vars.user, _collateral, _price);
if (!vars.backToNormalMode) {
// Skip this trove if ICR is greater than MCR and Stability Pool is empty
if (vars.ICR >= vars.collMCR && vars.remainingLUSDInStabPool == 0) { continue; }
uint TCR = LiquityMath._computeCR(vars.entireSystemColl, vars.entireSystemDebt, _price, vars.collDecimals);
singleLiquidation = _liquidateRecoveryMode(
_activePool,
_defaultPool,
_collateral,
vars.user,
vars.ICR,
vars.remainingLUSDInStabPool,
TCR,
_price,
vars.collMCR
);
// Update aggregate trackers
vars.remainingLUSDInStabPool = vars.remainingLUSDInStabPool.sub(singleLiquidation.debtToOffset);
vars.entireSystemDebt = vars.entireSystemDebt.sub(singleLiquidation.debtToOffset);
vars.entireSystemColl = vars.entireSystemColl.
sub(singleLiquidation.collToSendToSP).
sub(singleLiquidation.collGasCompensation).
sub(singleLiquidation.collSurplus);
// Add liquidation values to their respective running totals
totals = _addLiquidationValuesToTotals(totals, singleLiquidation);
vars.backToNormalMode = !_checkPotentialRecoveryMode(
vars.entireSystemColl,
vars.entireSystemDebt,
_price,
vars.collDecimals,
vars.collCCR
);
}
else if (vars.backToNormalMode && vars.ICR < vars.collMCR) {
singleLiquidation = _liquidateNormalMode(_activePool, _defaultPool, _collateral, vars.user, vars.remainingLUSDInStabPool);
vars.remainingLUSDInStabPool = vars.remainingLUSDInStabPool.sub(singleLiquidation.debtToOffset);
// Add liquidation values to their respective running totals
totals = _addLiquidationValuesToTotals(totals, singleLiquidation);
} else continue; // In Normal Mode skip troves with ICR >= MCR
}
}
function _getTotalsFromBatchLiquidate_NormalMode
(
IActivePool _activePool,
IDefaultPool _defaultPool,
address _collateral,
uint _price,
uint256 _MCR,
uint _LUSDInStabPool,
address[] memory _troveArray
)
internal
returns(LiquidationTotals memory totals)
{
LocalVariables_LiquidationSequence memory vars;
LiquidationValues memory singleLiquidation;
vars.remainingLUSDInStabPool = _LUSDInStabPool;
for (vars.i = 0; vars.i < _troveArray.length; vars.i++) {
vars.user = _troveArray[vars.i];
vars.ICR = getCurrentICR(vars.user, _collateral, _price);
if (vars.ICR < _MCR) {
singleLiquidation = _liquidateNormalMode(_activePool, _defaultPool, _collateral, vars.user, vars.remainingLUSDInStabPool);
vars.remainingLUSDInStabPool = vars.remainingLUSDInStabPool.sub(singleLiquidation.debtToOffset);
// Add liquidation values to their respective running totals
totals = _addLiquidationValuesToTotals(totals, singleLiquidation);
}
}
}
// --- Liquidation helper functions ---
function _addLiquidationValuesToTotals(LiquidationTotals memory oldTotals, LiquidationValues memory singleLiquidation)
internal pure returns(LiquidationTotals memory newTotals) {
// Tally all the values with their respective running totals
newTotals.totalCollGasCompensation = oldTotals.totalCollGasCompensation.add(singleLiquidation.collGasCompensation);
newTotals.totalLUSDGasCompensation = oldTotals.totalLUSDGasCompensation.add(singleLiquidation.LUSDGasCompensation);
newTotals.totalDebtInSequence = oldTotals.totalDebtInSequence.add(singleLiquidation.entireTroveDebt);
newTotals.totalCollInSequence = oldTotals.totalCollInSequence.add(singleLiquidation.entireTroveColl);
newTotals.totalDebtToOffset = oldTotals.totalDebtToOffset.add(singleLiquidation.debtToOffset);
newTotals.totalCollToSendToSP = oldTotals.totalCollToSendToSP.add(singleLiquidation.collToSendToSP);
newTotals.totalDebtToRedistribute = oldTotals.totalDebtToRedistribute.add(singleLiquidation.debtToRedistribute);
newTotals.totalCollToRedistribute = oldTotals.totalCollToRedistribute.add(singleLiquidation.collToRedistribute);
newTotals.totalCollSurplus = oldTotals.totalCollSurplus.add(singleLiquidation.collSurplus);
return newTotals;
}
function _sendGasCompensation(IActivePool _activePool, address _collateral, address _liquidator, uint _LUSD, uint _collAmount) internal {
if (_LUSD > 0) {
lusdToken.returnFromPool(gasPoolAddress, _liquidator, _LUSD);
}
if (_collAmount > 0) {
_activePool.sendCollateral(_collateral, _liquidator, _collAmount);
}
}
// Move a Trove's pending debt and collateral rewards from distributions, from the Default Pool to the Active Pool
function _movePendingTroveRewardsToActivePool(IActivePool _activePool, IDefaultPool _defaultPool, address _collateral, uint _LUSD, uint _collAmount) internal {
_defaultPool.decreaseLUSDDebt(_collateral, _LUSD);
_activePool.increaseLUSDDebt(_collateral, _LUSD);
_defaultPool.sendCollateralToActivePool(_collateral, _collAmount);
}
/*
* Called when a full redemption occurs, and closes the trove.
* The redeemer swaps (debt - liquidation reserve) LUSD for (debt - liquidation reserve) worth of collateral, so the LUSD liquidation reserve left corresponds to the remaining debt.
* In order to close the trove, the LUSD liquidation reserve is burned, and the corresponding debt is removed from the active pool.
* The debt recorded on the trove's struct is zero'd elswhere, in _closeTrove.
* Any surplus collateral left in the trove, is sent to the Coll surplus pool, and can be later claimed by the borrower.
*/
function redeemCloseTrove(
address _borrower,
address _collateral,
uint256 _LUSD,
uint256 _collAmount
) external override {
_requireCallerIsRedemptionHelper();
lusdToken.burn(gasPoolAddress, _LUSD);
// Update Active Pool LUSD, and send ETH to account
activePool.decreaseLUSDDebt(_collateral, _LUSD);
// send ETH from Active Pool to CollSurplus Pool
collSurplusPool.accountSurplus(_borrower, _collateral, _collAmount);
activePool.sendCollateral(_collateral, address(collSurplusPool), _collAmount);
emit TroveUpdated(_borrower, _collateral, 0, 0, 0, TroveManagerOperation.redeemCollateral);
}
function reInsert(address _id, address _collateral, uint256 _newNICR, address _prevId, address _nextId) external override {
_requireCallerIsRedemptionHelper();
sortedTroves.reInsert(_id, _collateral, _newNICR, _prevId, _nextId);
}
function updateDebtAndCollAndStakesPostRedemption(
address _borrower,
address _collateral,
uint256 _newDebt,
uint256 _newColl
) external override {
_requireCallerIsRedemptionHelper();
Troves[_borrower][_collateral].debt = _newDebt;
Troves[_borrower][_collateral].coll = _newColl;
_updateStakeAndTotalStakes(_borrower, _collateral);
emit TroveUpdated(
_borrower,
_collateral,
_newDebt, _newColl,
Troves[_borrower][_collateral].stake,
TroveManagerOperation.redeemCollateral
);
}
function burnLUSDAndEmitRedemptionEvent(
address _redeemer,
address _collateral,
uint _attemptedLUSDAmount,
uint _actualLUSDAmount,
uint _collSent,
uint _collFee
) external override {
_requireCallerIsRedemptionHelper();
lusdToken.burn(_redeemer, _actualLUSDAmount);
emit Redemption(_collateral, _attemptedLUSDAmount, _actualLUSDAmount, _collSent, _collFee);
}
/* Send _LUSDamount LUSD to the system and redeem the corresponding amount of collateral from as many Troves as are needed to fill the redemption
* request. Applies pending rewards to a Trove before reducing its debt and coll.
*
* Note that if _amount is very large, this function can run out of gas, specially if traversed troves are small. This can be easily avoided by
* splitting the total _amount in appropriate chunks and calling the function multiple times.
*