-
Notifications
You must be signed in to change notification settings - Fork 45
/
GenericLogic.sol
256 lines (227 loc) · 9.48 KB
/
GenericLogic.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
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.10;
import {IERC20} from '../../../dependencies/openzeppelin/contracts/IERC20.sol';
import {IScaledBalanceToken} from '../../../interfaces/IScaledBalanceToken.sol';
import {IPriceOracleGetter} from '../../../interfaces/IPriceOracleGetter.sol';
import {ReserveConfiguration} from '../configuration/ReserveConfiguration.sol';
import {UserConfiguration} from '../configuration/UserConfiguration.sol';
import {EModeConfiguration} from '../configuration/EModeConfiguration.sol';
import {PercentageMath} from '../math/PercentageMath.sol';
import {WadRayMath} from '../math/WadRayMath.sol';
import {DataTypes} from '../types/DataTypes.sol';
import {ReserveLogic} from './ReserveLogic.sol';
import {EModeLogic} from './EModeLogic.sol';
/**
* @title GenericLogic library
* @author Aave
* @notice Implements protocol-level logic to calculate and validate the state of a user
*/
library GenericLogic {
using ReserveLogic for DataTypes.ReserveData;
using WadRayMath for uint256;
using PercentageMath for uint256;
using ReserveConfiguration for DataTypes.ReserveConfigurationMap;
using UserConfiguration for DataTypes.UserConfigurationMap;
struct CalculateUserAccountDataVars {
uint256 assetPrice;
uint256 assetUnit;
uint256 userBalanceInBaseCurrency;
uint256 decimals;
uint256 ltv;
uint256 liquidationThreshold;
uint256 i;
uint256 healthFactor;
uint256 totalCollateralInBaseCurrency;
uint256 totalDebtInBaseCurrency;
uint256 avgLtv;
uint256 avgLiquidationThreshold;
uint256 eModeLtv;
uint256 eModeLiqThreshold;
address currentReserveAddress;
bool hasZeroLtvCollateral;
bool isInEModeCategory;
}
/**
* @notice Calculates the user data across the reserves.
* @dev It includes the total liquidity/collateral/borrow balances in the base currency used by the price feed,
* the average Loan To Value, the average Liquidation Ratio, and the Health factor.
* @param reservesData The state of all the reserves
* @param reservesList The addresses of all the active reserves
* @param eModeCategories The configuration of all the efficiency mode categories
* @param params Additional parameters needed for the calculation
* @return The total collateral of the user in the base currency used by the price feed
* @return The total debt of the user in the base currency used by the price feed
* @return The average ltv of the user
* @return The average liquidation threshold of the user
* @return The health factor of the user
* @return True if the ltv is zero, false otherwise
*/
function calculateUserAccountData(
mapping(address => DataTypes.ReserveData) storage reservesData,
mapping(uint256 => address) storage reservesList,
mapping(uint8 => DataTypes.EModeCategory) storage eModeCategories,
DataTypes.CalculateUserAccountDataParams memory params
) internal view returns (uint256, uint256, uint256, uint256, uint256, bool) {
if (params.userConfig.isEmpty()) {
return (0, 0, 0, 0, type(uint256).max, false);
}
CalculateUserAccountDataVars memory vars;
if (params.userEModeCategory != 0) {
vars.eModeLtv = eModeCategories[params.userEModeCategory].ltv;
vars.eModeLiqThreshold = eModeCategories[params.userEModeCategory].liquidationThreshold;
}
while (vars.i < params.reservesCount) {
if (!params.userConfig.isUsingAsCollateralOrBorrowing(vars.i)) {
unchecked {
++vars.i;
}
continue;
}
vars.currentReserveAddress = reservesList[vars.i];
if (vars.currentReserveAddress == address(0)) {
unchecked {
++vars.i;
}
continue;
}
DataTypes.ReserveData storage currentReserve = reservesData[vars.currentReserveAddress];
(vars.ltv, vars.liquidationThreshold, , vars.decimals, ) = currentReserve
.configuration
.getParams();
unchecked {
vars.assetUnit = 10 ** vars.decimals;
}
vars.assetPrice = IPriceOracleGetter(params.oracle).getAssetPrice(vars.currentReserveAddress);
if (vars.liquidationThreshold != 0 && params.userConfig.isUsingAsCollateral(vars.i)) {
vars.userBalanceInBaseCurrency = _getUserBalanceInBaseCurrency(
params.user,
currentReserve,
vars.assetPrice,
vars.assetUnit
);
vars.totalCollateralInBaseCurrency += vars.userBalanceInBaseCurrency;
vars.isInEModeCategory =
params.userEModeCategory != 0 &&
EModeConfiguration.isReserveEnabledOnBitmap(
eModeCategories[params.userEModeCategory].collateralBitmap,
vars.i
);
if (vars.ltv != 0) {
vars.avgLtv +=
vars.userBalanceInBaseCurrency *
(vars.isInEModeCategory ? vars.eModeLtv : vars.ltv);
} else {
vars.hasZeroLtvCollateral = true;
}
vars.avgLiquidationThreshold +=
vars.userBalanceInBaseCurrency *
(vars.isInEModeCategory ? vars.eModeLiqThreshold : vars.liquidationThreshold);
}
if (params.userConfig.isBorrowing(vars.i)) {
vars.totalDebtInBaseCurrency += _getUserDebtInBaseCurrency(
params.user,
currentReserve,
vars.assetPrice,
vars.assetUnit
);
}
unchecked {
++vars.i;
}
}
unchecked {
vars.avgLtv = vars.totalCollateralInBaseCurrency != 0
? vars.avgLtv / vars.totalCollateralInBaseCurrency
: 0;
vars.avgLiquidationThreshold = vars.totalCollateralInBaseCurrency != 0
? vars.avgLiquidationThreshold / vars.totalCollateralInBaseCurrency
: 0;
}
vars.healthFactor = (vars.totalDebtInBaseCurrency == 0)
? type(uint256).max
: (vars.totalCollateralInBaseCurrency.percentMul(vars.avgLiquidationThreshold)).wadDiv(
vars.totalDebtInBaseCurrency
);
return (
vars.totalCollateralInBaseCurrency,
vars.totalDebtInBaseCurrency,
vars.avgLtv,
vars.avgLiquidationThreshold,
vars.healthFactor,
vars.hasZeroLtvCollateral
);
}
/**
* @notice Calculates the maximum amount that can be borrowed depending on the available collateral, the total debt
* and the average Loan To Value
* @param totalCollateralInBaseCurrency The total collateral in the base currency used by the price feed
* @param totalDebtInBaseCurrency The total borrow balance in the base currency used by the price feed
* @param ltv The average loan to value
* @return The amount available to borrow in the base currency of the used by the price feed
*/
function calculateAvailableBorrows(
uint256 totalCollateralInBaseCurrency,
uint256 totalDebtInBaseCurrency,
uint256 ltv
) internal pure returns (uint256) {
uint256 availableBorrowsInBaseCurrency = totalCollateralInBaseCurrency.percentMul(ltv);
if (availableBorrowsInBaseCurrency <= totalDebtInBaseCurrency) {
return 0;
}
availableBorrowsInBaseCurrency = availableBorrowsInBaseCurrency - totalDebtInBaseCurrency;
return availableBorrowsInBaseCurrency;
}
/**
* @notice Calculates total debt of the user in the based currency used to normalize the values of the assets
* @dev This fetches the `balanceOf` of the variable debt token for the user. For gas reasons, the
* variable debt balance is calculated by fetching `scaledBalancesOf` normalized debt, which is cheaper than
* fetching `balanceOf`
* @param user The address of the user
* @param reserve The data of the reserve for which the total debt of the user is being calculated
* @param assetPrice The price of the asset for which the total debt of the user is being calculated
* @param assetUnit The value representing one full unit of the asset (10^decimals)
* @return The total debt of the user normalized to the base currency
*/
function _getUserDebtInBaseCurrency(
address user,
DataTypes.ReserveData storage reserve,
uint256 assetPrice,
uint256 assetUnit
) private view returns (uint256) {
// fetching variable debt
uint256 userTotalDebt = IScaledBalanceToken(reserve.variableDebtTokenAddress).scaledBalanceOf(
user
);
if (userTotalDebt == 0) {
return 0;
}
userTotalDebt = userTotalDebt.rayMul(reserve.getNormalizedDebt()) * assetPrice;
unchecked {
return userTotalDebt / assetUnit;
}
}
/**
* @notice Calculates total aToken balance of the user in the based currency used by the price oracle
* @dev For gas reasons, the aToken balance is calculated by fetching `scaledBalancesOf` normalized debt, which
* is cheaper than fetching `balanceOf`
* @param user The address of the user
* @param reserve The data of the reserve for which the total aToken balance of the user is being calculated
* @param assetPrice The price of the asset for which the total aToken balance of the user is being calculated
* @param assetUnit The value representing one full unit of the asset (10^decimals)
* @return The total aToken balance of the user normalized to the base currency of the price oracle
*/
function _getUserBalanceInBaseCurrency(
address user,
DataTypes.ReserveData storage reserve,
uint256 assetPrice,
uint256 assetUnit
) private view returns (uint256) {
uint256 normalizedIncome = reserve.getNormalizedIncome();
uint256 balance = (
IScaledBalanceToken(reserve.aTokenAddress).scaledBalanceOf(user).rayMul(normalizedIncome)
) * assetPrice;
unchecked {
return balance / assetUnit;
}
}
}