- Finished migration of basic structure of scenarios and deposit story.

This commit is contained in:
eboado 2020-06-12 22:12:53 +02:00
parent 0b17abc6eb
commit ef3e5b2cbb
8 changed files with 2270 additions and 2101 deletions

View File

@ -1,4 +1,4 @@
import {Contract, Signer, utils} from "ethers";
import {Contract, Signer, utils, ethers} from "ethers";
import {getDb, BRE} from "./misc-utils";
import {
@ -415,7 +415,7 @@ export const getAToken = async (address?: tEthereumAddress) => {
);
};
export const getMintableErc20 = async (address?: tEthereumAddress) => {
export const getMintableErc20 = async (address: tEthereumAddress) => {
return await getContract<MintableErc20>(
eContractid.MintableERC20,
address ||
@ -427,7 +427,7 @@ export const getMintableErc20 = async (address?: tEthereumAddress) => {
);
};
export const getIErc20Detailed = async (address?: tEthereumAddress) => {
export const getIErc20Detailed = async (address: tEthereumAddress) => {
return await getContract<Ierc20Detailed>(
eContractid.IERC20Detailed,
address ||
@ -491,6 +491,18 @@ export const getTokenDistributor = async (address?: tEthereumAddress) => {
);
};
export const getLendingRateOracle = async (address?: tEthereumAddress) => {
return await getContract<LendingRateOracle>(
eContractid.LendingRateOracle,
address ||
(
await getDb()
.get(`${eContractid.LendingRateOracle}.${BRE.network.name}`)
.value()
).address
);
};
const linkBytecode = (artifact: Artifact, libraries: any) => {
let bytecode = artifact.bytecode;
@ -551,18 +563,14 @@ export const convertToCurrencyDecimals = async (
amount: string
) => {
const isEth = tokenAddress === MOCK_ETH_ADDRESS;
let decimals = new BigNumber(18);
let decimals = "18";
if (!isEth) {
const token = await getIErc20Detailed(tokenAddress);
decimals = new BigNumber(await token.decimals());
decimals = (await token.decimals()).toString();
}
const currencyUnit = new BigNumber(10).pow(decimals);
const amountInCurrencyDecimals = new BigNumber(amount).multipliedBy(
currencyUnit
);
return amountInCurrencyDecimals.toFixed();
return ethers.utils.parseUnits(amount, decimals);
};
export const convertToCurrencyUnits = async (

View File

@ -31,6 +31,7 @@ import {
insertContractAddressInDb,
deployAaveProtocolTestHelpers,
getEthersSigners,
registerContractInJsonDb,
} from "../helpers/contracts-helpers";
import {LendingPoolAddressesProvider} from "../types/LendingPoolAddressesProvider";
import {Wallet, ContractTransaction, ethers, Signer} from "ethers";
@ -58,8 +59,6 @@ import {
ZERO_ADDRESS,
} from "../helpers/constants";
import {PriceOracle} from "../types/PriceOracle";
// @ts-ignore
import {accounts} from "../test-wallets.js";
import {MockAggregator} from "../types/MockAggregator";
import {LendingRateOracle} from "../types/LendingRateOracle";
import {LendingPoolCore} from "../types/LendingPoolCore";
@ -75,6 +74,10 @@ const deployAllMockTokens = async (deployer: Signer) => {
tokenSymbol,
18,
]);
await registerContractInJsonDb(
tokenSymbol.toUpperCase(),
tokens[tokenSymbol]
);
}
}
@ -345,7 +348,7 @@ const enableReservesAsCollateral = async (
}
};
const waitForTx = async (tx: ContractTransaction) => await tx.wait();
export const waitForTx = async (tx: ContractTransaction) => await tx.wait();
const buildTestEnv = async (deployer: Signer, secondaryWallet: Signer) => {
console.time("setup");

View File

@ -1,248 +1,254 @@
// import {convertToCurrencyDecimals} from '../../utils/misc-utils';
// import {
// LendingPoolInstance,
// LendingPoolCoreInstance,
// ATokenContract,
// ATokenInstance,
// ERC20Instance,
// ERC20DetailedInstance,
// MintableERC20Instance,
// } from '../../utils/typechain-types/truffle-contracts';
// import BigNumber from 'bignumber.js';
// import {getTruffleContractInstance} from '../../utils/truffle/truffle-core-utils';
// import {ContractId} from '../../utils/types';
// import {
// calcExpectedReserveDataAfterDeposit,
// calcExpectedReserveDataAfterRedeem,
// calcExpectedUserDataAfterDeposit,
// calcExpectedUserDataAfterRedeem,
// calcExpectedReserveDataAfterBorrow,
// calcExpectedUserDataAfterBorrow,
// calcExpectedReserveDataAfterRepay,
// calcExpectedUserDataAfterRepay,
// calcExpectedUserDataAfterSetUseAsCollateral,
// calcExpectedUserDataAfterSwapRateMode,
// calcExpectedReserveDataAfterSwapRateMode,
// calcExpectedReserveDataAfterStableRateRebalance,
// calcExpectedUserDataAfterStableRateRebalance,
// calcExpectedUsersDataAfterRedirectInterest,
// } from '../utils/calculations';
// import {getReserveAddressFromSymbol, getReserveData, getUserData} from '../utils/helpers';
// import {UserReserveData, ReserveData} from '../utils/interfaces';
// import {ONE_YEAR, MAX_UINT_AMOUNT, NIL_ADDRESS} from '../../utils/constants';
// import {TransactionObject} from 'web3/eth/types';
import BigNumber from "bignumber.js";
// const {time, expectRevert} = require('@openzeppelin/test-helpers');
import {
calcExpectedReserveDataAfterDeposit,
calcExpectedReserveDataAfterRedeem,
calcExpectedUserDataAfterDeposit,
calcExpectedUserDataAfterRedeem,
calcExpectedReserveDataAfterBorrow,
calcExpectedUserDataAfterBorrow,
calcExpectedReserveDataAfterRepay,
calcExpectedUserDataAfterRepay,
calcExpectedUserDataAfterSetUseAsCollateral,
calcExpectedUserDataAfterSwapRateMode,
calcExpectedReserveDataAfterSwapRateMode,
calcExpectedReserveDataAfterStableRateRebalance,
calcExpectedUserDataAfterStableRateRebalance,
calcExpectedUsersDataAfterRedirectInterest,
} from "./utils/calculations";
import {
getReserveAddressFromSymbol,
getReserveData,
getUserData,
} from "./utils/helpers";
// const truffleAssert = require('truffle-assertions');
import {
getMintableErc20,
convertToCurrencyDecimals,
} from "../../helpers/contracts-helpers";
import {MOCK_ETH_ADDRESS} from "../../helpers/constants";
import {TestEnv, SignerWithAddress} from "./make-suite";
import {BRE} from "../../helpers/misc-utils";
// const chai = require('chai');
import chai from "chai";
import {ReserveData, UserReserveData} from "./utils/interfaces";
import {waitForTx} from "../__setup.spec";
import {ContractReceipt} from "ethers/contract";
import {ethers} from "ethers";
// const {expect} = chai;
const {expect} = chai;
// const almostEqualOrEqual = function(
// this: any,
// expected: ReserveData | UserReserveData,
// actual: ReserveData | UserReserveData
// ) {
// const keys = Object.keys(actual);
const timeLatest = async () => {
const block = await BRE.ethers.provider.getBlock("latest");
return new BigNumber(block.timestamp);
};
// keys.forEach(key => {
// if (
// key === 'lastUpdateTimestamp' ||
// key === 'marketStableRate' ||
// key === 'symbol' ||
// key === 'aTokenAddress' ||
// key === 'initialATokenExchangeRate' ||
// key === 'decimals'
// ) {
// //skipping consistency check on accessory data
// return;
// }
const almostEqualOrEqual = function (
this: any,
expected: ReserveData | UserReserveData,
actual: ReserveData | UserReserveData
) {
const keys = Object.keys(actual);
// this.assert(actual[key] != undefined, `Property ${key} is undefined in the actual data`);
// expect(expected[key] != undefined, `Property ${key} is undefined in the expected data`);
keys.forEach((key) => {
if (
key === "lastUpdateTimestamp" ||
key === "marketStableRate" ||
key === "symbol" ||
key === "aTokenAddress" ||
key === "initialATokenExchangeRate" ||
key === "decimals"
) {
// skipping consistency check on accessory data
return;
}
// if (actual[key] instanceof BigNumber) {
// const actualValue = (<BigNumber>actual[key]).decimalPlaces(0, BigNumber.ROUND_DOWN);
// const expectedValue = (<BigNumber>expected[key]).decimalPlaces(0, BigNumber.ROUND_DOWN);
this.assert(
actual[key] != undefined,
`Property ${key} is undefined in the actual data`
);
expect(
expected[key] != undefined,
`Property ${key} is undefined in the expected data`
);
// this.assert(
// actualValue.eq(expectedValue) ||
// actualValue.plus(1).eq(expectedValue) ||
// actualValue.eq(expectedValue.plus(1)) ||
// actualValue.plus(2).eq(expectedValue) ||
// actualValue.eq(expectedValue.plus(2)) ||
// actualValue.plus(3).eq(expectedValue) ||
// actualValue.eq(expectedValue.plus(3)),
// `expected #{act} to be almost equal or equal #{exp} for property ${key}`,
// `expected #{act} to be almost equal or equal #{exp} for property ${key}`,
// expectedValue.toFixed(0),
// actualValue.toFixed(0)
// );
// } else {
// this.assert(
// actual[key] !== null &&
// expected[key] !== null &&
// actual[key].toString() === expected[key].toString(),
// `expected #{act} to be equal #{exp} for property ${key}`,
// `expected #{act} to be equal #{exp} for property ${key}`,
// expected[key],
// actual[key]
// );
// }
// });
// };
if (actual[key] instanceof BigNumber) {
const actualValue = (<BigNumber>actual[key]).decimalPlaces(
0,
BigNumber.ROUND_DOWN
);
const expectedValue = (<BigNumber>expected[key]).decimalPlaces(
0,
BigNumber.ROUND_DOWN
);
// chai.use(function(chai: any, utils: any) {
// chai.Assertion.overwriteMethod('almostEqualOrEqual', function(original: any) {
// return function(this: any, expected: ReserveData | UserReserveData) {
// const actual = (expected as ReserveData)
// ? <ReserveData>this._obj
// : <UserReserveData>this._obj;
this.assert(
actualValue.eq(expectedValue) ||
actualValue.plus(1).eq(expectedValue) ||
actualValue.eq(expectedValue.plus(1)) ||
actualValue.plus(2).eq(expectedValue) ||
actualValue.eq(expectedValue.plus(2)) ||
actualValue.plus(3).eq(expectedValue) ||
actualValue.eq(expectedValue.plus(3)),
`expected #{act} to be almost equal or equal #{exp} for property ${key}`,
`expected #{act} to be almost equal or equal #{exp} for property ${key}`,
expectedValue.toFixed(0),
actualValue.toFixed(0)
);
} else {
this.assert(
actual[key] !== null &&
expected[key] !== null &&
actual[key].toString() === expected[key].toString(),
`expected #{act} to be equal #{exp} for property ${key}`,
`expected #{act} to be equal #{exp} for property ${key}`,
expected[key],
actual[key]
);
}
});
};
// almostEqualOrEqual.apply(this, [expected, actual]);
// };
// });
// });
chai.use(function (chai: any, utils: any) {
chai.Assertion.overwriteMethod("almostEqualOrEqual", function (
original: any
) {
return function (this: any, expected: ReserveData | UserReserveData) {
const actual = (expected as ReserveData)
? <ReserveData>this._obj
: <UserReserveData>this._obj;
// interface ActionsConfig {
// lendingPoolInstance: LendingPoolInstance;
// lendingPoolCoreInstance: LendingPoolCoreInstance;
// ethereumAddress: string;
// artifacts: Truffle.Artifacts;
// web3: Web3;
// skipIntegrityCheck: boolean;
// }
almostEqualOrEqual.apply(this, [expected, actual]);
};
});
});
// export const configuration: ActionsConfig = <ActionsConfig>{};
interface ActionsConfig {
skipIntegrityCheck: boolean;
}
// export const mint = async (reserveSymbol: string, amount: string, user: string) => {
// const {ethereumAddress, artifacts} = configuration;
export const configuration: ActionsConfig = <ActionsConfig>{};
// const reserve = await getReserveAddressFromSymbol(reserveSymbol, artifacts);
export const mint = async (
reserveSymbol: string,
amount: string,
user: SignerWithAddress
) => {
const reserve = await getReserveAddressFromSymbol(reserveSymbol);
// if (ethereumAddress === reserve.toLowerCase()) {
// throw 'Cannot mint ethereum. Mint action is most likely not needed in this story';
// }
if (MOCK_ETH_ADDRESS.toLowerCase() === reserve.toLowerCase()) {
throw "Cannot mint ethereum. Mint action is most likely not needed in this story";
}
// const tokenInstance: MintableERC20Instance = await getTruffleContractInstance(
// artifacts,
// ContractId.MintableERC20,
// reserve
// );
const token = await getMintableErc20(reserve);
// const tokensToMint = await convertToCurrencyDecimals(reserve, amount);
await waitForTx(
await token
.connect(user.signer)
.mint(await convertToCurrencyDecimals(reserve, amount))
);
};
// const txOptions: any = {
// from: user,
// };
// await tokenInstance.mint(tokensToMint, txOptions);
// };
export const approve = async (
reserveSymbol: string,
user: SignerWithAddress,
testEnv: TestEnv
) => {
const {core} = testEnv;
const reserve = await getReserveAddressFromSymbol(reserveSymbol);
// export const approve = async (reserveSymbol: string, user: string) => {
// const {ethereumAddress, artifacts} = configuration;
if (MOCK_ETH_ADDRESS.toLowerCase() === reserve.toLowerCase()) {
throw "Cannot mint ethereum. Mint action is most likely not needed in this story";
}
// const reserve = await getReserveAddressFromSymbol(reserveSymbol, artifacts);
const token = await getMintableErc20(reserve);
// if (ethereumAddress === reserve) {
// throw 'Cannot mint ethereum. Mint action is most likely not needed in this story';
// }
await token
.connect(user.signer)
.approve(core.address, "100000000000000000000000000000");
};
// const tokenInstance: ERC20Instance = await getTruffleContractInstance(
// artifacts,
// ContractId.ERC20,
// reserve
// );
export const deposit = async (
reserveSymbol: string,
amount: string,
user: SignerWithAddress,
sendValue: string,
expectedResult: string,
testEnv: TestEnv,
revertMessage?: string
) => {
const {pool} = testEnv;
// const txOptions: any = {
// from: user,
// };
// await tokenInstance.approve(
// configuration.lendingPoolCoreInstance.address,
// '100000000000000000000000000000',
// txOptions
// );
// };
const reserve = await getReserveAddressFromSymbol(reserveSymbol);
// export const deposit = async (
// reserveSymbol: string,
// amount: string,
// user: string,
// sendValue: string,
// expectedResult: string,
// revertMessage?: string
// ) => {
// const {ethereumAddress, lendingPoolInstance, artifacts} = configuration;
const amountToDeposit = await convertToCurrencyDecimals(reserve, amount);
// const reserve = await getReserveAddressFromSymbol(reserveSymbol, artifacts);
const txOptions: any = {};
const {
reserveData: reserveDataBefore,
userData: userDataBefore,
} = await getContractsData(reserve, user.address, testEnv);
// const amountToDeposit = await convertToCurrencyDecimals(reserve, amount);
if (MOCK_ETH_ADDRESS === reserve) {
if (sendValue) {
const valueToSend = await convertToCurrencyDecimals(reserve, sendValue);
txOptions.value = valueToSend;
} else {
txOptions.value = amountToDeposit;
}
}
if (expectedResult === "success") {
const txResult = await waitForTx(
await await pool
.connect(user.signer)
.deposit(reserve, amountToDeposit, "0", txOptions)
);
// const txOptions: any = {
// from: user,
// };
const {
reserveData: reserveDataAfter,
userData: userDataAfter,
timestamp,
} = await getContractsData(reserve, user.address, testEnv);
// const {reserveData: reserveDataBefore, userData: userDataBefore} = await getContractsData(
// reserve,
// user
// );
const {txCost, txTimestamp} = await getTxCostAndTimestamp(txResult);
// if (ethereumAddress === reserve) {
// if (sendValue) {
// const valueToSend = await convertToCurrencyDecimals(reserve, sendValue);
// txOptions.value = valueToSend;
// } else {
// txOptions.value = amountToDeposit;
// }
// }
// if (expectedResult === 'success') {
// const txResult = await lendingPoolInstance.deposit(reserve, amountToDeposit, '0', txOptions);
const expectedReserveData = calcExpectedReserveDataAfterDeposit(
amountToDeposit.toString(),
reserveDataBefore,
txTimestamp
);
// const {
// reserveData: reserveDataAfter,
// userData: userDataAfter,
// timestamp,
// } = await getContractsData(reserve, user);
const expectedUserReserveData = calcExpectedUserDataAfterDeposit(
amountToDeposit.toString(),
reserveDataBefore,
expectedReserveData,
userDataBefore,
txTimestamp,
timestamp,
txCost
);
// const {txCost, txTimestamp} = await getTxCostAndTimestamp(txResult);
expectEqual(reserveDataAfter, expectedReserveData);
expectEqual(userDataAfter, expectedUserReserveData);
// const expectedReserveData = calcExpectedReserveDataAfterDeposit(
// amountToDeposit,
// reserveDataBefore,
// txTimestamp
// );
// const expectedUserReserveData = calcExpectedUserDataAfterDeposit(
// amountToDeposit,
// reserveDataBefore,
// expectedReserveData,
// userDataBefore,
// txTimestamp,
// timestamp,
// txCost
// );
// expectEqual(reserveDataAfter, expectedReserveData);
// expectEqual(userDataAfter, expectedUserReserveData);
// truffleAssert.eventEmitted(txResult, 'Deposit', (ev: any) => {
// const {_reserve, _user, _amount} = ev;
// return (
// _reserve === reserve &&
// _user === user &&
// new BigNumber(_amount).isEqualTo(new BigNumber(amountToDeposit))
// );
// });
// } else if (expectedResult === 'revert') {
// await expectRevert(
// lendingPoolInstance.deposit(reserve, amountToDeposit, '0', txOptions),
// revertMessage
// );
// }
// };
// truffleAssert.eventEmitted(txResult, "Deposit", (ev: any) => {
// const {_reserve, _user, _amount} = ev;
// return (
// _reserve === reserve &&
// _user === user &&
// new BigNumber(_amount).isEqualTo(new BigNumber(amountToDeposit))
// );
// });
} else if (expectedResult === "revert") {
await expect(
pool
.connect(user.signer)
.deposit(reserve, amountToDeposit, "0", txOptions),
revertMessage
).to.be.reverted;
}
};
// export const redeem = async (
// reserveSymbol: string,
@ -266,7 +272,7 @@
// amountToRedeem = await convertToCurrencyDecimals(reserve, amount);
// } else {
// amountToRedeem = MAX_UINT_AMOUNT;
// }
// }
// if (expectedResult === 'success') {
// const txResult = await aTokenInstance.redeem(amountToRedeem, txOptions);
@ -724,13 +730,13 @@
// txCost,
// txTimestamp
// );
// expectEqual(fromDataAfter, expectedFromData);
// expectEqual(toDataAfter, expectedToData);
// truffleAssert.eventEmitted(txResult, 'InterestStreamRedirected', (ev: any) => {
// const {_from, _to} = ev;
// return _from === user
// return _from === user
// && _to === (to === user ? NIL_ADDRESS : to);
// });
// } else if (expectedResult === 'revert') {
@ -809,14 +815,15 @@
// }
// };
// const expectEqual = (
// actual: UserReserveData | ReserveData,
// expected: UserReserveData | ReserveData
// ) => {
// if (!configuration.skipIntegrityCheck) {
// expect(actual).to.be.almostEqualOrEqual(expected);
// }
// };
const expectEqual = (
actual: UserReserveData | ReserveData,
expected: UserReserveData | ReserveData
) => {
if (!configuration.skipIntegrityCheck) {
// @ts-ignore
expect(actual).to.be.almostEqualOrEqual(expected);
}
};
// interface ActionData {
// reserve: string;
@ -854,31 +861,35 @@
// };
// };
// const getTxCostAndTimestamp = async (tx: any) => {
// const txTimestamp = new BigNumber((await web3.eth.getBlock(tx.receipt.blockNumber)).timestamp);
const getTxCostAndTimestamp = async (tx: ContractReceipt) => {
if (!tx.blockNumber || !tx.transactionHash || !tx.cumulativeGasUsed) {
throw new Error("No tx blocknumber");
}
const txTimestamp = new BigNumber(
(await BRE.ethers.provider.getBlock(tx.blockNumber)).timestamp
);
// const txInfo = await configuration.web3.eth.getTransaction(tx.receipt.transactionHash);
// const txCost = new BigNumber(tx.receipt.gasUsed).multipliedBy(txInfo.gasPrice);
const txInfo = await BRE.ethers.provider.getTransaction(tx.transactionHash);
const txCost = new BigNumber(tx.cumulativeGasUsed.toString()).multipliedBy(
txInfo.gasPrice.toString()
);
// return {txCost, txTimestamp};
// };
return {txCost, txTimestamp};
};
// const getContractsData = async (reserve: string, user: string) => {
// const [reserveData, userData, timestamp] = await Promise.all([
// getReserveData(configuration.lendingPoolInstance, reserve, artifacts),
// getUserData(
// configuration.lendingPoolInstance,
// configuration.lendingPoolCoreInstance,
// reserve,
// user,
// artifacts
// ),
// time.latest(),
// ]);
const getContractsData = async (
reserve: string,
user: string,
testEnv: TestEnv
) => {
const {pool, core} = testEnv;
const reserveData = await getReserveData(pool, reserve);
const userData = await getUserData(pool, core, reserve, user);
const timestamp = await timeLatest();
// return {
// reserveData,
// userData,
// timestamp: new BigNumber(timestamp),
// };
// };
return {
reserveData,
userData,
timestamp: new BigNumber(timestamp),
};
};

View File

@ -1,233 +1,266 @@
// import {
// deposit,
// mint,
// approve,
// redeem,
// borrow,
// repay,
// setUseAsCollateral,
// swapBorrowRateMode,
// rebalanceStableBorrowRate,
// allowInterestRedirectionTo,
// redirectInterestStream,
// redirectInterestStreamOf,
// } from '../actions';
// import {on} from 'cluster';
// import { RateMode } from '../../utils/types';
import {TestEnv, SignerWithAddress} from "./make-suite";
import {mint, approve, deposit} from "./actions";
// export interface Action {
// name: string;
// args?: any;
// expected: string;
// revertMessage?: string;
// }
export interface Action {
name: string;
args?: any;
expected: string;
revertMessage?: string;
}
// export interface Story {
// description: string;
// actions: Action[];
// }
export interface Story {
description: string;
actions: Action[];
}
// export interface Scenario {
// title: string;
// description: string;
// stories: Story[];
// }
export interface Scenario {
title: string;
description: string;
stories: Story[];
}
// export const executeStory = async (story: Story, users: string[]) => {
// for (const action of story.actions) {
// await executeAction(action, users);
// }
// };
export const executeStory = async (story: Story, testEnv: TestEnv) => {
for (const action of story.actions) {
const {users} = testEnv;
await executeAction(action, users, testEnv);
}
};
// const executeAction = async (action: Action, users: string[]) => {
// const {reserve, user} = action.args;
// const {name, expected, revertMessage} = action;
const executeAction = async (
action: Action,
users: SignerWithAddress[],
testEnv: TestEnv
) => {
const {reserve, user} = action.args;
const {name, expected, revertMessage} = action;
// if (!name || name === '') {
// throw 'Action name is missing';
// }
// if (!reserve || reserve === '') {
// throw 'Invalid reserve selected for deposit';
// }
// if (!user || user === '') {
// throw `Invalid user selected to deposit into the ${reserve} reserve`;
// }
if (!name || name === "") {
throw "Action name is missing";
}
if (!reserve || reserve === "") {
throw "Invalid reserve selected for deposit";
}
if (!user || user === "") {
throw `Invalid user selected to deposit into the ${reserve} reserve`;
}
// if (!expected || expected === '') {
// throw `An expected resut for action ${name} is required`;
// }
if (!expected || expected === "") {
throw `An expected resut for action ${name} is required`;
}
// const userAddress = users[parseInt(user)];
const userAddress = users[parseInt(user)];
// switch (name) {
// case 'mint':
// const {amount} = action.args;
switch (name) {
case "mint":
const {amount} = action.args;
// if (!amount || amount === '') {
// throw `Invalid amount of ${reserve} to mint`;
// }
if (!amount || amount === "") {
throw `Invalid amount of ${reserve} to mint`;
}
// await mint(reserve, amount, userAddress);
// break;
await mint(reserve, amount, userAddress);
break;
// case 'approve':
// await approve(reserve, userAddress);
// break;
case "approve":
await approve(reserve, userAddress, testEnv);
break;
// case 'deposit':
// {
// const {amount, sendValue} = action.args;
case "deposit":
{
const {amount, sendValue} = action.args;
// if (!amount || amount === '') {
// throw `Invalid amount to deposit into the ${reserve} reserve`;
// }
if (!amount || amount === "") {
throw `Invalid amount to deposit into the ${reserve} reserve`;
}
// await deposit(reserve, amount, userAddress, sendValue, expected, revertMessage);
// }
// break;
await deposit(
reserve,
amount,
userAddress,
sendValue,
expected,
testEnv,
revertMessage
);
}
break;
// case 'redeem':
// {
// const {amount} = action.args;
// case "redeem":
// {
// const {amount} = action.args;
// if (!amount || amount === '') {
// throw `Invalid amount to redeem from the ${reserve} reserve`;
// }
// if (!amount || amount === "") {
// throw `Invalid amount to redeem from the ${reserve} reserve`;
// }
// await redeem(reserve, amount, userAddress, expected, revertMessage);
// }
// break;
// case 'borrow':
// {
// const {amount, borrowRateMode, timeTravel} = action.args;
// await redeem(reserve, amount, userAddress, expected, revertMessage);
// }
// break;
// case "borrow":
// {
// const {amount, borrowRateMode, timeTravel} = action.args;
// if (!amount || amount === '') {
// throw `Invalid amount to borrow from the ${reserve} reserve`;
// }
// if (!amount || amount === "") {
// throw `Invalid amount to borrow from the ${reserve} reserve`;
// }
// let rateMode: string = RateMode.None;
// let rateMode: string = RateMode.None;
// if (borrowRateMode === 'none') {
// RateMode.None;
// } else if (borrowRateMode === 'stable') {
// rateMode = RateMode.Stable;
// } else if (borrowRateMode === 'variable') {
// rateMode = RateMode.Variable;
// } else {
// //random value, to test improper selection of the parameter
// rateMode = '4';
// }
// if (borrowRateMode === "none") {
// RateMode.None;
// } else if (borrowRateMode === "stable") {
// rateMode = RateMode.Stable;
// } else if (borrowRateMode === "variable") {
// rateMode = RateMode.Variable;
// } else {
// //random value, to test improper selection of the parameter
// rateMode = "4";
// }
// await borrow(reserve, amount, rateMode, userAddress, timeTravel, expected, revertMessage);
// }
// break;
// await borrow(
// reserve,
// amount,
// rateMode,
// userAddress,
// timeTravel,
// expected,
// revertMessage
// );
// }
// break;
// case 'repay':
// {
// const {amount, sendValue} = action.args;
// let {onBehalfOf} = action.args;
// case "repay":
// {
// const {amount, sendValue} = action.args;
// let {onBehalfOf} = action.args;
// if (!amount || amount === '') {
// throw `Invalid amount to repay into the ${reserve} reserve`;
// }
// if (!amount || amount === "") {
// throw `Invalid amount to repay into the ${reserve} reserve`;
// }
// if (!onBehalfOf || onBehalfOf === '') {
// console.log(
// 'WARNING: No onBehalfOf specified for a repay action. Defaulting to the repayer address'
// );
// onBehalfOf = userAddress;
// } else {
// onBehalfOf = users[parseInt(onBehalfOf)];
// }
// if (!onBehalfOf || onBehalfOf === "") {
// console.log(
// "WARNING: No onBehalfOf specified for a repay action. Defaulting to the repayer address"
// );
// onBehalfOf = userAddress;
// } else {
// onBehalfOf = users[parseInt(onBehalfOf)];
// }
// await repay(reserve, amount, userAddress, onBehalfOf, sendValue, expected, revertMessage);
// }
// break;
// await repay(
// reserve,
// amount,
// userAddress,
// onBehalfOf,
// sendValue,
// expected,
// revertMessage
// );
// }
// break;
// case 'setUseAsCollateral':
// {
// const {useAsCollateral} = action.args;
// case "setUseAsCollateral":
// {
// const {useAsCollateral} = action.args;
// if (!useAsCollateral || useAsCollateral === '') {
// throw `A valid value for useAsCollateral needs to be set when calling setUseReserveAsCollateral on reserve ${reserve}`;
// }
// await setUseAsCollateral(reserve, userAddress, useAsCollateral, expected, revertMessage);
// }
// break;
// if (!useAsCollateral || useAsCollateral === "") {
// throw `A valid value for useAsCollateral needs to be set when calling setUseReserveAsCollateral on reserve ${reserve}`;
// }
// await setUseAsCollateral(
// reserve,
// userAddress,
// useAsCollateral,
// expected,
// revertMessage
// );
// }
// break;
// case 'swapBorrowRateMode':
// await swapBorrowRateMode(reserve, userAddress, expected, revertMessage);
// break;
// case "swapBorrowRateMode":
// await swapBorrowRateMode(reserve, userAddress, expected, revertMessage);
// break;
// case 'rebalanceStableBorrowRate':
// {
// const {target} = action.args;
// case "rebalanceStableBorrowRate":
// {
// const {target} = action.args;
// if (!target || target === '') {
// throw `A target must be selected when trying to rebalance a stable rate`;
// }
// const targetAddress = users[parseInt(target)];
// if (!target || target === "") {
// throw `A target must be selected when trying to rebalance a stable rate`;
// }
// const targetAddress = users[parseInt(target)];
// await rebalanceStableBorrowRate(
// reserve,
// userAddress,
// targetAddress,
// expected,
// revertMessage
// );
// }
// break;
// await rebalanceStableBorrowRate(
// reserve,
// userAddress,
// targetAddress,
// expected,
// revertMessage
// );
// }
// break;
// case 'redirectInterestStream':
// {
// const {to} = action.args;
// case "redirectInterestStream":
// {
// const {to} = action.args;
// if (!to || to === '') {
// throw `A target must be selected when trying to redirect the interest`;
// }
// const toAddress = users[parseInt(to)];
// if (!to || to === "") {
// throw `A target must be selected when trying to redirect the interest`;
// }
// const toAddress = users[parseInt(to)];
// await redirectInterestStream(reserve, userAddress, toAddress, expected, revertMessage);
// }
// break;
// await redirectInterestStream(
// reserve,
// userAddress,
// toAddress,
// expected,
// revertMessage
// );
// }
// break;
// case 'redirectInterestStreamOf':
// {
// const {from, to} = action.args;
// case "redirectInterestStreamOf":
// {
// const {from, to} = action.args;
// if (!from || from === '') {
// throw `A from address must be specified when trying to redirect the interest`;
// }
// if (!to || to === '') {
// throw `A target must be selected when trying to redirect the interest`;
// }
// const toAddress = users[parseInt(to)];
// const fromAddress = users[parseInt(from)];
// if (!from || from === "") {
// throw `A from address must be specified when trying to redirect the interest`;
// }
// if (!to || to === "") {
// throw `A target must be selected when trying to redirect the interest`;
// }
// const toAddress = users[parseInt(to)];
// const fromAddress = users[parseInt(from)];
// await redirectInterestStreamOf(
// reserve,
// userAddress,
// fromAddress,
// toAddress,
// expected,
// revertMessage
// );
// }
// break;
// await redirectInterestStreamOf(
// reserve,
// userAddress,
// fromAddress,
// toAddress,
// expected,
// revertMessage
// );
// }
// break;
// case 'allowInterestRedirectionTo':
// {
// const {to} = action.args;
// case "allowInterestRedirectionTo":
// {
// const {to} = action.args;
// if (!to || to === '') {
// throw `A target must be selected when trying to redirect the interest`;
// }
// const toAddress = users[parseInt(to)];
// if (!to || to === "") {
// throw `A target must be selected when trying to redirect the interest`;
// }
// const toAddress = users[parseInt(to)];
// await allowInterestRedirectionTo(reserve, userAddress, toAddress, expected, revertMessage);
// }
// break;
// default:
// throw `Invalid action requested: ${name}`;
// }
// };
// await allowInterestRedirectionTo(
// reserve,
// userAddress,
// toAddress,
// expected,
// revertMessage
// );
// }
// break;
default:
throw `Invalid action requested: ${name}`;
}
};

File diff suppressed because it is too large Load Diff

View File

@ -1,172 +1,159 @@
// import {
// ERC20DetailedInstance,
// LendingPoolInstance,
// LendingRateOracleInstance,
// ATokenInstance,
// LendingPoolCoreInstance,
// } from '../../utils/typechain-types/truffle-contracts';
// import {getTruffleContractInstance} from '../../utils/truffle/truffle-core-utils';
// import {ContractId} from '../../utils/types';
// import {ReserveData, UserReserveData} from './interfaces';
// import BigNumber from 'bignumber.js';
// import {configuration} from '../actions';
// import {NIL_ADDRESS, ETHEREUM_ADDRESS} from '../../utils/constants';
import {LendingPool} from "../../../types/LendingPool";
import {ReserveData, UserReserveData} from "./interfaces";
import {
getLendingRateOracle,
getIErc20Detailed,
getMintableErc20,
getAToken,
} from "../../../helpers/contracts-helpers";
import {MOCK_ETH_ADDRESS, ZERO_ADDRESS} from "../../../helpers/constants";
import {tEthereumAddress} from "../../../helpers/types";
import BigNumber from "bignumber.js";
import {getDb, BRE} from "../../../helpers/misc-utils";
import {LendingPoolCore} from "../../../types/LendingPoolCore";
// export const getReserveData = async (
// poolInstance: LendingPoolInstance,
// reserve: string,
// artifacts: Truffle.Artifacts
// ): Promise<ReserveData> => {
// const data: any = await poolInstance.getReserveData(reserve);
// const rateOracle: LendingRateOracleInstance = await getTruffleContractInstance(
// artifacts,
// ContractId.LendingRateOracle
// );
export const getReserveData = async (
pool: LendingPool,
reserve: tEthereumAddress
): Promise<ReserveData> => {
const data: any = await pool.getReserveData(reserve);
const rateOracle = await getLendingRateOracle();
// const rate = await rateOracle.getMarketBorrowRate(reserve);
const rate = (await rateOracle.getMarketBorrowRate(reserve)).toString();
// const isEthReserve = reserve === ETHEREUM_ADDRESS;
// let symbol = 'ETH';
// let decimals = new BigNumber(18);
// if (!isEthReserve) {
// const contractInstance: ERC20DetailedInstance = await getTruffleContractInstance(
// artifacts,
// ContractId.ERC20Detailed,
// reserve
// );
// symbol = await contractInstance.symbol();
// decimals = new BigNumber(await contractInstance.decimals());
// }
const isEthReserve = reserve === MOCK_ETH_ADDRESS;
let symbol = "ETH";
let decimals = new BigNumber(18);
if (!isEthReserve) {
const token = await getIErc20Detailed(reserve);
symbol = await token.symbol();
decimals = new BigNumber(await token.decimals());
}
// return {
// totalLiquidity: new BigNumber(data.totalLiquidity),
// availableLiquidity: new BigNumber(data.availableLiquidity),
// totalBorrowsStable: new BigNumber(data.totalBorrowsStable),
// totalBorrowsVariable: new BigNumber(data.totalBorrowsVariable),
// liquidityRate: new BigNumber(data.liquidityRate),
// variableBorrowRate: new BigNumber(data.variableBorrowRate),
// stableBorrowRate: new BigNumber(data.stableBorrowRate),
// averageStableBorrowRate: new BigNumber(data.averageStableBorrowRate),
// utilizationRate: new BigNumber(data.utilizationRate),
// liquidityIndex: new BigNumber(data.liquidityIndex),
// variableBorrowIndex: new BigNumber(data.variableBorrowIndex),
// lastUpdateTimestamp: new BigNumber(data.lastUpdateTimestamp),
// address: reserve,
// aTokenAddress: data.aTokenAddress,
// symbol,
// decimals,
// marketStableRate: new BigNumber(rate),
// };
// };
return {
totalLiquidity: new BigNumber(data.totalLiquidity),
availableLiquidity: new BigNumber(data.availableLiquidity),
totalBorrowsStable: new BigNumber(data.totalBorrowsStable),
totalBorrowsVariable: new BigNumber(data.totalBorrowsVariable),
liquidityRate: new BigNumber(data.liquidityRate),
variableBorrowRate: new BigNumber(data.variableBorrowRate),
stableBorrowRate: new BigNumber(data.stableBorrowRate),
averageStableBorrowRate: new BigNumber(data.averageStableBorrowRate),
utilizationRate: new BigNumber(data.utilizationRate),
liquidityIndex: new BigNumber(data.liquidityIndex),
variableBorrowIndex: new BigNumber(data.variableBorrowIndex),
lastUpdateTimestamp: new BigNumber(data.lastUpdateTimestamp),
address: reserve,
aTokenAddress: data.aTokenAddress,
symbol,
decimals,
marketStableRate: new BigNumber(rate),
};
};
// export const getUserData = async (
// poolInstance: LendingPoolInstance,
// coreInstance: LendingPoolCoreInstance,
// reserve: string,
// user: string,
// artifacts: Truffle.Artifacts
// ): Promise<UserReserveData> => {
// const {web3} = configuration;
export const getUserData = async (
pool: LendingPool,
core: LendingPoolCore,
reserve: string,
user: string
): Promise<UserReserveData> => {
const [data, aTokenData] = await Promise.all([
pool.getUserReserveData(reserve, user),
getATokenUserData(reserve, user, core),
]);
// const [data, aTokenData] = await Promise.all([
// poolInstance.getUserReserveData(reserve, user),
// getATokenUserData(reserve, user, coreInstance),
// ]);
const [
userIndex,
redirectedBalance,
principalATokenBalance,
redirectionAddressRedirectedBalance,
interestRedirectionAddress,
] = aTokenData;
// const [
// userIndex,
// redirectedBalance,
// principalATokenBalance,
// redirectionAddressRedirectedBalance,
// interestRedirectionAddress,
// ] = aTokenData;
let walletBalance;
// let walletBalance;
if (reserve === MOCK_ETH_ADDRESS) {
walletBalance = new BigNumber(
(await BRE.ethers.provider.getBalance(user)).toString()
);
} else {
const token = await getMintableErc20(reserve);
walletBalance = new BigNumber((await token.balanceOf(user)).toString());
}
// if (reserve === ETHEREUM_ADDRESS) {
// walletBalance = new BigNumber(await web3.eth.getBalance(user));
// } else {
// const reserveInstance: ERC20DetailedInstance = await getTruffleContractInstance(
// artifacts,
// ContractId.ERC20Detailed,
// reserve
// );
// walletBalance = new BigNumber(await reserveInstance.balanceOf(user));
// }
const userData: any = data;
// const userData : any = data
// return {
// principalATokenBalance: new BigNumber(principalATokenBalance),
// interestRedirectionAddress,
// redirectionAddressRedirectedBalance: new BigNumber(redirectionAddressRedirectedBalance),
// redirectedBalance: new BigNumber(redirectedBalance),
// currentATokenUserIndex: new BigNumber(userIndex),
// currentATokenBalance: new BigNumber(userData.currentATokenBalance),
// currentBorrowBalance: new BigNumber(userData.currentBorrowBalance),
// principalBorrowBalance: new BigNumber(userData.principalBorrowBalance),
// borrowRateMode: userData.borrowRateMode.toString(),
// borrowRate: new BigNumber(userData.borrowRate),
// liquidityRate: new BigNumber(userData.liquidityRate),
// originationFee: new BigNumber(userData.originationFee),
// variableBorrowIndex: new BigNumber(userData.variableBorrowIndex),
// lastUpdateTimestamp: new BigNumber(userData.lastUpdateTimestamp),
// usageAsCollateralEnabled: userData.usageAsCollateralEnabled,
// walletBalance,
// };
// };
return {
principalATokenBalance: new BigNumber(principalATokenBalance),
interestRedirectionAddress,
redirectionAddressRedirectedBalance: new BigNumber(
redirectionAddressRedirectedBalance
),
redirectedBalance: new BigNumber(redirectedBalance),
currentATokenUserIndex: new BigNumber(userIndex),
currentATokenBalance: new BigNumber(userData.currentATokenBalance),
currentBorrowBalance: new BigNumber(userData.currentBorrowBalance),
principalBorrowBalance: new BigNumber(userData.principalBorrowBalance),
borrowRateMode: userData.borrowRateMode.toString(),
borrowRate: new BigNumber(userData.borrowRate),
liquidityRate: new BigNumber(userData.liquidityRate),
originationFee: new BigNumber(userData.originationFee),
variableBorrowIndex: new BigNumber(userData.variableBorrowIndex),
lastUpdateTimestamp: new BigNumber(userData.lastUpdateTimestamp),
usageAsCollateralEnabled: userData.usageAsCollateralEnabled,
walletBalance,
};
};
// export const getReserveAddressFromSymbol = async (symbol: string, artifacts: Truffle.Artifacts) => {
// if (symbol.toUpperCase() === 'ETH') {
// return ETHEREUM_ADDRESS;
// }
export const getReserveAddressFromSymbol = async (symbol: string) => {
if (symbol.toUpperCase() === "ETH") {
return MOCK_ETH_ADDRESS;
}
// const contractName: string = 'Mock' + symbol.toUpperCase();
const token = await getMintableErc20(
(await getDb().get(`${symbol}.${BRE.network.name}`).value()).address
);
// const contractInstance: ERC20DetailedInstance = await getTruffleContractInstance(artifacts, <
// ContractId
// >contractName);
if (!token) {
throw `Could not find instance for contract ${symbol}`;
}
return token.address;
};
// if (!contractInstance) {
// throw `Could not find instance for contract ${contractName}`;
// }
// return contractInstance.address;
// };
const getATokenUserData = async (
reserve: string,
user: string,
core: LendingPoolCore
) => {
const aTokenAddress: string = await core.getReserveATokenAddress(reserve);
// const getATokenUserData = async (
// reserve: string,
// user: string,
// coreInstance: LendingPoolCoreInstance
// ) => {
// const aTokenAddress: string = await coreInstance.getReserveATokenAddress(reserve);
const aToken = await getAToken(aTokenAddress);
const [
userIndex,
interestRedirectionAddress,
redirectedBalance,
principalTokenBalance,
] = await Promise.all([
aToken.getUserIndex(user),
aToken.getInterestRedirectionAddress(user),
aToken.getRedirectedBalance(user),
aToken.principalBalanceOf(user),
]);
// const aTokenInstance: ATokenInstance = await getTruffleContractInstance(
// artifacts,
// ContractId.AToken,
// aTokenAddress
// );
// const [
// userIndex,
// interestRedirectionAddress,
// redirectedBalance,
// principalTokenBalance,
// ] = await Promise.all([
// aTokenInstance.getUserIndex(user),
// aTokenInstance.getInterestRedirectionAddress(user),
// aTokenInstance.getRedirectedBalance(user),
// aTokenInstance.principalBalanceOf(user),
// ]);
const redirectionAddressRedirectedBalance =
interestRedirectionAddress !== ZERO_ADDRESS
? new BigNumber(
(
await aToken.getRedirectedBalance(interestRedirectionAddress)
).toString()
)
: new BigNumber("0");
// const redirectionAddressRedirectedBalance =
// interestRedirectionAddress !== NIL_ADDRESS
// ? new BigNumber(await aTokenInstance.getRedirectedBalance(interestRedirectionAddress))
// : new BigNumber('0');
// return [
// userIndex.toString(),
// redirectedBalance.toString(),
// principalTokenBalance.toString(),
// redirectionAddressRedirectedBalance.toString(),
// interestRedirectionAddress,
// ];
// };
return [
userIndex.toString(),
redirectedBalance.toString(),
principalTokenBalance.toString(),
redirectionAddressRedirectedBalance.toString(),
interestRedirectionAddress,
];
};

View File

@ -1,80 +1,102 @@
// import {RAY, WAD, HALF_RAY, HALF_WAD, WAD_RAY_RATIO} from "../../utils/constants"
// import BigNumber from "bignumber.js"
import BigNumber from "bignumber.js";
import {
RAY,
WAD,
HALF_RAY,
HALF_WAD,
WAD_RAY_RATIO,
} from "../../../helpers/constants";
declare module "bignumber.js" {
interface BigNumber {
ray: () => BigNumber;
wad: () => BigNumber;
halfRay: () => BigNumber;
halfWad: () => BigNumber;
wadMul: (a: BigNumber) => BigNumber;
wadDiv: (a: BigNumber) => BigNumber;
rayMul: (a: BigNumber) => BigNumber;
rayDiv: (a: BigNumber) => BigNumber;
rayToWad: () => BigNumber;
wadToRay: () => BigNumber;
rayPow: (n: BigNumber) => BigNumber;
}
}
// declare module "bignumber.js" {
// interface BigNumber {
// ray: () => BigNumber
// wad: () => BigNumber
// halfRay: () => BigNumber
// halfWad: () => BigNumber
// wadMul: (a: BigNumber) => BigNumber
// wadDiv: (a: BigNumber) => BigNumber
// rayMul: (a: BigNumber) => BigNumber
// rayDiv: (a: BigNumber) => BigNumber
// rayToWad: () => BigNumber
// wadToRay: () => BigNumber
// rayPow: (n: BigNumber) => BigNumber
// }
// }
BigNumber.prototype.ray = (): BigNumber => {
return new BigNumber(RAY).decimalPlaces(0);
};
BigNumber.prototype.wad = (): BigNumber => {
return new BigNumber(WAD).decimalPlaces(0);
};
// BigNumber.prototype.ray = (): BigNumber => {
// return new BigNumber(RAY).decimalPlaces(0)
// }
// BigNumber.prototype.wad = (): BigNumber => {
// return new BigNumber(WAD).decimalPlaces(0)
// }
BigNumber.prototype.halfRay = (): BigNumber => {
return new BigNumber(HALF_RAY).decimalPlaces(0, BigNumber.ROUND_DOWN);
};
// BigNumber.prototype.halfRay = (): BigNumber => {
// return new BigNumber(HALF_RAY).decimalPlaces(0, BigNumber.ROUND_DOWN)
// }
BigNumber.prototype.halfWad = (): BigNumber => {
return new BigNumber(HALF_WAD).decimalPlaces(0, BigNumber.ROUND_DOWN);
};
// BigNumber.prototype.halfWad = (): BigNumber => {
// return new BigNumber(HALF_WAD).decimalPlaces(0, BigNumber.ROUND_DOWN)
// }
BigNumber.prototype.wadMul = function (b: BigNumber): BigNumber {
return this.halfWad()
.plus(this.multipliedBy(b))
.div(WAD)
.decimalPlaces(0, BigNumber.ROUND_DOWN);
};
// BigNumber.prototype.wadMul = function(b: BigNumber): BigNumber {
// return this.halfWad().plus(this.multipliedBy(b)).div(WAD).decimalPlaces(0,BigNumber.ROUND_DOWN)
// }
BigNumber.prototype.wadDiv = function (a: BigNumber): BigNumber {
const halfA = a.div(2).decimalPlaces(0, BigNumber.ROUND_DOWN);
// BigNumber.prototype.wadDiv = function(a: BigNumber) : BigNumber {
// const halfA = a.div(2).decimalPlaces(0,BigNumber.ROUND_DOWN)
return halfA
.plus(this.multipliedBy(WAD))
.div(a)
.decimalPlaces(0, BigNumber.ROUND_DOWN);
};
// return halfA.plus(this.multipliedBy(WAD)).div(a).decimalPlaces(0, BigNumber.ROUND_DOWN)
// }
BigNumber.prototype.rayMul = function (a: BigNumber): BigNumber {
return this.halfRay()
.plus(this.multipliedBy(a))
.div(RAY)
.decimalPlaces(0, BigNumber.ROUND_DOWN);
};
// BigNumber.prototype.rayMul = function(a: BigNumber) : BigNumber {
// return this.halfRay().plus(this.multipliedBy(a)).div(RAY).decimalPlaces(0, BigNumber.ROUND_DOWN)
// }
BigNumber.prototype.rayDiv = function (a: BigNumber): BigNumber {
const halfA = a.div(2).decimalPlaces(0, BigNumber.ROUND_DOWN);
// BigNumber.prototype.rayDiv = function(a: BigNumber) : BigNumber{
// const halfA = a.div(2).decimalPlaces(0,BigNumber.ROUND_DOWN)
return halfA
.plus(this.multipliedBy(RAY))
.decimalPlaces(0, BigNumber.ROUND_DOWN)
.div(a)
.decimalPlaces(0, BigNumber.ROUND_DOWN);
};
// return halfA.plus(this.multipliedBy(RAY)).decimalPlaces(0,BigNumber.ROUND_DOWN).div(a).decimalPlaces(0,BigNumber.ROUND_DOWN)
// }
BigNumber.prototype.rayToWad = function (): BigNumber {
const halfRatio = new BigNumber(WAD_RAY_RATIO).div(2);
// BigNumber.prototype.rayToWad = function(): BigNumber{
// const halfRatio = new BigNumber(WAD_RAY_RATIO).div(2);
return halfRatio
.plus(this)
.div(WAD_RAY_RATIO)
.decimalPlaces(0, BigNumber.ROUND_DOWN);
};
// return halfRatio.plus(this).div(WAD_RAY_RATIO).decimalPlaces(0, BigNumber.ROUND_DOWN)
// }
BigNumber.prototype.wadToRay = function (): BigNumber {
return this.multipliedBy(WAD_RAY_RATIO).decimalPlaces(
0,
BigNumber.ROUND_DOWN
);
};
// BigNumber.prototype.wadToRay = function() : BigNumber {
// return this.multipliedBy(WAD_RAY_RATIO).decimalPlaces(0, BigNumber.ROUND_DOWN)
// }
BigNumber.prototype.rayPow = function (n: BigNumber): BigNumber {
let z = !n.modulo(2).eq(0) ? this : new BigNumber(RAY);
let x = new BigNumber(this);
for (n = n.div(2); !n.eq(0); n = n.div(2)) {
x = x.rayMul(x);
// BigNumber.prototype.rayPow = function(n: BigNumber) : BigNumber {
// let z = !n.modulo(2).eq(0) ? this : new BigNumber(RAY);
// let x = new BigNumber(this)
// for (n = n.div(2); !n.eq(0); n = n.div(2)) {
// x = x.rayMul(x);
// if (!n.modulo(2).eq(0)) {
// z = z.rayMul(x);
// }
// }
// return z;
// }
if (!n.modulo(2).eq(0)) {
z = z.rayMul(x);
}
}
return z;
};

View File

@ -1,56 +1,36 @@
// import {ITestEnvWithoutInstances} from '../utils/types';
import {configuration as actionsConfiguration} from "./helpers/actions";
import {configuration as calculationsConfiguration} from "./helpers/utils/calculations";
// import {testEnvProviderWithoutInstances} from '../utils/truffle/dlp-tests-env';
// import {configuration as actionsConfiguration, deposit} from './actions';
// import {configuration as calculationsConfiguration} from './utils/calculations';
// import {executeStory} from './engine/scenario-engine';
// import fs from 'fs';
// import BigNumber from 'bignumber.js';
// import {ETHEREUM_ADDRESS} from '../utils/constants';
import fs from "fs";
import BigNumber from "bignumber.js";
import {makeSuite} from "./helpers/make-suite";
import {MOCK_ETH_ADDRESS, getReservesConfigByPool} from "../helpers/constants";
import {AavePools, iAavePoolAssets, IReserveParams} from "../helpers/types";
import {executeStory} from "./helpers/scenario-engine";
// BigNumber.config({DECIMAL_PLACES: 0, ROUNDING_MODE: BigNumber.ROUND_DOWN});
BigNumber.config({DECIMAL_PLACES: 0, ROUNDING_MODE: BigNumber.ROUND_DOWN});
// const scenarioFolder = './test/scenarios/';
const scenarioFolder = "./test/helpers/scenarios/";
// fs.readdirSync(scenarioFolder).forEach(file => {
// // if (file !== "interest-redirection-negatives.json" &&
// // file !== "interest-redirection.json" ) return
fs.readdirSync(scenarioFolder).forEach((file) => {
if (file !== "deposit.json") return;
// const scenario = require(`./scenarios/${file}`);
const scenario = require(`./helpers/scenarios/${file}`);
// contract(scenario.title, async ([deployer, ...users]) => {
// let _testEnvProvider: ITestEnvWithoutInstances;
makeSuite(scenario.title, async (testEnv) => {
before("Initializing configuration", async () => {
actionsConfiguration.skipIntegrityCheck = false; //set this to true to execute solidity-coverage
// before('Initializing configuration', async () => {
// console.time('setup-test');
// _testEnvProvider = await testEnvProviderWithoutInstances(artifacts, [deployer, ...users]);
calculationsConfiguration.reservesParams = <
iAavePoolAssets<IReserveParams>
>getReservesConfigByPool(AavePools.proto);
calculationsConfiguration.ethereumAddress = MOCK_ETH_ADDRESS;
});
// const {
// getWeb3,
// getAavePoolReservesParams,
// getLendingPoolInstance,
// getLendingPoolCoreInstance,
// } = _testEnvProvider;
// const instances = await Promise.all([getLendingPoolInstance(), getLendingPoolCoreInstance()]);
// actionsConfiguration.lendingPoolInstance = instances[0];
// actionsConfiguration.lendingPoolCoreInstance = instances[1];
// actionsConfiguration.ethereumAddress = ETHEREUM_ADDRESS;
// actionsConfiguration.artifacts = artifacts;
// actionsConfiguration.web3 = await getWeb3();
// actionsConfiguration.skipIntegrityCheck = false; //set this to true to execute solidity-coverage
// calculationsConfiguration.reservesParams = await getAavePoolReservesParams();
// calculationsConfiguration.web3 = actionsConfiguration.web3;
// calculationsConfiguration.ethereumAddress = actionsConfiguration.ethereumAddress;
// console.time('setup-test');
// });
// for (const story of scenario.stories) {
// it(story.description, async () => {
// await executeStory(story, users);
// });
// }
// });
// });
for (const story of scenario.stories) {
it(story.description, async () => {
await executeStory(story, testEnv);
});
}
});
});