Merge branch 'fix/175' into 'master'

Resolve "Update test scenarios to properly handle the reserve factor"

Closes #175

See merge request aave-tech/protocol-v2!198
This commit is contained in:
Ernesto Boado 2020-11-28 17:29:02 +00:00
commit 495eed33ca
11 changed files with 95 additions and 131 deletions

View File

@ -31,20 +31,20 @@ contract ATokensAndRatesHelper is Ownable {
}
function initDeployment(
address[] calldata tokens,
address[] calldata assets,
string[] calldata symbols,
uint256[6][] calldata rates,
address treasuryAddress,
address incentivesController
) external onlyOwner {
require(tokens.length == symbols.length, 't Arrays not same length');
require(assets.length == symbols.length, 't Arrays not same length');
require(rates.length == symbols.length, 'r Arrays not same length');
for (uint256 i = 0; i < tokens.length; i++) {
for (uint256 i = 0; i < assets.length; i++) {
emit deployedContracts(
address(
new AToken(
LendingPool(pool),
tokens[i],
assets[i],
treasuryAddress,
StringLib.concat('Aave interest bearing ', symbols[i]),
StringLib.concat('a', symbols[i]),
@ -89,37 +89,34 @@ contract ATokensAndRatesHelper is Ownable {
}
}
function enableReservesAsCollateral(
address[] calldata tokens,
function configureReserves(
address[] calldata assets,
uint256[] calldata baseLTVs,
uint256[] calldata liquidationThresholds,
uint256[] calldata liquidationBonuses
uint256[] calldata liquidationBonuses,
uint256[] calldata reserveFactors,
bool[] calldata stableBorrowingEnabled
) external onlyOwner {
require(baseLTVs.length == tokens.length);
require(liquidationThresholds.length == tokens.length);
require(liquidationBonuses.length == tokens.length);
require(baseLTVs.length == assets.length);
require(liquidationThresholds.length == assets.length);
require(liquidationBonuses.length == assets.length);
require(stableBorrowingEnabled.length == assets.length);
require(reserveFactors.length == assets.length);
for (uint256 i = 0; i < tokens.length; i++) {
LendingPoolConfigurator(poolConfigurator).configureReserveAsCollateral(
tokens[i],
LendingPoolConfigurator configurator = LendingPoolConfigurator(poolConfigurator);
for (uint256 i = 0; i < assets.length; i++) {
configurator.configureReserveAsCollateral(
assets[i],
baseLTVs[i],
liquidationThresholds[i],
liquidationBonuses[i]
);
}
}
function enableBorrowingOnReserves(address[] calldata tokens, bool[] calldata stableBorrowingEnabled)
external
onlyOwner
{
require(stableBorrowingEnabled.length == tokens.length);
for (uint256 i = 0; i < tokens.length; i++) {
LendingPoolConfigurator(poolConfigurator).enableBorrowingOnReserve(
tokens[i],
configurator.enableBorrowingOnReserve(
assets[i],
stableBorrowingEnabled[i]
);
configurator.setReserveFactor(assets[i], reserveFactors[i]);
}
}
}

View File

@ -4,6 +4,8 @@ import BigNumber from 'bignumber.js';
// MATH
// ----------------
export const PERCENTAGE_FACTOR = '10000';
export const HALF_PERCENTAGE = '5000';
export const WAD = Math.pow(10, 18).toString();
export const HALF_WAD = new BigNumber(WAD).multipliedBy(0.5).toString();
export const RAY = new BigNumber(10).exponentiatedBy(27).toFixed();

View File

@ -286,74 +286,7 @@ export const getPairsTokenAggregator = (
return [mappedPairs, mappedAggregators];
};
export const enableReservesToBorrowByHelper = async (
reservesParams: iMultiPoolsAssets<IReserveParams>,
tokenAddresses: { [symbol: string]: tEthereumAddress },
helpers: AaveProtocolDataProvider,
admin: tEthereumAddress
) => {
const addressProvider = await getLendingPoolAddressesProvider();
const atokenAndRatesDeployer = await getATokensAndRatesHelper();
const tokens: string[] = [];
const symbols: string[] = [];
const stableEnabled: boolean[] = [];
// Prepare data
for (const [assetSymbol, { borrowingEnabled, stableBorrowRateEnabled }] of Object.entries(
reservesParams
) as [string, IReserveParams][]) {
if (!borrowingEnabled) continue;
const assetAddressIndex = Object.keys(tokenAddresses).findIndex(
(value) => value === assetSymbol
);
const [, tokenAddress] = (Object.entries(tokenAddresses) as [string, string][])[
assetAddressIndex
];
const { borrowingEnabled: borrowingAlreadyEnabled } = await helpers.getReserveConfigurationData(
tokenAddress
);
if (borrowingAlreadyEnabled) {
console.log(`Reserve ${assetSymbol} is already enabled for borrowing, skipping`);
continue;
}
tokens.push(tokenAddress);
stableEnabled.push(stableBorrowRateEnabled);
symbols.push(assetSymbol);
}
if (tokens.length) {
// Set aTokenAndRatesDeployer as temporal admin
await waitForTx(await addressProvider.setPoolAdmin(atokenAndRatesDeployer.address));
// Deploy init per chunks
const stableChunks = 20;
const chunkedTokens = chunk(tokens, stableChunks);
const chunkedSymbols = chunk(symbols, stableChunks);
const chunkedStableEnabled = chunk(stableEnabled, stableChunks);
console.log(`- Borrow stable initialization in ${chunkedTokens.length} txs`);
for (let chunkIndex = 0; chunkIndex < chunkedTokens.length; chunkIndex++) {
try {
await waitForTx(
await atokenAndRatesDeployer.enableBorrowingOnReserves(
chunkedTokens[chunkIndex],
chunkedStableEnabled[chunkIndex],
{ gasLimit: 12000000 }
)
);
} catch (error) {
console.error(error);
throw error;
}
console.log(` - Init for: ${chunkedSymbols[chunkIndex].join(', ')}`);
}
// Set deployer back as admin
await waitForTx(await addressProvider.setPoolAdmin(admin));
}
};
export const enableReservesAsCollateralByHelper = async (
export const configureReservesByHelper = async (
reservesParams: iMultiPoolsAssets<IReserveParams>,
tokenAddresses: { [symbol: string]: tEthereumAddress },
helpers: AaveProtocolDataProvider,
@ -366,10 +299,12 @@ export const enableReservesAsCollateralByHelper = async (
const baseLTVA: string[] = [];
const liquidationThresholds: string[] = [];
const liquidationBonuses: string[] = [];
const reserveFactors: string[] = [];
const stableRatesEnabled: boolean[] = [];
for (const [
assetSymbol,
{ baseLTVAsCollateral, liquidationBonus, liquidationThreshold },
{ baseLTVAsCollateral, liquidationBonus, liquidationThreshold, reserveFactor, stableBorrowRateEnabled },
] of Object.entries(reservesParams) as [string, IReserveParams][]) {
if (baseLTVAsCollateral === '-1') continue;
@ -393,6 +328,8 @@ export const enableReservesAsCollateralByHelper = async (
baseLTVA.push(baseLTVAsCollateral);
liquidationThresholds.push(liquidationThreshold);
liquidationBonuses.push(liquidationBonus);
reserveFactors.push(reserveFactor);
stableRatesEnabled.push(stableBorrowRateEnabled);
}
if (tokens.length) {
// Set aTokenAndRatesDeployer as temporal admin
@ -405,15 +342,19 @@ export const enableReservesAsCollateralByHelper = async (
const chunkedBase = chunk(baseLTVA, enableChunks);
const chunkedliquidationThresholds = chunk(liquidationThresholds, enableChunks);
const chunkedliquidationBonuses = chunk(liquidationBonuses, enableChunks);
const chunkedReserveFactors = chunk(reserveFactors, enableChunks);
const chunkedStableRatesEnabled = chunk(stableRatesEnabled, enableChunks);
console.log(`- Enable reserve as collateral in ${chunkedTokens.length} txs`);
console.log(`- Configure reserves in ${chunkedTokens.length} txs`);
for (let chunkIndex = 0; chunkIndex < chunkedTokens.length; chunkIndex++) {
await waitForTx(
await atokenAndRatesDeployer.enableReservesAsCollateral(
await atokenAndRatesDeployer.configureReserves(
chunkedTokens[chunkIndex],
chunkedBase[chunkIndex],
chunkedliquidationThresholds[chunkIndex],
chunkedliquidationBonuses[chunkIndex],
chunkedReserveFactors[chunkIndex],
chunkedStableRatesEnabled[chunkIndex],
{ gasLimit: 12000000 }
)
);

View File

@ -262,6 +262,7 @@ export enum TokenContractId {
export interface IReserveParams extends IReserveBorrowParams, IReserveCollateralParams {
aTokenImpl: eContractid;
reserveFactor: string;
}
export interface IReserveBorrowParams {

View File

@ -16,6 +16,7 @@ export const strategyBase: IReserveParams = {
stableBorrowRateEnabled: true,
reserveDecimals: '18',
aTokenImpl: eContractid.AToken,
reserveFactor: '1000'
};
export const stablecoinStrategyBase: IReserveParams = {
@ -32,6 +33,7 @@ export const stablecoinStrategyBase: IReserveParams = {
stableBorrowRateEnabled: true,
reserveDecimals: '18',
aTokenImpl: eContractid.AToken,
reserveFactor: '1000'
};
export const stablecoinStrategyCentralized: IReserveParams = {
@ -48,6 +50,7 @@ export const stablecoinStrategyCentralized: IReserveParams = {
stableBorrowRateEnabled: true,
reserveDecimals: '6',
aTokenImpl: eContractid.AToken,
reserveFactor: '1000'
};
export const strategyGovernanceTokens: IReserveParams = {
@ -136,6 +139,7 @@ export const stablecoinStrategySUSD: IReserveParams = {
stableBorrowRateEnabled: false,
reserveDecimals: '18',
aTokenImpl: eContractid.AToken,
reserveFactor: '1000'
};
export const strategySNX: IReserveParams = {
@ -196,6 +200,7 @@ export const strategyWBTC: IReserveParams = {
stableBorrowRateEnabled: true,
reserveDecimals: '8',
aTokenImpl: eContractid.AToken,
reserveFactor: '1000'
};
export const strategyWETH: IReserveParams = {
@ -212,6 +217,7 @@ export const strategyWETH: IReserveParams = {
stableBorrowRateEnabled: true,
reserveDecimals: '18',
aTokenImpl: eContractid.AToken,
reserveFactor: '1000'
};
export const strategyYFI: IReserveParams = {

View File

@ -17,8 +17,7 @@ import {
import { tEthereumAddress, AavePools, eContractid } from '../../helpers/types';
import { waitForTx, filterMapBy } from '../../helpers/misc-utils';
import {
enableReservesToBorrowByHelper,
enableReservesAsCollateralByHelper,
configureReservesByHelper,
initReservesByHelper,
} from '../../helpers/init-helpers';
import { getAllTokenAddresses } from '../../helpers/mock-helpers';
@ -61,13 +60,7 @@ task('dev:initialize-lending-pool', 'Initialize lending pool configuration.')
ZERO_ADDRESS,
verify
);
await enableReservesToBorrowByHelper(
reservesParams,
protoPoolReservesAddresses,
testHelpers,
admin
);
await enableReservesAsCollateralByHelper(
await configureReservesByHelper(
reservesParams,
protoPoolReservesAddresses,
testHelpers,

View File

@ -11,8 +11,7 @@ import { eEthereumNetwork, ICommonConfiguration } from '../../helpers/types';
import { waitForTx } from '../../helpers/misc-utils';
import {
initReservesByHelper,
enableReservesToBorrowByHelper,
enableReservesAsCollateralByHelper,
configureReservesByHelper,
} from '../../helpers/init-helpers';
import { exit } from 'process';
import {
@ -45,8 +44,7 @@ task('full:initialize-lending-pool', 'Initialize lending pool configuration.')
const treasuryAddress = await getTreasuryAddress(poolConfig);
await initReservesByHelper(ReservesConfig, reserveAssets, admin, treasuryAddress, ZERO_ADDRESS, verify);
await enableReservesToBorrowByHelper(ReservesConfig, reserveAssets, testHelpers, admin);
await enableReservesAsCollateralByHelper(ReservesConfig, reserveAssets, testHelpers, admin);
await configureReservesByHelper(ReservesConfig, reserveAssets, testHelpers, admin);
const collateralManager = await deployLendingPoolCollateralManager(verify);
await waitForTx(

View File

@ -37,8 +37,7 @@ import {
import { DRE, waitForTx } from '../helpers/misc-utils';
import {
initReservesByHelper,
enableReservesToBorrowByHelper,
enableReservesAsCollateralByHelper,
configureReservesByHelper,
} from '../helpers/init-helpers';
import AaveConfig from '../markets/aave';
import { ZERO_ADDRESS } from '../helpers/constants';
@ -215,8 +214,7 @@ const buildTestEnv = async (deployer: Signer, secondaryWallet: Signer) => {
const treasuryAddress = await getTreasuryAddress(config);
await initReservesByHelper(reservesParams, allReservesAddresses, admin, treasuryAddress, ZERO_ADDRESS, false);
await enableReservesToBorrowByHelper(reservesParams, allReservesAddresses, testHelpers, admin);
await enableReservesAsCollateralByHelper(
await configureReservesByHelper(
reservesParams,
allReservesAddresses,
testHelpers,

View File

@ -80,7 +80,7 @@ makeSuite('LendingPoolConfigurator', (testEnv: TestEnv) => {
expect(liquidationThreshold).to.be.equal(8000);
expect(liquidationBonus).to.be.equal(10500);
expect(stableBorrowRateEnabled).to.be.equal(true);
expect(reserveFactor).to.be.equal(0);
expect(reserveFactor).to.be.equal(1000);
});
it('Unfreezes the ETH reserve', async () => {
@ -107,7 +107,7 @@ makeSuite('LendingPoolConfigurator', (testEnv: TestEnv) => {
expect(liquidationThreshold).to.be.equal(8000);
expect(liquidationBonus).to.be.equal(10500);
expect(stableBorrowRateEnabled).to.be.equal(true);
expect(reserveFactor).to.be.equal(0);
expect(reserveFactor).to.be.equal(1000);
});
it('Check the onlyAaveAdmin on freezeReserve ', async () => {
@ -149,7 +149,7 @@ makeSuite('LendingPoolConfigurator', (testEnv: TestEnv) => {
expect(liquidationThreshold).to.be.equal(8000);
expect(liquidationBonus).to.be.equal(10500);
expect(stableBorrowRateEnabled).to.be.equal(true);
expect(reserveFactor).to.be.equal(0);
expect(reserveFactor).to.be.equal(1000);
});
it('Activates the ETH reserve for borrowing', async () => {
@ -177,7 +177,7 @@ makeSuite('LendingPoolConfigurator', (testEnv: TestEnv) => {
expect(liquidationThreshold).to.be.equal(8000);
expect(liquidationBonus).to.be.equal(10500);
expect(stableBorrowRateEnabled).to.be.equal(true);
expect(reserveFactor).to.be.equal(0);
expect(reserveFactor).to.be.equal(1000);
expect(variableBorrowIndex.toString()).to.be.equal(RAY);
});
@ -222,7 +222,7 @@ makeSuite('LendingPoolConfigurator', (testEnv: TestEnv) => {
expect(liquidationThreshold).to.be.equal(0);
expect(liquidationBonus).to.be.equal(0);
expect(stableBorrowRateEnabled).to.be.equal(true);
expect(reserveFactor).to.be.equal(0);
expect(reserveFactor).to.be.equal(1000);
});
it('Activates the ETH reserve as collateral', async () => {
@ -249,7 +249,7 @@ makeSuite('LendingPoolConfigurator', (testEnv: TestEnv) => {
expect(liquidationThreshold).to.be.equal(8000);
expect(liquidationBonus).to.be.equal(10500);
expect(stableBorrowRateEnabled).to.be.equal(true);
expect(reserveFactor).to.be.equal(0);
expect(reserveFactor).to.be.equal(1000);
});
it('Check the onlyAaveAdmin on configureReserveAsCollateral ', async () => {
@ -285,7 +285,7 @@ makeSuite('LendingPoolConfigurator', (testEnv: TestEnv) => {
expect(liquidationThreshold).to.be.equal(8000);
expect(liquidationBonus).to.be.equal(10500);
expect(stableBorrowRateEnabled).to.be.equal(false);
expect(reserveFactor).to.be.equal(0);
expect(reserveFactor).to.be.equal(1000);
});
it('Enables stable borrow rate on the ETH reserve', async () => {
@ -311,7 +311,7 @@ makeSuite('LendingPoolConfigurator', (testEnv: TestEnv) => {
expect(liquidationThreshold).to.be.equal(8000);
expect(liquidationBonus).to.be.equal(10500);
expect(stableBorrowRateEnabled).to.be.equal(true);
expect(reserveFactor).to.be.equal(0);
expect(reserveFactor).to.be.equal(1000);
});
it('Check the onlyAaveAdmin on disableReserveStableRate', async () => {

View File

@ -5,10 +5,16 @@ import {
MAX_UINT_AMOUNT,
OPTIMAL_UTILIZATION_RATE,
EXCESS_UTILIZATION_RATE,
PERCENTAGE_FACTOR,
} from '../../../helpers/constants';
import {IReserveParams, iAavePoolAssets, RateMode, tEthereumAddress} from '../../../helpers/types';
import {
IReserveParams,
iAavePoolAssets,
RateMode,
tEthereumAddress,
} from '../../../helpers/types';
import './math';
import {ReserveData, UserReserveData} from './interfaces';
import { ReserveData, UserReserveData } from './interfaces';
export const strToBN = (amount: string): BigNumber => new BigNumber(amount);
@ -758,7 +764,7 @@ export const calcExpectedUserDataAfterSetUseAsCollateral = (
userDataBeforeAction: UserReserveData,
txCost: BigNumber
): UserReserveData => {
const expectedUserData = {...userDataBeforeAction};
const expectedUserData = { ...userDataBeforeAction };
expectedUserData.usageAsCollateralEnabled = useAsCollateral;
@ -885,7 +891,7 @@ export const calcExpectedUserDataAfterSwapRateMode = (
txCost: BigNumber,
txTimestamp: BigNumber
): UserReserveData => {
const expectedUserData = {...userDataBeforeAction};
const expectedUserData = { ...userDataBeforeAction };
const stableDebtBalance = calcExpectedStableDebtTokenBalance(
userDataBeforeAction.principalStableDebt,
@ -1035,7 +1041,7 @@ export const calcExpectedUserDataAfterStableRateRebalance = (
txCost: BigNumber,
txTimestamp: BigNumber
): UserReserveData => {
const expectedUserData = {...userDataBeforeAction};
const expectedUserData = { ...userDataBeforeAction };
expectedUserData.principalVariableDebt = calcExpectedVariableDebtTokenBalance(
reserveDataBeforeAction,
@ -1084,7 +1090,7 @@ export const calcExpectedATokenBalance = (
) => {
const index = calcExpectedReserveNormalizedIncome(reserveData, currentTimestamp);
const {scaledATokenBalance: scaledBalanceBeforeAction} = userData;
const { scaledATokenBalance: scaledBalanceBeforeAction } = userData;
return scaledBalanceBeforeAction.rayMul(index);
};
@ -1119,7 +1125,7 @@ export const calcExpectedVariableDebtTokenBalance = (
currentTimestamp
);
const {scaledVariableDebt} = userData;
const { scaledVariableDebt } = userData;
return scaledVariableDebt.rayMul(normalizedDebt);
};
@ -1202,7 +1208,7 @@ export const calcExpectedInterestRates = (
totalVariableDebt: BigNumber,
averageStableBorrowRate: BigNumber
): BigNumber[] => {
const {reservesParams} = configuration;
const { reservesParams } = configuration;
const reserveIndex = Object.keys(reservesParams).findIndex((value) => value === reserveSymbol);
const [, reserveConfiguration] = (Object.entries(reservesParams) as [string, IReserveParams][])[
@ -1248,7 +1254,9 @@ export const calcExpectedInterestRates = (
variableBorrowRate,
averageStableBorrowRate
);
const liquidityRate = expectedOverallRate.rayMul(utilizationRate);
const liquidityRate = expectedOverallRate
.rayMul(utilizationRate)
.percentMul(new BigNumber(PERCENTAGE_FACTOR).minus(reserveConfiguration.reserveFactor));
return [liquidityRate, stableBorrowRate, variableBorrowRate];
};
@ -1292,7 +1300,7 @@ const calcExpectedReserveNormalizedIncome = (
reserveData: ReserveData,
currentTimestamp: BigNumber
) => {
const {liquidityRate, liquidityIndex, lastUpdateTimestamp} = reserveData;
const { liquidityRate, liquidityIndex, lastUpdateTimestamp } = reserveData;
//if utilization rate is 0, nothing to compound
if (liquidityRate.eq('0')) {

View File

@ -1,5 +1,5 @@
import BigNumber from 'bignumber.js';
import {RAY, WAD, HALF_RAY, HALF_WAD, WAD_RAY_RATIO} from '../../../helpers/constants';
import {RAY, WAD, HALF_RAY, HALF_WAD, WAD_RAY_RATIO, HALF_PERCENTAGE, PERCENTAGE_FACTOR} from '../../../helpers/constants';
declare module 'bignumber.js' {
interface BigNumber {
@ -7,10 +7,13 @@ declare module 'bignumber.js' {
wad: () => BigNumber;
halfRay: () => BigNumber;
halfWad: () => BigNumber;
halfPercentage: () => BigNumber;
wadMul: (a: BigNumber) => BigNumber;
wadDiv: (a: BigNumber) => BigNumber;
rayMul: (a: BigNumber) => BigNumber;
rayDiv: (a: BigNumber) => BigNumber;
percentMul: (a: BigNumber) => BigNumber;
percentDiv: (a: BigNumber) => BigNumber;
rayToWad: () => BigNumber;
wadToRay: () => BigNumber;
}
@ -64,3 +67,20 @@ BigNumber.prototype.rayToWad = function (): BigNumber {
BigNumber.prototype.wadToRay = function (): BigNumber {
return this.multipliedBy(WAD_RAY_RATIO).decimalPlaces(0, BigNumber.ROUND_DOWN);
};
BigNumber.prototype.halfPercentage = (): BigNumber => {
return new BigNumber(HALF_PERCENTAGE).decimalPlaces(0, BigNumber.ROUND_DOWN);
};
BigNumber.prototype.percentMul = function (b: BigNumber): BigNumber {
return this.halfPercentage().plus(this.multipliedBy(b)).div(PERCENTAGE_FACTOR).decimalPlaces(0, BigNumber.ROUND_DOWN);
};
BigNumber.prototype.percentDiv = function (a: BigNumber): BigNumber {
const halfA = a.div(2).decimalPlaces(0, BigNumber.ROUND_DOWN);
return halfA.plus(this.multipliedBy(PERCENTAGE_FACTOR)).div(a).decimalPlaces(0, BigNumber.ROUND_DOWN);
};