diff --git a/buidler.config.ts b/buidler.config.ts index 7bbdb4ea..1d8cc279 100644 --- a/buidler.config.ts +++ b/buidler.config.ts @@ -61,7 +61,7 @@ const config: BuidlerConfig = { url: "https://api-kovan.etherscan.io/api", apiKey: ETHERSCAN_KEY, }, - defaultNetwork: "ganache", + defaultNetwork: "buidlerevm", mocha: { timeout: 0, }, diff --git a/helpers/contracts-helpers.ts b/helpers/contracts-helpers.ts index e3344b44..58b6ce4e 100644 --- a/helpers/contracts-helpers.ts +++ b/helpers/contracts-helpers.ts @@ -467,6 +467,30 @@ export const getInterestRateStrategy = async (address?: tEthereumAddress) => { ); }; +export const getMockFlashLoanReceiver = async (address?: tEthereumAddress) => { + return await getContract( + eContractid.MockFlashLoanReceiver, + address || + ( + await getDb() + .get(`${eContractid.MockFlashLoanReceiver}.${BRE.network.name}`) + .value() + ).address + ); +}; + +export const getTokenDistributor = async (address?: tEthereumAddress) => { + return await getContract( + eContractid.TokenDistributor, + address || + ( + await getDb() + .get(`${eContractid.TokenDistributor}.${BRE.network.name}`) + .value() + ).address + ); +}; + const linkBytecode = (artifact: Artifact, libraries: any) => { let bytecode = artifact.bytecode; diff --git a/helpers/misc-utils.ts b/helpers/misc-utils.ts index cf3032ce..15fd61d6 100644 --- a/helpers/misc-utils.ts +++ b/helpers/misc-utils.ts @@ -27,7 +27,8 @@ export const sleep = (milliseconds: number) => { export const createRandomAddress = () => Wallet.createRandom().address; -export const evmSnapshot = () => BRE.ethereum.send("evm_snapshot", []); +export const evmSnapshot = async () => + await BRE.ethereum.send("evm_snapshot", []); export const evmRevert = async (id: string) => BRE.ethereum.send("evm_revert", [id]); diff --git a/helpers/types.ts b/helpers/types.ts index aca6c1ee..e623a95a 100644 --- a/helpers/types.ts +++ b/helpers/types.ts @@ -55,6 +55,9 @@ export enum ProtocolErrors { INVALID_REDIRECTION_ADDRESS = "Invalid redirection address", TRANSFERRED_AMOUNT_GT_ZERO = "Transferred amount needs to be greater than zero", ZERO_COLLATERAL = "The collateral balance is 0", + INCONSISTENT_PROTOCOL_BALANCE = "The actual balance of the protocol is inconsistent", + TOO_SMALL_FLASH_LOAN = "The requested amount is too small for a flashLoan.", + NOT_ENOUGH_LIQUIDITY_TO_BORROW = "There is not enough liquidity available to borrow", } export type tEthereumAddress = string; diff --git a/test/__setup.spec.ts b/test/__setup.spec.ts index 9dd8c671..787c0812 100644 --- a/test/__setup.spec.ts +++ b/test/__setup.spec.ts @@ -607,7 +607,18 @@ const buildTestEnv = async (deployer: Signer, secondaryWallet: Signer) => { await addressesProvider.setTokenDistributor(tokenDistributorProxy.address) ); - await deployMockFlashLoanReceiver(addressesProvider.address); + await insertContractAddressInDb( + eContractid.TokenDistributor, + tokenDistributorProxy.address + ); + + const mockFlashLoanReceiver = await deployMockFlashLoanReceiver( + addressesProvider.address + ); + await insertContractAddressInDb( + eContractid.MockFlashLoanReceiver, + mockFlashLoanReceiver.address + ); await deployWalletBalancerProvider(addressesProvider.address); @@ -626,7 +637,7 @@ const buildTestEnv = async (deployer: Signer, secondaryWallet: Signer) => { before(async () => { await rawBRE.run("set-bre"); const [deployer, secondaryWallet] = await getEthersSigners(); - console.log("-> Deploying test environment...") + console.log("-> Deploying test environment..."); await buildTestEnv(deployer, secondaryWallet); console.log("\n***************"); console.log("Setup and snapshot finished"); diff --git a/test/core.spec.ts b/test/core.spec.ts deleted file mode 100644 index 48ed0ace..00000000 --- a/test/core.spec.ts +++ /dev/null @@ -1,111 +0,0 @@ -// import { ITestEnv, ContractsInstancesOrigin } from "../utils/types"; -// import { LendingPoolCoreInstance, LendingPoolAddressesProviderInstance } from "../utils/typechain-types/truffle-contracts"; -// import { testEnvProvider } from "../utils/truffle/dlp-tests-env"; -// import { RAY, WAD, ETHEREUM_ADDRESS } from "../utils/constants"; -// import BigNumber from "bignumber.js"; - -// /*contract("LendingPoolCore", async ([deployer, ...users]) => { -// let _testEnvProvider: ITestEnv -// let _addressesProviderInstance: LendingPoolAddressesProviderInstance -// let _lendingPoolCoreInstance: LendingPoolCoreInstance; -// let _lendAddress: string; - -// before("Initializing LendingPoolCore test variables", async () => { -// _testEnvProvider = await testEnvProvider(artifacts, [deployer, ...users], ContractsInstancesOrigin.TruffleArtifacts) - -// const { -// deployedInstances: { -// lendingPoolAddressesProviderInstance, -// lendingPoolCoreInstance, -// }, -// getAllAssetsAddresses -// } = _testEnvProvider -// _addressesProviderInstance = lendingPoolAddressesProviderInstance -// _lendingPoolCoreInstance = lendingPoolCoreInstance -// _lendAddress = (await getAllAssetsAddresses()).LEND -// }) - -// it("Configure the lending pool address to the owner address to allow invocation of the methods", async () => { -// await _addressesProviderInstance.setLendingPoolConfiguratorImpl(deployer) -// await _addressesProviderInstance.setLendingPoolImpl(deployer) -// await _lendingPoolCoreInstance.refreshConfiguration() -// const providerAddress = await _addressesProviderInstance.getLendingPoolConfigurator() -// expect(providerAddress).to.be.equal(deployer) -// const poolAddress = await _addressesProviderInstance.getLendingPool() -// expect(poolAddress).to.be.equal(deployer) -// }) - -// it("Increases the stable total borrows of a reserve", async () => { -// await _lendingPoolCoreInstance.increaseReserveTotalBorrowsStableAndUpdateAverageRate( -// ETHEREUM_ADDRESS, -// WAD, -// new BigNumber(RAY).multipliedBy(10).toFixed(), -// ) //10% interest - -// const totalBorrows = await _lendingPoolCoreInstance.getReserveTotalBorrowsStable(ETHEREUM_ADDRESS) - -// expect(totalBorrows.toString()).to.be.equal(WAD) -// }) - -// it("Increases the variable total borrows of a reserve", async () => { -// await _lendingPoolCoreInstance.increaseReserveTotalBorrowsVariable(ETHEREUM_ADDRESS, WAD) //10% interest - -// const totalBorrows = await _lendingPoolCoreInstance.getReserveTotalBorrowsVariable(ETHEREUM_ADDRESS) - -// expect(totalBorrows.toString()).to.be.equal(WAD) -// }) - -// it("Decreases the stable total borrows of a reserve", async () => { -// await _lendingPoolCoreInstance.decreaseReserveTotalBorrowsStableAndUpdateAverageRate( -// ETHEREUM_ADDRESS, -// WAD, -// new BigNumber(RAY).multipliedBy(10).toFixed(), -// ) - -// const totalBorrows = await _lendingPoolCoreInstance.getReserveTotalBorrowsStable(ETHEREUM_ADDRESS) - -// expect(totalBorrows.toString()).to.be.equal("0") -// }) - -// it("Decreases the variable total borrows of a reserve", async () => { -// await _lendingPoolCoreInstance.decreaseReserveTotalBorrowsVariable(ETHEREUM_ADDRESS, WAD) - -// const totalBorrows = await _lendingPoolCoreInstance.getReserveTotalBorrowsVariable(ETHEREUM_ADDRESS) - -// expect(totalBorrows.toString()).to.be.equal("0") -// }) - -// it("Updates the variable borrow index, checks that is equal to 1 as there are no borrows from the user", async () => { -// await _lendingPoolCoreInstance.updateUserLastVariableBorrowCumulativeIndex(_lendAddress, deployer) -// await _lendingPoolCoreInstance.updateUserLastVariableBorrowCumulativeIndex(ETHEREUM_ADDRESS, deployer) - -// const indexLEND = await _lendingPoolCoreInstance.getUserVariableBorrowCumulativeIndex( -// _lendAddress, -// deployer, -// ) -// const indexETH = await _lendingPoolCoreInstance.getUserVariableBorrowCumulativeIndex(ETHEREUM_ADDRESS, deployer) - -// expect(indexLEND.toString()).to.be.equal(RAY, "Invalid user borrow index for LEND") -// expect(indexETH.toString()).to.be.equal(RAY, "Invalid user borrow index for ETH") -// }) - -// it("Disables the LEND collateral", async () => { -// await _lendingPoolCoreInstance.disableReserveAsCollateral(_lendAddress) - -// const collateralEnabled = await _lendingPoolCoreInstance.isReserveUsageAsCollateralEnabled( -// _lendAddress, -// ) - -// expect(collateralEnabled).to.be.equal(false) -// }) - -// it("Deactivates the ETH reserve", async () => { -// await _lendingPoolCoreInstance.disableBorrowingOnReserve(ETHEREUM_ADDRESS) - -// const isEnabled = await _lendingPoolCoreInstance.isReserveBorrowingEnabled(ETHEREUM_ADDRESS) - -// expect(isEnabled).to.be.equal(false) -// }) - -// }) -// */ \ No newline at end of file diff --git a/test/flashloan.spec.ts b/test/flashloan.spec.ts index b0f3ecb3..0a67de31 100644 --- a/test/flashloan.spec.ts +++ b/test/flashloan.spec.ts @@ -1,278 +1,256 @@ -// import { -// LendingPoolInstance, -// LendingPoolCoreInstance, -// IPriceOracleInstance, -// MockFlashLoanReceiverInstance, -// TokenDistributorInstance, -// MintableERC20Instance, -// ATokenInstance, -// } from '../utils/typechain-types/truffle-contracts'; -// import {iATokenBase, iAssetsWithoutETH, ITestEnvWithoutInstances} from '../utils/types'; -// import BigNumber from 'bignumber.js'; -// import { -// APPROVAL_AMOUNT_LENDING_POOL_CORE, -// oneEther, -// oneRay, -// ETHEREUM_ADDRESS, -// } from '../utils/constants'; -// import {testEnvProviderWithoutInstances} from '../utils/truffle/dlp-tests-env'; -// import {convertToCurrencyDecimals} from '../utils/misc-utils'; +import {TestEnv, makeSuite} from "./helpers/make-suite"; +import { + MOCK_ETH_ADDRESS, + APPROVAL_AMOUNT_LENDING_POOL_CORE, + oneRay, +} from "../helpers/constants"; +import { + convertToCurrencyDecimals, + getMockFlashLoanReceiver, + getTokenDistributor, +} from "../helpers/contracts-helpers"; +import {ethers} from "ethers"; +import {MockFlashLoanReceiver} from "../types/MockFlashLoanReceiver"; +import {TokenDistributor} from "../types/TokenDistributor"; +import {BRE} from "../helpers/misc-utils"; +import {ProtocolErrors} from "../helpers/types"; +import BigNumber from "bignumber.js"; -// const expectRevert = require('@openzeppelin/test-helpers').expectRevert; +const {expect} = require("chai"); -// const {expect} = require('chai'); +makeSuite("LendingPool FlashLoan function", (testEnv: TestEnv) => { + let _mockFlashLoanReceiver = {} as MockFlashLoanReceiver; + let _tokenDistributor = {} as TokenDistributor; + const { + INCONSISTENT_PROTOCOL_BALANCE, + TOO_SMALL_FLASH_LOAN, + NOT_ENOUGH_LIQUIDITY_TO_BORROW, + } = ProtocolErrors; -// contract('LendingPool FlashLoan function', async ([deployer, ...users]) => { -// let _testEnvProvider: ITestEnvWithoutInstances; -// let _lendingPoolInstance: LendingPoolInstance; -// let _lendingPoolCoreInstance: LendingPoolCoreInstance; -// let _mockFlashLoanReceiverInstance: MockFlashLoanReceiverInstance; -// let _priceOracleInstance: IPriceOracleInstance; -// let _aTokenInstances: iATokenBase; -// let _tokenInstances: iAssetsWithoutETH; -// let _tokenDistributor: TokenDistributorInstance; -// let _daiAddress: string; -// let _depositorAddress: string; -// let _web3: Web3; -// let _initialDepositorETHBalance: string; + before(async () => { + _mockFlashLoanReceiver = await getMockFlashLoanReceiver(); + _tokenDistributor = await getTokenDistributor(); + }); -// before('Initializing LendingPool test variables', async () => { -// console.time('setup-test'); -// _testEnvProvider = await testEnvProviderWithoutInstances(artifacts, [deployer, ...users]); + it("Deposits ETH into the reserve", async () => { + const {pool} = testEnv; + const amountToDeposit = ethers.utils.parseEther("1"); -// const { -// getWeb3, -// getAllAssetsInstances, -// getFirstDepositorAddressOnTests, -// getLendingPoolInstance, -// getLendingPoolCoreInstance, -// getPriceOracleInstance, -// getATokenInstances, -// getMockFlashLoanReceiverInstance, -// getTokenDistributorInstance, -// } = _testEnvProvider; + await pool.deposit(MOCK_ETH_ADDRESS, amountToDeposit, "0", { + value: amountToDeposit, + }); + }); -// const instances = await Promise.all([ -// getLendingPoolInstance(), -// getLendingPoolCoreInstance(), -// getPriceOracleInstance(), -// getATokenInstances(), -// getMockFlashLoanReceiverInstance(), -// getAllAssetsInstances(), -// getTokenDistributorInstance(), -// ]); + it("Takes ETH flashloan, returns the funds correctly", async () => { + const {pool, deployer} = testEnv; -// _lendingPoolInstance = instances[0]; -// _lendingPoolCoreInstance = instances[1]; -// _priceOracleInstance = instances[2]; -// _aTokenInstances = instances[3]; -// _mockFlashLoanReceiverInstance = instances[4]; -// _tokenInstances = instances[5]; -// _daiAddress = _tokenInstances.DAI.address; -// _depositorAddress = await getFirstDepositorAddressOnTests(); -// _tokenDistributor = instances[6]; + // move funds to the MockFlashLoanReceiver contract to pay the fee + await deployer.signer.sendTransaction({ + value: ethers.utils.parseEther("0.5"), + to: _mockFlashLoanReceiver.address, + }); -// _web3 = await getWeb3(); -// _initialDepositorETHBalance = await _web3.eth.getBalance(_depositorAddress); + await pool.flashLoan( + _mockFlashLoanReceiver.address, + MOCK_ETH_ADDRESS, + ethers.utils.parseEther("0.8"), + "0x10" + ); -// console.timeEnd('setup-test'); -// }); + ethers.utils.parseUnits("10000"); -// it('Deposits ETH into the reserve', async () => { -// const amountToDeposit = await convertToCurrencyDecimals(ETHEREUM_ADDRESS, '1'); + const reserveData: any = await pool.getReserveData(MOCK_ETH_ADDRESS); + const tokenDistributorBalance = await BRE.ethers.provider.getBalance( + _tokenDistributor.address + ); -// await _lendingPoolInstance.deposit(ETHEREUM_ADDRESS, amountToDeposit, '0', { -// from: _depositorAddress, -// value: amountToDeposit, -// }); -// }); + const currentLiquidityRate = reserveData.liquidityRate; + const currentLiquidityIndex = reserveData.liquidityIndex; -// it('Takes ETH flashloan, returns the funds correctly', async () => { -// //move funds to the MockFlashLoanReceiver contract + expect(reserveData.totalLiquidity).to.be.bignumber.equal( + "1000504000000000000" + ); + expect(currentLiquidityRate).to.be.bignumber.equal("0"); + expect(currentLiquidityIndex).to.be.bignumber.equal( + "1000504000000000000000000000" + ); + expect(tokenDistributorBalance).to.be.bignumber.equal("216000000000000"); + }); -// let send = web3.eth.sendTransaction({ -// from: deployer, -// to: _mockFlashLoanReceiverInstance.address, -// value: web3.utils.toWei('0.5', 'ether'), -// }); + it("Takes an ETH flashloan as big as the available liquidity", async () => { + const {pool, deployer} = testEnv; -// const txResult = await _lendingPoolInstance.flashLoan( -// _mockFlashLoanReceiverInstance.address, -// ETHEREUM_ADDRESS, -// new BigNumber(0.8).multipliedBy(oneEther), -// '0x10' -// ); + // move funds to the MockFlashLoanReceiver contract to pay the fee + await deployer.signer.sendTransaction({ + value: ethers.utils.parseEther("0.5"), + to: _mockFlashLoanReceiver.address, + }); -// const reserveData: any = await _lendingPoolInstance.getReserveData(ETHEREUM_ADDRESS); -// const tokenDistributorBalance = await _web3.eth.getBalance(_tokenDistributor.address); + const txResult = await pool.flashLoan( + _mockFlashLoanReceiver.address, + MOCK_ETH_ADDRESS, + "1000504000000000000", + "0x10" + ); -// const currentLiquidityRate = reserveData.liquidityRate; -// const currentLiquidityIndex = reserveData.liquidityIndex; + const reserveData: any = await pool.getReserveData(MOCK_ETH_ADDRESS); + const tokenDistributorBalance = await BRE.ethers.provider.getBalance( + _tokenDistributor.address + ); -// expect(reserveData.totalLiquidity.toString()).to.be.equal('1000504000000000000'); -// expect(currentLiquidityRate.toString()).to.be.equal('0'); -// expect(currentLiquidityIndex.toString()).to.be.equal('1000504000000000000000000000'); -// expect(tokenDistributorBalance.toString()).to.be.equal('216000000000000'); -// }); + const currentLiqudityRate = reserveData.liquidityRate; + const currentLiquidityIndex = reserveData.liquidityIndex; -// it('Takes an ETH flashloan as big as the available liquidity', async () => { -// //move funds to the MockFlashLoanReceiver contract + expect(reserveData.totalLiquidity).to.be.bignumber.equal( + "1001134317520000000" + ); + expect(currentLiqudityRate).to.be.bignumber.equal("0"); + expect(currentLiquidityIndex).to.be.bignumber.equal( + "1001134317520000000000000000" + ); + expect(tokenDistributorBalance).to.be.bignumber.equal("486136080000000"); + }); -// let send = web3.eth.sendTransaction({ -// from: deployer, -// to: _mockFlashLoanReceiverInstance.address, -// value: web3.utils.toWei('0.5', 'ether'), -// }); + it("Takes ETH flashloan, does not return the funds (revert expected)", async () => { + const {pool, deployer} = testEnv; -// const txResult = await _lendingPoolInstance.flashLoan( -// _mockFlashLoanReceiverInstance.address, -// ETHEREUM_ADDRESS, -// '1000504000000000000', -// '0x10' -// ); + // move funds to the MockFlashLoanReceiver contract to pay the fee + await deployer.signer.sendTransaction({ + value: ethers.utils.parseEther("0.5"), + to: _mockFlashLoanReceiver.address, + }); -// const reserveData: any = await _lendingPoolInstance.getReserveData(ETHEREUM_ADDRESS); -// const tokenDistributorBalance = await _web3.eth.getBalance(_tokenDistributor.address); + await _mockFlashLoanReceiver.setFailExecutionTransfer(true); -// const currentLiqudityRate = reserveData.liquidityRate; -// const currentLiquidityIndex = reserveData.liquidityIndex; + await expect( + pool.flashLoan( + _mockFlashLoanReceiver.address, + MOCK_ETH_ADDRESS, + ethers.utils.parseEther("0.8"), + "0x10" + ), + INCONSISTENT_PROTOCOL_BALANCE + ).to.be.revertedWith(INCONSISTENT_PROTOCOL_BALANCE); + }); -// expect(reserveData.totalLiquidity.toString()).to.be.equal('1001134317520000000'); -// expect(currentLiqudityRate.toString()).to.be.equal('0'); -// expect(currentLiquidityIndex.toString()).to.be.equal('1001134317520000000000000000'); -// expect(tokenDistributorBalance.toString()).to.be.equal('486136080000000'); -// }); + it("tries to take a very small flashloan, which would result in 0 fees (revert expected)", async () => { + const {pool} = testEnv; -// it('Takes ETH flashloan, does not return the funds (revert expected)', async () => { -// //move funds to the MockFlashLoanReceiver contract + await expect( + pool.flashLoan( + _mockFlashLoanReceiver.address, + MOCK_ETH_ADDRESS, + "1", //1 wei loan + "0x10" + ), + TOO_SMALL_FLASH_LOAN + ).to.be.revertedWith(TOO_SMALL_FLASH_LOAN); + }); -// let send = web3.eth.sendTransaction({ -// from: deployer, -// to: _mockFlashLoanReceiverInstance.address, -// value: web3.utils.toWei('0.5', 'ether'), -// }); + it("tries to take a flashloan that is bigger than the available liquidity (revert expected)", async () => { + const {pool} = testEnv; -// await _mockFlashLoanReceiverInstance.setFailExecutionTransfer(true); + await expect( + pool.flashLoan( + _mockFlashLoanReceiver.address, + MOCK_ETH_ADDRESS, + "1004415000000000000", //slightly higher than the available liquidity + "0x10" + ), + NOT_ENOUGH_LIQUIDITY_TO_BORROW + ).to.be.revertedWith(NOT_ENOUGH_LIQUIDITY_TO_BORROW); + }); -// await expectRevert( -// _lendingPoolInstance.flashLoan( -// _mockFlashLoanReceiverInstance.address, -// ETHEREUM_ADDRESS, -// new BigNumber(0.8).multipliedBy(oneEther), -// '0x10' -// ), -// 'The actual balance of the protocol is inconsistent' -// ); -// }); + it("tries to take a flashloan using a non contract address as receiver (revert expected)", async () => { + const {pool, deployer} = testEnv; -// it('tries to take a very small flashloan, which would result in 0 fees (revert expected)', async () => { -// //move funds to the MockFlashLoanReceiver contract + await expect( + pool.flashLoan( + deployer.address, + MOCK_ETH_ADDRESS, + "1000000000000000000", + "0x10" + ) + ).to.be.reverted; + }); -// await expectRevert( -// _lendingPoolInstance.flashLoan( -// _mockFlashLoanReceiverInstance.address, -// ETHEREUM_ADDRESS, -// '1', //1 wei loan -// '0x10' -// ), -// 'The requested amount is too small for a flashLoan.' -// ); -// }); + it("Deposits DAI into the reserve", async () => { + const {dai, core, pool} = testEnv; -// it('tries to take a flashloan that is bigger than the available liquidity (revert expected)', async () => { -// //move funds to the MockFlashLoanReceiver contract + await dai.mint(await convertToCurrencyDecimals(dai.address, "1000")); -// await expectRevert( -// _lendingPoolInstance.flashLoan( -// _mockFlashLoanReceiverInstance.address, -// ETHEREUM_ADDRESS, -// '1004415000000000000', //slightly higher than the available liquidity -// '0x10' -// ), -// 'There is not enough liquidity available to borrow' -// ); -// }); + await dai.approve(core.address, APPROVAL_AMOUNT_LENDING_POOL_CORE); -// it('tries to take a flashloan using a non contract address as receiver (revert expected)', async () => { -// //move funds to the MockFlashLoanReceiver contract + const amountToDeposit = await convertToCurrencyDecimals( + dai.address, + "1000" + ); -// await expectRevert( -// _lendingPoolInstance.flashLoan(deployer, ETHEREUM_ADDRESS, '1000000000000000000', '0x10'), -// 'revert' -// ); -// }); + await pool.deposit(dai.address, amountToDeposit, "0"); + }); -// it('Deposits DAI into the reserve', async () => { -// const {DAI: daiInstance} = _tokenInstances; + it("Takes out a 500 DAI flashloan, returns the funds correctly", async () => { + const {dai, pool, deployer: depositor} = testEnv; -// //mints DAI to depositor -// await daiInstance.mint(await convertToCurrencyDecimals(daiInstance.address, '1000'), { -// from: _depositorAddress, -// }); + await _mockFlashLoanReceiver.setFailExecutionTransfer(false); -// //approve protocol to access depositor wallet -// await daiInstance.approve(_lendingPoolCoreInstance.address, APPROVAL_AMOUNT_LENDING_POOL_CORE, { -// from: _depositorAddress, -// }); + await pool.flashLoan( + _mockFlashLoanReceiver.address, + dai.address, + ethers.utils.parseEther("500"), + "0x10" + ); -// const amountToDeposit = await convertToCurrencyDecimals(_daiAddress, '1000'); + const reserveData = await pool.getReserveData(dai.address); + const userData = await pool.getUserReserveData( + dai.address, + depositor.address + ); -// await _lendingPoolInstance.deposit(daiInstance.address, amountToDeposit, '0', { -// from: _depositorAddress, -// }); -// }); + const totalLiquidity = reserveData.totalLiquidity.toString(); + const currentLiqudityRate = reserveData.liquidityRate.toString(); + const currentLiquidityIndex = reserveData.liquidityIndex.toString(); + const currentUserBalance = userData.currentATokenBalance.toString(); -// it('Takes out a 500 DAI flashloan, returns the funds correctly', async () => { -// const {DAI: daiInstance} = _tokenInstances; + const expectedLiquidity = ethers.utils.parseEther("1000.315"); -// await _mockFlashLoanReceiverInstance.setFailExecutionTransfer(false); + const tokenDistributorBalance = await dai.balanceOf( + _tokenDistributor.address + ); -// await _lendingPoolInstance.flashLoan( -// _mockFlashLoanReceiverInstance.address, -// _daiAddress, -// new BigNumber(500).multipliedBy(oneEther), -// '0x10' -// ); + expect(totalLiquidity).to.be.equal( + expectedLiquidity, + "Invalid total liquidity" + ); + expect(currentLiqudityRate).to.be.equal("0", "Invalid liquidity rate"); + expect(currentLiquidityIndex).to.be.equal( + new BigNumber("1.000315").multipliedBy(oneRay).toFixed(), + "Invalid liquidity index" + ); + expect(currentUserBalance.toString()).to.be.equal( + expectedLiquidity, + "Invalid user balance" + ); -// const reserveData: any = await _lendingPoolInstance.getReserveData(_daiAddress); -// const userData: any = await _lendingPoolInstance.getUserReserveData(_daiAddress, deployer); + expect(tokenDistributorBalance.toString()).to.be.equal( + ethers.utils.parseEther("0.135"), + "Invalid token distributor balance" + ); + }); -// const totalLiquidity = reserveData.totalLiquidity.toString(); -// const currentLiqudityRate = reserveData.liquidityRate.toString(); -// const currentLiquidityIndex = reserveData.liquidityIndex.toString(); -// const currentUserBalance = userData.currentATokenBalance.toString(); + it("Takes out a 500 DAI flashloan, does not return the funds (revert expected)", async () => { + const {dai, pool} = testEnv; -// const expectedLiquidity = new BigNumber('1000.315').multipliedBy(oneEther).toFixed(); + await _mockFlashLoanReceiver.setFailExecutionTransfer(true); -// const tokenDistributorBalance = await daiInstance.balanceOf(_tokenDistributor.address); - -// expect(totalLiquidity).to.be.equal(expectedLiquidity, 'Invalid total liquidity'); -// expect(currentLiqudityRate).to.be.equal('0', 'Invalid liquidity rate'); -// expect(currentLiquidityIndex).to.be.equal( -// new BigNumber('1.000315').multipliedBy(oneRay).toFixed(), -// 'Invalid liquidity index' -// ); -// expect(currentUserBalance.toString()).to.be.equal(expectedLiquidity, 'Invalid user balance'); - -// expect(tokenDistributorBalance.toString()).to.be.equal( -// new BigNumber('0.135').multipliedBy(oneEther).toFixed(), -// 'Invalid token distributor balance' -// ); -// }); - -// it('Takes out a 500 DAI flashloan, does not return the funds (revert expected)', async () => { -// //move funds to the MockFlashLoanReceiver contract - -// await _mockFlashLoanReceiverInstance.setFailExecutionTransfer(true); - -// await expectRevert( -// _lendingPoolInstance.flashLoan( -// _mockFlashLoanReceiverInstance.address, -// _daiAddress, -// new BigNumber(500).multipliedBy(oneEther), -// '0x10' -// ), -// 'The actual balance of the protocol is inconsistent' -// ); -// }); -// }); + await expect( + pool.flashLoan( + _mockFlashLoanReceiver.address, + dai.address, + ethers.utils.parseEther("500"), + "0x10" + ), + INCONSISTENT_PROTOCOL_BALANCE + ).to.be.revertedWith(INCONSISTENT_PROTOCOL_BALANCE); + }); +}); diff --git a/test/helpers/make-suite.ts b/test/helpers/make-suite.ts index 5680ef46..89a9e8f8 100644 --- a/test/helpers/make-suite.ts +++ b/test/helpers/make-suite.ts @@ -1,4 +1,4 @@ -import {evmRevert, evmSnapshot} from "../../helpers/misc-utils"; +import {evmRevert, evmSnapshot, BRE} from "../../helpers/misc-utils"; import {TEST_SNAPSHOT_ID} from "../../helpers/constants"; import {Signer} from "ethers"; import { @@ -41,6 +41,13 @@ export interface TestEnv { aDai: AToken; } +let buidlerevmSnapshotId: string = "0x1"; +const setBuidlerevmSnapshotId = (id: string) => { + if (BRE.network.name === "buidlerevm") { + buidlerevmSnapshotId = id; + } +}; + export function makeSuite(name: string, tests: (testEnv: TestEnv) => void) { describe(name, () => { const testEnv: TestEnv = { @@ -56,7 +63,7 @@ export function makeSuite(name: string, tests: (testEnv: TestEnv) => void) { } as TestEnv; before(async () => { console.time("makeSuite"); - await evmSnapshot(); + setBuidlerevmSnapshotId(await evmSnapshot()); const [_deployer, ...restSigners] = await getEthersSigners(); const deployer: SignerWithAddress = { address: await _deployer.getAddress(), @@ -97,7 +104,7 @@ export function makeSuite(name: string, tests: (testEnv: TestEnv) => void) { }); tests(testEnv); after(async () => { - await evmRevert(TEST_SNAPSHOT_ID); + await evmRevert(buidlerevmSnapshotId); }); }); }