-
Notifications
You must be signed in to change notification settings - Fork 134
Expand file tree
/
Copy pathBorrowerOperations.sol
More file actions
1616 lines (1350 loc) · 63.4 KB
/
BorrowerOperations.sol
File metadata and controls
1616 lines (1350 loc) · 63.4 KB
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 "openzeppelin-contracts/contracts/token/ERC20/utils/SafeERC20.sol";
import "./Interfaces/IBorrowerOperations.sol";
import "./Interfaces/IAddressesRegistry.sol";
import "./Interfaces/ITroveManager.sol";
import "./Interfaces/IBoldToken.sol";
import "./Interfaces/ICollSurplusPool.sol";
import "./Interfaces/ISortedTroves.sol";
import "./Dependencies/LiquityBase.sol";
import "./Dependencies/AddRemoveManagers.sol";
import "./Types/LatestTroveData.sol";
import "./Types/LatestBatchData.sol";
contract BorrowerOperations is LiquityBase, AddRemoveManagers, IBorrowerOperations {
using SafeERC20 for IERC20;
// --- Connected contract declarations ---
IERC20 internal immutable collToken;
ITroveManager internal troveManager;
address internal gasPoolAddress;
ICollSurplusPool internal collSurplusPool;
IBoldToken internal boldToken;
// A doubly linked list of Troves, sorted by their collateral ratios
ISortedTroves internal sortedTroves;
// 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;
// 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 public immutable SCR;
bool public hasBeenShutDown;
// Minimum collateral ratio for individual troves
uint256 public immutable MCR;
// Extra buffer of collateral ratio to join a batch or adjust a trove inside a batch (on top of MCR)
uint256 public immutable BCR;
/*
* Mapping from TroveId to individual delegate for interest rate setting.
*
* This address then has the ability to update the borrower’s interest rate, but not change its debt or collateral.
* Useful for instance for cold/hot wallet setups.
*/
mapping(uint256 => InterestIndividualDelegate) private interestIndividualDelegateOf;
/*
* Mapping from TroveId to granted address for interest rate setting (batch manager).
*
* Batch managers set the interest rate for every Trove in the batch. The interest rate is the same for all Troves in the batch.
*/
mapping(uint256 => address) public interestBatchManagerOf;
// List of registered Interest Batch Managers
mapping(address => InterestBatchManager) private interestBatchManagers;
/* --- Variable container structs ---
Used to hold, return and assign variables inside a function, in order to avoid the error:
"CompilerError: Stack too deep". */
struct OpenTroveVars {
ITroveManager troveManager;
uint256 troveId;
TroveChange change;
LatestBatchData batch;
}
struct LocalVariables_openTrove {
ITroveManager troveManager;
IActivePool activePool;
IBoldToken boldToken;
uint256 troveId;
uint256 price;
uint256 avgInterestRate;
uint256 entireDebt;
uint256 ICR;
uint256 newTCR;
bool newOracleFailureDetected;
}
struct LocalVariables_adjustTrove {
IActivePool activePool;
IBoldToken boldToken;
LatestTroveData trove;
uint256 price;
bool isBelowCriticalThreshold;
uint256 newICR;
uint256 newDebt;
uint256 newColl;
bool newOracleFailureDetected;
}
struct LocalVariables_setInterestBatchManager {
ITroveManager troveManager;
IActivePool activePool;
ISortedTroves sortedTroves;
address oldBatchManager;
LatestTroveData trove;
LatestBatchData oldBatch;
LatestBatchData newBatch;
}
struct LocalVariables_removeFromBatch {
ITroveManager troveManager;
ISortedTroves sortedTroves;
address batchManager;
LatestTroveData trove;
LatestBatchData batch;
uint256 batchFutureDebt;
TroveChange batchChange;
}
error IsShutDown();
error TCRNotBelowSCR();
error ZeroAdjustment();
error NotOwnerNorInterestManager();
error TroveInBatch();
error TroveNotInBatch();
error InterestNotInRange();
error BatchInterestRateChangePeriodNotPassed();
error DelegateInterestRateChangePeriodNotPassed();
error TroveExists();
error TroveNotOpen();
error TroveNotActive();
error TroveNotZombie();
error TroveWithZeroDebt();
error UpfrontFeeTooHigh();
error ICRBelowMCR();
error ICRBelowMCRPlusBCR();
error RepaymentNotMatchingCollWithdrawal();
error TCRBelowCCR();
error DebtBelowMin();
error CollWithdrawalTooHigh();
error NotEnoughBoldBalance();
error InterestRateTooLow();
error InterestRateTooHigh();
error InterestRateNotNew();
error InvalidInterestBatchManager();
error BatchManagerExists();
error BatchManagerNotNew();
error NewFeeNotLower();
error CallerNotTroveManager();
error CallerNotPriceFeed();
error MinGeMax();
error AnnualManagementFeeTooHigh();
error MinInterestRateChangePeriodTooLow();
error NewOracleFailureDetected();
error BatchSharesRatioTooLow();
event TroveManagerAddressChanged(address _newTroveManagerAddress);
event GasPoolAddressChanged(address _gasPoolAddress);
event CollSurplusPoolAddressChanged(address _collSurplusPoolAddress);
event SortedTrovesAddressChanged(address _sortedTrovesAddress);
event BoldTokenAddressChanged(address _boldTokenAddress);
event ShutDown(uint256 _tcr);
constructor(IAddressesRegistry _addressesRegistry)
AddRemoveManagers(_addressesRegistry)
LiquityBase(_addressesRegistry)
{
// This makes impossible to open a trove with zero withdrawn Bold
assert(MIN_DEBT > 0);
collToken = _addressesRegistry.collToken();
WETH = _addressesRegistry.WETH();
CCR = _addressesRegistry.CCR();
SCR = _addressesRegistry.SCR();
MCR = _addressesRegistry.MCR();
BCR = _addressesRegistry.BCR();
troveManager = _addressesRegistry.troveManager();
gasPoolAddress = _addressesRegistry.gasPoolAddress();
collSurplusPool = _addressesRegistry.collSurplusPool();
sortedTroves = _addressesRegistry.sortedTroves();
boldToken = _addressesRegistry.boldToken();
emit TroveManagerAddressChanged(address(troveManager));
emit GasPoolAddressChanged(gasPoolAddress);
emit CollSurplusPoolAddressChanged(address(collSurplusPool));
emit SortedTrovesAddressChanged(address(sortedTroves));
emit BoldTokenAddressChanged(address(boldToken));
// Allow funds movements between Liquity contracts
collToken.approve(address(activePool), type(uint256).max);
}
// --- Borrower Trove Operations ---
function openTrove(
address _owner,
uint256 _ownerIndex,
uint256 _collAmount,
uint256 _boldAmount,
uint256 _upperHint,
uint256 _lowerHint,
uint256 _annualInterestRate,
uint256 _maxUpfrontFee,
address _addManager,
address _removeManager,
address _receiver
) external override returns (uint256) {
_requireValidAnnualInterestRate(_annualInterestRate);
OpenTroveVars memory vars;
vars.troveId = _openTrove(
_owner,
_ownerIndex,
_collAmount,
_boldAmount,
_annualInterestRate,
address(0),
0,
0,
_maxUpfrontFee,
_addManager,
_removeManager,
_receiver,
vars.change
);
// Set the stored Trove properties and mint the NFT
troveManager.onOpenTrove(_owner, vars.troveId, vars.change, _annualInterestRate);
sortedTroves.insert(vars.troveId, _annualInterestRate, _upperHint, _lowerHint);
return vars.troveId;
}
function openTroveAndJoinInterestBatchManager(OpenTroveAndJoinInterestBatchManagerParams calldata _params)
external
override
returns (uint256)
{
_requireValidInterestBatchManager(_params.interestBatchManager);
OpenTroveVars memory vars;
vars.troveManager = troveManager;
vars.batch = vars.troveManager.getLatestBatchData(_params.interestBatchManager);
// We set old weighted values here, as it’s only necessary for batches, so we don’t need to pass them to _openTrove func
vars.change.batchAccruedManagementFee = vars.batch.accruedManagementFee;
vars.change.oldWeightedRecordedDebt = vars.batch.weightedRecordedDebt;
vars.change.oldWeightedRecordedBatchManagementFee = vars.batch.weightedRecordedBatchManagementFee;
vars.troveId = _openTrove(
_params.owner,
_params.ownerIndex,
_params.collAmount,
_params.boldAmount,
vars.batch.annualInterestRate,
_params.interestBatchManager,
vars.batch.entireDebtWithoutRedistribution,
vars.batch.annualManagementFee,
_params.maxUpfrontFee,
_params.addManager,
_params.removeManager,
_params.receiver,
vars.change
);
interestBatchManagerOf[vars.troveId] = _params.interestBatchManager;
// Set the stored Trove properties and mint the NFT
vars.troveManager.onOpenTroveAndJoinBatch(
_params.owner,
vars.troveId,
vars.change,
_params.interestBatchManager,
vars.batch.entireCollWithoutRedistribution,
vars.batch.entireDebtWithoutRedistribution
);
sortedTroves.insertIntoBatch(
vars.troveId,
BatchId.wrap(_params.interestBatchManager),
vars.batch.annualInterestRate,
_params.upperHint,
_params.lowerHint
);
return vars.troveId;
}
function _openTrove(
address _owner,
uint256 _ownerIndex,
uint256 _collAmount,
uint256 _boldAmount,
uint256 _annualInterestRate,
address _interestBatchManager,
uint256 _batchEntireDebt,
uint256 _batchManagementAnnualFee,
uint256 _maxUpfrontFee,
address _addManager,
address _removeManager,
address _receiver,
TroveChange memory _change
) internal returns (uint256) {
_requireIsNotShutDown();
LocalVariables_openTrove memory vars;
// stack too deep not allowing to reuse troveManager from outer functions
vars.troveManager = troveManager;
vars.activePool = activePool;
vars.boldToken = boldToken;
vars.price = _requireOraclesLive();
// --- Checks ---
vars.troveId = uint256(keccak256(abi.encode(msg.sender, _owner, _ownerIndex)));
_requireTroveDoesNotExists(vars.troveManager, vars.troveId);
_change.collIncrease = _collAmount;
_change.debtIncrease = _boldAmount;
// For simplicity, we ignore the fee when calculating the approx. interest rate
_change.newWeightedRecordedDebt = (_batchEntireDebt + _change.debtIncrease) * _annualInterestRate;
vars.avgInterestRate = vars.activePool.getNewApproxAvgInterestRateFromTroveChange(_change);
_change.upfrontFee = _calcUpfrontFee(_change.debtIncrease, vars.avgInterestRate);
_requireUserAcceptsUpfrontFee(_change.upfrontFee, _maxUpfrontFee);
vars.entireDebt = _change.debtIncrease + _change.upfrontFee;
_requireAtLeastMinDebt(vars.entireDebt);
vars.ICR = LiquityMath._computeCR(_collAmount, vars.entireDebt, vars.price);
// Recalculate newWeightedRecordedDebt, now taking into account the upfront fee, and the batch fee if needed
if (_interestBatchManager == address(0)) {
_change.newWeightedRecordedDebt = vars.entireDebt * _annualInterestRate;
// ICR is based on the requested Bold amount + upfront fee.
_requireICRisAboveMCR(vars.ICR);
} else {
// old values have been set outside, before calling this function
_change.newWeightedRecordedDebt = (_batchEntireDebt + vars.entireDebt) * _annualInterestRate;
_change.newWeightedRecordedBatchManagementFee =
(_batchEntireDebt + vars.entireDebt) * _batchManagementAnnualFee;
// ICR is based on the requested Bold amount + upfront fee.
// Troves in a batch have a stronger requirement (MCR+BCR)
_requireICRisAboveMCRPlusBCR(vars.ICR);
}
vars.newTCR = _getNewTCRFromTroveChange(_change, vars.price);
_requireNewTCRisAboveCCR(vars.newTCR);
// --- Effects & interactions ---
// Set add/remove managers
_setAddManager(vars.troveId, _addManager);
_setRemoveManagerAndReceiver(vars.troveId, _removeManager, _receiver);
vars.activePool.mintAggInterestAndAccountForTroveChange(_change, _interestBatchManager);
// Pull coll tokens from sender and move them to the Active Pool
_pullCollAndSendToActivePool(vars.activePool, _collAmount);
// Mint the requested _boldAmount to the borrower and mint the gas comp to the GasPool
vars.boldToken.mint(msg.sender, _boldAmount);
WETH.transferFrom(msg.sender, gasPoolAddress, ETH_GAS_COMPENSATION);
return vars.troveId;
}
// Send collateral to a trove
function addColl(uint256 _troveId, uint256 _collAmount) external override {
ITroveManager troveManagerCached = troveManager;
_requireTroveIsActive(troveManagerCached, _troveId);
TroveChange memory troveChange;
troveChange.collIncrease = _collAmount;
_adjustTrove(
troveManagerCached,
_troveId,
troveChange,
0 // _maxUpfrontFee
);
}
// Withdraw collateral from a trove
function withdrawColl(uint256 _troveId, uint256 _collWithdrawal) external override {
ITroveManager troveManagerCached = troveManager;
_requireTroveIsActive(troveManagerCached, _troveId);
TroveChange memory troveChange;
troveChange.collDecrease = _collWithdrawal;
_adjustTrove(
troveManagerCached,
_troveId,
troveChange,
0 // _maxUpfrontFee
);
}
// Withdraw Bold tokens from a trove: mint new Bold tokens to the owner, and increase the trove's debt accordingly
function withdrawBold(uint256 _troveId, uint256 _boldAmount, uint256 _maxUpfrontFee) external override {
ITroveManager troveManagerCached = troveManager;
_requireTroveIsActive(troveManagerCached, _troveId);
TroveChange memory troveChange;
troveChange.debtIncrease = _boldAmount;
_adjustTrove(troveManagerCached, _troveId, troveChange, _maxUpfrontFee);
}
// Repay Bold tokens to a Trove: Burn the repaid Bold tokens, and reduce the trove's debt accordingly
function repayBold(uint256 _troveId, uint256 _boldAmount) external override {
ITroveManager troveManagerCached = troveManager;
_requireTroveIsActive(troveManagerCached, _troveId);
TroveChange memory troveChange;
troveChange.debtDecrease = _boldAmount;
_adjustTrove(
troveManagerCached,
_troveId,
troveChange,
0 // _maxUpfrontFee
);
}
function _initTroveChange(
TroveChange memory _troveChange,
uint256 _collChange,
bool _isCollIncrease,
uint256 _boldChange,
bool _isDebtIncrease
) internal pure {
if (_isCollIncrease) {
_troveChange.collIncrease = _collChange;
} else {
_troveChange.collDecrease = _collChange;
}
if (_isDebtIncrease) {
_troveChange.debtIncrease = _boldChange;
} else {
_troveChange.debtDecrease = _boldChange;
}
}
function adjustTrove(
uint256 _troveId,
uint256 _collChange,
bool _isCollIncrease,
uint256 _boldChange,
bool _isDebtIncrease,
uint256 _maxUpfrontFee
) external override {
ITroveManager troveManagerCached = troveManager;
_requireTroveIsActive(troveManagerCached, _troveId);
TroveChange memory troveChange;
_initTroveChange(troveChange, _collChange, _isCollIncrease, _boldChange, _isDebtIncrease);
_adjustTrove(troveManagerCached, _troveId, troveChange, _maxUpfrontFee);
}
function adjustZombieTrove(
uint256 _troveId,
uint256 _collChange,
bool _isCollIncrease,
uint256 _boldChange,
bool _isDebtIncrease,
uint256 _upperHint,
uint256 _lowerHint,
uint256 _maxUpfrontFee
) external override {
ITroveManager troveManagerCached = troveManager;
_requireTroveIsZombie(troveManagerCached, _troveId);
TroveChange memory troveChange;
_initTroveChange(troveChange, _collChange, _isCollIncrease, _boldChange, _isDebtIncrease);
_adjustTrove(troveManagerCached, _troveId, troveChange, _maxUpfrontFee);
troveManagerCached.setTroveStatusToActive(_troveId);
address batchManager = interestBatchManagerOf[_troveId];
uint256 batchAnnualInterestRate;
if (batchManager != address(0)) {
LatestBatchData memory batch = troveManagerCached.getLatestBatchData(batchManager);
batchAnnualInterestRate = batch.annualInterestRate;
}
_reInsertIntoSortedTroves(
_troveId,
troveManagerCached.getTroveAnnualInterestRate(_troveId),
_upperHint,
_lowerHint,
batchManager,
batchAnnualInterestRate
);
}
function adjustTroveInterestRate(
uint256 _troveId,
uint256 _newAnnualInterestRate,
uint256 _upperHint,
uint256 _lowerHint,
uint256 _maxUpfrontFee
) external {
_requireIsNotShutDown();
ITroveManager troveManagerCached = troveManager;
_requireValidAnnualInterestRate(_newAnnualInterestRate);
_requireIsNotInBatch(_troveId);
_requireSenderIsOwnerOrInterestManager(_troveId);
_requireTroveIsActive(troveManagerCached, _troveId);
LatestTroveData memory trove = troveManagerCached.getLatestTroveData(_troveId);
_requireValidDelegateAdustment(_troveId, trove.lastInterestRateAdjTime, _newAnnualInterestRate);
_requireAnnualInterestRateIsNew(trove.annualInterestRate, _newAnnualInterestRate);
uint256 newDebt = trove.entireDebt;
TroveChange memory troveChange;
troveChange.appliedRedistBoldDebtGain = trove.redistBoldDebtGain;
troveChange.appliedRedistCollGain = trove.redistCollGain;
troveChange.newWeightedRecordedDebt = newDebt * _newAnnualInterestRate;
troveChange.oldWeightedRecordedDebt = trove.weightedRecordedDebt;
// Apply upfront fee on premature adjustments. It checks the resulting ICR
if (block.timestamp < trove.lastInterestRateAdjTime + INTEREST_RATE_ADJ_COOLDOWN) {
newDebt = _applyUpfrontFee(trove.entireColl, newDebt, troveChange, _maxUpfrontFee, false);
}
// Recalculate newWeightedRecordedDebt, now taking into account the upfront fee
troveChange.newWeightedRecordedDebt = newDebt * _newAnnualInterestRate;
activePool.mintAggInterestAndAccountForTroveChange(troveChange, address(0));
sortedTroves.reInsert(_troveId, _newAnnualInterestRate, _upperHint, _lowerHint);
troveManagerCached.onAdjustTroveInterestRate(
_troveId, trove.entireColl, newDebt, _newAnnualInterestRate, troveChange
);
}
/*
* _adjustTrove(): Alongside a debt change, this function can perform either a collateral top-up or a collateral withdrawal.
*/
function _adjustTrove(
ITroveManager _troveManager,
uint256 _troveId,
TroveChange memory _troveChange,
uint256 _maxUpfrontFee
) internal {
_requireIsNotShutDown();
LocalVariables_adjustTrove memory vars;
vars.activePool = activePool;
vars.boldToken = boldToken;
vars.price = _requireOraclesLive();
vars.isBelowCriticalThreshold = _checkBelowCriticalThreshold(vars.price, CCR);
// --- Checks ---
_requireTroveIsOpen(_troveManager, _troveId);
address owner = troveNFT.ownerOf(_troveId);
address receiver = owner; // If it’s a withdrawal, and remove manager privilege is set, a different receiver can be defined
if (_troveChange.collDecrease > 0 || _troveChange.debtIncrease > 0) {
receiver = _requireSenderIsOwnerOrRemoveManagerAndGetReceiver(_troveId, owner);
} else {
// RemoveManager assumes AddManager, so if the former is set, there's no need to check the latter
_requireSenderIsOwnerOrAddManager(_troveId, owner);
// No need to check the type of trove change for two reasons:
// - If the check above fails, it means sender is not owner, nor AddManager, nor RemoveManager.
// An independent 3rd party should not be allowed here.
// - If it's not collIncrease or debtDecrease, _requireNonZeroAdjustment would revert
}
vars.trove = _troveManager.getLatestTroveData(_troveId);
// When the adjustment is a debt repayment, check it's a valid amount and that the caller has enough Bold
if (_troveChange.debtDecrease > 0) {
uint256 maxRepayment = vars.trove.entireDebt > MIN_DEBT ? vars.trove.entireDebt - MIN_DEBT : 0;
if (_troveChange.debtDecrease > maxRepayment) {
_troveChange.debtDecrease = maxRepayment;
}
_requireSufficientBoldBalance(vars.boldToken, msg.sender, _troveChange.debtDecrease);
}
_requireNonZeroAdjustment(_troveChange);
// When the adjustment is a collateral withdrawal, check that it's no more than the Trove's entire collateral
if (_troveChange.collDecrease > 0) {
_requireValidCollWithdrawal(vars.trove.entireColl, _troveChange.collDecrease);
}
vars.newColl = vars.trove.entireColl + _troveChange.collIncrease - _troveChange.collDecrease;
vars.newDebt = vars.trove.entireDebt + _troveChange.debtIncrease - _troveChange.debtDecrease;
address batchManager = interestBatchManagerOf[_troveId];
bool isTroveInBatch = batchManager != address(0);
LatestBatchData memory batch;
uint256 batchFutureDebt;
if (isTroveInBatch) {
batch = _troveManager.getLatestBatchData(batchManager);
batchFutureDebt = batch.entireDebtWithoutRedistribution + vars.trove.redistBoldDebtGain
+ _troveChange.debtIncrease - _troveChange.debtDecrease;
_troveChange.appliedRedistBoldDebtGain = vars.trove.redistBoldDebtGain;
_troveChange.appliedRedistCollGain = vars.trove.redistCollGain;
_troveChange.batchAccruedManagementFee = batch.accruedManagementFee;
_troveChange.oldWeightedRecordedDebt = batch.weightedRecordedDebt;
_troveChange.newWeightedRecordedDebt = batchFutureDebt * batch.annualInterestRate;
_troveChange.oldWeightedRecordedBatchManagementFee = batch.weightedRecordedBatchManagementFee;
_troveChange.newWeightedRecordedBatchManagementFee = batchFutureDebt * batch.annualManagementFee;
} else {
_troveChange.appliedRedistBoldDebtGain = vars.trove.redistBoldDebtGain;
_troveChange.appliedRedistCollGain = vars.trove.redistCollGain;
_troveChange.oldWeightedRecordedDebt = vars.trove.weightedRecordedDebt;
_troveChange.newWeightedRecordedDebt = vars.newDebt * vars.trove.annualInterestRate;
}
// Pay an upfront fee on debt increases
if (_troveChange.debtIncrease > 0) {
uint256 avgInterestRate = vars.activePool.getNewApproxAvgInterestRateFromTroveChange(_troveChange);
_troveChange.upfrontFee = _calcUpfrontFee(_troveChange.debtIncrease, avgInterestRate);
_requireUserAcceptsUpfrontFee(_troveChange.upfrontFee, _maxUpfrontFee);
vars.newDebt += _troveChange.upfrontFee;
if (isTroveInBatch) {
batchFutureDebt += _troveChange.upfrontFee;
// Recalculate newWeightedRecordedDebt, now taking into account the upfront fee
_troveChange.newWeightedRecordedDebt = batchFutureDebt * batch.annualInterestRate;
_troveChange.newWeightedRecordedBatchManagementFee = batchFutureDebt * batch.annualManagementFee;
} else {
// Recalculate newWeightedRecordedDebt, now taking into account the upfront fee
_troveChange.newWeightedRecordedDebt = vars.newDebt * vars.trove.annualInterestRate;
}
}
// Make sure the Trove doesn't end up zombie
// Now the max repayment is capped to stay above MIN_DEBT, so this only applies to adjustZombieTrove
_requireAtLeastMinDebt(vars.newDebt);
vars.newICR = LiquityMath._computeCR(vars.newColl, vars.newDebt, vars.price);
// Check the adjustment satisfies all conditions for the current system mode
_requireValidAdjustmentInCurrentMode(_troveChange, vars, isTroveInBatch);
// --- Effects and interactions ---
if (isTroveInBatch) {
_troveManager.onAdjustTroveInsideBatch(
_troveId,
vars.newColl,
vars.newDebt,
_troveChange,
batchManager,
batch.entireCollWithoutRedistribution,
batch.entireDebtWithoutRedistribution
);
} else {
_troveManager.onAdjustTrove(_troveId, vars.newColl, vars.newDebt, _troveChange);
}
vars.activePool.mintAggInterestAndAccountForTroveChange(_troveChange, batchManager);
_moveTokensFromAdjustment(receiver, _troveChange, vars.boldToken, vars.activePool);
}
function closeTrove(uint256 _troveId) external override {
ITroveManager troveManagerCached = troveManager;
IActivePool activePoolCached = activePool;
IBoldToken boldTokenCached = boldToken;
// --- Checks ---
address owner = troveNFT.ownerOf(_troveId);
address receiver = _requireSenderIsOwnerOrRemoveManagerAndGetReceiver(_troveId, owner);
_requireTroveIsOpen(troveManagerCached, _troveId);
LatestTroveData memory trove = troveManagerCached.getLatestTroveData(_troveId);
// The borrower must repay their entire debt including accrued interest, batch fee and redist. gains
_requireSufficientBoldBalance(boldTokenCached, msg.sender, trove.entireDebt);
TroveChange memory troveChange;
troveChange.appliedRedistBoldDebtGain = trove.redistBoldDebtGain;
troveChange.appliedRedistCollGain = trove.redistCollGain;
troveChange.collDecrease = trove.entireColl;
troveChange.debtDecrease = trove.entireDebt;
address batchManager = interestBatchManagerOf[_troveId];
LatestBatchData memory batch;
if (batchManager != address(0)) {
batch = troveManagerCached.getLatestBatchData(batchManager);
uint256 batchFutureDebt =
batch.entireDebtWithoutRedistribution - (trove.entireDebt - trove.redistBoldDebtGain);
troveChange.batchAccruedManagementFee = batch.accruedManagementFee;
troveChange.oldWeightedRecordedDebt = batch.weightedRecordedDebt;
troveChange.newWeightedRecordedDebt = batchFutureDebt * batch.annualInterestRate;
troveChange.oldWeightedRecordedBatchManagementFee = batch.weightedRecordedBatchManagementFee;
troveChange.newWeightedRecordedBatchManagementFee = batchFutureDebt * batch.annualManagementFee;
} else {
troveChange.oldWeightedRecordedDebt = trove.weightedRecordedDebt;
// troveChange.newWeightedRecordedDebt = 0;
}
(uint256 price,) = priceFeed.fetchPrice();
uint256 newTCR = _getNewTCRFromTroveChange(troveChange, price);
if (!hasBeenShutDown) _requireNewTCRisAboveCCR(newTCR);
troveManagerCached.onCloseTrove(
_troveId,
troveChange,
batchManager,
batch.entireCollWithoutRedistribution,
batch.entireDebtWithoutRedistribution
);
// If trove is in batch
if (batchManager != address(0)) {
// Unlink here in BorrowerOperations
interestBatchManagerOf[_troveId] = address(0);
}
activePoolCached.mintAggInterestAndAccountForTroveChange(troveChange, batchManager);
// Return ETH gas compensation
WETH.transferFrom(gasPoolAddress, receiver, ETH_GAS_COMPENSATION);
// Burn the remainder of the Trove's entire debt from the user
boldTokenCached.burn(msg.sender, trove.entireDebt);
// Send the collateral back to the user
activePoolCached.sendColl(receiver, trove.entireColl);
_wipeTroveMappings(_troveId);
}
function applyPendingDebt(uint256 _troveId, uint256 _lowerHint, uint256 _upperHint) public {
_requireIsNotShutDown();
ITroveManager troveManagerCached = troveManager;
_requireTroveIsOpen(troveManagerCached, _troveId);
LatestTroveData memory trove = troveManagerCached.getLatestTroveData(_troveId);
_requireNonZeroDebt(trove.entireDebt);
TroveChange memory change;
change.appliedRedistBoldDebtGain = trove.redistBoldDebtGain;
change.appliedRedistCollGain = trove.redistCollGain;
address batchManager = interestBatchManagerOf[_troveId];
LatestBatchData memory batch;
if (batchManager == address(0)) {
change.oldWeightedRecordedDebt = trove.weightedRecordedDebt;
change.newWeightedRecordedDebt = trove.entireDebt * trove.annualInterestRate;
} else {
batch = troveManagerCached.getLatestBatchData(batchManager);
change.batchAccruedManagementFee = batch.accruedManagementFee;
change.oldWeightedRecordedDebt = batch.weightedRecordedDebt;
change.newWeightedRecordedDebt =
(batch.entireDebtWithoutRedistribution + trove.redistBoldDebtGain) * batch.annualInterestRate;
change.oldWeightedRecordedBatchManagementFee = batch.weightedRecordedBatchManagementFee;
change.newWeightedRecordedBatchManagementFee =
(batch.entireDebtWithoutRedistribution + trove.redistBoldDebtGain) * batch.annualManagementFee;
}
troveManagerCached.onApplyTroveInterest(
_troveId,
trove.entireColl,
trove.entireDebt,
batchManager,
batch.entireCollWithoutRedistribution,
batch.entireDebtWithoutRedistribution,
change
);
activePool.mintAggInterestAndAccountForTroveChange(change, batchManager);
// If the trove was zombie, and now it’s not anymore, put it back in the list
if (_checkTroveIsZombie(troveManagerCached, _troveId) && trove.entireDebt >= MIN_DEBT) {
troveManagerCached.setTroveStatusToActive(_troveId);
_reInsertIntoSortedTroves(
_troveId, trove.annualInterestRate, _upperHint, _lowerHint, batchManager, batch.annualInterestRate
);
}
}
function getInterestIndividualDelegateOf(uint256 _troveId)
external
view
returns (InterestIndividualDelegate memory)
{
return interestIndividualDelegateOf[_troveId];
}
function setInterestIndividualDelegate(
uint256 _troveId,
address _delegate,
uint128 _minInterestRate,
uint128 _maxInterestRate,
// only needed if trove was previously in a batch:
uint256 _newAnnualInterestRate,
uint256 _upperHint,
uint256 _lowerHint,
uint256 _maxUpfrontFee,
uint256 _minInterestRateChangePeriod
) external {
_requireIsNotShutDown();
_requireTroveIsActive(troveManager, _troveId);
_requireCallerIsBorrower(_troveId);
_requireValidAnnualInterestRate(_minInterestRate);
_requireValidAnnualInterestRate(_maxInterestRate);
// With the check below, it could only be ==
_requireOrderedRange(_minInterestRate, _maxInterestRate);
interestIndividualDelegateOf[_troveId] =
InterestIndividualDelegate(_delegate, _minInterestRate, _maxInterestRate, _minInterestRateChangePeriod);
// Can’t have both individual delegation and batch manager
if (interestBatchManagerOf[_troveId] != address(0)) {
// Not needed, implicitly checked in removeFromBatch
//_requireValidAnnualInterestRate(_newAnnualInterestRate);
removeFromBatch(_troveId, _newAnnualInterestRate, _upperHint, _lowerHint, _maxUpfrontFee);
}
}
function removeInterestIndividualDelegate(uint256 _troveId) external {
_requireCallerIsBorrower(_troveId);
delete interestIndividualDelegateOf[_troveId];
}
function getInterestBatchManager(address _account) external view returns (InterestBatchManager memory) {
return interestBatchManagers[_account];
}
function registerBatchManager(
uint128 _minInterestRate,
uint128 _maxInterestRate,
uint128 _currentInterestRate,
uint128 _annualManagementFee,
uint128 _minInterestRateChangePeriod
) external {
_requireIsNotShutDown();
_requireNonExistentInterestBatchManager(msg.sender);
_requireValidAnnualInterestRate(_minInterestRate);
_requireValidAnnualInterestRate(_maxInterestRate);
// With the check below, it could only be ==
_requireOrderedRange(_minInterestRate, _maxInterestRate);
_requireInterestRateInRange(_currentInterestRate, _minInterestRate, _maxInterestRate);
// Not needed, implicitly checked in the condition above:
//_requireValidAnnualInterestRate(_currentInterestRate);
if (_annualManagementFee > MAX_ANNUAL_BATCH_MANAGEMENT_FEE) revert AnnualManagementFeeTooHigh();
if (_minInterestRateChangePeriod < MIN_INTEREST_RATE_CHANGE_PERIOD) revert MinInterestRateChangePeriodTooLow();
interestBatchManagers[msg.sender] =
InterestBatchManager(_minInterestRate, _maxInterestRate, _minInterestRateChangePeriod);
troveManager.onRegisterBatchManager(msg.sender, _currentInterestRate, _annualManagementFee);
}
function lowerBatchManagementFee(uint256 _newAnnualManagementFee) external {
_requireIsNotShutDown();
_requireValidInterestBatchManager(msg.sender);
ITroveManager troveManagerCached = troveManager;
LatestBatchData memory batch = troveManagerCached.getLatestBatchData(msg.sender);
if (_newAnnualManagementFee >= batch.annualManagementFee) {
revert NewFeeNotLower();
}
// Lower batch fee on TM
troveManagerCached.onLowerBatchManagerAnnualFee(
msg.sender,
batch.entireCollWithoutRedistribution,
batch.entireDebtWithoutRedistribution,
_newAnnualManagementFee
);
// active pool mint
TroveChange memory batchChange;
batchChange.batchAccruedManagementFee = batch.accruedManagementFee;
batchChange.oldWeightedRecordedDebt = batch.weightedRecordedDebt;
batchChange.newWeightedRecordedDebt = batch.entireDebtWithoutRedistribution * batch.annualInterestRate;
batchChange.oldWeightedRecordedBatchManagementFee = batch.weightedRecordedBatchManagementFee;
batchChange.newWeightedRecordedBatchManagementFee =
batch.entireDebtWithoutRedistribution * _newAnnualManagementFee;
activePool.mintAggInterestAndAccountForTroveChange(batchChange, msg.sender);
}
function setBatchManagerAnnualInterestRate(
uint128 _newAnnualInterestRate,
uint256 _upperHint,
uint256 _lowerHint,
uint256 _maxUpfrontFee
) external {
_requireIsNotShutDown();
_requireValidInterestBatchManager(msg.sender);
_requireInterestRateInBatchManagerRange(msg.sender, _newAnnualInterestRate);
// Not needed, implicitly checked in the condition above:
//_requireValidAnnualInterestRate(_newAnnualInterestRate);
ITroveManager troveManagerCached = troveManager;
IActivePool activePoolCached = activePool;
LatestBatchData memory batch = troveManagerCached.getLatestBatchData(msg.sender);
_requireBatchInterestRateChangePeriodPassed(msg.sender, uint256(batch.lastInterestRateAdjTime));
uint256 newDebt = batch.entireDebtWithoutRedistribution;
TroveChange memory batchChange;
batchChange.batchAccruedManagementFee = batch.accruedManagementFee;
batchChange.oldWeightedRecordedDebt = batch.weightedRecordedDebt;
batchChange.newWeightedRecordedDebt = newDebt * _newAnnualInterestRate;
batchChange.oldWeightedRecordedBatchManagementFee = batch.weightedRecordedBatchManagementFee;
batchChange.newWeightedRecordedBatchManagementFee = newDebt * batch.annualManagementFee;
// Apply upfront fee on premature adjustments
if (
batch.annualInterestRate != _newAnnualInterestRate
&& block.timestamp < batch.lastInterestRateAdjTime + INTEREST_RATE_ADJ_COOLDOWN
) {
uint256 price = _requireOraclesLive();
uint256 avgInterestRate = activePoolCached.getNewApproxAvgInterestRateFromTroveChange(batchChange);
batchChange.upfrontFee = _calcUpfrontFee(newDebt, avgInterestRate);
_requireUserAcceptsUpfrontFee(batchChange.upfrontFee, _maxUpfrontFee);
newDebt += batchChange.upfrontFee;
// Recalculate the batch's weighted terms, now taking into account the upfront fee
batchChange.newWeightedRecordedDebt = newDebt * _newAnnualInterestRate;
batchChange.newWeightedRecordedBatchManagementFee = newDebt * batch.annualManagementFee;
// Disallow a premature adjustment if it would result in TCR < CCR
// (which includes the case when TCR is already below CCR before the adjustment).
uint256 newTCR = _getNewTCRFromTroveChange(batchChange, price);
_requireNewTCRisAboveCCR(newTCR);
}
activePoolCached.mintAggInterestAndAccountForTroveChange(batchChange, msg.sender);
// Check batch is not empty, and then reinsert in sorted list
if (!sortedTroves.isEmptyBatch(BatchId.wrap(msg.sender))) {
sortedTroves.reInsertBatch(BatchId.wrap(msg.sender), _newAnnualInterestRate, _upperHint, _lowerHint);
}
troveManagerCached.onSetBatchManagerAnnualInterestRate(
msg.sender, batch.entireCollWithoutRedistribution, newDebt, _newAnnualInterestRate, batchChange.upfrontFee
);
}
function setInterestBatchManager(
uint256 _troveId,
address _newBatchManager,
uint256 _upperHint,
uint256 _lowerHint,
uint256 _maxUpfrontFee
) public override {
_requireIsNotShutDown();
LocalVariables_setInterestBatchManager memory vars;
vars.troveManager = troveManager;
vars.activePool = activePool;
vars.sortedTroves = sortedTroves;
_requireTroveIsActive(vars.troveManager, _troveId);
_requireCallerIsBorrower(_troveId);
_requireValidInterestBatchManager(_newBatchManager);
_requireIsNotInBatch(_troveId);
interestBatchManagerOf[_troveId] = _newBatchManager;
// Can’t have both individual delegation and batch manager
if (interestIndividualDelegateOf[_troveId].account != address(0)) delete interestIndividualDelegateOf[_troveId];
vars.trove = vars.troveManager.getLatestTroveData(_troveId);
vars.newBatch = vars.troveManager.getLatestBatchData(_newBatchManager);
TroveChange memory newBatchTroveChange;
newBatchTroveChange.appliedRedistBoldDebtGain = vars.trove.redistBoldDebtGain;
newBatchTroveChange.appliedRedistCollGain = vars.trove.redistCollGain;
newBatchTroveChange.batchAccruedManagementFee = vars.newBatch.accruedManagementFee;
newBatchTroveChange.oldWeightedRecordedDebt =
vars.newBatch.weightedRecordedDebt + vars.trove.weightedRecordedDebt;
newBatchTroveChange.newWeightedRecordedDebt =
(vars.newBatch.entireDebtWithoutRedistribution + vars.trove.entireDebt) * vars.newBatch.annualInterestRate;