-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathBorrowerOperations.sol
1164 lines (1029 loc) · 39.3 KB
/
BorrowerOperations.sol
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
pragma experimental ABIEncoderV2;
import "./Interfaces/IBorrowerOperations.sol";
import "./Interfaces/ITroveManager.sol";
import "./Interfaces/IZUSDToken.sol";
import "./Interfaces/ICollSurplusPool.sol";
import "./Interfaces/ISortedTroves.sol";
import "./Interfaces/IZEROStaking.sol";
import "./Interfaces/IFeeDistributor.sol";
import "./Dependencies/LiquityBase.sol";
import "./Dependencies/CheckContract.sol";
import "./Dependencies/console.sol";
import "./BorrowerOperationsStorage.sol";
import "./Dependencies/Mynt/MyntLib.sol";
import "./Interfaces/IPermit2.sol";
contract BorrowerOperations is
LiquityBase,
BorrowerOperationsStorage,
CheckContract,
IBorrowerOperations
{
/** CONSTANT / IMMUTABLE VARIABLE ONLY */
IPermit2 public immutable permit2;
/* --- Variable container structs ---
Used to hold, return and assign variables inside a function, in order to avoid the error:
"CompilerError: Stack too deep". */
struct LocalVariables_adjustTrove {
uint256 price;
uint256 collChange;
uint256 netDebtChange;
bool isCollIncrease;
uint256 debt;
uint256 coll;
uint256 oldICR;
uint256 newICR;
uint256 newTCR;
uint256 ZUSDFee;
uint256 newDebt;
uint256 newColl;
uint256 stake;
uint256 newNICR;
bool isRecoveryMode;
}
struct LocalVariables_openTrove {
uint256 price;
uint256 ZUSDFee;
uint256 netDebt;
uint256 compositeDebt;
uint256 ICR;
uint256 NICR;
uint256 stake;
uint256 arrayIndex;
}
struct ContractsCache {
ITroveManager troveManager;
IActivePool activePool;
IZUSDToken zusdToken;
}
enum BorrowerOperation {
openTrove,
closeTrove,
adjustTrove
}
event FeeDistributorAddressChanged(address _feeDistributorAddress);
event TroveManagerAddressChanged(address _newTroveManagerAddress);
event ActivePoolAddressChanged(address _activePoolAddress);
event DefaultPoolAddressChanged(address _defaultPoolAddress);
event StabilityPoolAddressChanged(address _stabilityPoolAddress);
event GasPoolAddressChanged(address _gasPoolAddress);
event CollSurplusPoolAddressChanged(address _collSurplusPoolAddress);
event PriceFeedAddressChanged(address _newPriceFeedAddress);
event SortedTrovesAddressChanged(address _sortedTrovesAddress);
event ZUSDTokenAddressChanged(address _zusdTokenAddress);
event ZEROStakingAddressChanged(address _zeroStakingAddress);
event MassetManagerAddressChanged(address _massetManagerAddress);
event TroveCreated(address indexed _borrower, uint256 arrayIndex);
event TroveUpdated(
address indexed _borrower,
uint256 _debt,
uint256 _coll,
uint256 stake,
BorrowerOperation operation
);
event ZUSDBorrowingFeePaid(address indexed _borrower, uint256 _ZUSDFee);
/** Constructor */
constructor(address _permit2) public {
permit2 = IPermit2(_permit2);
}
// --- Dependency setters ---
function setAddresses(
address _feeDistributorAddress,
address _liquityBaseParamsAddress,
address _troveManagerAddress,
address _activePoolAddress,
address _defaultPoolAddress,
address _stabilityPoolAddress,
address _gasPoolAddress,
address _collSurplusPoolAddress,
address _priceFeedAddress,
address _sortedTrovesAddress,
address _zusdTokenAddress,
address _zeroStakingAddress
) external override onlyOwner {
// This makes impossible to open a trove with zero withdrawn ZUSD
assert(MIN_NET_DEBT > 0);
checkContract(_feeDistributorAddress);
checkContract(_liquityBaseParamsAddress);
checkContract(_troveManagerAddress);
checkContract(_activePoolAddress);
checkContract(_defaultPoolAddress);
checkContract(_stabilityPoolAddress);
checkContract(_gasPoolAddress);
checkContract(_collSurplusPoolAddress);
checkContract(_priceFeedAddress);
checkContract(_sortedTrovesAddress);
checkContract(_zusdTokenAddress);
checkContract(_zeroStakingAddress);
feeDistributor = IFeeDistributor(_feeDistributorAddress);
liquityBaseParams = ILiquityBaseParams(_liquityBaseParamsAddress);
troveManager = ITroveManager(_troveManagerAddress);
activePool = IActivePool(_activePoolAddress);
defaultPool = IDefaultPool(_defaultPoolAddress);
stabilityPoolAddress = _stabilityPoolAddress;
gasPoolAddress = _gasPoolAddress;
collSurplusPool = ICollSurplusPool(_collSurplusPoolAddress);
priceFeed = IPriceFeed(_priceFeedAddress);
sortedTroves = ISortedTroves(_sortedTrovesAddress);
zusdToken = IZUSDToken(_zusdTokenAddress);
zeroStakingAddress = _zeroStakingAddress;
zeroStaking = IZEROStaking(_zeroStakingAddress);
emit FeeDistributorAddressChanged(_feeDistributorAddress);
emit TroveManagerAddressChanged(_troveManagerAddress);
emit ActivePoolAddressChanged(_activePoolAddress);
emit DefaultPoolAddressChanged(_defaultPoolAddress);
emit StabilityPoolAddressChanged(_stabilityPoolAddress);
emit GasPoolAddressChanged(_gasPoolAddress);
emit CollSurplusPoolAddressChanged(_collSurplusPoolAddress);
emit PriceFeedAddressChanged(_priceFeedAddress);
emit SortedTrovesAddressChanged(_sortedTrovesAddress);
emit ZUSDTokenAddressChanged(_zusdTokenAddress);
emit ZEROStakingAddressChanged(_zeroStakingAddress);
}
function setMassetManagerAddress(address _massetManagerAddress) external onlyOwner {
massetManager = IMassetManager(_massetManagerAddress);
emit MassetManagerAddressChanged(_massetManagerAddress);
}
function openTrove(
uint256 _maxFeePercentage,
uint256 _ZUSDAmount,
address _upperHint,
address _lowerHint
) external payable override {
_openTrove(_maxFeePercentage, _ZUSDAmount, _upperHint, _lowerHint, msg.sender);
}
function openNueTrove(
uint256 _maxFeePercentage,
uint256 _ZUSDAmount,
address _upperHint,
address _lowerHint
) external payable override {
require(address(massetManager) != address(0), "Masset address not set");
_openTrove(_maxFeePercentage, _ZUSDAmount, _upperHint, _lowerHint, address(this));
require(
zusdToken.approve(address(massetManager), _ZUSDAmount),
"Failed to approve ZUSD amount for Mynt mAsset to redeem"
);
massetManager.mintTo(address(zusdToken), _ZUSDAmount, msg.sender);
}
// --- Borrower Trove Operations ---
function _openTrove(
uint256 _maxFeePercentage,
uint256 _ZUSDAmount,
address _upperHint,
address _lowerHint,
address _tokensRecipient
) internal {
ContractsCache memory contractsCache = ContractsCache(troveManager, activePool, zusdToken);
LocalVariables_openTrove memory vars;
vars.price = priceFeed.fetchPrice();
bool isRecoveryMode = _checkRecoveryMode(vars.price);
_requireValidMaxFeePercentage(_maxFeePercentage, isRecoveryMode);
_requireTroveisNotActive(contractsCache.troveManager, msg.sender);
vars.ZUSDFee;
vars.netDebt = _ZUSDAmount;
if (!isRecoveryMode) {
vars.ZUSDFee = _triggerBorrowingFee(
contractsCache.troveManager,
contractsCache.zusdToken,
_ZUSDAmount,
_maxFeePercentage
);
vars.netDebt = vars.netDebt.add(vars.ZUSDFee);
}
_requireAtLeastMinNetDebt(vars.netDebt);
// ICR is based on the composite debt, i.e. the requested ZUSD amount + ZUSD borrowing fee + ZUSD gas comp.
vars.compositeDebt = _getCompositeDebt(vars.netDebt);
assert(vars.compositeDebt > 0);
vars.ICR = LiquityMath._computeCR(msg.value, vars.compositeDebt, vars.price);
vars.NICR = LiquityMath._computeNominalCR(msg.value, vars.compositeDebt);
if (isRecoveryMode) {
_requireICRisAboveCCR(vars.ICR);
} else {
_requireICRisAboveMCR(vars.ICR);
uint256 newTCR = _getNewTCRFromTroveChange(
msg.value,
true,
vars.compositeDebt,
true,
vars.price
); // bools: coll increase, debt increase
_requireNewTCRisAboveCCR(newTCR);
}
// Set the trove struct's properties
contractsCache.troveManager.setTroveStatus(msg.sender, 1);
contractsCache.troveManager.increaseTroveColl(msg.sender, msg.value);
contractsCache.troveManager.increaseTroveDebt(msg.sender, vars.compositeDebt);
contractsCache.troveManager.updateTroveRewardSnapshots(msg.sender);
vars.stake = contractsCache.troveManager.updateStakeAndTotalStakes(msg.sender);
sortedTroves.insert(msg.sender, vars.NICR, _upperHint, _lowerHint);
vars.arrayIndex = contractsCache.troveManager.addTroveOwnerToArray(msg.sender);
emit TroveCreated(msg.sender, vars.arrayIndex);
// Move the ether to the Active Pool, and mint the ZUSDAmount to the borrower
_activePoolAddColl(contractsCache.activePool, msg.value);
_mintZusdAndIncreaseActivePoolDebt(
contractsCache.activePool,
contractsCache.zusdToken,
_tokensRecipient,
_ZUSDAmount,
vars.netDebt
);
// Move the ZUSD gas compensation to the Gas Pool
_mintZusdAndIncreaseActivePoolDebt(
contractsCache.activePool,
contractsCache.zusdToken,
gasPoolAddress,
ZUSD_GAS_COMPENSATION,
ZUSD_GAS_COMPENSATION
);
emit TroveUpdated(
msg.sender,
vars.compositeDebt,
msg.value,
vars.stake,
BorrowerOperation.openTrove
);
emit ZUSDBorrowingFeePaid(msg.sender, vars.ZUSDFee);
}
/// Send ETH as collateral to a trove
function addColl(address _upperHint, address _lowerHint) external payable override {
_adjustTrove(msg.sender, 0, 0, false, _upperHint, _lowerHint, 0);
}
/// Send ETH as collateral to a trove. Called by only the Stability Pool.
function moveETHGainToTrove(
address _borrower,
address _upperHint,
address _lowerHint
) external payable override {
_requireCallerIsStabilityPool();
_adjustTrove(_borrower, 0, 0, false, _upperHint, _lowerHint, 0);
}
/// Withdraw ETH collateral from a trove
function withdrawColl(
uint256 _collWithdrawal,
address _upperHint,
address _lowerHint
) external override {
_adjustTrove(msg.sender, _collWithdrawal, 0, false, _upperHint, _lowerHint, 0);
}
/// Withdraw ZUSD tokens from a trove: mint new ZUSD tokens to the owner, and increase the trove's debt accordingly
function withdrawZUSD(
uint256 _maxFeePercentage,
uint256 _ZUSDAmount,
address _upperHint,
address _lowerHint
) external override {
_adjustTrove(msg.sender, 0, _ZUSDAmount, true, _upperHint, _lowerHint, _maxFeePercentage);
}
/// Borrow (withdraw) ZUSD tokens from a trove: mint new ZUSD tokens to the owner and convert it to DLLR in one transaction
/// Zero Line of Credit owner can borrow a specified amount of ZUSD and convert it to DLLR via Sovryn Mynt
///@return DLLR amount minted
function withdrawZusdAndConvertToDLLR(
uint256 _maxFeePercentage,
uint256 _ZUSDAmount,
address _upperHint,
address _lowerHint
) external override returns (uint256) {
address thisAddress = address(this);
uint256 balanceBefore = zusdToken.balanceOf(thisAddress);
_withdrawZusdTo(
msg.sender,
thisAddress,
_ZUSDAmount,
_upperHint,
_lowerHint,
_maxFeePercentage
);
require(
zusdToken.balanceOf(thisAddress) == balanceBefore.add(_ZUSDAmount),
"ZUSD is not borrowed correctly"
);
require(
zusdToken.approve(address(massetManager), _ZUSDAmount),
"Failed to approve ZUSD amount for Mynt mAsset to redeem"
);
return massetManager.mintTo(address(zusdToken), _ZUSDAmount, msg.sender);
}
/// Repay ZUSD tokens to a Trove: Burn the repaid ZUSD tokens, and reduce the trove's debt accordingly
function repayZUSD(
uint256 _ZUSDAmount,
address _upperHint,
address _lowerHint
) external override {
_adjustTrove(msg.sender, 0, _ZUSDAmount, false, _upperHint, _lowerHint, 0);
}
/// Repay ZUSD tokens to a Trove by DLLR: convert DLLR to ZUSD tokens, and then reduce the trove's debt accordingly
function repayZusdFromDLLR(
uint256 _dllrAmount,
address _upperHint,
address _lowerHint,
IMassetManager.PermitParams calldata _permitParams
) external override {
_adjustNueTrove(0, 0, _dllrAmount, false, _upperHint, _lowerHint, _permitParams);
}
/// Repay ZUSD tokens to a Trove by DLLR: convert DLLR to ZUSD tokens, and then reduce the trove's debt accordingly
function repayZusdFromDLLRWithPermit2(
uint256 _dllrAmount,
address _upperHint,
address _lowerHint,
ISignatureTransfer.PermitTransferFrom memory _permit,
bytes calldata _signature
) external override {
_adjustNueTroveWithPermit2(0, 0, _dllrAmount, false, _upperHint, _lowerHint, _permit, _signature);
}
function adjustTrove(
uint256 _maxFeePercentage,
uint256 _collWithdrawal,
uint256 _ZUSDChange,
bool _isDebtIncrease,
address _upperHint,
address _lowerHint
) external payable override {
_adjustTrove(
msg.sender,
_collWithdrawal,
_ZUSDChange,
_isDebtIncrease,
_upperHint,
_lowerHint,
_maxFeePercentage
);
}
// in case of _isDebtIncrease = false MassetManager contract must have an approval of NUE tokens
function adjustNueTrove(
uint256 _maxFeePercentage,
uint256 _collWithdrawal,
uint256 _ZUSDChange,
bool _isDebtIncrease,
address _upperHint,
address _lowerHint,
IMassetManager.PermitParams calldata _permitParams
) external payable override {
_adjustNueTrove(
_maxFeePercentage,
_collWithdrawal,
_ZUSDChange,
_isDebtIncrease,
_upperHint,
_lowerHint,
_permitParams
);
}
// in case of _isDebtIncrease = false MassetManager contract must have an approval of NUE tokens
function adjustNueTroveWithPermit2(
uint256 _maxFeePercentage,
uint256 _collWithdrawal,
uint256 _ZUSDChange,
bool _isDebtIncrease,
address _upperHint,
address _lowerHint,
ISignatureTransfer.PermitTransferFrom memory _permit,
bytes calldata _signature
) external payable override {
_adjustNueTroveWithPermit2(
_maxFeePercentage,
_collWithdrawal,
_ZUSDChange,
_isDebtIncrease,
_upperHint,
_lowerHint,
_permit,
_signature
);
}
// in case of _isDebtIncrease = false Masset Manager contract must have an approval of NUE tokens
function _adjustNueTrove(
uint256 _maxFeePercentage,
uint256 _collWithdrawal,
uint256 _ZUSDChange,
bool _isDebtIncrease,
address _upperHint,
address _lowerHint,
IMassetManager.PermitParams calldata _permitParams
) internal {
require(address(massetManager) != address(0), "Masset address not set");
if (!_isDebtIncrease && _ZUSDChange > 0) {
MyntLib.redeemZusdFromDllrWithPermit(
massetManager,
_ZUSDChange,
address(zusdToken),
_permitParams
);
}
_adjustSenderTrove(
msg.sender,
_collWithdrawal,
_ZUSDChange,
_isDebtIncrease,
_upperHint,
_lowerHint,
_maxFeePercentage,
address(this)
);
if (_isDebtIncrease && _ZUSDChange > 0) {
require(
zusdToken.approve(address(massetManager), _ZUSDChange),
"Failed to approve ZUSD amount for Mynt mAsset to redeem"
);
massetManager.mintTo(address(zusdToken), _ZUSDChange, msg.sender);
}
}
// in case of _isDebtIncrease = false Masset Manager contract must have an approval of NUE tokens
function _adjustNueTroveWithPermit2(
uint256 _maxFeePercentage,
uint256 _collWithdrawal,
uint256 _ZUSDChange,
bool _isDebtIncrease,
address _upperHint,
address _lowerHint,
ISignatureTransfer.PermitTransferFrom memory _permit,
bytes calldata _signature
) internal {
require(address(massetManager) != address(0), "Masset address not set");
if (!_isDebtIncrease && _ZUSDChange > 0) {
MyntLib.redeemZusdFromDllrWithPermit2(
massetManager,
address(zusdToken),
_permit,
permit2,
_signature
);
}
_adjustSenderTrove(
msg.sender,
_collWithdrawal,
_ZUSDChange,
_isDebtIncrease,
_upperHint,
_lowerHint,
_maxFeePercentage,
address(this)
);
if (_isDebtIncrease && _ZUSDChange > 0) {
require(
zusdToken.approve(address(massetManager), _ZUSDChange),
"Failed to approve ZUSD amount for Mynt mAsset to redeem"
);
massetManager.mintTo(address(zusdToken), _ZUSDChange, msg.sender);
}
}
function _adjustTrove(
address _borrower,
uint256 _collWithdrawal,
uint256 _ZUSDChange,
bool _isDebtIncrease,
address _upperHint,
address _lowerHint,
uint256 _maxFeePercentage
) internal {
_adjustSenderTrove(
_borrower,
_collWithdrawal,
_ZUSDChange,
_isDebtIncrease,
_upperHint,
_lowerHint,
_maxFeePercentage,
msg.sender
);
}
// _withdrawZusd: _adjustTrove(msg.sender, 0, _ZUSDAmount, true, _upperHint, _lowerHint, _maxFeePercentage);
function _withdrawZusdTo(
address _borrower,
address _receiver,
uint256 _ZUSDChange,
address _upperHint,
address _lowerHint,
uint256 _maxFeePercentage
) internal {
_adjustSenderTrove(
_borrower,
0,
_ZUSDChange,
true,
_upperHint,
_lowerHint,
_maxFeePercentage,
_receiver
);
}
/**
* _adjustSenderTrove(): Alongside a debt change, this function can perform either a collateral top-up or a collateral withdrawal.
*
* It therefore expects either a positive msg.value, or a positive _collWithdrawal argument.
*
* If both are positive, it will revert.
*/
function _adjustSenderTrove(
address _borrower,
uint256 _collWithdrawal,
uint256 _ZUSDChange,
bool _isDebtIncrease,
address _upperHint,
address _lowerHint,
uint256 _maxFeePercentage,
address _tokensRecipient
) internal {
ContractsCache memory contractsCache = ContractsCache(troveManager, activePool, zusdToken);
LocalVariables_adjustTrove memory vars;
vars.price = priceFeed.fetchPrice();
vars.isRecoveryMode = _checkRecoveryMode(vars.price);
if (_isDebtIncrease) {
_requireValidMaxFeePercentage(_maxFeePercentage, vars.isRecoveryMode);
_requireNonZeroDebtChange(_ZUSDChange);
}
_requireSingularCollChange(_collWithdrawal);
_requireNonZeroAdjustment(_collWithdrawal, _ZUSDChange);
_requireTroveisActive(contractsCache.troveManager, _borrower);
// Confirm the operation is either a borrower adjusting their own trove, or a pure ETH transfer from the Stability Pool to a trove
assert(
msg.sender == _borrower ||
(msg.sender == stabilityPoolAddress && msg.value > 0 && _ZUSDChange == 0)
);
contractsCache.troveManager.applyPendingRewards(_borrower);
// Get the collChange based on whether or not ETH was sent in the transaction
(vars.collChange, vars.isCollIncrease) = _getCollChange(msg.value, _collWithdrawal);
vars.netDebtChange = _ZUSDChange;
// If the adjustment incorporates a debt increase and system is in Normal Mode, then trigger a borrowing fee
if (_isDebtIncrease && !vars.isRecoveryMode) {
vars.ZUSDFee = _triggerBorrowingFee(
contractsCache.troveManager,
contractsCache.zusdToken,
_ZUSDChange,
_maxFeePercentage
);
vars.netDebtChange = vars.netDebtChange.add(vars.ZUSDFee); // The raw debt change includes the fee
}
vars.debt = contractsCache.troveManager.getTroveDebt(_borrower);
vars.coll = contractsCache.troveManager.getTroveColl(_borrower);
// Get the trove's old ICR before the adjustment, and what its new ICR will be after the adjustment
vars.oldICR = LiquityMath._computeCR(vars.coll, vars.debt, vars.price);
vars.newICR = _getNewICRFromTroveChange(
vars.coll,
vars.debt,
vars.collChange,
vars.isCollIncrease,
vars.netDebtChange,
_isDebtIncrease,
vars.price
);
assert(_collWithdrawal <= vars.coll);
// Check the adjustment satisfies all conditions for the current system mode
_requireValidAdjustmentInCurrentMode(
vars.isRecoveryMode,
_collWithdrawal,
_isDebtIncrease,
vars
);
// When the adjustment is a debt repayment, check it's a valid amount and that the caller has enough ZUSD
if (!_isDebtIncrease && _ZUSDChange > 0) {
_requireAtLeastMinNetDebt(_getNetDebt(vars.debt).sub(vars.netDebtChange));
_requireValidZUSDRepayment(vars.debt, vars.netDebtChange);
_requireSufficientZUSDBalance(contractsCache.zusdToken, _borrower, vars.netDebtChange);
}
(vars.newColl, vars.newDebt) = _updateTroveFromAdjustment(
contractsCache.troveManager,
_borrower,
vars.collChange,
vars.isCollIncrease,
vars.netDebtChange,
_isDebtIncrease
);
vars.stake = contractsCache.troveManager.updateStakeAndTotalStakes(_borrower);
// Re-insert trove in to the sorted list
vars.newNICR = _getNewNominalICRFromTroveChange(
vars.coll,
vars.debt,
vars.collChange,
vars.isCollIncrease,
vars.netDebtChange,
_isDebtIncrease
);
sortedTroves.reInsert(_borrower, vars.newNICR, _upperHint, _lowerHint);
emit TroveUpdated(
_borrower,
vars.newDebt,
vars.newColl,
vars.stake,
BorrowerOperation.adjustTrove
);
emit ZUSDBorrowingFeePaid(msg.sender, vars.ZUSDFee);
// Use the unmodified _ZUSDChange here, as we don't send the fee to the user
_moveTokensAndETHfromAdjustment(
contractsCache.activePool,
contractsCache.zusdToken,
msg.sender,
vars.collChange,
vars.isCollIncrease,
_ZUSDChange,
_isDebtIncrease,
vars.netDebtChange,
_tokensRecipient
);
}
function closeTrove() external override {
_closeTrove();
}
function closeNueTrove(IMassetManager.PermitParams calldata _permitParams) external override {
require(address(massetManager) != address(0), "Masset address not set");
uint256 debt = troveManager.getTroveDebt(msg.sender);
MyntLib.redeemZusdFromDllrWithPermit(
massetManager,
debt.sub(ZUSD_GAS_COMPENSATION),
address(zusdToken),
_permitParams
);
_closeTrove();
}
function closeNueTroveWithPermit2(ISignatureTransfer.PermitTransferFrom memory _permit, bytes calldata _signature) external override {
require(address(massetManager) != address(0), "Masset address not set");
uint256 debt = troveManager.getTroveDebt(msg.sender);
MyntLib.redeemZusdFromDllrWithPermit2(
massetManager,
address(zusdToken),
_permit,
permit2,
_signature
);
_closeTrove();
}
function _closeTrove() internal {
ITroveManager troveManagerCached = troveManager;
IActivePool activePoolCached = activePool;
IZUSDToken zusdTokenCached = zusdToken;
_requireTroveisActive(troveManagerCached, msg.sender);
uint256 price = priceFeed.fetchPrice();
_requireNotInRecoveryMode(price);
troveManagerCached.applyPendingRewards(msg.sender);
uint256 coll = troveManagerCached.getTroveColl(msg.sender);
uint256 debt = troveManagerCached.getTroveDebt(msg.sender);
_requireSufficientZUSDBalance(
zusdTokenCached,
msg.sender,
debt.sub(ZUSD_GAS_COMPENSATION)
);
uint256 newTCR = _getNewTCRFromTroveChange(coll, false, debt, false, price);
_requireNewTCRisAboveCCR(newTCR);
troveManagerCached.removeStake(msg.sender);
troveManagerCached.closeTrove(msg.sender);
emit TroveUpdated(msg.sender, 0, 0, 0, BorrowerOperation.closeTrove);
// Burn the repaid ZUSD from the user's balance and the gas compensation from the Gas Pool
_burnZusdAndDecreaseActivePoolDebt(
activePoolCached,
zusdTokenCached,
msg.sender,
debt.sub(ZUSD_GAS_COMPENSATION)
);
_burnZusdAndDecreaseActivePoolDebt(
activePoolCached,
zusdTokenCached,
gasPoolAddress,
ZUSD_GAS_COMPENSATION
);
// Send the collateral back to the user
activePoolCached.sendETH(msg.sender, coll);
}
/**
* Claim remaining collateral from a redemption or from a liquidation with ICR > MCR in Recovery Mode
*/
function claimCollateral() external override {
// send ETH from CollSurplus Pool to owner
collSurplusPool.claimColl(msg.sender);
}
// --- Helper functions ---
function _triggerBorrowingFee(
ITroveManager _troveManager,
IZUSDToken _zusdToken,
uint256 _ZUSDAmount,
uint256 _maxFeePercentage
) internal returns (uint256) {
_troveManager.decayBaseRateFromBorrowing(); // decay the baseRate state variable
uint256 ZUSDFee = _troveManager.getBorrowingFee(_ZUSDAmount);
_requireUserAcceptsFee(ZUSDFee, _ZUSDAmount, _maxFeePercentage);
_zusdToken.mint(address(feeDistributor), ZUSDFee);
feeDistributor.distributeFees();
return ZUSDFee;
}
function _getUSDValue(uint256 _coll, uint256 _price) internal pure returns (uint256) {
uint256 usdValue = _price.mul(_coll).div(DECIMAL_PRECISION);
return usdValue;
}
function _getCollChange(uint256 _collReceived, uint256 _requestedCollWithdrawal)
internal
pure
returns (uint256 collChange, bool isCollIncrease)
{
if (_collReceived != 0) {
collChange = _collReceived;
isCollIncrease = true;
} else {
collChange = _requestedCollWithdrawal;
}
}
/// Update trove's coll and debt based on whether they increase or decrease
function _updateTroveFromAdjustment(
ITroveManager _troveManager,
address _borrower,
uint256 _collChange,
bool _isCollIncrease,
uint256 _debtChange,
bool _isDebtIncrease
) internal returns (uint256, uint256) {
uint256 newColl = (_isCollIncrease)
? _troveManager.increaseTroveColl(_borrower, _collChange)
: _troveManager.decreaseTroveColl(_borrower, _collChange);
uint256 newDebt = (_isDebtIncrease)
? _troveManager.increaseTroveDebt(_borrower, _debtChange)
: _troveManager.decreaseTroveDebt(_borrower, _debtChange);
return (newColl, newDebt);
}
function _moveTokensAndETHfromAdjustment(
IActivePool _activePool,
IZUSDToken _zusdToken,
address _borrower,
uint256 _collChange,
bool _isCollIncrease,
uint256 _ZUSDChange,
bool _isDebtIncrease,
uint256 _netDebtChange,
address _tokensRecipient
) internal {
if (_isDebtIncrease) {
_mintZusdAndIncreaseActivePoolDebt(
_activePool,
_zusdToken,
_tokensRecipient,
_ZUSDChange,
_netDebtChange
);
} else {
_burnZusdAndDecreaseActivePoolDebt(_activePool, _zusdToken, _borrower, _ZUSDChange);
}
if (_isCollIncrease) {
_activePoolAddColl(_activePool, _collChange);
} else {
_activePool.sendETH(_borrower, _collChange);
}
}
/// Send ETH to Active Pool and increase its recorded ETH balance
function _activePoolAddColl(IActivePool _activePool, uint256 _amount) internal {
(bool success, ) = address(_activePool).call{ value: _amount }("");
require(success, "BorrowerOps: Sending ETH to ActivePool failed");
}
/// Issue the specified amount of ZUSD to _account and increases the total active debt (_netDebtIncrease potentially includes a ZUSDFee)
function _mintZusdAndIncreaseActivePoolDebt(
IActivePool _activePool,
IZUSDToken _zusdToken,
address _account,
uint256 _ZUSDAmount,
uint256 _netDebtIncrease
) internal {
_activePool.increaseZUSDDebt(_netDebtIncrease);
_zusdToken.mint(_account, _ZUSDAmount);
}
/// Burn the specified amount of ZUSD from _account and decreases the total active debt
function _burnZusdAndDecreaseActivePoolDebt(
IActivePool _activePool,
IZUSDToken _zusdToken,
address _account,
uint256 _ZUSD
) internal {
_activePool.decreaseZUSDDebt(_ZUSD);
_zusdToken.burn(_account, _ZUSD);
}
// --- 'Require' wrapper functions ---
function _requireSingularCollChange(uint256 _collWithdrawal) internal view {
require(
msg.value == 0 || _collWithdrawal == 0,
"BorrowerOperations: Cannot withdraw and add coll"
);
}
function _requireCallerIsBorrower(address _borrower) internal view {
require(
msg.sender == _borrower,
"BorrowerOps: Caller must be the borrower for a withdrawal"
);
}
function _requireNonZeroAdjustment(uint256 _collWithdrawal, uint256 _ZUSDChange)
internal
view
{
require(
msg.value != 0 || _collWithdrawal != 0 || _ZUSDChange != 0,
"BorrowerOps: There must be either a collateral change or a debt change"
);
}
function _requireTroveisActive(ITroveManager _troveManager, address _borrower) internal view {
uint256 status = _troveManager.getTroveStatus(_borrower);
require(status == 1, "BorrowerOps: Trove does not exist or is closed");
}
function _requireTroveisNotActive(ITroveManager _troveManager, address _borrower)
internal
view
{
uint256 status = _troveManager.getTroveStatus(_borrower);
require(status != 1, "BorrowerOps: Trove is active");
}
function _requireNonZeroDebtChange(uint256 _ZUSDChange) internal pure {
require(_ZUSDChange > 0, "BorrowerOps: Debt increase requires non-zero debtChange");
}
function _requireNotInRecoveryMode(uint256 _price) internal view {
require(
!_checkRecoveryMode(_price),
"BorrowerOps: Operation not permitted during Recovery Mode"
);
}
function _requireNoCollWithdrawal(uint256 _collWithdrawal) internal pure {
require(
_collWithdrawal == 0,
"BorrowerOps: Collateral withdrawal not permitted Recovery Mode"
);
}
function _requireValidAdjustmentInCurrentMode(
bool _isRecoveryMode,
uint256 _collWithdrawal,
bool _isDebtIncrease,
LocalVariables_adjustTrove memory _vars
) internal view {
/*
*In Recovery Mode, only allow:
*
* - Pure collateral top-up
* - Pure debt repayment
* - Collateral top-up with debt repayment
* - A debt increase combined with a collateral top-up which makes the ICR >= 150% and improves the ICR (and by extension improves the TCR).
*
* In Normal Mode, ensure:
*
* - The new ICR is above MCR
* - The adjustment won't pull the TCR below CCR
*/
if (_isRecoveryMode) {
_requireNoCollWithdrawal(_collWithdrawal);
if (_isDebtIncrease) {
_requireICRisAboveCCR(_vars.newICR);
_requireNewICRisAboveOldICR(_vars.newICR, _vars.oldICR);
}
} else {
// if Normal Mode
_requireICRisAboveMCR(_vars.newICR);
_vars.newTCR = _getNewTCRFromTroveChange(
_vars.collChange,
_vars.isCollIncrease,
_vars.netDebtChange,
_isDebtIncrease,
_vars.price
);
_requireNewTCRisAboveCCR(_vars.newTCR);
}
}
function _requireICRisAboveMCR(uint256 _newICR) internal view {
require(
_newICR >= liquityBaseParams.MCR(),
"BorrowerOps: An operation that would result in ICR < MCR is not permitted"
);
}