update lending contract and lending test case
This commit is contained in:
@@ -182,6 +182,7 @@ contract Lending is
|
||||
|
||||
/**
|
||||
* @notice 取出基础资产(如果余额不足会自动借款)
|
||||
* @dev 如果用户余额不足,会自动借款,借款金额为 amount,借款利率为 borrowRate,借款期限为 borrowPeriod
|
||||
*/
|
||||
function withdraw(uint256 amount) external override nonReentrant whenNotPaused {
|
||||
accrueInterest();
|
||||
@@ -224,6 +225,7 @@ contract Lending is
|
||||
|
||||
/**
|
||||
* @notice 存入抵押品
|
||||
* @dev 由于不涉及债务计算,存入抵押品反而会让账户更安全,所以不用更新利息因子
|
||||
*/
|
||||
function supplyCollateral(address asset, uint256 amount) external override nonReentrant whenNotPaused {
|
||||
AssetConfig memory config = assetConfigs[asset];
|
||||
@@ -272,8 +274,6 @@ contract Lending is
|
||||
int104 oldPrincipal = user.principal;
|
||||
|
||||
// 计算当前实际余额(含利息)
|
||||
// 如果 principal >= 0(存款),使用 supplyIndex
|
||||
// 如果 principal < 0(借款),使用 borrowIndex
|
||||
uint256 index = oldPrincipal >= 0 ? supplyIndex : borrowIndex;
|
||||
int256 oldBalance = LendingMath.principalToBalance(oldPrincipal, index);
|
||||
|
||||
@@ -370,13 +370,19 @@ contract Lending is
|
||||
// 计算偿还和供应金额
|
||||
(uint104 repayAmount, uint104 supplyAmount) = LendingMath.repayAndSupplyAmount(oldPrincipal, newPrincipal);
|
||||
|
||||
// 更新全局状态
|
||||
// 储备金通过减少 totalBorrowBase 和增加 totalSupplyBase 来承担坏账
|
||||
// 更新全局状态(储备金通过减少 totalBorrowBase 和增加 totalSupplyBase 来承担坏账)
|
||||
totalSupplyBase += supplyAmount;
|
||||
totalBorrowBase -= repayAmount;
|
||||
|
||||
// 计算协议支付的债务(坏账部分)
|
||||
uint256 basePaidOut = uint256(newBalance - oldBalance);
|
||||
// 计算协议承担的坏账部分
|
||||
// 坏账 = 用户债务 - 抵押品价值(当抵押品不足时)
|
||||
uint256 basePaidOut = 0;
|
||||
if (int256(collateralInBase) < -oldBalance) {
|
||||
// 抵押品不足以覆盖债务,差额由协议储备金承担
|
||||
basePaidOut = uint256(-oldBalance) - collateralInBase;
|
||||
}
|
||||
// 如果 collateralInBase >= -oldBalance,说明抵押品足够,无坏账
|
||||
|
||||
uint256 valueOfBasePaidOut = (basePaidOut * basePrice) / baseScale;
|
||||
|
||||
// 发射债务吸收事件
|
||||
@@ -513,18 +519,6 @@ contract Lending is
|
||||
return totalValue;
|
||||
}
|
||||
|
||||
/**
|
||||
* @notice 获取最小借款抵押率
|
||||
*/
|
||||
function _getMinBorrowCollateralFactor() internal view returns (uint64) {
|
||||
uint64 minFactor = type(uint64).max;
|
||||
for (uint i = 0; i < assetList.length; i++) {
|
||||
uint64 factor = assetConfigs[assetList[i]].borrowCollateralFactor;
|
||||
if (factor < minFactor) minFactor = factor;
|
||||
}
|
||||
return minFactor;
|
||||
}
|
||||
|
||||
// ========== View Functions ==========
|
||||
|
||||
function getBalance(address account) external view override returns (int256) {
|
||||
|
||||
Reference in New Issue
Block a user