-
Notifications
You must be signed in to change notification settings - Fork 50
/
Copy pathMoneyMarket.sol
2043 lines (1689 loc) · 99.3 KB
/
MoneyMarket.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
pragma solidity ^0.4.24;
import "./Exponential.sol";
import "./InterestRateModel.sol";
import "./PriceOracleInterface.sol";
import "./SafeToken.sol";
/**
* @title The Compound MoneyMarket Contract
* @author Compound
* @notice The Compound MoneyMarket Contract in the core contract governing
* all accounts in Compound.
*/
contract MoneyMarket is Exponential, SafeToken {
uint constant initialInterestIndex = 10 ** 18;
uint constant defaultOriginationFee = 0; // default is zero bps
uint constant minimumCollateralRatioMantissa = 11 * (10 ** 17); // 1.1
uint constant maximumLiquidationDiscountMantissa = (10 ** 17); // 0.1
/**
* @notice `MoneyMarket` is the core Compound MoneyMarket contract
*/
constructor() public {
admin = msg.sender;
collateralRatio = Exp({mantissa: 2 * mantissaOne});
originationFee = Exp({mantissa: defaultOriginationFee});
liquidationDiscount = Exp({mantissa: 0});
// oracle must be configured via _setOracle
}
/**
* @notice Do not pay directly into MoneyMarket, please use `supply`.
*/
function() payable public {
revert();
}
/**
* @dev pending Administrator for this contract.
*/
address public pendingAdmin;
/**
* @dev Administrator for this contract. Initially set in constructor, but can
* be changed by the admin itself.
*/
address public admin;
/**
* @dev Account allowed to set oracle prices for this contract. Initially set
* in constructor, but can be changed by the admin.
*/
address public oracle;
/**
* @dev Container for customer balance information written to storage.
*
* struct Balance {
* principal = customer total balance with accrued interest after applying the customer's most recent balance-changing action
* interestIndex = the total interestIndex as calculated after applying the customer's most recent balance-changing action
* }
*/
struct Balance {
uint principal;
uint interestIndex;
}
/**
* @dev 2-level map: customerAddress -> assetAddress -> balance for supplies
*/
mapping(address => mapping(address => Balance)) public supplyBalances;
/**
* @dev 2-level map: customerAddress -> assetAddress -> balance for borrows
*/
mapping(address => mapping(address => Balance)) public borrowBalances;
/**
* @dev Container for per-asset balance sheet and interest rate information written to storage, intended to be stored in a map where the asset address is the key
*
* struct Market {
* isSupported = Whether this market is supported or not (not to be confused with the list of collateral assets)
* blockNumber = when the other values in this struct were calculated
* totalSupply = total amount of this asset supplied (in asset wei)
* supplyRateMantissa = the per-block interest rate for supplies of asset as of blockNumber, scaled by 10e18
* supplyIndex = the interest index for supplies of asset as of blockNumber; initialized in _supportMarket
* totalBorrows = total amount of this asset borrowed (in asset wei)
* borrowRateMantissa = the per-block interest rate for borrows of asset as of blockNumber, scaled by 10e18
* borrowIndex = the interest index for borrows of asset as of blockNumber; initialized in _supportMarket
* }
*/
struct Market {
bool isSupported;
uint blockNumber;
InterestRateModel interestRateModel;
uint totalSupply;
uint supplyRateMantissa;
uint supplyIndex;
uint totalBorrows;
uint borrowRateMantissa;
uint borrowIndex;
}
/**
* @dev map: assetAddress -> Market
*/
mapping(address => Market) public markets;
/**
* @dev list: collateralMarkets
*/
address[] public collateralMarkets;
/**
* @dev The collateral ratio that borrows must maintain (e.g. 2 implies 2:1). This
* is initially set in the constructor, but can be changed by the admin.
*/
Exp public collateralRatio;
/**
* @dev originationFee for new borrows.
*
*/
Exp public originationFee;
/**
* @dev liquidationDiscount for collateral when liquidating borrows
*
*/
Exp public liquidationDiscount;
/**
* @dev flag for whether or not contract is paused
*
*/
bool public paused;
/**
* @dev emitted when a supply is received
* Note: newBalance - amount - startingBalance = interest accumulated since last change
*/
event SupplyReceived(address account, address asset, uint amount, uint startingBalance, uint newBalance);
/**
* @dev emitted when a supply is withdrawn
* Note: startingBalance - amount - startingBalance = interest accumulated since last change
*/
event SupplyWithdrawn(address account, address asset, uint amount, uint startingBalance, uint newBalance);
/**
* @dev emitted when a new borrow is taken
* Note: newBalance - borrowAmountWithFee - startingBalance = interest accumulated since last change
*/
event BorrowTaken(address account, address asset, uint amount, uint startingBalance, uint borrowAmountWithFee, uint newBalance);
/**
* @dev emitted when a borrow is repaid
* Note: newBalance - amount - startingBalance = interest accumulated since last change
*/
event BorrowRepaid(address account, address asset, uint amount, uint startingBalance, uint newBalance);
/**
* @dev emitted when a borrow is liquidated
* targetAccount = user whose borrow was liquidated
* assetBorrow = asset borrowed
* borrowBalanceBefore = borrowBalance as most recently stored before the liquidation
* borrowBalanceAccumulated = borroBalanceBefore + accumulated interest as of immediately prior to the liquidation
* amountRepaid = amount of borrow repaid
* liquidator = account requesting the liquidation
* assetCollateral = asset taken from targetUser and given to liquidator in exchange for liquidated loan
* borrowBalanceAfter = new stored borrow balance (should equal borrowBalanceAccumulated - amountRepaid)
* collateralBalanceBefore = collateral balance as most recently stored before the liquidation
* collateralBalanceAccumulated = collateralBalanceBefore + accumulated interest as of immediately prior to the liquidation
* amountSeized = amount of collateral seized by liquidator
* collateralBalanceAfter = new stored collateral balance (should equal collateralBalanceAccumulated - amountSeized)
*/
event BorrowLiquidated(address targetAccount,
address assetBorrow,
uint borrowBalanceBefore,
uint borrowBalanceAccumulated,
uint amountRepaid,
uint borrowBalanceAfter,
address liquidator,
address assetCollateral,
uint collateralBalanceBefore,
uint collateralBalanceAccumulated,
uint amountSeized,
uint collateralBalanceAfter);
/**
* @dev emitted when pendingAdmin is changed
*/
event NewPendingAdmin(address oldPendingAdmin, address newPendingAdmin);
/**
* @dev emitted when pendingAdmin is accepted, which means admin is updated
*/
event NewAdmin(address oldAdmin, address newAdmin);
/**
* @dev newOracle - address of new oracle
*/
event NewOracle(address oldOracle, address newOracle);
/**
* @dev emitted when new market is supported by admin
*/
event SupportedMarket(address asset, address interestRateModel);
/**
* @dev emitted when risk parameters are changed by admin
*/
event NewRiskParameters(uint oldCollateralRatioMantissa, uint newCollateralRatioMantissa, uint oldLiquidationDiscountMantissa, uint newLiquidationDiscountMantissa);
/**
* @dev emitted when origination fee is changed by admin
*/
event NewOriginationFee(uint oldOriginationFeeMantissa, uint newOriginationFeeMantissa);
/**
* @dev emitted when market has new interest rate model set
*/
event SetMarketInterestRateModel(address asset, address interestRateModel);
/**
* @dev emitted when admin withdraws equity
* Note that `equityAvailableBefore` indicates equity before `amount` was removed.
*/
event EquityWithdrawn(address asset, uint equityAvailableBefore, uint amount, address owner);
/**
* @dev emitted when a supported market is suspended by admin
*/
event SuspendedMarket(address asset);
/**
* @dev emitted when admin either pauses or resumes the contract; newState is the resulting state
*/
event SetPaused(bool newState);
/**
* @dev Simple function to calculate min between two numbers.
*/
function min(uint a, uint b) pure internal returns (uint) {
if (a < b) {
return a;
} else {
return b;
}
}
/**
* @dev Function to simply retrieve block number
* This exists mainly for inheriting test contracts to stub this result.
*/
function getBlockNumber() internal view returns (uint) {
return block.number;
}
/**
* @dev Adds a given asset to the list of collateral markets. This operation is impossible to reverse.
* Note: this will not add the asset if it already exists.
*/
function addCollateralMarket(address asset) internal {
for (uint i = 0; i < collateralMarkets.length; i++) {
if (collateralMarkets[i] == asset) {
return;
}
}
collateralMarkets.push(asset);
}
/**
* @notice return the number of elements in `collateralMarkets`
* @dev you can then externally call `collateralMarkets(uint)` to pull each market address
* @return the length of `collateralMarkets`
*/
function getCollateralMarketsLength() public view returns (uint) {
return collateralMarkets.length;
}
/**
* @dev Calculates a new supply index based on the prevailing interest rates applied over time
* This is defined as `we multiply the most recent supply index by (1 + blocks times rate)`
*/
function calculateInterestIndex(uint startingInterestIndex, uint interestRateMantissa, uint blockStart, uint blockEnd) pure internal returns (Error, uint) {
// Get the block delta
(Error err0, uint blockDelta) = sub(blockEnd, blockStart);
if (err0 != Error.NO_ERROR) {
return (err0, 0);
}
// Scale the interest rate times number of blocks
// Note: Doing Exp construction inline to avoid `CompilerError: Stack too deep, try removing local variables.`
(Error err1, Exp memory blocksTimesRate) = mulScalar(Exp({mantissa: interestRateMantissa}), blockDelta);
if (err1 != Error.NO_ERROR) {
return (err1, 0);
}
// Add one to that result (which is really Exp({mantissa: expScale}) which equals 1.0)
(Error err2, Exp memory onePlusBlocksTimesRate) = addExp(blocksTimesRate, Exp({mantissa: mantissaOne}));
if (err2 != Error.NO_ERROR) {
return (err2, 0);
}
// Then scale that accumulated interest by the old interest index to get the new interest index
(Error err3, Exp memory newInterestIndexExp) = mulScalar(onePlusBlocksTimesRate, startingInterestIndex);
if (err3 != Error.NO_ERROR) {
return (err3, 0);
}
// Finally, truncate the interest index. This works only if interest index starts large enough
// that is can be accurately represented with a whole number.
return (Error.NO_ERROR, truncate(newInterestIndexExp));
}
/**
* @dev Calculates a new balance based on a previous balance and a pair of interest indices
* This is defined as: `The user's last balance checkpoint is multiplied by the currentSupplyIndex
* value and divided by the user's checkpoint index value`
*
* TODO: Is there a way to handle this that is less likely to overflow?
*/
function calculateBalance(uint startingBalance, uint interestIndexStart, uint interestIndexEnd) pure internal returns (Error, uint) {
if (startingBalance == 0) {
// We are accumulating interest on any previous balance; if there's no previous balance, then there is
// nothing to accumulate.
return (Error.NO_ERROR, 0);
}
(Error err0, uint balanceTimesIndex) = mul(startingBalance, interestIndexEnd);
if (err0 != Error.NO_ERROR) {
return (err0, 0);
}
return div(balanceTimesIndex, interestIndexStart);
}
/**
* @dev Gets the price for the amount specified of the given asset.
*/
function getPriceForAssetAmount(address asset, uint assetAmount) internal view returns (Error, Exp memory) {
(Error err, Exp memory assetPrice) = fetchAssetPrice(asset);
if (err != Error.NO_ERROR) {
return (err, Exp({mantissa: 0}));
}
if (isZeroExp(assetPrice)) {
return (Error.MISSING_ASSET_PRICE, Exp({mantissa: 0}));
}
return mulScalar(assetPrice, assetAmount); // assetAmountWei * oraclePrice = assetValueInEth
}
/**
* @dev Gets the price for the amount specified of the given asset multiplied by the current
* collateral ratio (i.e., assetAmountWei * collateralRatio * oraclePrice = totalValueInEth).
* We will group this as `(oraclePrice * collateralRatio) * assetAmountWei`
*/
function getPriceForAssetAmountMulCollatRatio(address asset, uint assetAmount) internal view returns (Error, Exp memory) {
Error err;
Exp memory assetPrice;
Exp memory scaledPrice;
(err, assetPrice) = fetchAssetPrice(asset);
if (err != Error.NO_ERROR) {
return (err, Exp({mantissa: 0}));
}
if (isZeroExp(assetPrice)) {
return (Error.MISSING_ASSET_PRICE, Exp({mantissa: 0}));
}
// Now, multiply the assetValue by the collateral ratio
(err, scaledPrice) = mulExp(collateralRatio, assetPrice);
if (err != Error.NO_ERROR) {
return (err, Exp({mantissa: 0}));
}
// Get the price for the given asset amount
return mulScalar(scaledPrice, assetAmount);
}
/**
* @dev Calculates the origination fee added to a given borrowAmount
* This is simply `(1 + originationFee) * borrowAmount`
*
* TODO: Track at what magnitude this fee rounds down to zero?
*/
function calculateBorrowAmountWithFee(uint borrowAmount) view internal returns (Error, uint) {
// When origination fee is zero, the amount with fee is simply equal to the amount
if (isZeroExp(originationFee)) {
return (Error.NO_ERROR, borrowAmount);
}
(Error err0, Exp memory originationFeeFactor) = addExp(originationFee, Exp({mantissa: mantissaOne}));
if (err0 != Error.NO_ERROR) {
return (err0, 0);
}
(Error err1, Exp memory borrowAmountWithFee) = mulScalar(originationFeeFactor, borrowAmount);
if (err1 != Error.NO_ERROR) {
return (err1, 0);
}
return (Error.NO_ERROR, truncate(borrowAmountWithFee));
}
/**
* @dev fetches the price of asset from the PriceOracle and converts it to Exp
* @param asset asset whose price should be fetched
*/
function fetchAssetPrice(address asset) internal view returns (Error, Exp memory) {
if (oracle == address(0)) {
return (Error.ZERO_ORACLE_ADDRESS, Exp({mantissa: 0}));
}
PriceOracleInterface oracleInterface = PriceOracleInterface(oracle);
uint priceMantissa = oracleInterface.assetPrices(asset);
return (Error.NO_ERROR, Exp({mantissa: priceMantissa}));
}
/**
* @notice Reads scaled price of specified asset from the price oracle
* @dev Reads scaled price of specified asset from the price oracle.
* The plural name is to match a previous storage mapping that this function replaced.
* @param asset Asset whose price should be retrieved
* @return 0 on an error or missing price, the price scaled by 1e18 otherwise
*/
function assetPrices(address asset) public view returns (uint) {
(Error err, Exp memory result) = fetchAssetPrice(asset);
if (err != Error.NO_ERROR) {
return 0;
}
return result.mantissa;
}
/**
* @dev Gets the amount of the specified asset given the specified Eth value
* ethValue / oraclePrice = assetAmountWei
* If there's no oraclePrice, this returns (Error.DIVISION_BY_ZERO, 0)
*/
function getAssetAmountForValue(address asset, Exp ethValue) internal view returns (Error, uint) {
Error err;
Exp memory assetPrice;
Exp memory assetAmount;
(err, assetPrice) = fetchAssetPrice(asset);
if (err != Error.NO_ERROR) {
return (err, 0);
}
(err, assetAmount) = divExp(ethValue, assetPrice);
if (err != Error.NO_ERROR) {
return (err, 0);
}
return (Error.NO_ERROR, truncate(assetAmount));
}
/**
* @notice Begins transfer of admin rights. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer.
* @dev Admin function to begin change of admin. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer.
* @param newPendingAdmin New pending admin.
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*
* TODO: Should we add a second arg to verify, like a checksum of `newAdmin` address?
*/
function _setPendingAdmin(address newPendingAdmin) public returns (uint) {
// Check caller = admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_PENDING_ADMIN_OWNER_CHECK);
}
// save current value, if any, for inclusion in log
address oldPendingAdmin = pendingAdmin;
// Store pendingAdmin = newPendingAdmin
pendingAdmin = newPendingAdmin;
emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin);
return uint(Error.NO_ERROR);
}
/**
* @notice Accepts transfer of admin rights. msg.sender must be pendingAdmin
* @dev Admin function for pending admin to accept role and update admin
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _acceptAdmin() public returns (uint) {
// Check caller = pendingAdmin
// msg.sender can't be zero
if (msg.sender != pendingAdmin) {
return fail(Error.UNAUTHORIZED, FailureInfo.ACCEPT_ADMIN_PENDING_ADMIN_CHECK);
}
// Save current value for inclusion in log
address oldAdmin = admin;
// Store admin = pendingAdmin
admin = pendingAdmin;
// Clear the pending value
pendingAdmin = 0;
emit NewAdmin(oldAdmin, msg.sender);
return uint(Error.NO_ERROR);
}
/**
* @notice Set new oracle, who can set asset prices
* @dev Admin function to change oracle
* @param newOracle New oracle address
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setOracle(address newOracle) public returns (uint) {
// Check caller = admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_ORACLE_OWNER_CHECK);
}
// Verify contract at newOracle address supports assetPrices call.
// This will revert if it doesn't.
PriceOracleInterface oracleInterface = PriceOracleInterface(newOracle);
oracleInterface.assetPrices(address(0));
address oldOracle = oracle;
// Store oracle = newOracle
oracle = newOracle;
emit NewOracle(oldOracle, newOracle);
return uint(Error.NO_ERROR);
}
/**
* @notice set `paused` to the specified state
* @dev Admin function to pause or resume the market
* @param requestedState value to assign to `paused`
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setPaused(bool requestedState) public returns (uint) {
// Check caller = admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_PAUSED_OWNER_CHECK);
}
paused = requestedState;
emit SetPaused(requestedState);
return uint(Error.NO_ERROR);
}
/**
* @notice returns the liquidity for given account.
* a positive result indicates ability to borrow, whereas
* a negative result indicates a shortfall which may be liquidated
* @dev returns account liquidity in terms of eth-wei value, scaled by 1e18
* note: this includes interest trued up on all balances
* @param account the account to examine
* @return signed integer in terms of eth-wei (negative indicates a shortfall)
*/
function getAccountLiquidity(address account) public view returns (int) {
(Error err, Exp memory accountLiquidity, Exp memory accountShortfall) = calculateAccountLiquidity(account);
require(err == Error.NO_ERROR);
if (isZeroExp(accountLiquidity)) {
return -1 * int(truncate(accountShortfall));
} else {
return int(truncate(accountLiquidity));
}
}
/**
* @notice return supply balance with any accumulated interest for `asset` belonging to `account`
* @dev returns supply balance with any accumulated interest for `asset` belonging to `account`
* @param account the account to examine
* @param asset the market asset whose supply balance belonging to `account` should be checked
* @return uint supply balance on success, throws on failed assertion otherwise
*/
function getSupplyBalance(address account, address asset) view public returns (uint) {
Error err;
uint newSupplyIndex;
uint userSupplyCurrent;
Market storage market = markets[asset];
Balance storage supplyBalance = supplyBalances[account][asset];
// Calculate the newSupplyIndex, needed to calculate user's supplyCurrent
(err, newSupplyIndex) = calculateInterestIndex(market.supplyIndex, market.supplyRateMantissa, market.blockNumber, getBlockNumber());
require(err == Error.NO_ERROR);
// Use newSupplyIndex and stored principal to calculate the accumulated balance
(err, userSupplyCurrent) = calculateBalance(supplyBalance.principal, supplyBalance.interestIndex, newSupplyIndex);
require(err == Error.NO_ERROR);
return userSupplyCurrent;
}
/**
* @notice return borrow balance with any accumulated interest for `asset` belonging to `account`
* @dev returns borrow balance with any accumulated interest for `asset` belonging to `account`
* @param account the account to examine
* @param asset the market asset whose borrow balance belonging to `account` should be checked
* @return uint borrow balance on success, throws on failed assertion otherwise
*/
function getBorrowBalance(address account, address asset) view public returns (uint) {
Error err;
uint newBorrowIndex;
uint userBorrowCurrent;
Market storage market = markets[asset];
Balance storage borrowBalance = borrowBalances[account][asset];
// Calculate the newBorrowIndex, needed to calculate user's borrowCurrent
(err, newBorrowIndex) = calculateInterestIndex(market.borrowIndex, market.borrowRateMantissa, market.blockNumber, getBlockNumber());
require(err == Error.NO_ERROR);
// Use newBorrowIndex and stored principal to calculate the accumulated balance
(err, userBorrowCurrent) = calculateBalance(borrowBalance.principal, borrowBalance.interestIndex, newBorrowIndex);
require(err == Error.NO_ERROR);
return userBorrowCurrent;
}
/**
* @notice Supports a given market (asset) for use with Compound
* @dev Admin function to add support for a market
* @param asset Asset to support; MUST already have a non-zero price set
* @param interestRateModel InterestRateModel to use for the asset
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _supportMarket(address asset, InterestRateModel interestRateModel) public returns (uint) {
// Check caller = admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SUPPORT_MARKET_OWNER_CHECK);
}
(Error err, Exp memory assetPrice) = fetchAssetPrice(asset);
if (err != Error.NO_ERROR) {
return fail(err, FailureInfo.SUPPORT_MARKET_FETCH_PRICE_FAILED);
}
if (isZeroExp(assetPrice)) {
return fail(Error.ASSET_NOT_PRICED, FailureInfo.SUPPORT_MARKET_PRICE_CHECK);
}
// Set the interest rate model to `modelAddress`
markets[asset].interestRateModel = interestRateModel;
// Append asset to collateralAssets if not set
addCollateralMarket(asset);
// Set market isSupported to true
markets[asset].isSupported = true;
// Default supply and borrow index to 1e18
if (markets[asset].supplyIndex == 0) {
markets[asset].supplyIndex = initialInterestIndex;
}
if (markets[asset].borrowIndex == 0) {
markets[asset].borrowIndex = initialInterestIndex;
}
emit SupportedMarket(asset, interestRateModel);
return uint(Error.NO_ERROR);
}
/**
* @notice Suspends a given *supported* market (asset) from use with Compound.
* Assets in this state do count for collateral, but users may only withdraw, payBorrow,
* and liquidate the asset. The liquidate function no longer checks collateralization.
* @dev Admin function to suspend a market
* @param asset Asset to suspend
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _suspendMarket(address asset) public returns (uint) {
// Check caller = admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SUSPEND_MARKET_OWNER_CHECK);
}
// If the market is not configured at all, we don't want to add any configuration for it.
// If we find !markets[asset].isSupported then either the market is not configured at all, or it
// has already been marked as unsupported. We can just return without doing anything.
// Caller is responsible for knowing the difference between not-configured and already unsupported.
if (!markets[asset].isSupported) {
return uint(Error.NO_ERROR);
}
// If we get here, we know market is configured and is supported, so set isSupported to false
markets[asset].isSupported = false;
emit SuspendedMarket(asset);
return uint(Error.NO_ERROR);
}
/**
* @notice Sets the risk parameters: collateral ratio and liquidation discount
* @dev Owner function to set the risk parameters
* @param collateralRatioMantissa rational collateral ratio, scaled by 1e18. The de-scaled value must be >= 1.1
* @param liquidationDiscountMantissa rational liquidation discount, scaled by 1e18. The de-scaled value must be <= 0.1 and must be less than (descaled collateral ratio minus 1)
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setRiskParameters(uint collateralRatioMantissa, uint liquidationDiscountMantissa) public returns (uint) {
// Check caller = admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_RISK_PARAMETERS_OWNER_CHECK);
}
Exp memory newCollateralRatio = Exp({mantissa: collateralRatioMantissa});
Exp memory newLiquidationDiscount = Exp({mantissa: liquidationDiscountMantissa});
Exp memory minimumCollateralRatio = Exp({mantissa: minimumCollateralRatioMantissa});
Exp memory maximumLiquidationDiscount = Exp({mantissa: maximumLiquidationDiscountMantissa});
Error err;
Exp memory newLiquidationDiscountPlusOne;
// Make sure new collateral ratio value is not below minimum value
if (lessThanExp(newCollateralRatio, minimumCollateralRatio)) {
return fail(Error.INVALID_COLLATERAL_RATIO, FailureInfo.SET_RISK_PARAMETERS_VALIDATION);
}
// Make sure new liquidation discount does not exceed the maximum value, but reverse operands so we can use the
// existing `lessThanExp` function rather than adding a `greaterThan` function to Exponential.
if (lessThanExp(maximumLiquidationDiscount, newLiquidationDiscount)) {
return fail(Error.INVALID_LIQUIDATION_DISCOUNT, FailureInfo.SET_RISK_PARAMETERS_VALIDATION);
}
// C = L+1 is not allowed because it would cause division by zero error in `calculateDiscountedRepayToEvenAmount`
// C < L+1 is not allowed because it would cause integer underflow error in `calculateDiscountedRepayToEvenAmount`
(err, newLiquidationDiscountPlusOne) = addExp(newLiquidationDiscount, Exp({mantissa: mantissaOne}));
assert(err == Error.NO_ERROR); // We already validated that newLiquidationDiscount does not approach overflow size
if (lessThanOrEqualExp(newCollateralRatio, newLiquidationDiscountPlusOne)) {
return fail(Error.INVALID_COMBINED_RISK_PARAMETERS, FailureInfo.SET_RISK_PARAMETERS_VALIDATION);
}
// Save current values so we can emit them in log.
Exp memory oldCollateralRatio = collateralRatio;
Exp memory oldLiquidationDiscount = liquidationDiscount;
// Store new values
collateralRatio = newCollateralRatio;
liquidationDiscount = newLiquidationDiscount;
emit NewRiskParameters(oldCollateralRatio.mantissa, collateralRatioMantissa, oldLiquidationDiscount.mantissa, liquidationDiscountMantissa);
return uint(Error.NO_ERROR);
}
/**
* @notice Sets the origination fee (which is a multiplier on new borrows)
* @dev Owner function to set the origination fee
* @param originationFeeMantissa rational collateral ratio, scaled by 1e18. The de-scaled value must be >= 1.1
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setOriginationFee(uint originationFeeMantissa) public returns (uint) {
// Check caller = admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_ORIGINATION_FEE_OWNER_CHECK);
}
// Save current value so we can emit it in log.
Exp memory oldOriginationFee = originationFee;
originationFee = Exp({mantissa: originationFeeMantissa});
emit NewOriginationFee(oldOriginationFee.mantissa, originationFeeMantissa);
return uint(Error.NO_ERROR);
}
/**
* @notice Sets the interest rate model for a given market
* @dev Admin function to set interest rate model
* @param asset Asset to support
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setMarketInterestRateModel(address asset, InterestRateModel interestRateModel) public returns (uint) {
// Check caller = admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_MARKET_INTEREST_RATE_MODEL_OWNER_CHECK);
}
// Set the interest rate model to `modelAddress`
markets[asset].interestRateModel = interestRateModel;
emit SetMarketInterestRateModel(asset, interestRateModel);
return uint(Error.NO_ERROR);
}
/**
* @notice withdraws `amount` of `asset` from equity for asset, as long as `amount` <= equity. Equity= cash - (supply + borrows)
* @dev withdraws `amount` of `asset` from equity for asset, enforcing amount <= cash - (supply + borrows)
* @param asset asset whose equity should be withdrawn
* @param amount amount of equity to withdraw; must not exceed equity available
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _withdrawEquity(address asset, uint amount) public returns (uint) {
// Check caller = admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.EQUITY_WITHDRAWAL_MODEL_OWNER_CHECK);
}
// Check that amount is less than cash (from ERC-20 of self) plus borrows minus supply.
uint cash = getCash(asset);
(Error err0, uint equity) = addThenSub(cash, markets[asset].totalBorrows, markets[asset].totalSupply);
if (err0 != Error.NO_ERROR) {
return fail(err0, FailureInfo.EQUITY_WITHDRAWAL_CALCULATE_EQUITY);
}
if (amount > equity) {
return fail(Error.EQUITY_INSUFFICIENT_BALANCE, FailureInfo.EQUITY_WITHDRAWAL_AMOUNT_VALIDATION);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
// We ERC-20 transfer the asset out of the protocol to the admin
Error err2 = doTransferOut(asset, admin, amount);
if (err2 != Error.NO_ERROR) {
// This is safe since it's our first interaction and it didn't do anything if it failed
return fail(err2, FailureInfo.EQUITY_WITHDRAWAL_TRANSFER_OUT_FAILED);
}
//event EquityWithdrawn(address asset, uint equityAvailableBefore, uint amount, address owner)
emit EquityWithdrawn(asset, equity, amount, admin);
return uint(Error.NO_ERROR); // success
}
/**
* The `SupplyLocalVars` struct is used internally in the `supply` function.
*
* To avoid solidity limits on the number of local variables we:
* 1. Use a struct to hold local computation localResults
* 2. Re-use a single variable for Error returns. (This is required with 1 because variable binding to tuple localResults
* requires either both to be declared inline or both to be previously declared.
* 3. Re-use a boolean error-like return variable.
*/
struct SupplyLocalVars {
uint startingBalance;
uint newSupplyIndex;
uint userSupplyCurrent;
uint userSupplyUpdated;
uint newTotalSupply;
uint currentCash;
uint updatedCash;
uint newSupplyRateMantissa;
uint newBorrowIndex;
uint newBorrowRateMantissa;
}
/**
* @notice supply `amount` of `asset` (which must be supported) to `msg.sender` in the protocol
* @dev add amount of supported asset to msg.sender's account
* @param asset The market asset to supply
* @param amount The amount to supply
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function supply(address asset, uint amount) public returns (uint) {
if (paused) {
return fail(Error.CONTRACT_PAUSED, FailureInfo.SUPPLY_CONTRACT_PAUSED);
}
Market storage market = markets[asset];
Balance storage balance = supplyBalances[msg.sender][asset];
SupplyLocalVars memory localResults; // Holds all our uint calculation results
Error err; // Re-used for every function call that includes an Error in its return value(s).
uint rateCalculationResultCode; // Used for 2 interest rate calculation calls
// Fail if market not supported
if (!market.isSupported) {
return fail(Error.MARKET_NOT_SUPPORTED, FailureInfo.SUPPLY_MARKET_NOT_SUPPORTED);
}
// Fail gracefully if asset is not approved or has insufficient balance
err = checkTransferIn(asset, msg.sender, amount);
if (err != Error.NO_ERROR) {
return fail(err, FailureInfo.SUPPLY_TRANSFER_IN_NOT_POSSIBLE);
}
// We calculate the newSupplyIndex, user's supplyCurrent and supplyUpdated for the asset
(err, localResults.newSupplyIndex) = calculateInterestIndex(market.supplyIndex, market.supplyRateMantissa, market.blockNumber, getBlockNumber());
if (err != Error.NO_ERROR) {
return fail(err, FailureInfo.SUPPLY_NEW_SUPPLY_INDEX_CALCULATION_FAILED);
}
(err, localResults.userSupplyCurrent) = calculateBalance(balance.principal, balance.interestIndex, localResults.newSupplyIndex);
if (err != Error.NO_ERROR) {
return fail(err, FailureInfo.SUPPLY_ACCUMULATED_BALANCE_CALCULATION_FAILED);
}
(err, localResults.userSupplyUpdated) = add(localResults.userSupplyCurrent, amount);
if (err != Error.NO_ERROR) {
return fail(err, FailureInfo.SUPPLY_NEW_TOTAL_BALANCE_CALCULATION_FAILED);
}
// We calculate the protocol's totalSupply by subtracting the user's prior checkpointed balance, adding user's updated supply
(err, localResults.newTotalSupply) = addThenSub(market.totalSupply, localResults.userSupplyUpdated, balance.principal);
if (err != Error.NO_ERROR) {
return fail(err, FailureInfo.SUPPLY_NEW_TOTAL_SUPPLY_CALCULATION_FAILED);
}
// We need to calculate what the updated cash will be after we transfer in from user
localResults.currentCash = getCash(asset);
(err, localResults.updatedCash) = add(localResults.currentCash, amount);
if (err != Error.NO_ERROR) {
return fail(err, FailureInfo.SUPPLY_NEW_TOTAL_CASH_CALCULATION_FAILED);
}
// The utilization rate has changed! We calculate a new supply index and borrow index for the asset, and save it.
(rateCalculationResultCode, localResults.newSupplyRateMantissa) = market.interestRateModel.getSupplyRate(asset, localResults.updatedCash, market.totalBorrows);
if (rateCalculationResultCode != 0) {
return failOpaque(FailureInfo.SUPPLY_NEW_SUPPLY_RATE_CALCULATION_FAILED, rateCalculationResultCode);
}
// We calculate the newBorrowIndex (we already had newSupplyIndex)
(err, localResults.newBorrowIndex) = calculateInterestIndex(market.borrowIndex, market.borrowRateMantissa, market.blockNumber, getBlockNumber());
if (err != Error.NO_ERROR) {
return fail(err, FailureInfo.SUPPLY_NEW_BORROW_INDEX_CALCULATION_FAILED);
}
(rateCalculationResultCode, localResults.newBorrowRateMantissa) = market.interestRateModel.getBorrowRate(asset, localResults.updatedCash, market.totalBorrows);
if (rateCalculationResultCode != 0) {
return failOpaque(FailureInfo.SUPPLY_NEW_BORROW_RATE_CALCULATION_FAILED, rateCalculationResultCode);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
// We ERC-20 transfer the asset into the protocol (note: pre-conditions already checked above)
err = doTransferIn(asset, msg.sender, amount);
if (err != Error.NO_ERROR) {
// This is safe since it's our first interaction and it didn't do anything if it failed
return fail(err, FailureInfo.SUPPLY_TRANSFER_IN_FAILED);
}
// Save market updates
market.blockNumber = getBlockNumber();
market.totalSupply = localResults.newTotalSupply;
market.supplyRateMantissa = localResults.newSupplyRateMantissa;
market.supplyIndex = localResults.newSupplyIndex;
market.borrowRateMantissa = localResults.newBorrowRateMantissa;
market.borrowIndex = localResults.newBorrowIndex;
// Save user updates
localResults.startingBalance = balance.principal; // save for use in `SupplyReceived` event
balance.principal = localResults.userSupplyUpdated;
balance.interestIndex = localResults.newSupplyIndex;
emit SupplyReceived(msg.sender, asset, amount, localResults.startingBalance, localResults.userSupplyUpdated);
return uint(Error.NO_ERROR); // success
}
struct WithdrawLocalVars {
uint withdrawAmount;
uint startingBalance;
uint newSupplyIndex;
uint userSupplyCurrent;
uint userSupplyUpdated;
uint newTotalSupply;
uint currentCash;
uint updatedCash;
uint newSupplyRateMantissa;
uint newBorrowIndex;
uint newBorrowRateMantissa;
Exp accountLiquidity;
Exp accountShortfall;
Exp ethValueOfWithdrawal;
uint withdrawCapacity;
}
/**
* @notice withdraw `amount` of `asset` from sender's account to sender's address
* @dev withdraw `amount` of `asset` from msg.sender's account to msg.sender
* @param asset The market asset to withdraw
* @param requestedAmount The amount to withdraw (or -1 for max)