-
Notifications
You must be signed in to change notification settings - Fork 24
/
TroveManager.sol
1970 lines (1683 loc) · 85.8 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.8.24;
import "./Interfaces/ITroveManager.sol";
import "./Interfaces/IAddressesRegistry.sol";
import "./Interfaces/IStabilityPool.sol";
import "./Interfaces/ICollSurplusPool.sol";
import "./Interfaces/IBoldToken.sol";
import "./Interfaces/ISortedTroves.sol";
import "./Interfaces/ITroveEvents.sol";
import "./Interfaces/ITroveNFT.sol";
import "./Interfaces/ICollateralRegistry.sol";
import "./Interfaces/IWETH.sol";
import "./Dependencies/LiquityBase.sol";
contract TroveManager is LiquityBase, ITroveManager, ITroveEvents {
// --- Connected contract declarations ---
ITroveNFT public troveNFT;
IBorrowerOperations public borrowerOperations;
IStabilityPool public stabilityPool;
address internal gasPoolAddress;
ICollSurplusPool internal collSurplusPool;
IBoldToken internal boldToken;
// A doubly linked list of Troves, sorted by their interest rate
ISortedTroves public sortedTroves;
ICollateralRegistry internal collateralRegistry;
// Wrapped ETH for liquidation reserve (gas compensation)
IWETH internal immutable WETH;
// Critical system collateral ratio. If the system's total collateral ratio (TCR) falls below the CCR, some borrowing operation restrictions are applied
uint256 public immutable CCR;
// Minimum collateral ratio for individual troves
uint256 internal immutable MCR;
// Shutdown system collateral ratio. If the system's total collateral ratio (TCR) for a given collateral falls below the SCR,
// the protocol triggers the shutdown of the borrow market and permanently disables all borrowing operations except for closing Troves.
uint256 internal immutable SCR;
// Liquidation penalty for troves offset to the SP
uint256 internal immutable LIQUIDATION_PENALTY_SP;
// Liquidation penalty for troves redistributed
uint256 internal immutable LIQUIDATION_PENALTY_REDISTRIBUTION;
// --- Data structures ---
// Store the necessary data for a trove
struct Trove {
uint256 debt;
uint256 coll;
uint256 stake;
Status status;
uint64 arrayIndex;
uint64 lastDebtUpdateTime;
uint64 lastInterestRateAdjTime;
uint256 annualInterestRate;
address interestBatchManager;
uint256 batchDebtShares;
}
mapping(uint256 => Trove) public Troves;
// Store the necessary data for an interest batch manager. We treat each batch as a “big trove”.
// Each trove has a share of the debt of the global batch. Collateral is stored per trove (as CRs are different)
// Still the total amount of batch collateral is stored for informational purposes
struct Batch {
uint256 debt;
uint256 coll;
uint64 arrayIndex;
uint64 lastDebtUpdateTime;
uint64 lastInterestRateAdjTime;
uint256 annualInterestRate;
uint256 annualManagementFee;
uint256 totalDebtShares;
}
mapping(address => Batch) internal batches;
uint256 internal totalStakes;
// Snapshot of the value of totalStakes, taken immediately after the latest liquidation
uint256 internal totalStakesSnapshot;
// Snapshot of the total collateral across the ActivePool and DefaultPool, immediately after the latest liquidation.
uint256 internal totalCollateralSnapshot;
/*
* L_coll and L_boldDebt track the sums of accumulated liquidation rewards per unit staked. During its lifetime, each stake earns:
*
* An Coll gain of ( stake * [L_coll - L_coll(0)] )
* A boldDebt increase of ( stake * [L_boldDebt - L_boldDebt(0)] )
*
* Where L_coll(0) and L_boldDebt(0) are snapshots of L_coll and L_boldDebt for the active Trove taken at the instant the stake was made
*/
uint256 internal L_coll;
uint256 internal L_boldDebt;
// Map active troves to their RewardSnapshot
mapping(uint256 => RewardSnapshot) public rewardSnapshots;
// Object containing the Coll and Bold snapshots for a given active trove
struct RewardSnapshot {
uint256 coll;
uint256 boldDebt;
}
// Array of all active trove addresses - used to compute an approximate hint off-chain, for the sorted list insertion
uint256[] internal TroveIds;
// Array of all batch managers - used to fetch them off-chain
address[] public batchIds;
uint256 public lastZombieTroveId;
// Error trackers for the trove redistribution calculation
uint256 internal lastCollError_Redistribution;
uint256 internal lastBoldDebtError_Redistribution;
// Timestamp at which branch was shut down. 0 if not shut down.
uint256 public shutdownTime;
/*
* --- 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 LiquidationValues {
uint256 collGasCompensation;
uint256 debtToOffset;
uint256 collToSendToSP;
uint256 debtToRedistribute;
uint256 collToRedistribute;
uint256 collSurplus;
uint256 ETHGasCompensation;
uint256 oldWeightedRecordedDebt;
uint256 newWeightedRecordedDebt;
}
// --- Variable container structs for redemptions ---
struct SingleRedemptionValues {
uint256 troveId;
address batchAddress;
uint256 boldLot;
uint256 collLot;
uint256 collFee;
uint256 appliedRedistBoldDebtGain;
uint256 oldWeightedRecordedDebt;
uint256 newWeightedRecordedDebt;
uint256 newStake;
bool isZombieTrove;
LatestTroveData trove;
LatestBatchData batch;
}
// --- Errors ---
error EmptyData();
error NothingToLiquidate();
error CallerNotBorrowerOperations();
error CallerNotCollateralRegistry();
error OnlyOneTroveLeft();
error NotShutDown();
error ZeroAmount();
error NotEnoughBoldBalance();
error MinCollNotReached(uint256 _coll);
error BatchSharesRatioTooHigh();
// --- Events ---
event TroveNFTAddressChanged(address _newTroveNFTAddress);
event BorrowerOperationsAddressChanged(address _newBorrowerOperationsAddress);
event BoldTokenAddressChanged(address _newBoldTokenAddress);
event StabilityPoolAddressChanged(address _stabilityPoolAddress);
event GasPoolAddressChanged(address _gasPoolAddress);
event CollSurplusPoolAddressChanged(address _collSurplusPoolAddress);
event SortedTrovesAddressChanged(address _sortedTrovesAddress);
event CollateralRegistryAddressChanged(address _collateralRegistryAddress);
constructor(IAddressesRegistry _addressesRegistry) LiquityBase(_addressesRegistry) {
CCR = _addressesRegistry.CCR();
MCR = _addressesRegistry.MCR();
SCR = _addressesRegistry.SCR();
LIQUIDATION_PENALTY_SP = _addressesRegistry.LIQUIDATION_PENALTY_SP();
LIQUIDATION_PENALTY_REDISTRIBUTION = _addressesRegistry.LIQUIDATION_PENALTY_REDISTRIBUTION();
troveNFT = _addressesRegistry.troveNFT();
borrowerOperations = _addressesRegistry.borrowerOperations();
stabilityPool = _addressesRegistry.stabilityPool();
gasPoolAddress = _addressesRegistry.gasPoolAddress();
collSurplusPool = _addressesRegistry.collSurplusPool();
boldToken = _addressesRegistry.boldToken();
sortedTroves = _addressesRegistry.sortedTroves();
WETH = _addressesRegistry.WETH();
collateralRegistry = _addressesRegistry.collateralRegistry();
emit TroveNFTAddressChanged(address(troveNFT));
emit BorrowerOperationsAddressChanged(address(borrowerOperations));
emit StabilityPoolAddressChanged(address(stabilityPool));
emit GasPoolAddressChanged(gasPoolAddress);
emit CollSurplusPoolAddressChanged(address(collSurplusPool));
emit BoldTokenAddressChanged(address(boldToken));
emit SortedTrovesAddressChanged(address(sortedTroves));
emit CollateralRegistryAddressChanged(address(collateralRegistry));
}
// --- Getters ---
function getTroveIdsCount() external view override returns (uint256) {
return TroveIds.length;
}
function getTroveFromTroveIdsArray(uint256 _index) external view override returns (uint256) {
return TroveIds[_index];
}
// --- Trove Liquidation functions ---
// --- Inner single liquidation functions ---
// Liquidate one trove
function _liquidate(
IDefaultPool _defaultPool,
uint256 _troveId,
uint256 _boldInStabPool,
uint256 _price,
LatestTroveData memory trove,
LiquidationValues memory singleLiquidation
) internal {
address owner = troveNFT.ownerOf(_troveId);
_getLatestTroveData(_troveId, trove);
address batchAddress = _getBatchManager(_troveId);
bool isTroveInBatch = batchAddress != address(0);
LatestBatchData memory batch;
if (isTroveInBatch) _getLatestBatchData(batchAddress, batch);
_movePendingTroveRewardsToActivePool(_defaultPool, trove.redistBoldDebtGain, trove.redistCollGain);
singleLiquidation.collGasCompensation = _getCollGasCompensation(trove.entireColl);
uint256 collToLiquidate = trove.entireColl - singleLiquidation.collGasCompensation;
(
singleLiquidation.debtToOffset,
singleLiquidation.collToSendToSP,
singleLiquidation.debtToRedistribute,
singleLiquidation.collToRedistribute,
singleLiquidation.collSurplus
) = _getOffsetAndRedistributionVals(trove.entireDebt, collToLiquidate, _boldInStabPool, _price);
TroveChange memory troveChange;
troveChange.collDecrease = trove.entireColl;
troveChange.debtDecrease = trove.entireDebt;
troveChange.appliedRedistCollGain = trove.redistCollGain;
troveChange.appliedRedistBoldDebtGain = trove.redistBoldDebtGain;
_closeTrove(
_troveId,
troveChange,
batchAddress,
batch.entireCollWithoutRedistribution,
batch.entireDebtWithoutRedistribution,
Status.closedByLiquidation
);
if (isTroveInBatch) {
singleLiquidation.oldWeightedRecordedDebt =
batch.weightedRecordedDebt + (trove.entireDebt - trove.redistBoldDebtGain) * batch.annualInterestRate;
singleLiquidation.newWeightedRecordedDebt = batch.entireDebtWithoutRedistribution * batch.annualInterestRate;
// Mint batch management fee
troveChange.batchAccruedManagementFee = batch.accruedManagementFee;
troveChange.oldWeightedRecordedBatchManagementFee = batch.weightedRecordedBatchManagementFee
+ (trove.entireDebt - trove.redistBoldDebtGain) * batch.annualManagementFee;
troveChange.newWeightedRecordedBatchManagementFee =
batch.entireDebtWithoutRedistribution * batch.annualManagementFee;
activePool.mintBatchManagementFeeAndAccountForChange(troveChange, batchAddress);
} else {
singleLiquidation.oldWeightedRecordedDebt = trove.weightedRecordedDebt;
}
// Differencen between liquidation penalty and liquidation threshold
if (singleLiquidation.collSurplus > 0) {
collSurplusPool.accountSurplus(owner, singleLiquidation.collSurplus);
}
// Wipe out state in BO
borrowerOperations.onLiquidateTrove(_troveId);
emit TroveUpdated({
_troveId: _troveId,
_debt: 0,
_coll: 0,
_stake: 0,
_annualInterestRate: 0,
_snapshotOfTotalCollRedist: 0,
_snapshotOfTotalDebtRedist: 0
});
emit TroveOperation({
_troveId: _troveId,
_operation: Operation.liquidate,
_annualInterestRate: 0,
_debtIncreaseFromRedist: trove.redistBoldDebtGain,
_debtIncreaseFromUpfrontFee: 0,
_debtChangeFromOperation: -int256(trove.entireDebt),
_collIncreaseFromRedist: trove.redistCollGain,
_collChangeFromOperation: -int256(trove.entireColl)
});
if (isTroveInBatch) {
emit BatchUpdated({
_interestBatchManager: batchAddress,
_operation: BatchOperation.exitBatch,
_debt: batches[batchAddress].debt,
_coll: batches[batchAddress].coll,
_annualInterestRate: batch.annualInterestRate,
_annualManagementFee: batch.annualManagementFee,
_totalDebtShares: batches[batchAddress].totalDebtShares,
_debtIncreaseFromUpfrontFee: 0
});
}
}
// Return the amount of Coll to be drawn from a trove's collateral and sent as gas compensation.
function _getCollGasCompensation(uint256 _entireColl) internal pure returns (uint256) {
return LiquityMath._min(_entireColl / COLL_GAS_COMPENSATION_DIVISOR, COLL_GAS_COMPENSATION_CAP);
}
/* 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(
uint256 _entireTroveDebt,
uint256 _collToLiquidate, // gas compensation is already subtracted
uint256 _boldInStabPool,
uint256 _price
)
internal
view
returns (
uint256 debtToOffset,
uint256 collToSendToSP,
uint256 debtToRedistribute,
uint256 collToRedistribute,
uint256 collSurplus
)
{
uint256 collSPPortion;
/*
* 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 Bold in the Stability Pool:
*
* - Offset an amount of the trove's debt equal to the Bold in the Stability Pool
* - Send a fraction of the trove's collateral to the Stability Pool, equal to the fraction of its offset debt
*
*/
if (_boldInStabPool > 0) {
debtToOffset = LiquityMath._min(_entireTroveDebt, _boldInStabPool);
collSPPortion = _collToLiquidate * debtToOffset / _entireTroveDebt;
(collToSendToSP, collSurplus) =
_getCollPenaltyAndSurplus(collSPPortion, debtToOffset, LIQUIDATION_PENALTY_SP, _price);
}
// Redistribution
debtToRedistribute = _entireTroveDebt - debtToOffset;
if (debtToRedistribute > 0) {
uint256 collRedistributionPortion = _collToLiquidate - collSPPortion;
if (collRedistributionPortion > 0) {
(collToRedistribute, collSurplus) = _getCollPenaltyAndSurplus(
collRedistributionPortion + collSurplus, // Coll surplus from offset can be eaten up by red. penalty
debtToRedistribute,
LIQUIDATION_PENALTY_REDISTRIBUTION, // _penaltyRatio
_price
);
}
}
// assert(_collToLiquidate == collToSendToSP + collToRedistribute + collSurplus);
}
function _getCollPenaltyAndSurplus(
uint256 _collToLiquidate,
uint256 _debtToLiquidate,
uint256 _penaltyRatio,
uint256 _price
) internal pure returns (uint256 seizedColl, uint256 collSurplus) {
uint256 maxSeizedColl = _debtToLiquidate * (DECIMAL_PRECISION + _penaltyRatio) / _price;
if (_collToLiquidate > maxSeizedColl) {
seizedColl = maxSeizedColl;
collSurplus = _collToLiquidate - maxSeizedColl;
} else {
seizedColl = _collToLiquidate;
collSurplus = 0;
}
}
/*
* Attempt to liquidate a custom list of troves provided by the caller.
*/
function batchLiquidateTroves(uint256[] memory _troveArray) public override {
if (_troveArray.length == 0) {
revert EmptyData();
}
IActivePool activePoolCached = activePool;
IDefaultPool defaultPoolCached = defaultPool;
IStabilityPool stabilityPoolCached = stabilityPool;
TroveChange memory troveChange;
LiquidationValues memory totals;
(uint256 price,) = priceFeed.fetchPrice();
uint256 boldInStabPool = stabilityPoolCached.getTotalBoldDeposits();
// Perform the appropriate liquidation sequence - tally values and obtain their totals.
_batchLiquidateTroves(defaultPoolCached, price, boldInStabPool, _troveArray, totals, troveChange);
if (troveChange.debtDecrease == 0) {
revert NothingToLiquidate();
}
activePoolCached.mintAggInterestAndAccountForTroveChange(troveChange, address(0));
// Move liquidated Coll and Bold to the appropriate pools
if (totals.debtToOffset > 0 || totals.collToSendToSP > 0) {
stabilityPoolCached.offset(totals.debtToOffset, totals.collToSendToSP);
}
// we check amount is not zero inside
_redistributeDebtAndColl(
activePoolCached, defaultPoolCached, totals.debtToRedistribute, totals.collToRedistribute
);
if (totals.collSurplus > 0) {
activePoolCached.sendColl(address(collSurplusPool), totals.collSurplus);
}
// Update system snapshots
_updateSystemSnapshots_excludeCollRemainder(activePoolCached, totals.collGasCompensation);
emit Liquidation(
totals.debtToOffset,
totals.debtToRedistribute,
totals.ETHGasCompensation,
totals.collGasCompensation,
totals.collToSendToSP,
totals.collToRedistribute,
totals.collSurplus,
L_coll,
L_boldDebt,
price
);
// Send gas compensation to caller
_sendGasCompensation(activePoolCached, msg.sender, totals.ETHGasCompensation, totals.collGasCompensation);
}
function _isActiveOrZombie(Status _status) internal pure returns (bool) {
return _status == Status.active || _status == Status.zombie;
}
function _batchLiquidateTroves(
IDefaultPool _defaultPool,
uint256 _price,
uint256 _boldInStabPool,
uint256[] memory _troveArray,
LiquidationValues memory totals,
TroveChange memory troveChange
) internal {
uint256 remainingBoldInStabPool = _boldInStabPool;
for (uint256 i = 0; i < _troveArray.length; i++) {
uint256 troveId = _troveArray[i];
// Skip non-liquidatable troves
if (!_isActiveOrZombie(Troves[troveId].status)) continue;
uint256 ICR = getCurrentICR(troveId, _price);
if (ICR < MCR) {
LiquidationValues memory singleLiquidation;
LatestTroveData memory trove;
_liquidate(_defaultPool, troveId, remainingBoldInStabPool, _price, trove, singleLiquidation);
remainingBoldInStabPool -= singleLiquidation.debtToOffset;
// Add liquidation values to their respective running totals
_addLiquidationValuesToTotals(trove, singleLiquidation, totals, troveChange);
}
}
}
// --- Liquidation helper functions ---
// Adds all values from `singleLiquidation` to their respective totals in `totals` in-place
function _addLiquidationValuesToTotals(
LatestTroveData memory _trove,
LiquidationValues memory _singleLiquidation,
LiquidationValues memory totals,
TroveChange memory troveChange
) internal pure {
// Tally all the values with their respective running totals
totals.collGasCompensation += _singleLiquidation.collGasCompensation;
totals.ETHGasCompensation += ETH_GAS_COMPENSATION;
troveChange.debtDecrease += _trove.entireDebt;
troveChange.collDecrease += _trove.entireColl;
troveChange.appliedRedistBoldDebtGain += _trove.redistBoldDebtGain;
troveChange.oldWeightedRecordedDebt += _singleLiquidation.oldWeightedRecordedDebt;
troveChange.newWeightedRecordedDebt += _singleLiquidation.newWeightedRecordedDebt;
totals.debtToOffset += _singleLiquidation.debtToOffset;
totals.collToSendToSP += _singleLiquidation.collToSendToSP;
totals.debtToRedistribute += _singleLiquidation.debtToRedistribute;
totals.collToRedistribute += _singleLiquidation.collToRedistribute;
totals.collSurplus += _singleLiquidation.collSurplus;
}
function _sendGasCompensation(IActivePool _activePool, address _liquidator, uint256 _eth, uint256 _coll) internal {
if (_eth > 0) {
WETH.transferFrom(gasPoolAddress, _liquidator, _eth);
}
if (_coll > 0) {
_activePool.sendColl(_liquidator, _coll);
}
}
// Move a Trove's pending debt and collateral rewards from distributions, from the Default Pool to the Active Pool
function _movePendingTroveRewardsToActivePool(IDefaultPool _defaultPool, uint256 _bold, uint256 _coll) internal {
if (_bold > 0) {
_defaultPool.decreaseBoldDebt(_bold);
}
if (_coll > 0) {
_defaultPool.sendCollToActivePool(_coll);
}
}
// --- Redemption functions ---
function _applySingleRedemption(
IDefaultPool _defaultPool,
SingleRedemptionValues memory _singleRedemption,
bool _isTroveInBatch
) internal returns (uint256) {
// Decrease the debt and collateral of the current Trove according to the Bold lot and corresponding ETH to send
uint256 newDebt = _singleRedemption.trove.entireDebt - _singleRedemption.boldLot;
uint256 newColl = _singleRedemption.trove.entireColl - _singleRedemption.collLot;
_singleRedemption.appliedRedistBoldDebtGain = _singleRedemption.trove.redistBoldDebtGain;
if (_isTroveInBatch) {
_getLatestBatchData(_singleRedemption.batchAddress, _singleRedemption.batch);
// We know boldLot <= trove entire debt, so this subtraction is safe
uint256 newAmountForWeightedDebt = _singleRedemption.batch.entireDebtWithoutRedistribution
+ _singleRedemption.trove.redistBoldDebtGain - _singleRedemption.boldLot;
_singleRedemption.oldWeightedRecordedDebt = _singleRedemption.batch.weightedRecordedDebt;
_singleRedemption.newWeightedRecordedDebt =
newAmountForWeightedDebt * _singleRedemption.batch.annualInterestRate;
TroveChange memory troveChange;
troveChange.debtDecrease = _singleRedemption.boldLot;
troveChange.collDecrease = _singleRedemption.collLot;
troveChange.appliedRedistBoldDebtGain = _singleRedemption.trove.redistBoldDebtGain;
troveChange.appliedRedistCollGain = _singleRedemption.trove.redistCollGain;
// batchAccruedManagementFee is handled in the outer function
troveChange.oldWeightedRecordedBatchManagementFee =
_singleRedemption.batch.weightedRecordedBatchManagementFee;
troveChange.newWeightedRecordedBatchManagementFee =
newAmountForWeightedDebt * _singleRedemption.batch.annualManagementFee;
activePool.mintBatchManagementFeeAndAccountForChange(troveChange, _singleRedemption.batchAddress);
Troves[_singleRedemption.troveId].coll = newColl;
// interest and fee were updated in the outer function
// This call could revert due to BatchSharesRatioTooHigh if trove.redistCollGain > boldLot
// so we skip that check to avoid blocking redemptions
_updateBatchShares(
_singleRedemption.troveId,
_singleRedemption.batchAddress,
troveChange,
newDebt,
_singleRedemption.batch.entireCollWithoutRedistribution,
_singleRedemption.batch.entireDebtWithoutRedistribution,
false // _checkBatchSharesRatio
);
} else {
_singleRedemption.oldWeightedRecordedDebt = _singleRedemption.trove.weightedRecordedDebt;
_singleRedemption.newWeightedRecordedDebt = newDebt * _singleRedemption.trove.annualInterestRate;
Troves[_singleRedemption.troveId].debt = newDebt;
Troves[_singleRedemption.troveId].coll = newColl;
Troves[_singleRedemption.troveId].lastDebtUpdateTime = uint64(block.timestamp);
}
_singleRedemption.newStake = _updateStakeAndTotalStakes(_singleRedemption.troveId, newColl);
_movePendingTroveRewardsToActivePool(
_defaultPool, _singleRedemption.trove.redistBoldDebtGain, _singleRedemption.trove.redistCollGain
);
_updateTroveRewardSnapshots(_singleRedemption.troveId);
if (_isTroveInBatch) {
emit BatchedTroveUpdated({
_troveId: _singleRedemption.troveId,
_interestBatchManager: _singleRedemption.batchAddress,
_batchDebtShares: Troves[_singleRedemption.troveId].batchDebtShares,
_coll: newColl,
_stake: _singleRedemption.newStake,
_snapshotOfTotalCollRedist: L_coll,
_snapshotOfTotalDebtRedist: L_boldDebt
});
} else {
emit TroveUpdated({
_troveId: _singleRedemption.troveId,
_debt: newDebt,
_coll: newColl,
_stake: _singleRedemption.newStake,
_annualInterestRate: _singleRedemption.trove.annualInterestRate,
_snapshotOfTotalCollRedist: L_coll,
_snapshotOfTotalDebtRedist: L_boldDebt
});
}
emit TroveOperation({
_troveId: _singleRedemption.troveId,
_operation: Operation.redeemCollateral,
_annualInterestRate: _singleRedemption.trove.annualInterestRate,
_debtIncreaseFromRedist: _singleRedemption.trove.redistBoldDebtGain,
_debtIncreaseFromUpfrontFee: 0,
_debtChangeFromOperation: -int256(_singleRedemption.boldLot),
_collIncreaseFromRedist: _singleRedemption.trove.redistCollGain,
_collChangeFromOperation: -int256(_singleRedemption.collLot)
});
if (_isTroveInBatch) {
emit BatchUpdated({
_interestBatchManager: _singleRedemption.batchAddress,
_operation: BatchOperation.troveChange,
_debt: batches[_singleRedemption.batchAddress].debt,
_coll: batches[_singleRedemption.batchAddress].coll,
_annualInterestRate: _singleRedemption.batch.annualInterestRate,
_annualManagementFee: _singleRedemption.batch.annualManagementFee,
_totalDebtShares: batches[_singleRedemption.batchAddress].totalDebtShares,
_debtIncreaseFromUpfrontFee: 0
});
}
emit RedemptionFeePaidToTrove(_singleRedemption.troveId, _singleRedemption.collFee);
return newDebt;
}
// Redeem as much collateral as possible from _borrower's Trove in exchange for Bold up to _maxBoldamount
function _redeemCollateralFromTrove(
IDefaultPool _defaultPool,
SingleRedemptionValues memory _singleRedemption,
uint256 _maxBoldamount,
uint256 _price,
uint256 _redemptionRate
) internal {
_getLatestTroveData(_singleRedemption.troveId, _singleRedemption.trove);
// Determine the remaining amount (lot) to be redeemed, capped by the entire debt of the Trove
_singleRedemption.boldLot = LiquityMath._min(_maxBoldamount, _singleRedemption.trove.entireDebt);
// Get the amount of Coll equal in USD value to the boldLot redeemed
uint256 correspondingColl = _singleRedemption.boldLot * DECIMAL_PRECISION / _price;
// Calculate the collFee separately (for events)
_singleRedemption.collFee = correspondingColl * _redemptionRate / DECIMAL_PRECISION;
// Get the final collLot to send to redeemer, leaving the fee in the Trove
_singleRedemption.collLot = correspondingColl - _singleRedemption.collFee;
bool isTroveInBatch = _singleRedemption.batchAddress != address(0);
uint256 newDebt = _applySingleRedemption(_defaultPool, _singleRedemption, isTroveInBatch);
// Make Trove zombie if it's tiny (and it wasn’t already), in order to prevent griefing future (normal, sequential) redemptions
if (newDebt < MIN_DEBT) {
if (!_singleRedemption.isZombieTrove) {
Troves[_singleRedemption.troveId].status = Status.zombie;
if (isTroveInBatch) {
sortedTroves.removeFromBatch(_singleRedemption.troveId);
} else {
sortedTroves.remove(_singleRedemption.troveId);
}
// If it’s a partial redemption, let’s store a pointer to it so it’s used first in the next one
if (newDebt > 0) {
lastZombieTroveId = _singleRedemption.troveId;
}
} else if (newDebt == 0) {
// Reset last zombie trove pointer if the previous one was fully redeemed now
lastZombieTroveId = 0;
}
}
// Note: technically, it could happen that the Trove pointed to by `lastZombieTroveId` ends up with
// newDebt >= MIN_DEBT thanks to BOLD debt redistribution, which means it _could_ be made active again,
// however we don't do that here, as it would require hints for re-insertion into `SortedTroves`.
}
function _updateBatchInterestPriorToRedemption(IActivePool _activePool, address _batchAddress) internal {
LatestBatchData memory batch;
_getLatestBatchData(_batchAddress, batch);
batches[_batchAddress].debt = batch.entireDebtWithoutRedistribution;
batches[_batchAddress].lastDebtUpdateTime = uint64(block.timestamp);
// As we are updating the batch, we update the ActivePool weighted sum too
TroveChange memory batchTroveChange;
batchTroveChange.oldWeightedRecordedDebt = batch.weightedRecordedDebt;
batchTroveChange.newWeightedRecordedDebt = batch.entireDebtWithoutRedistribution * batch.annualInterestRate;
batchTroveChange.batchAccruedManagementFee = batch.accruedManagementFee;
batchTroveChange.oldWeightedRecordedBatchManagementFee = batch.weightedRecordedBatchManagementFee;
batchTroveChange.newWeightedRecordedBatchManagementFee =
batch.entireDebtWithoutRedistribution * batch.annualManagementFee;
_activePool.mintAggInterestAndAccountForTroveChange(batchTroveChange, _batchAddress);
}
/* Send _boldamount Bold to the system and redeem the corresponding amount of collateral from as many Troves as are needed to fill the redemption
* request. Applies redistribution gains 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.
*
* Param `_maxIterations` can also be provided, so the loop through Troves is capped (if it’s zero, it will be ignored).This makes it easier to
* avoid OOG for the frontend, as only knowing approximately the average cost of an iteration is enough, without needing to know the “topology”
* of the trove list. It also avoids the need to set the cap in stone in the contract, nor doing gas calculations, as both gas price and opcode
* costs can vary.
*
* All Troves that are redeemed from -- with the likely exception of the last one -- will end up with no debt left, and therefore in “zombie” state
*/
function redeemCollateral(
address _redeemer,
uint256 _boldamount,
uint256 _price,
uint256 _redemptionRate,
uint256 _maxIterations
) external override returns (uint256 _redemeedAmount) {
_requireCallerIsCollateralRegistry();
IActivePool activePoolCached = activePool;
ISortedTroves sortedTrovesCached = sortedTroves;
TroveChange memory totalsTroveChange;
uint256 totalCollFee;
uint256 remainingBold = _boldamount;
SingleRedemptionValues memory singleRedemption;
// Let’s check if there’s a pending zombie trove from previous redemption
if (lastZombieTroveId != 0) {
singleRedemption.troveId = lastZombieTroveId;
singleRedemption.isZombieTrove = true;
} else {
singleRedemption.troveId = sortedTrovesCached.getLast();
}
address lastBatchUpdatedInterest = address(0);
// Loop through the Troves starting from the one with lowest interest rate until _amount of Bold is exchanged for collateral
if (_maxIterations == 0) _maxIterations = type(uint256).max;
while (singleRedemption.troveId != 0 && remainingBold > 0 && _maxIterations > 0) {
_maxIterations--;
// Save the uint256 of the Trove preceding the current one
uint256 nextUserToCheck;
if (singleRedemption.isZombieTrove) {
nextUserToCheck = sortedTrovesCached.getLast();
} else {
nextUserToCheck = sortedTrovesCached.getPrev(singleRedemption.troveId);
}
// Skip if ICR < 100%, to make sure that redemptions don’t decrease the CR of hit Troves
if (getCurrentICR(singleRedemption.troveId, _price) < _100pct) {
singleRedemption.troveId = nextUserToCheck;
singleRedemption.isZombieTrove = false;
continue;
}
// If it’s in a batch, we need to update interest first
// We do it here outside, to avoid repeating for each trove in the same batch
singleRedemption.batchAddress = _getBatchManager(singleRedemption.troveId);
if (
singleRedemption.batchAddress != address(0) && singleRedemption.batchAddress != lastBatchUpdatedInterest
) {
_updateBatchInterestPriorToRedemption(activePoolCached, singleRedemption.batchAddress);
lastBatchUpdatedInterest = singleRedemption.batchAddress;
}
_redeemCollateralFromTrove(defaultPool, singleRedemption, remainingBold, _price, _redemptionRate);
totalsTroveChange.collDecrease += singleRedemption.collLot;
totalsTroveChange.debtDecrease += singleRedemption.boldLot;
totalsTroveChange.appliedRedistBoldDebtGain += singleRedemption.appliedRedistBoldDebtGain;
// For recorded and weighted recorded debt totals, we need to capture the increases and decreases,
// since the net debt change for a given Trove could be positive or negative: redemptions decrease a Trove's recorded
// (and weighted recorded) debt, but the accrued interest increases it.
totalsTroveChange.newWeightedRecordedDebt += singleRedemption.newWeightedRecordedDebt;
totalsTroveChange.oldWeightedRecordedDebt += singleRedemption.oldWeightedRecordedDebt;
totalCollFee += singleRedemption.collFee;
remainingBold -= singleRedemption.boldLot;
singleRedemption.troveId = nextUserToCheck;
singleRedemption.isZombieTrove = false;
}
// We are removing this condition to prevent blocking redemptions
//require(totals.totalCollDrawn > 0, "TroveManager: Unable to redeem any amount");
emit Redemption(
_boldamount, totalsTroveChange.debtDecrease, totalsTroveChange.collDecrease, totalCollFee, _price
);
activePoolCached.mintAggInterestAndAccountForTroveChange(totalsTroveChange, address(0));
// Send the redeemed Coll to sender
activePoolCached.sendColl(_redeemer, totalsTroveChange.collDecrease);
// We’ll burn all the Bold together out in the CollateralRegistry, to save gas
return totalsTroveChange.debtDecrease;
}
// Redeem as much collateral as possible from _borrower's Trove in exchange for Bold up to _maxBoldamount
function _urgentRedeemCollateralFromTrove(
IDefaultPool _defaultPool,
uint256 _maxBoldamount,
uint256 _price,
SingleRedemptionValues memory _singleRedemption
) internal {
// Determine the remaining amount (lot) to be redeemed, capped by the entire debt of the Trove minus the liquidation reserve
_singleRedemption.boldLot = LiquityMath._min(_maxBoldamount, _singleRedemption.trove.entireDebt);
// Get the amount of ETH equal in USD value to the BOLD lot redeemed
_singleRedemption.collLot = _singleRedemption.boldLot * (DECIMAL_PRECISION + URGENT_REDEMPTION_BONUS) / _price;
// As here we can redeem when CR < 101% (accounting for 1% bonus), we need to cap by collateral too
if (_singleRedemption.collLot > _singleRedemption.trove.entireColl) {
_singleRedemption.collLot = _singleRedemption.trove.entireColl;
_singleRedemption.boldLot =
_singleRedemption.trove.entireColl * _price / (DECIMAL_PRECISION + URGENT_REDEMPTION_BONUS);
}
bool isTroveInBatch = _singleRedemption.batchAddress != address(0);
_applySingleRedemption(_defaultPool, _singleRedemption, isTroveInBatch);
// No need to make this Trove zombie if it has tiny debt, since:
// - This collateral branch has shut down and urgent redemptions are enabled
// - Urgent redemptions aren't sequential, so they can't be griefed by tiny Troves.
}
function urgentRedemption(uint256 _boldAmount, uint256[] calldata _troveIds, uint256 _minCollateral) external {
_requireIsShutDown();
_requireAmountGreaterThanZero(_boldAmount);
_requireBoldBalanceCoversRedemption(boldToken, msg.sender, _boldAmount);
IActivePool activePoolCached = activePool;
TroveChange memory totalsTroveChange;
// Use the standard fetchPrice here, since if branch has shut down we don't worry about small redemption arbs
(uint256 price,) = priceFeed.fetchPrice();
uint256 remainingBold = _boldAmount;
for (uint256 i = 0; i < _troveIds.length; i++) {
if (remainingBold == 0) break;
SingleRedemptionValues memory singleRedemption;
singleRedemption.troveId = _troveIds[i];
_getLatestTroveData(singleRedemption.troveId, singleRedemption.trove);
if (!_isActiveOrZombie(Troves[singleRedemption.troveId].status) || singleRedemption.trove.entireDebt == 0) {
continue;
}
// If it’s in a batch, we need to update interest first
// As we don’t have them ordered now, we cannot avoid repeating for each trove in the same batch
singleRedemption.batchAddress = _getBatchManager(singleRedemption.troveId);
if (singleRedemption.batchAddress != address(0)) {
_updateBatchInterestPriorToRedemption(activePoolCached, singleRedemption.batchAddress);
}
_urgentRedeemCollateralFromTrove(defaultPool, remainingBold, price, singleRedemption);
totalsTroveChange.collDecrease += singleRedemption.collLot;
totalsTroveChange.debtDecrease += singleRedemption.boldLot;
totalsTroveChange.appliedRedistBoldDebtGain += singleRedemption.appliedRedistBoldDebtGain;
// For recorded and weighted recorded debt totals, we need to capture the increases and decreases,
// since the net debt change for a given Trove could be positive or negative: redemptions decrease a Trove's recorded
// (and weighted recorded) debt, but the accrued interest increases it.
totalsTroveChange.newWeightedRecordedDebt += singleRedemption.newWeightedRecordedDebt;
totalsTroveChange.oldWeightedRecordedDebt += singleRedemption.oldWeightedRecordedDebt;
remainingBold -= singleRedemption.boldLot;
}
if (totalsTroveChange.collDecrease < _minCollateral) {
revert MinCollNotReached(totalsTroveChange.collDecrease);
}
emit Redemption(_boldAmount, totalsTroveChange.debtDecrease, totalsTroveChange.collDecrease, 0, price);
// Since this branch is shut down, this will mint 0 interest.
// We call this only to update the aggregate debt and weighted debt trackers.
activePoolCached.mintAggInterestAndAccountForTroveChange(totalsTroveChange, address(0));
// Send the redeemed coll to caller
activePoolCached.sendColl(msg.sender, totalsTroveChange.collDecrease);
// Burn bold
boldToken.burn(msg.sender, totalsTroveChange.debtDecrease);
}
function shutdown() external {
_requireCallerIsBorrowerOperations();
shutdownTime = block.timestamp;
activePool.setShutdownFlag();
}
// --- Helper functions ---
// Return the current collateral ratio (ICR) of a given Trove. Takes a trove's pending coll and debt rewards from redistributions into account.
function getCurrentICR(uint256 _troveId, uint256 _price) public view override returns (uint256) {
LatestTroveData memory trove;
_getLatestTroveData(_troveId, trove);
return LiquityMath._computeCR(trove.entireColl, trove.entireDebt, _price);
}
function _updateTroveRewardSnapshots(uint256 _troveId) internal {
rewardSnapshots[_troveId].coll = L_coll;
rewardSnapshots[_troveId].boldDebt = L_boldDebt;
}
// Return the Troves entire debt and coll, including redistribution gains from redistributions.
function _getLatestTroveData(uint256 _troveId, LatestTroveData memory trove) internal view {
// If trove belongs to a batch, we fetch the batch and apply its share to obtained values
address batchAddress = _getBatchManager(_troveId);
if (batchAddress != address(0)) {
LatestBatchData memory batch;
_getLatestBatchData(batchAddress, batch);
_getLatestTroveDataFromBatch(_troveId, batchAddress, trove, batch);
return;
}
uint256 stake = Troves[_troveId].stake;
trove.redistBoldDebtGain = stake * (L_boldDebt - rewardSnapshots[_troveId].boldDebt) / DECIMAL_PRECISION;
trove.redistCollGain = stake * (L_coll - rewardSnapshots[_troveId].coll) / DECIMAL_PRECISION;
trove.recordedDebt = Troves[_troveId].debt;
trove.annualInterestRate = Troves[_troveId].annualInterestRate;
trove.weightedRecordedDebt = trove.recordedDebt * trove.annualInterestRate;
uint256 period = _getInterestPeriod(Troves[_troveId].lastDebtUpdateTime);
trove.accruedInterest = _calcInterest(trove.weightedRecordedDebt, period);
trove.entireDebt = trove.recordedDebt + trove.redistBoldDebtGain + trove.accruedInterest;
trove.entireColl = Troves[_troveId].coll + trove.redistCollGain;
trove.lastInterestRateAdjTime = Troves[_troveId].lastInterestRateAdjTime;
}
function _getLatestTroveDataFromBatch(
uint256 _troveId,
address _batchAddress,
LatestTroveData memory _latestTroveData,
LatestBatchData memory _latestBatchData
) internal view {
Trove memory trove = Troves[_troveId];
uint256 batchDebtShares = trove.batchDebtShares;
uint256 totalDebtShares = batches[_batchAddress].totalDebtShares;
uint256 stake = trove.stake;
_latestTroveData.redistBoldDebtGain =
stake * (L_boldDebt - rewardSnapshots[_troveId].boldDebt) / DECIMAL_PRECISION;
_latestTroveData.redistCollGain = stake * (L_coll - rewardSnapshots[_troveId].coll) / DECIMAL_PRECISION;
if (totalDebtShares > 0) {
_latestTroveData.recordedDebt = _latestBatchData.recordedDebt * batchDebtShares / totalDebtShares;
_latestTroveData.weightedRecordedDebt = _latestTroveData.recordedDebt * _latestBatchData.annualInterestRate;
_latestTroveData.accruedInterest = _latestBatchData.accruedInterest * batchDebtShares / totalDebtShares;
_latestTroveData.accruedBatchManagementFee =
_latestBatchData.accruedManagementFee * batchDebtShares / totalDebtShares;
}
_latestTroveData.annualInterestRate = _latestBatchData.annualInterestRate;
// We can’t do pro-rata batch entireDebt, because redist gains are proportional to coll, not to debt
_latestTroveData.entireDebt = _latestTroveData.recordedDebt + _latestTroveData.redistBoldDebtGain
+ _latestTroveData.accruedInterest + _latestTroveData.accruedBatchManagementFee;
_latestTroveData.entireColl = trove.coll + _latestTroveData.redistCollGain;
_latestTroveData.lastInterestRateAdjTime =
LiquityMath._max(_latestBatchData.lastInterestRateAdjTime, trove.lastInterestRateAdjTime);
}
function getLatestTroveData(uint256 _troveId) external view returns (LatestTroveData memory trove) {
_getLatestTroveData(_troveId, trove);
}
function getTroveAnnualInterestRate(uint256 _troveId) external view returns (uint256) {
Trove memory trove = Troves[_troveId];
address batchAddress = _getBatchManager(trove);
if (batchAddress != address(0)) {
return batches[batchAddress].annualInterestRate;
}
return trove.annualInterestRate;
}
function _getBatchManager(uint256 _troveId) internal view returns (address) {
return Troves[_troveId].interestBatchManager;
}
function _getBatchManager(Trove memory trove) internal pure returns (address) {
return trove.interestBatchManager;