This repository has been archived by the owner on Apr 22, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 4
/
Market.sol
1367 lines (1170 loc) · 59.9 KB
/
Market.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.17;
import { Initializable } from "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import { FixedPointMathLib } from "solmate/src/utils/FixedPointMathLib.sol";
import { PausableUpgradeable } from "@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol";
import { MathUpgradeable as Math } from "@openzeppelin/contracts-upgradeable/utils/math/MathUpgradeable.sol";
import { AccessControlUpgradeable } from "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol";
import { ERC4626, ERC20, SafeTransferLib } from "solmate/src/mixins/ERC4626.sol";
import { InterestRateModel } from "./InterestRateModel.sol";
import { RewardsController } from "./RewardsController.sol";
import { FixedLib } from "./utils/FixedLib.sol";
import { Auditor } from "./Auditor.sol";
contract Market is Initializable, AccessControlUpgradeable, PausableUpgradeable, ERC4626 {
using FixedPointMathLib for int256;
using FixedPointMathLib for uint256;
using FixedPointMathLib for uint128;
using SafeTransferLib for ERC20;
using FixedLib for FixedLib.Pool;
using FixedLib for FixedLib.Position;
using FixedLib for uint256;
bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE");
bytes32 public constant EMERGENCY_ADMIN_ROLE = keccak256("EMERGENCY_ADMIN_ROLE");
/// @custom:oz-upgrades-unsafe-allow state-variable-immutable
Auditor public immutable auditor;
/// @notice Tracks account's fixed deposit positions by maturity, account and position.
mapping(uint256 => mapping(address => FixedLib.Position)) public fixedDepositPositions;
/// @notice Tracks account's fixed borrow positions by maturity, account and position.
mapping(uint256 => mapping(address => FixedLib.Position)) public fixedBorrowPositions;
/// @notice Tracks fixed pools state by maturity.
mapping(uint256 => FixedLib.Pool) public fixedPools;
/// @notice Tracks fixed deposit and borrow map and floating borrow shares of an account.
mapping(address => Account) public accounts;
/// @notice Amount of assets lent by the floating pool to the fixed pools.
uint256 public floatingBackupBorrowed;
/// @notice Amount of assets lent by the floating pool to accounts.
uint256 public floatingDebt;
/// @notice Accumulated earnings from extraordinary sources to be gradually distributed.
uint256 public earningsAccumulator;
/// @notice Rate per second to be charged to delayed fixed pools borrowers after maturity.
uint256 public penaltyRate;
/// @notice Rate charged to the fixed pool to be retained by the floating pool for initially providing liquidity.
uint256 public backupFeeRate;
/// @notice Damp speed factor to update `floatingAssetsAverage` when `floatingAssets` is higher.
uint256 public dampSpeedUp;
/// @notice Damp speed factor to update `floatingAssetsAverage` when `floatingAssets` is lower.
uint256 public dampSpeedDown;
/// @notice Number of fixed pools to be active at the same time.
uint8 public maxFuturePools;
/// @notice Last time the accumulator distributed earnings.
uint32 public lastAccumulatorAccrual;
/// @notice Last time the floating debt was updated.
uint32 public lastFloatingDebtUpdate;
/// @notice Last time the floating assets average was updated.
uint32 public lastAverageUpdate;
/// @notice Interest rate model contract used to get the borrow rates.
InterestRateModel public interestRateModel;
/// @notice Factor used for gradual accrual of earnings to the floating pool.
uint128 public earningsAccumulatorSmoothFactor;
/// @notice Percentage factor that represents the liquidity reserves that can't be borrowed.
uint128 public reserveFactor;
/// @notice Amount of floating assets deposited to the pool.
uint256 public floatingAssets;
/// @notice Average of the floating assets to get fixed borrow rates and prevent rate manipulation.
uint256 public floatingAssetsAverage;
/// @notice Total amount of floating borrow shares assigned to floating borrow accounts.
uint256 public totalFloatingBorrowShares;
/// @dev gap from deprecated state.
/// @custom:oz-renamed-from floatingUtilization
uint256 private __gap;
/// @notice Address of the treasury that will receive the allocated earnings.
address public treasury;
/// @notice Rate to be charged by the treasury to floating and fixed borrows.
uint256 public treasuryFeeRate;
/// @notice Address of the rewards controller that will accrue rewards for accounts operating with the Market.
RewardsController public rewardsController;
/// @notice Flag to prevent new borrows and deposits.
bool public isFrozen;
/// @custom:oz-upgrades-unsafe-allow constructor
constructor(ERC20 asset_, Auditor auditor_) ERC4626(asset_, "", "") {
auditor = auditor_;
_disableInitializers();
}
/// @notice Initializes the contract.
/// @dev can only be called once.
function initialize(
string calldata assetSymbol,
uint8 maxFuturePools_,
uint128 earningsAccumulatorSmoothFactor_,
InterestRateModel interestRateModel_,
uint256 penaltyRate_,
uint256 backupFeeRate_,
uint128 reserveFactor_,
uint256 dampSpeedUp_,
uint256 dampSpeedDown_
) external initializer {
__AccessControl_init();
__Pausable_init();
lastAccumulatorAccrual = uint32(block.timestamp);
lastFloatingDebtUpdate = uint32(block.timestamp);
lastAverageUpdate = uint32(block.timestamp);
_grantRole(DEFAULT_ADMIN_ROLE, msg.sender);
setAssetSymbol(assetSymbol);
setMaxFuturePools(maxFuturePools_);
setEarningsAccumulatorSmoothFactor(earningsAccumulatorSmoothFactor_);
setInterestRateModel(interestRateModel_);
setPenaltyRate(penaltyRate_);
setBackupFeeRate(backupFeeRate_);
setReserveFactor(reserveFactor_);
setDampSpeed(dampSpeedUp_, dampSpeedDown_);
}
/// @notice Borrows a certain amount from the floating pool.
/// @param assets amount to be sent to receiver and repaid by borrower.
/// @param receiver address that will receive the borrowed assets.
/// @param borrower address that will repay the borrowed assets.
/// @return borrowShares shares corresponding to the borrowed assets.
function borrow(
uint256 assets,
address receiver,
address borrower
) external whenNotPaused whenNotFrozen returns (uint256 borrowShares) {
spendAllowance(borrower, assets);
RewardsController memRewardsController = rewardsController;
if (address(memRewardsController) != address(0)) memRewardsController.handleBorrow(borrower);
depositToTreasury(updateFloatingDebt());
borrowShares = previewBorrow(assets);
uint256 newFloatingDebt = floatingDebt + assets;
floatingDebt = newFloatingDebt;
// check if the underlying liquidity that the account wants to withdraw is borrowed, also considering the reserves
if (floatingBackupBorrowed + newFloatingDebt > floatingAssets.mulWadDown(1e18 - reserveFactor)) {
revert InsufficientProtocolLiquidity();
}
totalFloatingBorrowShares += borrowShares;
accounts[borrower].floatingBorrowShares += borrowShares;
emit Borrow(msg.sender, receiver, borrower, assets, borrowShares);
emitMarketUpdate();
auditor.checkBorrow(this, borrower);
asset.safeTransfer(receiver, assets);
}
/// @notice Repays a certain amount of assets to the floating pool.
/// @param assets assets to be subtracted from the borrower's accountability.
/// @param borrower address of the account that has the debt.
/// @return actualRepay the actual amount that should be transferred into the protocol.
/// @return borrowShares subtracted shares from the borrower's accountability.
function repay(
uint256 assets,
address borrower
) external whenNotPaused returns (uint256 actualRepay, uint256 borrowShares) {
(actualRepay, borrowShares) = noTransferRefund(previewRepay(assets), borrower);
emitMarketUpdate();
asset.safeTransferFrom(msg.sender, address(this), actualRepay);
}
/// @notice Repays a certain amount of shares to the floating pool.
/// @param borrowShares shares to be subtracted from the borrower's accountability.
/// @param borrower address of the account that has the debt.
/// @return assets subtracted assets from the borrower's accountability.
/// @return actualShares actual subtracted shares from the borrower's accountability.
function refund(
uint256 borrowShares,
address borrower
) external whenNotPaused returns (uint256 assets, uint256 actualShares) {
(assets, actualShares) = noTransferRefund(borrowShares, borrower);
emitMarketUpdate();
asset.safeTransferFrom(msg.sender, address(this), assets);
}
/// @notice Allows to (partially) repay a floating borrow. It does not transfer assets.
/// @param borrowShares shares to be subtracted from the borrower's accountability.
/// @param borrower the address of the account that has the debt.
/// @return assets the actual amount that should be transferred into the protocol.
/// @return actualShares actual subtracted shares from the borrower's accountability.
function noTransferRefund(
uint256 borrowShares,
address borrower
) internal returns (uint256 assets, uint256 actualShares) {
RewardsController memRewardsController = rewardsController;
if (address(memRewardsController) != address(0)) memRewardsController.handleBorrow(borrower);
depositToTreasury(updateFloatingDebt());
Account storage account = accounts[borrower];
uint256 accountBorrowShares = account.floatingBorrowShares;
actualShares = Math.min(borrowShares, accountBorrowShares);
assets = previewRefund(actualShares);
if (assets == 0) revert ZeroRepay();
floatingDebt -= assets;
account.floatingBorrowShares = accountBorrowShares - actualShares;
totalFloatingBorrowShares -= actualShares;
emit Repay(msg.sender, borrower, assets, actualShares);
}
/// @notice Deposits a certain amount to a maturity.
/// @param maturity maturity date where the assets will be deposited.
/// @param assets amount to receive from the msg.sender.
/// @param minAssetsRequired minimum amount of assets required by the depositor for the transaction to be accepted.
/// @param receiver address that will be able to withdraw the deposited assets.
/// @return positionAssets total amount of assets (principal + fee) to be withdrawn at maturity.
function depositAtMaturity(
uint256 maturity,
uint256 assets,
uint256 minAssetsRequired,
address receiver
) external whenNotPaused whenNotFrozen returns (uint256 positionAssets) {
if (assets == 0) revert ZeroDeposit();
// reverts on failure
FixedLib.checkPoolState(maturity, maxFuturePools, FixedLib.State.VALID, FixedLib.State.NONE);
FixedLib.Pool storage pool = fixedPools[maturity];
uint256 backupEarnings = pool.accrueEarnings(maturity);
floatingAssets += backupEarnings;
(uint256 fee, uint256 backupFee) = pool.calculateDeposit(assets, backupFeeRate);
positionAssets = assets + fee;
if (positionAssets < minAssetsRequired) revert Disagreement();
floatingBackupBorrowed -= pool.deposit(assets);
pool.unassignedEarnings -= fee + backupFee;
earningsAccumulator += backupFee;
// update account's position
FixedLib.Position storage position = fixedDepositPositions[maturity][receiver];
// if account doesn't have a current position, add it to the list
if (position.principal == 0) {
Account storage account = accounts[receiver];
account.fixedDeposits = account.fixedDeposits.setMaturity(maturity);
}
position.principal += assets;
position.fee += fee;
emit DepositAtMaturity(maturity, msg.sender, receiver, assets, fee);
emitMarketUpdate();
emitFixedEarningsUpdate(maturity);
asset.safeTransferFrom(msg.sender, address(this), assets);
}
/// @notice Borrows a certain amount from a maturity.
/// @param maturity maturity date for repayment.
/// @param assets amount to be sent to receiver and repaid by borrower.
/// @param maxAssets maximum amount of debt that the account is willing to accept.
/// @param receiver address that will receive the borrowed assets.
/// @param borrower address that will repay the borrowed assets.
/// @return assetsOwed total amount of assets (principal + fee) to be repaid at maturity.
function borrowAtMaturity(
uint256 maturity,
uint256 assets,
uint256 maxAssets,
address receiver,
address borrower
) external whenNotPaused whenNotFrozen returns (uint256 assetsOwed) {
if (assets == 0) revert ZeroBorrow();
// reverts on failure
FixedLib.checkPoolState(maturity, maxFuturePools, FixedLib.State.VALID, FixedLib.State.NONE);
FixedLib.Pool storage pool = fixedPools[maturity];
floatingAssets += pool.accrueEarnings(maturity);
RewardsController memRewardsController = rewardsController;
if (address(memRewardsController) != address(0)) memRewardsController.handleBorrow(borrower);
{
uint256 backupDebtAddition = pool.borrow(assets);
if (backupDebtAddition != 0) {
uint256 newFloatingBackupBorrowed = floatingBackupBorrowed + backupDebtAddition;
depositToTreasury(updateFloatingDebt());
if (newFloatingBackupBorrowed + floatingDebt > floatingAssets.mulWadDown(1e18 - reserveFactor)) {
revert InsufficientProtocolLiquidity();
}
floatingBackupBorrowed = newFloatingBackupBorrowed;
}
}
uint256 fee;
{
uint256 memFloatingAssetsAverage = previewFloatingAssetsAverage();
uint256 memFloatingDebt = floatingDebt;
uint256 fixedRate = interestRateModel.fixedRate(
maturity,
maxFuturePools,
fixedUtilization(pool.supplied, pool.borrowed, memFloatingAssetsAverage),
floatingUtilization(memFloatingAssetsAverage, memFloatingDebt),
globalUtilization(memFloatingAssetsAverage, memFloatingDebt, floatingBackupBorrowed)
);
fee = assets.mulWadDown(fixedRate.mulDivDown(maturity - block.timestamp, 365 days));
}
assetsOwed = assets + fee;
// validate that the account is not taking arbitrary fees
if (assetsOwed > maxAssets) revert Disagreement();
spendAllowance(borrower, assetsOwed);
{
// if account doesn't have a current position, add it to the list
FixedLib.Position storage position = fixedBorrowPositions[maturity][borrower];
if (position.principal == 0) {
Account storage account = accounts[borrower];
account.fixedBorrows = account.fixedBorrows.setMaturity(maturity);
}
// calculate what portion of the fees are to be accrued and what portion goes to earnings accumulator
(uint256 newUnassignedEarnings, uint256 newBackupEarnings) = pool.distributeEarnings(
chargeTreasuryFee(fee),
assets
);
if (newUnassignedEarnings != 0) pool.unassignedEarnings += newUnassignedEarnings;
collectFreeLunch(newBackupEarnings);
fixedBorrowPositions[maturity][borrower] = FixedLib.Position(position.principal + assets, position.fee + fee);
}
emit BorrowAtMaturity(maturity, msg.sender, receiver, borrower, assets, fee);
emitMarketUpdate();
emitFixedEarningsUpdate(maturity);
auditor.checkBorrow(this, borrower);
asset.safeTransfer(receiver, assets);
}
/// @notice Withdraws a certain amount from a maturity.
/// @param maturity maturity date where the assets will be withdrawn.
/// @param positionAssets position size to be reduced.
/// @param minAssetsRequired minimum amount required by the account (if discount included for early withdrawal).
/// @param receiver address that will receive the withdrawn assets.
/// @param owner address that previously deposited the assets.
/// @return assetsDiscounted amount of assets withdrawn (can include a discount for early withdraw).
function withdrawAtMaturity(
uint256 maturity,
uint256 positionAssets,
uint256 minAssetsRequired,
address receiver,
address owner
) external whenNotPaused returns (uint256 assetsDiscounted) {
if (positionAssets == 0) revert ZeroWithdraw();
// reverts on failure
FixedLib.checkPoolState(maturity, maxFuturePools, FixedLib.State.VALID, FixedLib.State.MATURED);
FixedLib.Pool storage pool = fixedPools[maturity];
floatingAssets += pool.accrueEarnings(maturity);
FixedLib.Position memory position = fixedDepositPositions[maturity][owner];
if (positionAssets > position.principal + position.fee) positionAssets = position.principal + position.fee;
{
// remove the supply from the fixed rate pool
uint256 newFloatingBackupBorrowed = floatingBackupBorrowed +
pool.withdraw(
FixedLib.Position(position.principal, position.fee).scaleProportionally(positionAssets).principal
);
if (newFloatingBackupBorrowed + floatingDebt > floatingAssets) revert InsufficientProtocolLiquidity();
floatingBackupBorrowed = newFloatingBackupBorrowed;
}
// verify if there are any penalties/fee for the account because of early withdrawal, if so discount
if (block.timestamp < maturity) {
uint256 memFloatingAssetsAverage = previewFloatingAssetsAverage();
uint256 memFloatingDebt = floatingDebt;
uint256 memFloatingBackupBorrowed = floatingBackupBorrowed;
uint256 fixedRate = interestRateModel.fixedRate(
maturity,
maxFuturePools,
fixedUtilization(pool.supplied, pool.borrowed, memFloatingAssetsAverage),
floatingUtilization(memFloatingAssetsAverage, memFloatingDebt),
globalUtilization(memFloatingAssetsAverage, memFloatingDebt, memFloatingBackupBorrowed)
);
assetsDiscounted = positionAssets.divWadDown(1e18 + fixedRate.mulDivDown(maturity - block.timestamp, 365 days));
} else {
assetsDiscounted = positionAssets;
}
if (assetsDiscounted < minAssetsRequired) revert Disagreement();
spendAllowance(owner, assetsDiscounted);
// all the fees go to unassigned or to the floating pool
(uint256 unassignedEarnings, uint256 newBackupEarnings) = pool.distributeEarnings(
chargeTreasuryFee(positionAssets - assetsDiscounted),
assetsDiscounted
);
pool.unassignedEarnings += unassignedEarnings;
collectFreeLunch(newBackupEarnings);
// the account gets discounted the full amount
position.reduceProportionally(positionAssets);
if (position.principal | position.fee == 0) {
delete fixedDepositPositions[maturity][owner];
Account storage account = accounts[owner];
account.fixedDeposits = account.fixedDeposits.clearMaturity(maturity);
} else {
// proportionally reduce the values
fixedDepositPositions[maturity][owner] = position;
}
emit WithdrawAtMaturity(maturity, msg.sender, receiver, owner, positionAssets, assetsDiscounted);
emitMarketUpdate();
emitFixedEarningsUpdate(maturity);
asset.safeTransfer(receiver, assetsDiscounted);
}
/// @notice Repays a certain amount to a maturity.
/// @param maturity maturity date where the assets will be repaid.
/// @param positionAssets amount to be paid for the borrower's debt.
/// @param maxAssets maximum amount of debt that the account is willing to accept to be repaid.
/// @param borrower address of the account that has the debt.
/// @return actualRepayAssets the actual amount that was transferred into the protocol.
function repayAtMaturity(
uint256 maturity,
uint256 positionAssets,
uint256 maxAssets,
address borrower
) external whenNotPaused returns (uint256 actualRepayAssets) {
// reverts on failure
FixedLib.checkPoolState(maturity, maxFuturePools, FixedLib.State.VALID, FixedLib.State.MATURED);
actualRepayAssets = noTransferRepayAtMaturity(maturity, positionAssets, maxAssets, borrower, true);
emitMarketUpdate();
asset.safeTransferFrom(msg.sender, address(this), actualRepayAssets);
}
/// @notice Allows to (partially) repay a fixed rate position. It does not transfer assets.
/// @param maturity the maturity to access the pool.
/// @param positionAssets the amount of debt of the pool that should be paid.
/// @param maxAssets maximum amount of debt that the account is willing to accept to be repaid.
/// @param borrower the address of the account that has the debt.
/// @param canDiscount should early repay discounts be applied.
/// @return actualRepayAssets the actual amount that should be transferred into the protocol.
function noTransferRepayAtMaturity(
uint256 maturity,
uint256 positionAssets,
uint256 maxAssets,
address borrower,
bool canDiscount
) internal returns (uint256 actualRepayAssets) {
if (positionAssets == 0) revert ZeroRepay();
FixedLib.Pool storage pool = fixedPools[maturity];
uint256 backupEarnings = pool.accrueEarnings(maturity);
floatingAssets += backupEarnings;
FixedLib.Position memory position = fixedBorrowPositions[maturity][borrower];
uint256 debtCovered = Math.min(positionAssets, position.principal + position.fee);
uint256 principalCovered = FixedLib
.Position(position.principal, position.fee)
.scaleProportionally(debtCovered)
.principal;
RewardsController memRewardsController = rewardsController;
if (address(memRewardsController) != address(0)) memRewardsController.handleBorrow(borrower);
// early repayment allows a discount from the unassigned earnings
if (block.timestamp < maturity) {
if (canDiscount) {
// calculate the deposit fee considering the amount of debt the account'll pay
(uint256 discountFee, uint256 backupFee) = pool.calculateDeposit(principalCovered, backupFeeRate);
// remove the fee from unassigned earnings
pool.unassignedEarnings -= discountFee + backupFee;
// the fee charged to the fixed pool supplier goes to the earnings accumulator
earningsAccumulator += backupFee;
// the fee gets discounted from the account through `actualRepayAssets`
actualRepayAssets = debtCovered - discountFee;
} else {
actualRepayAssets = debtCovered;
}
} else {
actualRepayAssets = debtCovered + debtCovered.mulWadDown((block.timestamp - maturity) * penaltyRate);
// all penalties go to the earnings accumulator
earningsAccumulator += actualRepayAssets - debtCovered;
}
// verify that the account agrees to this discount or penalty
if (actualRepayAssets > maxAssets) revert Disagreement();
// reduce the borrowed from the pool and might decrease the floating backup borrowed
floatingBackupBorrowed -= pool.repay(principalCovered);
// update the account position
position.reduceProportionally(debtCovered);
if (position.principal | position.fee == 0) {
delete fixedBorrowPositions[maturity][borrower];
Account storage account = accounts[borrower];
account.fixedBorrows = account.fixedBorrows.clearMaturity(maturity);
} else {
// proportionally reduce the values
fixedBorrowPositions[maturity][borrower] = position;
}
emit RepayAtMaturity(maturity, msg.sender, borrower, actualRepayAssets, debtCovered);
emitFixedEarningsUpdate(maturity);
}
/// @notice Liquidates undercollateralized fixed/floating (or both) position(s).
/// @dev Msg.sender liquidates borrower's position(s) and repays a certain amount of debt for the floating pool,
/// or/and for multiple fixed pools, seizing a portion of borrower's collateral.
/// @param borrower account that has an outstanding debt across floating or fixed pools.
/// @param maxAssets maximum amount of debt that the liquidator is willing to accept. (it can be less)
/// @param seizeMarket market from which the collateral will be seized to give to the liquidator.
/// @return repaidAssets actual amount repaid.
function liquidate(
address borrower,
uint256 maxAssets,
Market seizeMarket
) external whenNotPaused returns (uint256 repaidAssets) {
if (msg.sender == borrower) revert SelfLiquidation();
maxAssets = auditor.checkLiquidation(this, seizeMarket, borrower, maxAssets);
if (maxAssets == 0) revert ZeroRepay();
Account storage account = accounts[borrower];
{
uint256 packedMaturities = account.fixedBorrows;
uint256 maturity = packedMaturities & ((1 << 32) - 1);
packedMaturities = packedMaturities >> 32;
while (packedMaturities != 0 && maxAssets != 0) {
if (packedMaturities & 1 != 0) {
uint256 actualRepay;
if (block.timestamp < maturity) {
actualRepay = noTransferRepayAtMaturity(maturity, maxAssets, maxAssets, borrower, false);
maxAssets -= actualRepay;
} else {
uint256 position;
{
FixedLib.Position storage p = fixedBorrowPositions[maturity][borrower];
position = p.principal + p.fee;
}
uint256 debt = position + position.mulWadDown((block.timestamp - maturity) * penaltyRate);
actualRepay = debt > maxAssets ? maxAssets.mulDivDown(position, debt) : maxAssets;
if (actualRepay == 0) maxAssets = 0;
else {
actualRepay = noTransferRepayAtMaturity(maturity, actualRepay, maxAssets, borrower, false);
maxAssets -= actualRepay;
}
}
repaidAssets += actualRepay;
}
packedMaturities >>= 1;
maturity += FixedLib.INTERVAL;
}
}
if (maxAssets != 0 && account.floatingBorrowShares != 0) {
uint256 borrowShares = previewRepay(maxAssets);
if (borrowShares != 0) {
(uint256 actualRepayAssets, ) = noTransferRefund(borrowShares, borrower);
repaidAssets += actualRepayAssets;
}
}
// reverts on failure
(uint256 lendersAssets, uint256 seizeAssets) = auditor.calculateSeize(this, seizeMarket, borrower, repaidAssets);
earningsAccumulator += lendersAssets;
if (address(seizeMarket) == address(this)) {
internalSeize(this, msg.sender, borrower, seizeAssets);
} else {
seizeMarket.seize(msg.sender, borrower, seizeAssets);
emitMarketUpdate();
}
emit Liquidate(msg.sender, borrower, repaidAssets, lendersAssets, seizeMarket, seizeAssets);
auditor.handleBadDebt(borrower);
asset.safeTransferFrom(msg.sender, address(this), repaidAssets + lendersAssets);
}
/// @notice Clears floating and fixed debt for an account spreading the losses to the `earningsAccumulator`.
/// @dev Can only be called from the auditor.
/// @param borrower account with insufficient collateral to be cleared the debt.
function clearBadDebt(address borrower) external {
if (msg.sender != address(auditor)) revert NotAuditor();
floatingAssets += accrueAccumulatedEarnings();
Account storage account = accounts[borrower];
uint256 accumulator = earningsAccumulator;
uint256 totalBadDebt = 0;
uint256 packedMaturities = account.fixedBorrows;
uint256 maturity = packedMaturities & ((1 << 32) - 1);
packedMaturities = packedMaturities >> 32;
while (packedMaturities != 0) {
if (packedMaturities & 1 != 0) {
FixedLib.Position storage position = fixedBorrowPositions[maturity][borrower];
uint256 badDebt = position.principal + position.fee;
if (accumulator >= badDebt) {
RewardsController memRewardsController = rewardsController;
if (address(memRewardsController) != address(0)) memRewardsController.handleBorrow(borrower);
accumulator -= badDebt;
totalBadDebt += badDebt;
floatingBackupBorrowed -= fixedPools[maturity].repay(position.principal);
delete fixedBorrowPositions[maturity][borrower];
account.fixedBorrows = account.fixedBorrows.clearMaturity(maturity);
emit RepayAtMaturity(maturity, msg.sender, borrower, badDebt, badDebt);
}
}
packedMaturities >>= 1;
maturity += FixedLib.INTERVAL;
}
if (account.floatingBorrowShares != 0 && (accumulator = previewRepay(accumulator)) != 0) {
(uint256 badDebt, ) = noTransferRefund(accumulator, borrower);
totalBadDebt += badDebt;
}
if (totalBadDebt != 0) {
earningsAccumulator -= totalBadDebt;
emit SpreadBadDebt(borrower, totalBadDebt);
}
emitMarketUpdate();
}
/// @notice Public function to seize a certain amount of assets.
/// @dev Public function for liquidator to seize borrowers assets in the floating pool.
/// This function will only be called from another Market, on `liquidation` calls.
/// That's why msg.sender needs to be passed to the internal function (to be validated as a Market).
/// @param liquidator address which will receive the seized assets.
/// @param borrower address from which the assets will be seized.
/// @param assets amount to be removed from borrower's possession.
function seize(address liquidator, address borrower, uint256 assets) external whenNotPaused {
internalSeize(Market(msg.sender), liquidator, borrower, assets);
}
/// @notice Internal function to seize a certain amount of assets.
/// @dev Internal function for liquidator to seize borrowers assets in the floating pool.
/// Will only be called from this Market on `liquidation` or through `seize` calls from another Market.
/// That's why msg.sender needs to be passed to the internal function (to be validated as a Market).
/// @param seizeMarket address which is calling the seize function (see `seize` public function).
/// @param liquidator address which will receive the seized assets.
/// @param borrower address from which the assets will be seized.
/// @param assets amount to be removed from borrower's possession.
function internalSeize(Market seizeMarket, address liquidator, address borrower, uint256 assets) internal {
if (assets == 0) revert ZeroWithdraw();
// reverts on failure
auditor.checkSeize(seizeMarket, this);
RewardsController memRewardsController = rewardsController;
if (address(memRewardsController) != address(0)) memRewardsController.handleDeposit(borrower);
uint256 shares = previewWithdraw(assets);
beforeWithdraw(assets, shares);
_burn(borrower, shares);
emit Withdraw(msg.sender, liquidator, borrower, assets, shares);
emit Seize(liquidator, borrower, assets);
emitMarketUpdate();
asset.safeTransfer(liquidator, assets);
}
/// @notice Hook to update the floating pool average, floating pool balance and distribute earnings from accumulator.
/// @param assets amount of assets to be withdrawn from the floating pool.
function beforeWithdraw(uint256 assets, uint256) internal override whenNotPaused {
updateFloatingAssetsAverage();
depositToTreasury(updateFloatingDebt());
uint256 earnings = accrueAccumulatedEarnings();
uint256 newFloatingAssets = floatingAssets + earnings - assets;
// check if the underlying liquidity that the account wants to withdraw is borrowed
if (floatingBackupBorrowed + floatingDebt > newFloatingAssets) revert InsufficientProtocolLiquidity();
floatingAssets = newFloatingAssets;
}
/// @notice Hook to update the floating pool average, floating pool balance and distribute earnings from accumulator.
/// @param assets amount of assets to be deposited to the floating pool.
function afterDeposit(uint256 assets, uint256) internal override whenNotPaused whenNotFrozen {
updateFloatingAssetsAverage();
uint256 treasuryFee = updateFloatingDebt();
uint256 earnings = accrueAccumulatedEarnings();
floatingAssets += earnings + assets;
depositToTreasury(treasuryFee);
emitMarketUpdate();
}
/// @notice Withdraws the owner's floating pool assets to the receiver address.
/// @dev Makes sure that the owner doesn't have shortfall after withdrawing.
/// @param assets amount of underlying to be withdrawn.
/// @param receiver address to which the assets will be transferred.
/// @param owner address which owns the floating pool assets.
/// @return shares amount of shares redeemed for underlying asset.
function withdraw(uint256 assets, address receiver, address owner) public override returns (uint256 shares) {
auditor.checkShortfall(this, owner, assets);
RewardsController memRewardsController = rewardsController;
if (address(memRewardsController) != address(0)) memRewardsController.handleDeposit(owner);
shares = super.withdraw(assets, receiver, owner);
emitMarketUpdate();
}
/// @notice Redeems the owner's floating pool assets to the receiver address.
/// @dev Makes sure that the owner doesn't have shortfall after withdrawing.
/// @param shares amount of shares to be redeemed for underlying asset.
/// @param receiver address to which the assets will be transferred.
/// @param owner address which owns the floating pool assets.
/// @return assets amount of underlying asset that was withdrawn.
function redeem(uint256 shares, address receiver, address owner) public override returns (uint256 assets) {
auditor.checkShortfall(this, owner, previewRedeem(shares));
RewardsController memRewardsController = rewardsController;
if (address(memRewardsController) != address(0)) memRewardsController.handleDeposit(owner);
assets = super.redeem(shares, receiver, owner);
emitMarketUpdate();
}
function _mint(address to, uint256 amount) internal override {
RewardsController memRewardsController = rewardsController;
if (address(memRewardsController) != address(0)) memRewardsController.handleDeposit(to);
super._mint(to, amount);
}
/// @notice Moves amount of shares from the caller's account to `to`.
/// @dev Makes sure that the caller doesn't have shortfall after transferring.
/// @param to address to which the assets will be transferred.
/// @param shares amount of shares to be transferred.
function transfer(address to, uint256 shares) public override whenNotPaused returns (bool) {
auditor.checkShortfall(this, msg.sender, previewRedeem(shares));
RewardsController memRewardsController = rewardsController;
if (address(memRewardsController) != address(0)) {
memRewardsController.handleDeposit(msg.sender);
memRewardsController.handleDeposit(to);
}
return super.transfer(to, shares);
}
/// @notice Moves amount of shares from `from` to `to` using the allowance mechanism.
/// @dev Makes sure that `from` address doesn't have shortfall after transferring.
/// @param from address from which the assets will be transferred.
/// @param to address to which the assets will be transferred.
/// @param shares amount of shares to be transferred.
function transferFrom(address from, address to, uint256 shares) public override whenNotPaused returns (bool) {
auditor.checkShortfall(this, from, previewRedeem(shares));
RewardsController memRewardsController = rewardsController;
if (address(memRewardsController) != address(0)) {
memRewardsController.handleDeposit(from);
memRewardsController.handleDeposit(to);
}
return super.transferFrom(from, to, shares);
}
/// @notice Gets current snapshot for an account across all maturities.
/// @param account account to return status snapshot in the specified maturity date.
/// @return the amount deposited to the floating pool and the amount owed to floating and fixed pools.
function accountSnapshot(address account) external view returns (uint256, uint256) {
return (convertToAssets(balanceOf[account]), previewDebt(account));
}
/// @notice Gets all borrows and penalties for an account.
/// @param borrower account to return status snapshot for fixed and floating borrows.
/// @return debt the total debt, denominated in number of assets.
function previewDebt(address borrower) public view returns (uint256 debt) {
Account storage account = accounts[borrower];
uint256 memPenaltyRate = penaltyRate;
uint256 packedMaturities = account.fixedBorrows;
uint256 maturity = packedMaturities & ((1 << 32) - 1);
packedMaturities = packedMaturities >> 32;
// calculate all maturities using the base maturity and the following bits representing the following intervals
while (packedMaturities != 0) {
if (packedMaturities & 1 != 0) {
FixedLib.Position storage position = fixedBorrowPositions[maturity][borrower];
uint256 positionAssets = position.principal + position.fee;
debt += positionAssets;
if (block.timestamp > maturity) {
debt += positionAssets.mulWadDown((block.timestamp - maturity) * memPenaltyRate);
}
}
packedMaturities >>= 1;
maturity += FixedLib.INTERVAL;
}
// calculate floating borrowed debt
uint256 shares = account.floatingBorrowShares;
if (shares != 0) debt += previewRefund(shares);
}
/// @notice Charges treasury fee to certain amount of earnings.
/// @param earnings amount of earnings.
/// @return earnings minus the fees charged by the treasury.
function chargeTreasuryFee(uint256 earnings) internal returns (uint256) {
uint256 fee = earnings.mulWadDown(treasuryFeeRate);
depositToTreasury(fee);
return earnings - fee;
}
/// @notice Collects all earnings that are charged to borrowers that make use of fixed pool deposits' assets.
/// @param earnings amount of earnings.
function collectFreeLunch(uint256 earnings) internal {
if (earnings == 0) return;
if (treasuryFeeRate != 0) {
depositToTreasury(earnings);
} else {
earningsAccumulator += earnings;
}
}
/// @notice Deposits amount of assets on behalf of the treasury address.
/// @param fee amount of assets to be deposited.
function depositToTreasury(uint256 fee) internal {
if (fee != 0) {
_mint(treasury, previewDeposit(fee));
floatingAssets += fee;
}
}
/// @notice Calculates the earnings to be distributed from the accumulator given the current timestamp.
/// @return earnings to be distributed from the accumulator.
function accumulatedEarnings() internal view returns (uint256 earnings) {
uint256 elapsed = block.timestamp - lastAccumulatorAccrual;
if (elapsed == 0) return 0;
return
earningsAccumulator.mulDivDown(
elapsed,
elapsed + earningsAccumulatorSmoothFactor.mulWadDown(maxFuturePools * FixedLib.INTERVAL)
);
}
/// @notice Accrues the earnings to be distributed from the accumulator given the current timestamp.
/// @return earnings distributed from the accumulator.
function accrueAccumulatedEarnings() internal returns (uint256 earnings) {
earnings = accumulatedEarnings();
earningsAccumulator -= earnings;
lastAccumulatorAccrual = uint32(block.timestamp);
emit AccumulatorAccrual(block.timestamp);
}
/// @notice Updates the `floatingAssetsAverage`.
function updateFloatingAssetsAverage() internal {
floatingAssetsAverage = previewFloatingAssetsAverage();
lastAverageUpdate = uint32(block.timestamp);
}
/// @notice Returns the current `floatingAssetsAverage` without updating the storage variable.
/// @return projected `floatingAssetsAverage`.
function previewFloatingAssetsAverage() public view returns (uint256) {
uint256 memFloatingAssets = floatingAssets;
uint256 memFloatingAssetsAverage = floatingAssetsAverage;
uint256 dampSpeedFactor = memFloatingAssets < memFloatingAssetsAverage ? dampSpeedDown : dampSpeedUp;
uint256 averageFactor = uint256(1e18 - (-int256(dampSpeedFactor * (block.timestamp - lastAverageUpdate))).expWad());
return memFloatingAssetsAverage.mulWadDown(1e18 - averageFactor) + averageFactor.mulWadDown(memFloatingAssets);
}
/// @notice Updates the floating pool borrows' variables.
/// @return treasuryFee amount of fees charged by the treasury to the new calculated floating debt.
function updateFloatingDebt() internal returns (uint256 treasuryFee) {
uint256 memFloatingDebt = floatingDebt;
uint256 memFloatingAssets = floatingAssets;
uint256 utilization = floatingUtilization(memFloatingAssets, memFloatingDebt);
uint256 newDebt = memFloatingDebt.mulWadDown(
interestRateModel
.floatingRate(utilization, globalUtilization(memFloatingAssets, memFloatingDebt, floatingBackupBorrowed))
.mulDivDown(block.timestamp - lastFloatingDebtUpdate, 365 days)
);
memFloatingDebt += newDebt;
treasuryFee = newDebt.mulWadDown(treasuryFeeRate);
floatingAssets = memFloatingAssets + newDebt - treasuryFee;
floatingDebt = memFloatingDebt;
lastFloatingDebtUpdate = uint32(block.timestamp);
emit FloatingDebtUpdate(block.timestamp, utilization);
}
/// @notice Calculates the total floating debt, considering elapsed time since last update and current interest rate.
/// @return actual floating debt plus projected interest.
function totalFloatingBorrowAssets() public view returns (uint256) {
uint256 memFloatingDebt = floatingDebt;
uint256 memFloatingAssets = floatingAssets;
uint256 newDebt = memFloatingDebt.mulWadDown(
interestRateModel
.floatingRate(
floatingUtilization(memFloatingAssets, memFloatingDebt),
globalUtilization(memFloatingAssets, memFloatingDebt, floatingBackupBorrowed)
)
.mulDivDown(block.timestamp - lastFloatingDebtUpdate, 365 days)
);
return memFloatingDebt + newDebt;
}
/// @notice Calculates the floating pool balance plus earnings to be accrued at current timestamp
/// from maturities and accumulator.
/// @return actual floatingAssets plus earnings to be accrued at current timestamp.
function totalAssets() public view override returns (uint256) {
unchecked {
uint256 backupEarnings = 0;
uint256 latestMaturity = block.timestamp - (block.timestamp % FixedLib.INTERVAL);
uint256 maxMaturity = latestMaturity + maxFuturePools * FixedLib.INTERVAL;
for (uint256 maturity = latestMaturity; maturity <= maxMaturity; maturity += FixedLib.INTERVAL) {
FixedLib.Pool storage pool = fixedPools[maturity];
uint256 lastAccrual = pool.lastAccrual;
if (maturity > lastAccrual) {
backupEarnings += block.timestamp < maturity
? pool.unassignedEarnings.mulDivDown(block.timestamp - lastAccrual, maturity - lastAccrual)
: pool.unassignedEarnings;
}
}
return
floatingAssets +
backupEarnings +
accumulatedEarnings() +
(totalFloatingBorrowAssets() - floatingDebt).mulWadDown(1e18 - treasuryFeeRate);
}
}
/// @notice Simulates the effects of a borrow at the current time, given current contract conditions.
/// @param assets amount of assets to borrow.
/// @return amount of shares that will be asigned to the account after the borrow.
function previewBorrow(uint256 assets) public view returns (uint256) {
uint256 supply = totalFloatingBorrowShares; // Saves an extra SLOAD if totalFloatingBorrowShares is non-zero.
return supply == 0 ? assets : assets.mulDivUp(supply, totalFloatingBorrowAssets());
}
/// @notice Simulates the effects of a repay at the current time, given current contract conditions.
/// @param assets amount of assets to repay.
/// @return amount of shares that will be subtracted from the account after the repay.
function previewRepay(uint256 assets) public view returns (uint256) {
uint256 supply = totalFloatingBorrowShares; // Saves an extra SLOAD if totalFloatingBorrowShares is non-zero.
return supply == 0 ? assets : assets.mulDivDown(supply, totalFloatingBorrowAssets());
}
/// @notice Simulates the effects of a refund at the current time, given current contract conditions.
/// @param shares amount of shares to subtract from caller's accountability.
/// @return amount of assets that will be repaid.
function previewRefund(uint256 shares) public view returns (uint256) {
uint256 supply = totalFloatingBorrowShares; // Saves an extra SLOAD if totalFloatingBorrowShares is non-zero.
return supply == 0 ? shares : shares.mulDivUp(totalFloatingBorrowAssets(), supply);
}
/// @notice Checks msg.sender's allowance over account's assets.
/// @param account account in which the allowance will be checked.
/// @param assets assets from account that msg.sender wants to operate on.
function spendAllowance(address account, uint256 assets) internal {
if (msg.sender != account) {
uint256 allowed = allowance[account][msg.sender]; // saves gas for limited approvals.
if (allowed != type(uint256).max) allowance[account][msg.sender] = allowed - previewWithdraw(assets);
}
}
/// @notice Retrieves a fixed pool's borrowed amount.
/// @param maturity maturity date of the fixed pool.
/// @return borrowed amount of the fixed pool.
function fixedPoolBorrowed(uint256 maturity) external view returns (uint256) {
return fixedPools[maturity].borrowed;
}
/// @notice Retrieves a fixed pool's borrowed and supplied amount.
/// @param maturity maturity date of the fixed pool.
/// @return borrowed and supplied amount of the fixed pool.
function fixedPoolBalance(uint256 maturity) external view returns (uint256, uint256) {
return (fixedPools[maturity].borrowed, fixedPools[maturity].supplied);