diff --git a/contracts/arbitrum/connectors/aave/v3/events.sol b/contracts/arbitrum/connectors/aave/v3/events.sol new file mode 100644 index 00000000..9f60f22b --- /dev/null +++ b/contracts/arbitrum/connectors/aave/v3/events.sol @@ -0,0 +1,33 @@ +pragma solidity ^0.7.0; + +contract Events { + event LogDeposit( + address indexed token, + uint256 tokenAmt, + uint256 getId, + uint256 setId + ); + event LogWithdraw( + address indexed token, + uint256 tokenAmt, + uint256 getId, + uint256 setId + ); + event LogBorrow( + address indexed token, + uint256 tokenAmt, + uint256 indexed rateMode, + uint256 getId, + uint256 setId + ); + event LogPayback( + address indexed token, + uint256 tokenAmt, + uint256 indexed rateMode, + uint256 getId, + uint256 setId + ); + event LogEnableCollateral(address[] tokens); + event LogSwapRateMode(address indexed token, uint256 rateMode); + event LogSetUserEMode(uint8 categoryId); +} diff --git a/contracts/arbitrum/connectors/aave/v3/helpers.sol b/contracts/arbitrum/connectors/aave/v3/helpers.sol new file mode 100644 index 00000000..1fff06e8 --- /dev/null +++ b/contracts/arbitrum/connectors/aave/v3/helpers.sol @@ -0,0 +1,66 @@ +pragma solidity ^0.7.0; + +import { DSMath } from "../../../common/math.sol"; +import { Basic } from "../../../common/basic.sol"; +import { AavePoolProviderInterface, AaveDataProviderInterface } from "./interface.sol"; + +abstract contract Helpers is DSMath, Basic { + /** + * @dev Aave Pool Provider + */ + AavePoolProviderInterface internal constant aaveProvider = + AavePoolProviderInterface(0xa97684ead0e402dC232d5A977953DF7ECBaB3CDb); // Arbitrum address - PoolAddressesProvider + + /** + * @dev Aave Pool Data Provider + */ + AaveDataProviderInterface internal constant aaveData = + AaveDataProviderInterface(0x69FA688f1Dc47d4B5d8029D5a35FB7a548310654); //Arbitrum address - PoolDataProvider + + /** + * @dev Aave Referral Code + */ + uint16 internal constant referralCode = 3228; + + /** + * @dev Checks if collateral is enabled for an asset + * @param token token address of the asset.(For ETH: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) + */ + + function getIsColl(address token) internal view returns (bool isCol) { + (, , , , , , , , isCol) = aaveData.getUserReserveData( + token, + address(this) + ); + } + + /** + * @dev Get total debt balance & fee for an asset + * @param token token address of the debt.(For ETH: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) + * @param rateMode Borrow rate mode (Stable = 1, Variable = 2) + */ + function getPaybackBalance(address token, uint256 rateMode) + internal + view + returns (uint256) + { + (, uint256 stableDebt, uint256 variableDebt, , , , , , ) = aaveData + .getUserReserveData(token, address(this)); + return rateMode == 1 ? stableDebt : variableDebt; + } + + /** + * @dev Get total collateral balance for an asset + * @param token token address of the collateral.(For ETH: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) + */ + function getCollateralBalance(address token) + internal + view + returns (uint256 bal) + { + (bal, , , , , , , , ) = aaveData.getUserReserveData( + token, + address(this) + ); + } +} diff --git a/contracts/arbitrum/connectors/aave/v3/interface.sol b/contracts/arbitrum/connectors/aave/v3/interface.sol new file mode 100644 index 00000000..8ae14716 --- /dev/null +++ b/contracts/arbitrum/connectors/aave/v3/interface.sol @@ -0,0 +1,91 @@ +pragma solidity ^0.7.0; + +interface AaveInterface { + function supply( + address asset, + uint256 amount, + address onBehalfOf, + uint16 referralCode + ) external; + + function withdraw( + address asset, + uint256 amount, + address to + ) external returns (uint256); + + function borrow( + address asset, + uint256 amount, + uint256 interestRateMode, + uint16 referralCode, + address onBehalfOf + ) external; + + function repay( + address asset, + uint256 amount, + uint256 interestRateMode, + address onBehalfOf + ) external returns (uint256); + + function repayWithATokens( + address asset, + uint256 amount, + uint256 interestRateMode + ) external returns (uint256); + + function setUserUseReserveAsCollateral(address asset, bool useAsCollateral) + external; + + function swapBorrowRateMode(address asset, uint256 interestRateMode) + external; + + function setUserEMode(uint8 categoryId) external; +} + +interface AavePoolProviderInterface { + function getPool() external view returns (address); +} + +interface AaveDataProviderInterface { + function getReserveTokensAddresses(address _asset) + external + view + returns ( + address aTokenAddress, + address stableDebtTokenAddress, + address variableDebtTokenAddress + ); + + function getUserReserveData(address _asset, address _user) + external + view + returns ( + uint256 currentATokenBalance, + uint256 currentStableDebt, + uint256 currentVariableDebt, + uint256 principalStableDebt, + uint256 scaledVariableDebt, + uint256 stableBorrowRate, + uint256 liquidityRate, + uint40 stableRateLastUpdated, + bool usageAsCollateralEnabled + ); + + function getReserveEModeCategory(address asset) + external + view + returns (uint256); +} + +interface AaveAddressProviderRegistryInterface { + function getAddressesProvidersList() + external + view + returns (address[] memory); +} + +interface ATokenInterface { + function balanceOf(address _user) external view returns (uint256); +} diff --git a/contracts/arbitrum/connectors/aave/v3/main.sol b/contracts/arbitrum/connectors/aave/v3/main.sol new file mode 100644 index 00000000..1004d0ec --- /dev/null +++ b/contracts/arbitrum/connectors/aave/v3/main.sol @@ -0,0 +1,296 @@ +pragma solidity ^0.7.0; + +/** + * @title Aave v3. + * @dev Lending & Borrowing. + */ + +import { TokenInterface } from "../../../common/interfaces.sol"; +import { Stores } from "../../../common/stores.sol"; +import { Helpers } from "./helpers.sol"; +import { Events } from "./events.sol"; +import { AaveInterface } from "./interface.sol"; + +abstract contract AaveResolver is Events, Helpers { + /** + * @dev Deposit ETH/ERC20_Token. + * @notice Deposit a token to Aave v2 for lending / collaterization. + * @param token The address of the token to deposit.(For ETH: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) + * @param amt The amount of the token to deposit. (For max: `uint256(-1)`) + * @param getId ID to retrieve amt. + * @param setId ID stores the amount of tokens deposited. + */ + function deposit( + address token, + uint256 amt, + uint256 getId, + uint256 setId + ) + external + payable + returns (string memory _eventName, bytes memory _eventParam) + { + uint256 _amt = getUint(getId, amt); + + AaveInterface aave = AaveInterface(aaveProvider.getPool()); + + bool isEth = token == ethAddr; + address _token = isEth ? wethAddr : token; + + TokenInterface tokenContract = TokenInterface(_token); + + if (isEth) { + _amt = _amt == uint256(-1) ? address(this).balance : _amt; + convertEthToWeth(isEth, tokenContract, _amt); + } else { + _amt = _amt == uint256(-1) + ? tokenContract.balanceOf(address(this)) + : _amt; + } + + approve(tokenContract, address(aave), _amt); + + aave.supply(_token, _amt, address(this), referralCode); + + if (!getIsColl(_token)) { + aave.setUserUseReserveAsCollateral(_token, true); + } + + setUint(setId, _amt); + + _eventName = "LogDeposit(address,uint256,uint256,uint256)"; + _eventParam = abi.encode(token, _amt, getId, setId); + } + + /** + * @dev Withdraw ETH/ERC20_Token. + * @notice Withdraw deposited token from Aave v2 + * @param token The address of the token to withdraw.(For ETH: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) + * @param amt The amount of the token to withdraw. (For max: `uint256(-1)`) + * @param getId ID to retrieve amt. + * @param setId ID stores the amount of tokens withdrawn. + */ + function withdraw( + address token, + uint256 amt, + uint256 getId, + uint256 setId + ) + external + payable + returns (string memory _eventName, bytes memory _eventParam) + { + uint256 _amt = getUint(getId, amt); + + AaveInterface aave = AaveInterface(aaveProvider.getPool()); + bool isEth = token == ethAddr; + address _token = isEth ? wethAddr : token; + + TokenInterface tokenContract = TokenInterface(_token); + + uint256 initialBal = tokenContract.balanceOf(address(this)); + aave.withdraw(_token, _amt, address(this)); + uint256 finalBal = tokenContract.balanceOf(address(this)); + + _amt = sub(finalBal, initialBal); + + convertWethToEth(isEth, tokenContract, _amt); + + setUint(setId, _amt); + + _eventName = "LogWithdraw(address,uint256,uint256,uint256)"; + _eventParam = abi.encode(token, _amt, getId, setId); + } + + /** + * @dev Borrow ETH/ERC20_Token. + * @notice Borrow a token using Aave v2 + * @param token The address of the token to borrow.(For ETH: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) + * @param amt The amount of the token to borrow. + * @param rateMode The type of borrow debt. (For Stable: 1, Variable: 2) + * @param getId ID to retrieve amt. + * @param setId ID stores the amount of tokens borrowed. + */ + function borrow( + address token, + uint256 amt, + uint256 rateMode, + uint256 getId, + uint256 setId + ) + external + payable + returns (string memory _eventName, bytes memory _eventParam) + { + uint256 _amt = getUint(getId, amt); + + AaveInterface aave = AaveInterface(aaveProvider.getPool()); + + bool isEth = token == ethAddr; + address _token = isEth ? wethAddr : token; + + aave.borrow(_token, _amt, rateMode, referralCode, address(this)); + convertWethToEth(isEth, TokenInterface(_token), _amt); + + setUint(setId, _amt); + + _eventName = "LogBorrow(address,uint256,uint256,uint256,uint256)"; + _eventParam = abi.encode(token, _amt, rateMode, getId, setId); + } + + /** + * @dev Payback borrowed ETH/ERC20_Token. + * @notice Payback debt owed. + * @param token The address of the token to payback.(For ETH: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) + * @param amt The amount of the token to payback. (For max: `uint256(-1)`) + * @param rateMode The type of debt paying back. (For Stable: 1, Variable: 2) + * @param getId ID to retrieve amt. + * @param setId ID stores the amount of tokens paid back. + */ + function payback( + address token, + uint256 amt, + uint256 rateMode, + uint256 getId, + uint256 setId + ) + external + payable + returns (string memory _eventName, bytes memory _eventParam) + { + uint256 _amt = getUint(getId, amt); + + AaveInterface aave = AaveInterface(aaveProvider.getPool()); + + bool isEth = token == ethAddr; + address _token = isEth ? wethAddr : token; + + TokenInterface tokenContract = TokenInterface(_token); + + _amt = _amt == uint256(-1) ? getPaybackBalance(_token, rateMode) : _amt; + + if (isEth) convertEthToWeth(isEth, tokenContract, _amt); + + approve(tokenContract, address(aave), _amt); + + aave.repay(_token, _amt, rateMode, address(this)); + + setUint(setId, _amt); + + _eventName = "LogPayback(address,uint256,uint256,uint256,uint256)"; + _eventParam = abi.encode(token, _amt, rateMode, getId, setId); + } + + /** + * @dev Payback borrowed ETH/ERC20_Token using aTokens. + * @notice Repays a borrowed `amount` on a specific reserve using the reserve aTokens, burning the equivalent debt tokens. + * @param token The address of the token to payback.(For ETH: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) + * @param amt The amount of the token to payback. (For max: `uint256(-1)`) + * @param rateMode The type of debt paying back. (For Stable: 1, Variable: 2) + * @param getId ID to retrieve amt. + * @param setId ID stores the amount of tokens paid back. + */ + function paybackWithATokens( + address token, + uint256 amt, + uint256 rateMode, + uint256 getId, + uint256 setId + ) + external + payable + returns (string memory _eventName, bytes memory _eventParam) + { + uint256 _amt = getUint(getId, amt); + + AaveInterface aave = AaveInterface(aaveProvider.getPool()); + + bool isEth = token == ethAddr; + address _token = isEth ? wethAddr : token; + + TokenInterface tokenContract = TokenInterface(_token); + + _amt = _amt == uint256(-1) ? getPaybackBalance(_token, rateMode) : _amt; + + if (isEth) convertEthToWeth(isEth, tokenContract, _amt); + + approve(tokenContract, address(aave), _amt); + + aave.repayWithATokens(_token, _amt, rateMode); + + setUint(setId, _amt); + + _eventName = "LogPayback(address,uint256,uint256,uint256,uint256)"; + _eventParam = abi.encode(token, _amt, rateMode, getId, setId); + } + + /** + * @dev Enable collateral + * @notice Enable an array of tokens as collateral + * @param tokens Array of tokens to enable collateral + */ + function enableCollateral(address[] calldata tokens) + external + payable + returns (string memory _eventName, bytes memory _eventParam) + { + uint256 _length = tokens.length; + require(_length > 0, "0-tokens-not-allowed"); + + AaveInterface aave = AaveInterface(aaveProvider.getPool()); + + for (uint256 i = 0; i < _length; i++) { + address token = tokens[i]; + if (getCollateralBalance(token) > 0 && !getIsColl(token)) { + aave.setUserUseReserveAsCollateral(token, true); + } + } + + _eventName = "LogEnableCollateral(address[])"; + _eventParam = abi.encode(tokens); + } + + /** + * @dev Swap borrow rate mode + * @notice Swaps user borrow rate mode between variable and stable + * @param token The address of the token to swap borrow rate.(For ETH: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) + * @param rateMode Desired borrow rate mode. (Stable = 1, Variable = 2) + */ + function swapBorrowRateMode(address token, uint256 rateMode) + external + payable + returns (string memory _eventName, bytes memory _eventParam) + { + AaveInterface aave = AaveInterface(aaveProvider.getPool()); + + uint256 currentRateMode = rateMode == 1 ? 2 : 1; + + if (getPaybackBalance(token, currentRateMode) > 0) { + aave.swapBorrowRateMode(token, rateMode); + } + + _eventName = "LogSwapRateMode(address,uint256)"; + _eventParam = abi.encode(token, rateMode); + } + + /** + * @dev Set user e-mode + * @notice Updates the user's e-mode category + * @param categoryId The category Id of the e-mode user want to set + */ + function setUserEMode(uint8 categoryId) + external + returns (string memory _eventName, bytes memory _eventParam) + { + AaveInterface aave = AaveInterface(aaveProvider.getPool()); + + aave.setUserEMode(categoryId); + + _eventName = "LogSetUserEMode(uint8)"; + _eventParam = abi.encode(categoryId); + } +} + +contract ConnectV2AaveV3Arbitrum is AaveResolver { + string public constant name = "AaveV3-v1.0"; +} diff --git a/contracts/avalanche/connectors/aave/v2-to-v3-import/events.sol b/contracts/avalanche/connectors/aave/v2-to-v3-import/events.sol new file mode 100644 index 00000000..84bb146f --- /dev/null +++ b/contracts/avalanche/connectors/aave/v2-to-v3-import/events.sol @@ -0,0 +1,15 @@ +pragma solidity ^0.7.0; + +contract Events { + event LogAaveImportV2ToV3( + address indexed user, + bool doImport, + bool convertStable, + address[] supplyTokens, + address[] borrowTokens, + uint256[] flashLoanFees, + uint256[] supplyAmts, + uint256[] stableBorrowAmts, + uint256[] variableBorrowAmts + ); +} diff --git a/contracts/avalanche/connectors/aave/v2-to-v3-import/helpers.sol b/contracts/avalanche/connectors/aave/v2-to-v3-import/helpers.sol new file mode 100644 index 00000000..d53dba5a --- /dev/null +++ b/contracts/avalanche/connectors/aave/v2-to-v3-import/helpers.sol @@ -0,0 +1,328 @@ +pragma solidity ^0.7.0; + +import { DSMath } from "../../../common/math.sol"; +import { Basic } from "../../../common/basic.sol"; +import { TokenInterface, AccountInterface } from "../../../common/interfaces.sol"; +import "./events.sol"; +import "./interfaces.sol"; + +abstract contract Helper is DSMath, Basic { + /** + * @dev Aave referal code + */ + uint16 internal constant referalCode = 3228; + + /** + * @dev AaveV2 Lending Pool Provider + */ + AaveV2LendingPoolProviderInterface internal constant aaveV2Provider = + AaveV2LendingPoolProviderInterface( + 0xb6A86025F0FE1862B372cb0ca18CE3EDe02A318f // v2 address: LendingPoolAddressProvider avax + ); + + /** + * @dev AaveV3 Lending Pool Provider + */ + AaveV3PoolProviderInterface internal constant aaveV3Provider = + AaveV3PoolProviderInterface( + 0xa97684ead0e402dC232d5A977953DF7ECBaB3CDb // v3 - PoolAddressesProvider Avalanche + ); + + /** + * @dev Aave Protocol Data Provider + */ + AaveV2DataProviderInterface internal constant aaveV2Data = + AaveV2DataProviderInterface(0x65285E9dfab318f57051ab2b139ccCf232945451); // aave v2 - avax + + function getIsColl(address token, address user) + internal + view + returns (bool isCol) + { + (, , , , , , , , isCol) = aaveV2Data.getUserReserveData(token, user); + } + + struct ImportData { + address[] _supplyTokens; + address[] _borrowTokens; + ATokenV2Interface[] aTokens; + uint256[] supplyAmts; + uint256[] variableBorrowAmts; + uint256[] variableBorrowAmtsWithFee; + uint256[] stableBorrowAmts; + uint256[] stableBorrowAmtsWithFee; + uint256[] totalBorrowAmts; + uint256[] totalBorrowAmtsWithFee; + bool convertStable; + } + + struct ImportInputData { + address[] supplyTokens; + address[] borrowTokens; + bool convertStable; + uint256[] flashLoanFees; + } +} + +contract _AaveHelper is Helper { + function getBorrowAmountV2(address _token, address userAccount) + internal + view + returns (uint256 stableBorrow, uint256 variableBorrow) + { + ( + , + address stableDebtTokenAddress, + address variableDebtTokenAddress + ) = aaveV2Data.getReserveTokensAddresses(_token); + + stableBorrow = ATokenV2Interface(stableDebtTokenAddress).balanceOf( + userAccount + ); + variableBorrow = ATokenV2Interface(variableDebtTokenAddress).balanceOf( + userAccount + ); + } + + function getBorrowAmountsV2( + address userAccount, + AaveV2Interface aaveV2, + ImportInputData memory inputData, + ImportData memory data + ) internal returns (ImportData memory) { + if (inputData.borrowTokens.length > 0) { + data._borrowTokens = new address[](inputData.borrowTokens.length); + data.variableBorrowAmts = new uint256[]( + inputData.borrowTokens.length + ); + data.stableBorrowAmts = new uint256[]( + inputData.borrowTokens.length + ); + data.totalBorrowAmts = new uint256[](inputData.borrowTokens.length); + for (uint256 i = 0; i < inputData.borrowTokens.length; i++) { + for (uint256 j = i; j < inputData.borrowTokens.length; j++) { + if (j != i) { + require( + inputData.borrowTokens[i] != + inputData.borrowTokens[j], + "token-repeated" + ); + } + } + } + for (uint256 i = 0; i < inputData.borrowTokens.length; i++) { + address _token = inputData.borrowTokens[i] == avaxAddr + ? wavaxAddr + : inputData.borrowTokens[i]; + data._borrowTokens[i] = _token; + + ( + data.stableBorrowAmts[i], + data.variableBorrowAmts[i] + ) = getBorrowAmountV2(_token, userAccount); + + if (data.variableBorrowAmts[i] != 0) { + data.variableBorrowAmtsWithFee[i] = add( + data.variableBorrowAmts[i], + inputData.flashLoanFees[i] + ); + data.stableBorrowAmtsWithFee[i] = data.stableBorrowAmts[i]; + } else { + data.stableBorrowAmtsWithFee[i] = add( + data.stableBorrowAmts[i], + inputData.flashLoanFees[i] + ); + } + + data.totalBorrowAmts[i] = add( + data.stableBorrowAmts[i], + data.variableBorrowAmts[i] + ); + data.totalBorrowAmtsWithFee[i] = add( + data.stableBorrowAmtsWithFee[i], + data.variableBorrowAmtsWithFee[i] + ); + + if (data.totalBorrowAmts[i] > 0) { + uint256 _amt = data.totalBorrowAmts[i]; + TokenInterface(_token).approve(address(aaveV2), _amt); + } + } + } + return data; + } + + function getSupplyAmountsV2( + address userAccount, + ImportInputData memory inputData, + ImportData memory data + ) internal view returns (ImportData memory) { + data.supplyAmts = new uint256[](inputData.supplyTokens.length); + data._supplyTokens = new address[](inputData.supplyTokens.length); + data.aTokens = new ATokenV2Interface[](inputData.supplyTokens.length); + + for (uint256 i = 0; i < inputData.supplyTokens.length; i++) { + for (uint256 j = i; j < inputData.supplyTokens.length; j++) { + if (j != i) { + require( + inputData.supplyTokens[i] != inputData.supplyTokens[j], + "token-repeated" + ); + } + } + } + for (uint256 i = 0; i < inputData.supplyTokens.length; i++) { + address _token = inputData.supplyTokens[i] == avaxAddr + ? wavaxAddr + : inputData.supplyTokens[i]; + (address _aToken, , ) = aaveV2Data.getReserveTokensAddresses( + _token + ); + data._supplyTokens[i] = _token; + data.aTokens[i] = ATokenV2Interface(_aToken); + data.supplyAmts[i] = data.aTokens[i].balanceOf(userAccount); + } + + return data; + } + + function _paybackBehalfOneV2( + AaveV2Interface aaveV2, + address token, + uint256 amt, + uint256 rateMode, + address user + ) private { + aaveV2.repay(token, amt, rateMode, user); + } + + function _PaybackStableV2( + uint256 _length, + AaveV2Interface aaveV2, + address[] memory tokens, + uint256[] memory amts, + address user + ) internal { + for (uint256 i = 0; i < _length; i++) { + if (amts[i] > 0) { + _paybackBehalfOneV2(aaveV2, tokens[i], amts[i], 1, user); + } + } + } + + function _PaybackVariableV2( + uint256 _length, + AaveV2Interface aaveV2, + address[] memory tokens, + uint256[] memory amts, + address user + ) internal { + for (uint256 i = 0; i < _length; i++) { + if (amts[i] > 0) { + _paybackBehalfOneV2(aaveV2, tokens[i], amts[i], 2, user); + } + } + } + + function _TransferAtokensV2( + uint256 _length, + AaveV2Interface aaveV2, + ATokenV2Interface[] memory atokenContracts, + uint256[] memory amts, + address[] memory tokens, + address userAccount + ) internal { + for (uint256 i = 0; i < _length; i++) { + if (amts[i] > 0) { + uint256 _amt = amts[i]; + require( + atokenContracts[i].transferFrom( + userAccount, + address(this), + _amt + ), + "allowance?" + ); + + if (!getIsColl(tokens[i], address(this))) { + aaveV2.setUserUseReserveAsCollateral(tokens[i], true); + } + } + } + } + + function _WithdrawTokensFromV2( + uint256 _length, + AaveV2Interface aaveV2, + uint256[] memory amts, + address[] memory tokens + ) internal { + for (uint256 i = 0; i < _length; i++) { + if (amts[i] > 0) { + uint256 _amt = amts[i]; + address _token = tokens[i]; + aaveV2.withdraw(_token, _amt, address(this)); + } + } + } + + function _depositTokensV3( + uint256 _length, + AaveV3Interface aaveV3, + uint256[] memory amts, + address[] memory tokens + ) internal { + for (uint256 i = 0; i < _length; i++) { + if (amts[i] > 0) { + uint256 _amt = amts[i]; + address _token = tokens[i]; + TokenInterface tokenContract = TokenInterface(_token); + require( + tokenContract.balanceOf(address(this)) >= _amt, + "Insufficient funds to deposit in v3" + ); + approve(tokenContract, address(aaveV3), _amt); + aaveV3.supply(_token, _amt, address(this), referalCode); + + if (!getIsColl(_token, address(this))) { + aaveV3.setUserUseReserveAsCollateral(_token, true); + } + } + } + } + + function _BorrowVariableV3( + uint256 _length, + AaveV3Interface aaveV3, + address[] memory tokens, + uint256[] memory amts + ) internal { + for (uint256 i = 0; i < _length; i++) { + if (amts[i] > 0) { + _borrowOneV3(aaveV3, tokens[i], amts[i], 2); + } + } + } + + function _BorrowStableV3( + uint256 _length, + AaveV3Interface aaveV3, + address[] memory tokens, + uint256[] memory amts + ) internal { + for (uint256 i = 0; i < _length; i++) { + if (amts[i] > 0) { + _borrowOneV3(aaveV3, tokens[i], amts[i], 1); + } + } + } + + function _borrowOneV3( + AaveV3Interface aaveV3, + address token, + uint256 amt, + uint256 rateMode + ) private { + aaveV3.borrow(token, amt, rateMode, referalCode, address(this)); + } +} diff --git a/contracts/avalanche/connectors/aave/v2-to-v3-import/interfaces.sol b/contracts/avalanche/connectors/aave/v2-to-v3-import/interfaces.sol new file mode 100644 index 00000000..b28f49e0 --- /dev/null +++ b/contracts/avalanche/connectors/aave/v2-to-v3-import/interfaces.sol @@ -0,0 +1,150 @@ +pragma solidity ^0.7.0; +pragma experimental ABIEncoderV2; + +// aave v2 +interface AaveV2Interface { + function withdraw( + address _asset, + uint256 _amount, + address _to + ) external; + + function borrow( + address _asset, + uint256 _amount, + uint256 _interestRateMode, + uint16 _referralCode, + address _onBehalfOf + ) external; + + function repay( + address _asset, + uint256 _amount, + uint256 _rateMode, + address _onBehalfOf + ) external; + + function setUserUseReserveAsCollateral( + address _asset, + bool _useAsCollateral + ) external; + + function getUserAccountData(address user) + external + view + returns ( + uint256 totalCollateralETH, + uint256 totalDebtETH, + uint256 availableBorrowsETH, + uint256 currentLiquidationThreshold, + uint256 ltv, + uint256 healthFactor + ); +} + +interface AaveV2LendingPoolProviderInterface { + function getLendingPool() external view returns (address); +} + +// Aave Protocol Data Provider +interface AaveV2DataProviderInterface { + function getUserReserveData(address _asset, address _user) + external + view + returns ( + uint256 currentATokenBalance, + uint256 currentStableDebt, + uint256 currentVariableDebt, + uint256 principalStableDebt, + uint256 scaledVariableDebt, + uint256 stableBorrowRate, + uint256 liquidityRate, + uint40 stableRateLastUpdated, + bool usageAsCollateralEnabled + ); + + // function getReserveConfigurationData(address asset) + // external + // view + // returns ( + // uint256 decimals, + // uint256 ltv, + // uint256 liquidationThreshold, + // uint256 liquidationBonus, + // uint256 reserveFactor, + // bool usageAsCollateralEnabled, + // bool borrowingEnabled, + // bool stableBorrowRateEnabled, + // bool isActive, + // bool isFrozen + // ); + + function getReserveTokensAddresses(address asset) + external + view + returns ( + address aTokenAddress, + address stableDebtTokenAddress, + address variableDebtTokenAddress + ); +} + +interface ATokenV2Interface { + function scaledBalanceOf(address _user) external view returns (uint256); + + function isTransferAllowed(address _user, uint256 _amount) + external + view + returns (bool); + + function balanceOf(address _user) external view returns (uint256); + + function transferFrom( + address, + address, + uint256 + ) external returns (bool); + + function allowance(address, address) external returns (uint256); +} + +// aave v3 +interface AaveV3Interface { + function supply( + address asset, + uint256 amount, + address onBehalfOf, + uint16 referralCode + ) external; + + function withdraw( + address asset, + uint256 amount, + address to + ) external returns (uint256); + + function borrow( + address asset, + uint256 amount, + uint256 interestRateMode, + uint16 referralCode, + address onBehalfOf + ) external; + + function repay( + address asset, + uint256 amount, + uint256 interestRateMode, + address onBehalfOf + ) external returns (uint256); + + function setUserUseReserveAsCollateral(address asset, bool useAsCollateral) + external; + + function swapBorrowRateMode(address asset, uint256 interestRateMode) + external; +} + +interface AaveV3PoolProviderInterface { + function getPool() external view returns (address); +} diff --git a/contracts/avalanche/connectors/aave/v2-to-v3-import/main.sol b/contracts/avalanche/connectors/aave/v2-to-v3-import/main.sol new file mode 100644 index 00000000..8e360e81 --- /dev/null +++ b/contracts/avalanche/connectors/aave/v2-to-v3-import/main.sol @@ -0,0 +1,150 @@ +pragma solidity ^0.7.0; +pragma experimental ABIEncoderV2; + +import { TokenInterface, AccountInterface } from "../../../common/interfaces.sol"; +import "./interfaces.sol"; +import "./helpers.sol"; +import "./events.sol"; + +/** + * @title Aave v2 to v3 import connector . + * @dev migrate aave V2 position to aave v3 position + */ +contract _AaveV2ToV3MigrationResolver is _AaveHelper { + function _importAave( + address userAccount, + ImportInputData memory inputData, + bool doImport + ) internal returns (string memory _eventName, bytes memory _eventParam) { + if (doImport) { + // check only when we are importing from user's address + require( + AccountInterface(address(this)).isAuth(userAccount), + "user-account-not-auth" + ); + } + require(inputData.supplyTokens.length > 0, "0-length-not-allowed"); + + ImportData memory data; + + AaveV2Interface aaveV2 = AaveV2Interface( + aaveV2Provider.getLendingPool() + ); + AaveV3Interface aaveV3 = AaveV3Interface(aaveV3Provider.getPool()); + + data = getBorrowAmountsV2(userAccount, aaveV2, inputData, data); + data = getSupplyAmountsV2(userAccount, inputData, data); + + // payback borrowed amount; + _PaybackStableV2( + data._borrowTokens.length, + aaveV2, + data._borrowTokens, + data.stableBorrowAmts, + userAccount + ); + _PaybackVariableV2( + data._borrowTokens.length, + aaveV2, + data._borrowTokens, + data.variableBorrowAmts, + userAccount + ); + + if (doImport) { + // transfer atokens to this address; + _TransferAtokensV2( + data._supplyTokens.length, + aaveV2, + data.aTokens, + data.supplyAmts, + data._supplyTokens, + userAccount + ); + } + // withdraw v2 supplied tokens + _WithdrawTokensFromV2( + data._supplyTokens.length, + aaveV2, + data.supplyAmts, + data._supplyTokens + ); + // deposit tokens in v3 + _depositTokensV3( + data._supplyTokens.length, + aaveV3, + data.supplyAmts, + data._supplyTokens + ); + + // borrow assets in aave v3 after migrating position + if (data.convertStable) { + _BorrowVariableV3( + data._borrowTokens.length, + aaveV3, + data._borrowTokens, + data.totalBorrowAmtsWithFee + ); + } else { + _BorrowStableV3( + data._borrowTokens.length, + aaveV3, + data._borrowTokens, + data.stableBorrowAmtsWithFee + ); + _BorrowVariableV3( + data._borrowTokens.length, + aaveV3, + data._borrowTokens, + data.variableBorrowAmtsWithFee + ); + } + + _eventName = "LogAaveImportV2ToV3(address,bool,bool,address[],address[],uint256[],uint256[],uint256[],uint256[])"; + _eventParam = abi.encode( + userAccount, + doImport, + inputData.convertStable, + inputData.supplyTokens, + inputData.borrowTokens, + inputData.flashLoanFees, + data.supplyAmts, + data.stableBorrowAmts, + data.variableBorrowAmts + ); + } + + /** + * @dev Import aave position . + * @notice Import EOA's aave V2 position to DSA's aave v3 position + * @param userAccount The address of the EOA from which aave position will be imported + * @param inputData The struct containing all the neccessary input data + */ + function importAaveV2ToV3( + address userAccount, + ImportInputData memory inputData + ) + external + payable + returns (string memory _eventName, bytes memory _eventParam) + { + (_eventName, _eventParam) = _importAave(userAccount, inputData, true); + } + + /** + * @dev Migrate aave position . + * @notice Migrate DSA's aave V2 position to DSA's aave v3 position + * @param inputData The struct containing all the neccessary input data + */ + function migrateAaveV2ToV3(ImportInputData memory inputData) + external + payable + returns (string memory _eventName, bytes memory _eventParam) + { + (_eventName, _eventParam) = _importAave(msg.sender, inputData, false); + } +} + +contract ConnectV2AaveV2ToV3MigrationAvalanche is _AaveV2ToV3MigrationResolver { + string public constant name = "Aave-Import-v2-to-v3"; +} diff --git a/contracts/avalanche/connectors/aave/v3/events.sol b/contracts/avalanche/connectors/aave/v3/events.sol new file mode 100644 index 00000000..9f60f22b --- /dev/null +++ b/contracts/avalanche/connectors/aave/v3/events.sol @@ -0,0 +1,33 @@ +pragma solidity ^0.7.0; + +contract Events { + event LogDeposit( + address indexed token, + uint256 tokenAmt, + uint256 getId, + uint256 setId + ); + event LogWithdraw( + address indexed token, + uint256 tokenAmt, + uint256 getId, + uint256 setId + ); + event LogBorrow( + address indexed token, + uint256 tokenAmt, + uint256 indexed rateMode, + uint256 getId, + uint256 setId + ); + event LogPayback( + address indexed token, + uint256 tokenAmt, + uint256 indexed rateMode, + uint256 getId, + uint256 setId + ); + event LogEnableCollateral(address[] tokens); + event LogSwapRateMode(address indexed token, uint256 rateMode); + event LogSetUserEMode(uint8 categoryId); +} diff --git a/contracts/avalanche/connectors/aave/v3/helpers.sol b/contracts/avalanche/connectors/aave/v3/helpers.sol new file mode 100644 index 00000000..6c2f581e --- /dev/null +++ b/contracts/avalanche/connectors/aave/v3/helpers.sol @@ -0,0 +1,66 @@ +pragma solidity ^0.7.0; + +import { DSMath } from "../../../common/math.sol"; +import { Basic } from "../../../common/basic.sol"; +import { AavePoolProviderInterface, AaveDataProviderInterface } from "./interface.sol"; + +abstract contract Helpers is DSMath, Basic { + /** + * @dev Aave Pool Provider + */ + AavePoolProviderInterface internal constant aaveProvider = + AavePoolProviderInterface(0xa97684ead0e402dC232d5A977953DF7ECBaB3CDb); // Avalanche address - PoolAddressesProvider + + /** + * @dev Aave Pool Data Provider + */ + AaveDataProviderInterface internal constant aaveData = + AaveDataProviderInterface(0x69FA688f1Dc47d4B5d8029D5a35FB7a548310654); // Avalanche address - PoolDataProvider + + /** + * @dev Aave Referral Code + */ + uint16 internal constant referralCode = 3228; + + /** + * @dev Checks if collateral is enabled for an asset + * @param token token address of the asset.(For ETH: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) + */ + + function getIsColl(address token) internal view returns (bool isCol) { + (, , , , , , , , isCol) = aaveData.getUserReserveData( + token, + address(this) + ); + } + + /** + * @dev Get total debt balance & fee for an asset + * @param token token address of the debt.(For ETH: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) + * @param rateMode Borrow rate mode (Stable = 1, Variable = 2) + */ + function getPaybackBalance(address token, uint256 rateMode) + internal + view + returns (uint256) + { + (, uint256 stableDebt, uint256 variableDebt, , , , , , ) = aaveData + .getUserReserveData(token, address(this)); + return rateMode == 1 ? stableDebt : variableDebt; + } + + /** + * @dev Get total collateral balance for an asset + * @param token token address of the collateral.(For ETH: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) + */ + function getCollateralBalance(address token) + internal + view + returns (uint256 bal) + { + (bal, , , , , , , , ) = aaveData.getUserReserveData( + token, + address(this) + ); + } +} diff --git a/contracts/avalanche/connectors/aave/v3/interface.sol b/contracts/avalanche/connectors/aave/v3/interface.sol new file mode 100644 index 00000000..8ae14716 --- /dev/null +++ b/contracts/avalanche/connectors/aave/v3/interface.sol @@ -0,0 +1,91 @@ +pragma solidity ^0.7.0; + +interface AaveInterface { + function supply( + address asset, + uint256 amount, + address onBehalfOf, + uint16 referralCode + ) external; + + function withdraw( + address asset, + uint256 amount, + address to + ) external returns (uint256); + + function borrow( + address asset, + uint256 amount, + uint256 interestRateMode, + uint16 referralCode, + address onBehalfOf + ) external; + + function repay( + address asset, + uint256 amount, + uint256 interestRateMode, + address onBehalfOf + ) external returns (uint256); + + function repayWithATokens( + address asset, + uint256 amount, + uint256 interestRateMode + ) external returns (uint256); + + function setUserUseReserveAsCollateral(address asset, bool useAsCollateral) + external; + + function swapBorrowRateMode(address asset, uint256 interestRateMode) + external; + + function setUserEMode(uint8 categoryId) external; +} + +interface AavePoolProviderInterface { + function getPool() external view returns (address); +} + +interface AaveDataProviderInterface { + function getReserveTokensAddresses(address _asset) + external + view + returns ( + address aTokenAddress, + address stableDebtTokenAddress, + address variableDebtTokenAddress + ); + + function getUserReserveData(address _asset, address _user) + external + view + returns ( + uint256 currentATokenBalance, + uint256 currentStableDebt, + uint256 currentVariableDebt, + uint256 principalStableDebt, + uint256 scaledVariableDebt, + uint256 stableBorrowRate, + uint256 liquidityRate, + uint40 stableRateLastUpdated, + bool usageAsCollateralEnabled + ); + + function getReserveEModeCategory(address asset) + external + view + returns (uint256); +} + +interface AaveAddressProviderRegistryInterface { + function getAddressesProvidersList() + external + view + returns (address[] memory); +} + +interface ATokenInterface { + function balanceOf(address _user) external view returns (uint256); +} diff --git a/contracts/avalanche/connectors/aave/v3/main.sol b/contracts/avalanche/connectors/aave/v3/main.sol new file mode 100644 index 00000000..aa9611fb --- /dev/null +++ b/contracts/avalanche/connectors/aave/v3/main.sol @@ -0,0 +1,296 @@ +pragma solidity ^0.7.0; + +/** + * @title Aave v3. + * @dev Lending & Borrowing. + */ + +import { TokenInterface } from "../../../common/interfaces.sol"; +import { Stores } from "../../../common/stores.sol"; +import { Helpers } from "./helpers.sol"; +import { Events } from "./events.sol"; +import { AaveInterface } from "./interface.sol"; + +abstract contract AaveResolver is Events, Helpers { + /** + * @dev Deposit avax/ERC20_Token. + * @notice Deposit a token to Aave v3 for lending / collaterization. + * @param token The address of the token to deposit.(For avax: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) + * @param amt The amount of the token to deposit. (For max: `uint256(-1)`) + * @param getId ID to retrieve amt. + * @param setId ID stores the amount of tokens deposited. + */ + function deposit( + address token, + uint256 amt, + uint256 getId, + uint256 setId + ) + external + payable + returns (string memory _eventName, bytes memory _eventParam) + { + uint256 _amt = getUint(getId, amt); + + AaveInterface aave = AaveInterface(aaveProvider.getPool()); + + bool isAVAX = token == avaxAddr; + address _token = isAVAX ? wavaxAddr : token; + + TokenInterface tokenContract = TokenInterface(_token); + + if (isAVAX) { + _amt = _amt == uint256(-1) ? address(this).balance : _amt; + convertAvaxToWavax(isAVAX, tokenContract, _amt); + } else { + _amt = _amt == uint256(-1) + ? tokenContract.balanceOf(address(this)) + : _amt; + } + + approve(tokenContract, address(aave), _amt); + + aave.supply(_token, _amt, address(this), referralCode); + + if (!getIsColl(_token)) { + aave.setUserUseReserveAsCollateral(_token, true); + } + + setUint(setId, _amt); + + _eventName = "LogDeposit(address,uint256,uint256,uint256)"; + _eventParam = abi.encode(token, _amt, getId, setId); + } + + /** + * @dev Withdraw avax/ERC20_Token. + * @notice Withdraw deposited token from Aave v3 + * @param token The address of the token to withdraw.(For avax: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) + * @param amt The amount of the token to withdraw. (For max: `uint256(-1)`) + * @param getId ID to retrieve amt. + * @param setId ID stores the amount of tokens withdrawn. + */ + function withdraw( + address token, + uint256 amt, + uint256 getId, + uint256 setId + ) + external + payable + returns (string memory _eventName, bytes memory _eventParam) + { + uint256 _amt = getUint(getId, amt); + + AaveInterface aave = AaveInterface(aaveProvider.getPool()); + bool isAVAX = token == avaxAddr; + address _token = isAVAX ? wavaxAddr : token; + + TokenInterface tokenContract = TokenInterface(_token); + + uint256 initialBal = tokenContract.balanceOf(address(this)); + aave.withdraw(_token, _amt, address(this)); + uint256 finalBal = tokenContract.balanceOf(address(this)); + + _amt = sub(finalBal, initialBal); + + convertWavaxToAvax(isAVAX, tokenContract, _amt); + + setUint(setId, _amt); + + _eventName = "LogWithdraw(address,uint256,uint256,uint256)"; + _eventParam = abi.encode(token, _amt, getId, setId); + } + + /** + * @dev Borrow avax/ERC20_Token. + * @notice Borrow a token using Aave v3 + * @param token The address of the token to borrow.(For avax: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) + * @param amt The amount of the token to borrow. + * @param rateMode The type of borrow debt. (For Stable: 1, Variable: 2) + * @param getId ID to retrieve amt. + * @param setId ID stores the amount of tokens borrowed. + */ + function borrow( + address token, + uint256 amt, + uint256 rateMode, + uint256 getId, + uint256 setId + ) + external + payable + returns (string memory _eventName, bytes memory _eventParam) + { + uint256 _amt = getUint(getId, amt); + + AaveInterface aave = AaveInterface(aaveProvider.getPool()); + + bool isAVAX = token == avaxAddr; + address _token = isAVAX ? wavaxAddr : token; + + aave.borrow(_token, _amt, rateMode, referralCode, address(this)); + convertWavaxToAvax(isAVAX, TokenInterface(_token), _amt); + + setUint(setId, _amt); + + _eventName = "LogBorrow(address,uint256,uint256,uint256,uint256)"; + _eventParam = abi.encode(token, _amt, rateMode, getId, setId); + } + + /** + * @dev Payback borrowed avax/ERC20_Token. + * @notice Payback debt owed. + * @param token The address of the token to payback.(For avax: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) + * @param amt The amount of the token to payback. (For max: `uint256(-1)`) + * @param rateMode The type of debt paying back. (For Stable: 1, Variable: 2) + * @param getId ID to retrieve amt. + * @param setId ID stores the amount of tokens paid back. + */ + function payback( + address token, + uint256 amt, + uint256 rateMode, + uint256 getId, + uint256 setId + ) + external + payable + returns (string memory _eventName, bytes memory _eventParam) + { + uint256 _amt = getUint(getId, amt); + + AaveInterface aave = AaveInterface(aaveProvider.getPool()); + + bool isAVAX = token == avaxAddr; + address _token = isAVAX ? wavaxAddr : token; + + TokenInterface tokenContract = TokenInterface(_token); + + _amt = _amt == uint256(-1) ? getPaybackBalance(_token, rateMode) : _amt; + + if (isAVAX) convertAvaxToWavax(isAVAX, tokenContract, _amt); + + approve(tokenContract, address(aave), _amt); + + aave.repay(_token, _amt, rateMode, address(this)); + + setUint(setId, _amt); + + _eventName = "LogPayback(address,uint256,uint256,uint256,uint256)"; + _eventParam = abi.encode(token, _amt, rateMode, getId, setId); + } + + /** + * @dev Payback borrowed avax/ERC20_Token using aTokens. + * @notice Repays a borrowed `amount` on a specific reserve using the reserve aTokens, burning the equivalent debt tokens. + * @param token The address of the token to payback.(For avax: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) + * @param amt The amount of the token to payback. (For max: `uint256(-1)`) + * @param rateMode The type of debt paying back. (For Stable: 1, Variable: 2) + * @param getId ID to retrieve amt. + * @param setId ID stores the amount of tokens paid back. + */ + function paybackWithATokens( + address token, + uint256 amt, + uint256 rateMode, + uint256 getId, + uint256 setId + ) + external + payable + returns (string memory _eventName, bytes memory _eventParam) + { + uint256 _amt = getUint(getId, amt); + + AaveInterface aave = AaveInterface(aaveProvider.getPool()); + + bool isAVAX = token == avaxAddr; + address _token = isAVAX ? wavaxAddr : token; + + TokenInterface tokenContract = TokenInterface(_token); + + _amt = _amt == uint256(-1) ? getPaybackBalance(_token, rateMode) : _amt; + + if (isAVAX) convertAvaxToWavax(isAVAX, tokenContract, _amt); + + approve(tokenContract, address(aave), _amt); + + aave.repayWithATokens(_token, _amt, rateMode); + + setUint(setId, _amt); + + _eventName = "LogPayback(address,uint256,uint256,uint256,uint256)"; + _eventParam = abi.encode(token, _amt, rateMode, getId, setId); + } + + /** + * @dev Enable collateral + * @notice Enable an array of tokens as collateral + * @param tokens Array of tokens to enable collateral + */ + function enableCollateral(address[] calldata tokens) + external + payable + returns (string memory _eventName, bytes memory _eventParam) + { + uint256 _length = tokens.length; + require(_length > 0, "0-tokens-not-allowed"); + + AaveInterface aave = AaveInterface(aaveProvider.getPool()); + + for (uint256 i = 0; i < _length; i++) { + address token = tokens[i]; + if (getCollateralBalance(token) > 0 && !getIsColl(token)) { + aave.setUserUseReserveAsCollateral(token, true); + } + } + + _eventName = "LogEnableCollateral(address[])"; + _eventParam = abi.encode(tokens); + } + + /** + * @dev Swap borrow rate mode + * @notice Swaps user borrow rate mode between variable and stable + * @param token The address of the token to swap borrow rate.(For avax: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) + * @param rateMode Desired borrow rate mode. (Stable = 1, Variable = 2) + */ + function swapBorrowRateMode(address token, uint256 rateMode) + external + payable + returns (string memory _eventName, bytes memory _eventParam) + { + AaveInterface aave = AaveInterface(aaveProvider.getPool()); + + uint256 currentRateMode = rateMode == 1 ? 2 : 1; + + if (getPaybackBalance(token, currentRateMode) > 0) { + aave.swapBorrowRateMode(token, rateMode); + } + + _eventName = "LogSwapRateMode(address,uint256)"; + _eventParam = abi.encode(token, rateMode); + } + + /** + * @dev Set user e-mode + * @notice Updates the user's e-mode category + * @param categoryId The category Id of the e-mode user want to set + */ + function setUserEMode(uint8 categoryId) + external + returns (string memory _eventName, bytes memory _eventParam) + { + AaveInterface aave = AaveInterface(aaveProvider.getPool()); + + aave.setUserEMode(categoryId); + + _eventName = "LogSetUserEMode(uint8)"; + _eventParam = abi.encode(categoryId); + } +} + +contract ConnectV2AaveV3Avalanche is AaveResolver { + string public constant name = "AaveV3-v1.0"; +} diff --git a/contracts/fantom/connectors/aave/v3/events.sol b/contracts/fantom/connectors/aave/v3/events.sol new file mode 100644 index 00000000..9f60f22b --- /dev/null +++ b/contracts/fantom/connectors/aave/v3/events.sol @@ -0,0 +1,33 @@ +pragma solidity ^0.7.0; + +contract Events { + event LogDeposit( + address indexed token, + uint256 tokenAmt, + uint256 getId, + uint256 setId + ); + event LogWithdraw( + address indexed token, + uint256 tokenAmt, + uint256 getId, + uint256 setId + ); + event LogBorrow( + address indexed token, + uint256 tokenAmt, + uint256 indexed rateMode, + uint256 getId, + uint256 setId + ); + event LogPayback( + address indexed token, + uint256 tokenAmt, + uint256 indexed rateMode, + uint256 getId, + uint256 setId + ); + event LogEnableCollateral(address[] tokens); + event LogSwapRateMode(address indexed token, uint256 rateMode); + event LogSetUserEMode(uint8 categoryId); +} diff --git a/contracts/fantom/connectors/aave/v3/helpers.sol b/contracts/fantom/connectors/aave/v3/helpers.sol new file mode 100644 index 00000000..8b970670 --- /dev/null +++ b/contracts/fantom/connectors/aave/v3/helpers.sol @@ -0,0 +1,66 @@ +pragma solidity ^0.7.0; + +import { DSMath } from "../../../common/math.sol"; +import { Basic } from "../../../common/basic.sol"; +import { AavePoolProviderInterface, AaveDataProviderInterface } from "./interface.sol"; + +abstract contract Helpers is DSMath, Basic { + /** + * @dev Aave Pool Provider + */ + AavePoolProviderInterface internal constant aaveProvider = + AavePoolProviderInterface(0xa97684ead0e402dC232d5A977953DF7ECBaB3CDb); // fantom address - PoolAddressesProvider + + /** + * @dev Aave Pool Data Provider + */ + AaveDataProviderInterface internal constant aaveData = + AaveDataProviderInterface(0x69FA688f1Dc47d4B5d8029D5a35FB7a548310654); // fantom address - PoolDataProvider + + /** + * @dev Aave Referral Code + */ + uint16 internal constant referralCode = 3228; + + /** + * @dev Checks if collateral is enabled for an asset + * @param token token address of the asset.(For ETH: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) + */ + + function getIsColl(address token) internal view returns (bool isCol) { + (, , , , , , , , isCol) = aaveData.getUserReserveData( + token, + address(this) + ); + } + + /** + * @dev Get total debt balance & fee for an asset + * @param token token address of the debt.(For ETH: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) + * @param rateMode Borrow rate mode (Stable = 1, Variable = 2) + */ + function getPaybackBalance(address token, uint256 rateMode) + internal + view + returns (uint256) + { + (, uint256 stableDebt, uint256 variableDebt, , , , , , ) = aaveData + .getUserReserveData(token, address(this)); + return rateMode == 1 ? stableDebt : variableDebt; + } + + /** + * @dev Get total collateral balance for an asset + * @param token token address of the collateral.(For ETH: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) + */ + function getCollateralBalance(address token) + internal + view + returns (uint256 bal) + { + (bal, , , , , , , , ) = aaveData.getUserReserveData( + token, + address(this) + ); + } +} diff --git a/contracts/fantom/connectors/aave/v3/interface.sol b/contracts/fantom/connectors/aave/v3/interface.sol new file mode 100644 index 00000000..8ae14716 --- /dev/null +++ b/contracts/fantom/connectors/aave/v3/interface.sol @@ -0,0 +1,91 @@ +pragma solidity ^0.7.0; + +interface AaveInterface { + function supply( + address asset, + uint256 amount, + address onBehalfOf, + uint16 referralCode + ) external; + + function withdraw( + address asset, + uint256 amount, + address to + ) external returns (uint256); + + function borrow( + address asset, + uint256 amount, + uint256 interestRateMode, + uint16 referralCode, + address onBehalfOf + ) external; + + function repay( + address asset, + uint256 amount, + uint256 interestRateMode, + address onBehalfOf + ) external returns (uint256); + + function repayWithATokens( + address asset, + uint256 amount, + uint256 interestRateMode + ) external returns (uint256); + + function setUserUseReserveAsCollateral(address asset, bool useAsCollateral) + external; + + function swapBorrowRateMode(address asset, uint256 interestRateMode) + external; + + function setUserEMode(uint8 categoryId) external; +} + +interface AavePoolProviderInterface { + function getPool() external view returns (address); +} + +interface AaveDataProviderInterface { + function getReserveTokensAddresses(address _asset) + external + view + returns ( + address aTokenAddress, + address stableDebtTokenAddress, + address variableDebtTokenAddress + ); + + function getUserReserveData(address _asset, address _user) + external + view + returns ( + uint256 currentATokenBalance, + uint256 currentStableDebt, + uint256 currentVariableDebt, + uint256 principalStableDebt, + uint256 scaledVariableDebt, + uint256 stableBorrowRate, + uint256 liquidityRate, + uint40 stableRateLastUpdated, + bool usageAsCollateralEnabled + ); + + function getReserveEModeCategory(address asset) + external + view + returns (uint256); +} + +interface AaveAddressProviderRegistryInterface { + function getAddressesProvidersList() + external + view + returns (address[] memory); +} + +interface ATokenInterface { + function balanceOf(address _user) external view returns (uint256); +} diff --git a/contracts/fantom/connectors/aave/v3/main.sol b/contracts/fantom/connectors/aave/v3/main.sol new file mode 100644 index 00000000..66506cff --- /dev/null +++ b/contracts/fantom/connectors/aave/v3/main.sol @@ -0,0 +1,296 @@ +pragma solidity ^0.7.0; + +/** + * @title Aave v3. + * @dev Lending & Borrowing. + */ + +import { TokenInterface } from "../../../common/interfaces.sol"; +import { Stores } from "../../../common/stores.sol"; +import { Helpers } from "./helpers.sol"; +import { Events } from "./events.sol"; +import { AaveInterface } from "./interface.sol"; + +abstract contract AaveResolver is Events, Helpers { + /** + * @dev Deposit Ftm/ERC20_Token. + * @notice Deposit a token to Aave v3 for lending / collaterization. + * @param token The address of the token to deposit.(For ftm: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) + * @param amt The amount of the token to deposit. (For max: `uint256(-1)`) + * @param getId ID to retrieve amt. + * @param setId ID stores the amount of tokens deposited. + */ + function deposit( + address token, + uint256 amt, + uint256 getId, + uint256 setId + ) + external + payable + returns (string memory _eventName, bytes memory _eventParam) + { + uint256 _amt = getUint(getId, amt); + + AaveInterface aave = AaveInterface(aaveProvider.getPool()); + + bool isFTM = token == ftmAddr; + address _token = isFTM ? wftmAddr : token; + + TokenInterface tokenContract = TokenInterface(_token); + + if (isFTM) { + _amt = _amt == uint256(-1) ? address(this).balance : _amt; + convertFtmToWftm(isFTM, tokenContract, _amt); + } else { + _amt = _amt == uint256(-1) + ? tokenContract.balanceOf(address(this)) + : _amt; + } + + approve(tokenContract, address(aave), _amt); + + aave.supply(_token, _amt, address(this), referralCode); + + if (!getIsColl(_token)) { + aave.setUserUseReserveAsCollateral(_token, true); + } + + setUint(setId, _amt); + + _eventName = "LogDeposit(address,uint256,uint256,uint256)"; + _eventParam = abi.encode(token, _amt, getId, setId); + } + + /** + * @dev Withdraw ftm/ERC20_Token. + * @notice Withdraw deposited token from Aave v3 + * @param token The address of the token to withdraw.(For ftm: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) + * @param amt The amount of the token to withdraw. (For max: `uint256(-1)`) + * @param getId ID to retrieve amt. + * @param setId ID stores the amount of tokens withdrawn. + */ + function withdraw( + address token, + uint256 amt, + uint256 getId, + uint256 setId + ) + external + payable + returns (string memory _eventName, bytes memory _eventParam) + { + uint256 _amt = getUint(getId, amt); + + AaveInterface aave = AaveInterface(aaveProvider.getPool()); + bool isFTM = token == ftmAddr; + address _token = isFTM ? wftmAddr : token; + + TokenInterface tokenContract = TokenInterface(_token); + + uint256 initialBal = tokenContract.balanceOf(address(this)); + aave.withdraw(_token, _amt, address(this)); + uint256 finalBal = tokenContract.balanceOf(address(this)); + + _amt = sub(finalBal, initialBal); + + convertWftmToFtm(isFTM, tokenContract, _amt); + + setUint(setId, _amt); + + _eventName = "LogWithdraw(address,uint256,uint256,uint256)"; + _eventParam = abi.encode(token, _amt, getId, setId); + } + + /** + * @dev Borrow ftm/ERC20_Token. + * @notice Borrow a token using Aave v3 + * @param token The address of the token to borrow.(For ftm: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) + * @param amt The amount of the token to borrow. + * @param rateMode The type of borrow debt. (For Stable: 1, Variable: 2) + * @param getId ID to retrieve amt. + * @param setId ID stores the amount of tokens borrowed. + */ + function borrow( + address token, + uint256 amt, + uint256 rateMode, + uint256 getId, + uint256 setId + ) + external + payable + returns (string memory _eventName, bytes memory _eventParam) + { + uint256 _amt = getUint(getId, amt); + + AaveInterface aave = AaveInterface(aaveProvider.getPool()); + + bool isFTM = token == ftmAddr; + address _token = isFTM ? wftmAddr : token; + + aave.borrow(_token, _amt, rateMode, referralCode, address(this)); + convertWftmToFtm(isFTM, TokenInterface(_token), _amt); + + setUint(setId, _amt); + + _eventName = "LogBorrow(address,uint256,uint256,uint256,uint256)"; + _eventParam = abi.encode(token, _amt, rateMode, getId, setId); + } + + /** + * @dev Payback borrowed ftm/ERC20_Token. + * @notice Payback debt owed. + * @param token The address of the token to payback.(For ftm: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) + * @param amt The amount of the token to payback. (For max: `uint256(-1)`) + * @param rateMode The type of debt paying back. (For Stable: 1, Variable: 2) + * @param getId ID to retrieve amt. + * @param setId ID stores the amount of tokens paid back. + */ + function payback( + address token, + uint256 amt, + uint256 rateMode, + uint256 getId, + uint256 setId + ) + external + payable + returns (string memory _eventName, bytes memory _eventParam) + { + uint256 _amt = getUint(getId, amt); + + AaveInterface aave = AaveInterface(aaveProvider.getPool()); + + bool isFTM = token == ftmAddr; + address _token = isFTM ? wftmAddr : token; + + TokenInterface tokenContract = TokenInterface(_token); + + _amt = _amt == uint256(-1) ? getPaybackBalance(_token, rateMode) : _amt; + + if (isFTM) convertFtmToWftm(isFTM, tokenContract, _amt); + + approve(tokenContract, address(aave), _amt); + + aave.repay(_token, _amt, rateMode, address(this)); + + setUint(setId, _amt); + + _eventName = "LogPayback(address,uint256,uint256,uint256,uint256)"; + _eventParam = abi.encode(token, _amt, rateMode, getId, setId); + } + + /** + * @dev Payback borrowed ftm/ERC20_Token using aTokens. + * @notice Repays a borrowed `amount` on a specific reserve using the reserve aTokens, burning the equivalent debt tokens. + * @param token The address of the token to payback.(For ftm: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) + * @param amt The amount of the token to payback. (For max: `uint256(-1)`) + * @param rateMode The type of debt paying back. (For Stable: 1, Variable: 2) + * @param getId ID to retrieve amt. + * @param setId ID stores the amount of tokens paid back. + */ + function paybackWithATokens( + address token, + uint256 amt, + uint256 rateMode, + uint256 getId, + uint256 setId + ) + external + payable + returns (string memory _eventName, bytes memory _eventParam) + { + uint256 _amt = getUint(getId, amt); + + AaveInterface aave = AaveInterface(aaveProvider.getPool()); + + bool isFTM = token == ftmAddr; + address _token = isFTM ? wftmAddr : token; + + TokenInterface tokenContract = TokenInterface(_token); + + _amt = _amt == uint256(-1) ? getPaybackBalance(_token, rateMode) : _amt; + + if (isFTM) convertFtmToWftm(isFTM, tokenContract, _amt); + + approve(tokenContract, address(aave), _amt); + + aave.repayWithATokens(_token, _amt, rateMode); + + setUint(setId, _amt); + + _eventName = "LogPayback(address,uint256,uint256,uint256,uint256)"; + _eventParam = abi.encode(token, _amt, rateMode, getId, setId); + } + + /** + * @dev Enable collateral + * @notice Enable an array of tokens as collateral + * @param tokens Array of tokens to enable collateral + */ + function enableCollateral(address[] calldata tokens) + external + payable + returns (string memory _eventName, bytes memory _eventParam) + { + uint256 _length = tokens.length; + require(_length > 0, "0-tokens-not-allowed"); + + AaveInterface aave = AaveInterface(aaveProvider.getPool()); + + for (uint256 i = 0; i < _length; i++) { + address token = tokens[i]; + if (getCollateralBalance(token) > 0 && !getIsColl(token)) { + aave.setUserUseReserveAsCollateral(token, true); + } + } + + _eventName = "LogEnableCollateral(address[])"; + _eventParam = abi.encode(tokens); + } + + /** + * @dev Swap borrow rate mode + * @notice Swaps user borrow rate mode between variable and stable + * @param token The address of the token to swap borrow rate.(For ftm: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) + * @param rateMode Desired borrow rate mode. (Stable = 1, Variable = 2) + */ + function swapBorrowRateMode(address token, uint256 rateMode) + external + payable + returns (string memory _eventName, bytes memory _eventParam) + { + AaveInterface aave = AaveInterface(aaveProvider.getPool()); + + uint256 currentRateMode = rateMode == 1 ? 2 : 1; + + if (getPaybackBalance(token, currentRateMode) > 0) { + aave.swapBorrowRateMode(token, rateMode); + } + + _eventName = "LogSwapRateMode(address,uint256)"; + _eventParam = abi.encode(token, rateMode); + } + + /** + * @dev Set user e-mode + * @notice Updates the user's e-mode category + * @param categoryId The category Id of the e-mode user want to set + */ + function setUserEMode(uint8 categoryId) + external + returns (string memory _eventName, bytes memory _eventParam) + { + AaveInterface aave = AaveInterface(aaveProvider.getPool()); + + aave.setUserEMode(categoryId); + + _eventName = "LogSetUserEMode(uint8)"; + _eventParam = abi.encode(categoryId); + } +} + +contract ConnectV2AaveV3Fantom is AaveResolver { + string public constant name = "AaveV3-v1"; +} diff --git a/contracts/mainnet/connectors/aave/v3/events.sol b/contracts/mainnet/connectors/aave/v3/events.sol new file mode 100644 index 00000000..9f60f22b --- /dev/null +++ b/contracts/mainnet/connectors/aave/v3/events.sol @@ -0,0 +1,33 @@ +pragma solidity ^0.7.0; + +contract Events { + event LogDeposit( + address indexed token, + uint256 tokenAmt, + uint256 getId, + uint256 setId + ); + event LogWithdraw( + address indexed token, + uint256 tokenAmt, + uint256 getId, + uint256 setId + ); + event LogBorrow( + address indexed token, + uint256 tokenAmt, + uint256 indexed rateMode, + uint256 getId, + uint256 setId + ); + event LogPayback( + address indexed token, + uint256 tokenAmt, + uint256 indexed rateMode, + uint256 getId, + uint256 setId + ); + event LogEnableCollateral(address[] tokens); + event LogSwapRateMode(address indexed token, uint256 rateMode); + event LogSetUserEMode(uint8 categoryId); +} diff --git a/contracts/mainnet/connectors/aave/v3/helpers.sol b/contracts/mainnet/connectors/aave/v3/helpers.sol new file mode 100644 index 00000000..13431d11 --- /dev/null +++ b/contracts/mainnet/connectors/aave/v3/helpers.sol @@ -0,0 +1,66 @@ +pragma solidity ^0.7.0; + +import { DSMath } from "../../../common/math.sol"; +import { Basic } from "../../../common/basic.sol"; +import { AavePoolProviderInterface, AaveDataProviderInterface } from "./interface.sol"; + +abstract contract Helpers is DSMath, Basic { + /** + * @dev Aave Pool Provider + */ + AavePoolProviderInterface internal constant aaveProvider = + AavePoolProviderInterface(0xA55125A90d75a95EC00130E8E8C197dB5641Eb19); // rinkeby address + + /** + * @dev Aave Pool Data Provider + */ + AaveDataProviderInterface internal constant aaveData = + AaveDataProviderInterface(0x256bBbeDbA70a1240a1EB64210abB1b063267408); // rinkeby address + + /** + * @dev Aave Referral Code + */ + uint16 internal constant referralCode = 3228; + + /** + * @dev Checks if collateral is enabled for an asset + * @param token token address of the asset.(For ETH: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) + */ + + function getIsColl(address token) internal view returns (bool isCol) { + (, , , , , , , , isCol) = aaveData.getUserReserveData( + token, + address(this) + ); + } + + /** + * @dev Get total debt balance & fee for an asset + * @param token token address of the debt.(For ETH: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) + * @param rateMode Borrow rate mode (Stable = 1, Variable = 2) + */ + function getPaybackBalance(address token, uint256 rateMode) + internal + view + returns (uint256) + { + (, uint256 stableDebt, uint256 variableDebt, , , , , , ) = aaveData + .getUserReserveData(token, address(this)); + return rateMode == 1 ? stableDebt : variableDebt; + } + + /** + * @dev Get total collateral balance for an asset + * @param token token address of the collateral.(For ETH: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) + */ + function getCollateralBalance(address token) + internal + view + returns (uint256 bal) + { + (bal, , , , , , , , ) = aaveData.getUserReserveData( + token, + address(this) + ); + } +} diff --git a/contracts/mainnet/connectors/aave/v3/interface.sol b/contracts/mainnet/connectors/aave/v3/interface.sol new file mode 100644 index 00000000..8ae14716 --- /dev/null +++ b/contracts/mainnet/connectors/aave/v3/interface.sol @@ -0,0 +1,91 @@ +pragma solidity ^0.7.0; + +interface AaveInterface { + function supply( + address asset, + uint256 amount, + address onBehalfOf, + uint16 referralCode + ) external; + + function withdraw( + address asset, + uint256 amount, + address to + ) external returns (uint256); + + function borrow( + address asset, + uint256 amount, + uint256 interestRateMode, + uint16 referralCode, + address onBehalfOf + ) external; + + function repay( + address asset, + uint256 amount, + uint256 interestRateMode, + address onBehalfOf + ) external returns (uint256); + + function repayWithATokens( + address asset, + uint256 amount, + uint256 interestRateMode + ) external returns (uint256); + + function setUserUseReserveAsCollateral(address asset, bool useAsCollateral) + external; + + function swapBorrowRateMode(address asset, uint256 interestRateMode) + external; + + function setUserEMode(uint8 categoryId) external; +} + +interface AavePoolProviderInterface { + function getPool() external view returns (address); +} + +interface AaveDataProviderInterface { + function getReserveTokensAddresses(address _asset) + external + view + returns ( + address aTokenAddress, + address stableDebtTokenAddress, + address variableDebtTokenAddress + ); + + function getUserReserveData(address _asset, address _user) + external + view + returns ( + uint256 currentATokenBalance, + uint256 currentStableDebt, + uint256 currentVariableDebt, + uint256 principalStableDebt, + uint256 scaledVariableDebt, + uint256 stableBorrowRate, + uint256 liquidityRate, + uint40 stableRateLastUpdated, + bool usageAsCollateralEnabled + ); + + function getReserveEModeCategory(address asset) + external + view + returns (uint256); +} + +interface AaveAddressProviderRegistryInterface { + function getAddressesProvidersList() + external + view + returns (address[] memory); +} + +interface ATokenInterface { + function balanceOf(address _user) external view returns (uint256); +} diff --git a/contracts/mainnet/connectors/aave/v3/main.sol b/contracts/mainnet/connectors/aave/v3/main.sol new file mode 100644 index 00000000..1c7b0a8b --- /dev/null +++ b/contracts/mainnet/connectors/aave/v3/main.sol @@ -0,0 +1,296 @@ +pragma solidity ^0.7.0; + +/** + * @title Aave v3. + * @dev Lending & Borrowing. + */ + +import { TokenInterface } from "../../../common/interfaces.sol"; +import { Stores } from "../../../common/stores.sol"; +import { Helpers } from "./helpers.sol"; +import { Events } from "./events.sol"; +import { AaveInterface } from "./interface.sol"; + +abstract contract AaveResolver is Events, Helpers { + /** + * @dev Deposit ETH/ERC20_Token. + * @notice Deposit a token to Aave v3 for lending / collaterization. + * @param token The address of the token to deposit.(For ETH: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) + * @param amt The amount of the token to deposit. (For max: `uint256(-1)`) + * @param getId ID to retrieve amt. + * @param setId ID stores the amount of tokens deposited. + */ + function deposit( + address token, + uint256 amt, + uint256 getId, + uint256 setId + ) + external + payable + returns (string memory _eventName, bytes memory _eventParam) + { + uint256 _amt = getUint(getId, amt); + + AaveInterface aave = AaveInterface(aaveProvider.getPool()); + + bool isEth = token == ethAddr; + address _token = isEth ? wethAddr : token; + + TokenInterface tokenContract = TokenInterface(_token); + + if (isEth) { + _amt = _amt == uint256(-1) ? address(this).balance : _amt; + convertEthToWeth(isEth, tokenContract, _amt); + } else { + _amt = _amt == uint256(-1) + ? tokenContract.balanceOf(address(this)) + : _amt; + } + + approve(tokenContract, address(aave), _amt); + + aave.supply(_token, _amt, address(this), referralCode); + + if (!getIsColl(_token)) { + aave.setUserUseReserveAsCollateral(_token, true); + } + + setUint(setId, _amt); + + _eventName = "LogDeposit(address,uint256,uint256,uint256)"; + _eventParam = abi.encode(token, _amt, getId, setId); + } + + /** + * @dev Withdraw ETH/ERC20_Token. + * @notice Withdraw deposited token from Aave v3 + * @param token The address of the token to withdraw.(For ETH: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) + * @param amt The amount of the token to withdraw. (For max: `uint256(-1)`) + * @param getId ID to retrieve amt. + * @param setId ID stores the amount of tokens withdrawn. + */ + function withdraw( + address token, + uint256 amt, + uint256 getId, + uint256 setId + ) + external + payable + returns (string memory _eventName, bytes memory _eventParam) + { + uint256 _amt = getUint(getId, amt); + + AaveInterface aave = AaveInterface(aaveProvider.getPool()); + bool isEth = token == ethAddr; + address _token = isEth ? wethAddr : token; + + TokenInterface tokenContract = TokenInterface(_token); + + uint256 initialBal = tokenContract.balanceOf(address(this)); + aave.withdraw(_token, _amt, address(this)); + uint256 finalBal = tokenContract.balanceOf(address(this)); + + _amt = sub(finalBal, initialBal); + + convertWethToEth(isEth, tokenContract, _amt); + + setUint(setId, _amt); + + _eventName = "LogWithdraw(address,uint256,uint256,uint256)"; + _eventParam = abi.encode(token, _amt, getId, setId); + } + + /** + * @dev Borrow ETH/ERC20_Token. + * @notice Borrow a token using Aave v3 + * @param token The address of the token to borrow.(For ETH: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) + * @param amt The amount of the token to borrow. + * @param rateMode The type of borrow debt. (For Stable: 1, Variable: 2) + * @param getId ID to retrieve amt. + * @param setId ID stores the amount of tokens borrowed. + */ + function borrow( + address token, + uint256 amt, + uint256 rateMode, + uint256 getId, + uint256 setId + ) + external + payable + returns (string memory _eventName, bytes memory _eventParam) + { + uint256 _amt = getUint(getId, amt); + + AaveInterface aave = AaveInterface(aaveProvider.getPool()); + + bool isEth = token == ethAddr; + address _token = isEth ? wethAddr : token; + + aave.borrow(_token, _amt, rateMode, referralCode, address(this)); + convertWethToEth(isEth, TokenInterface(_token), _amt); + + setUint(setId, _amt); + + _eventName = "LogBorrow(address,uint256,uint256,uint256,uint256)"; + _eventParam = abi.encode(token, _amt, rateMode, getId, setId); + } + + /** + * @dev Payback borrowed ETH/ERC20_Token. + * @notice Payback debt owed. + * @param token The address of the token to payback.(For ETH: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) + * @param amt The amount of the token to payback. (For max: `uint256(-1)`) + * @param rateMode The type of debt paying back. (For Stable: 1, Variable: 2) + * @param getId ID to retrieve amt. + * @param setId ID stores the amount of tokens paid back. + */ + function payback( + address token, + uint256 amt, + uint256 rateMode, + uint256 getId, + uint256 setId + ) + external + payable + returns (string memory _eventName, bytes memory _eventParam) + { + uint256 _amt = getUint(getId, amt); + + AaveInterface aave = AaveInterface(aaveProvider.getPool()); + + bool isEth = token == ethAddr; + address _token = isEth ? wethAddr : token; + + TokenInterface tokenContract = TokenInterface(_token); + + _amt = _amt == uint256(-1) ? getPaybackBalance(_token, rateMode) : _amt; + + if (isEth) convertEthToWeth(isEth, tokenContract, _amt); + + approve(tokenContract, address(aave), _amt); + + aave.repay(_token, _amt, rateMode, address(this)); + + setUint(setId, _amt); + + _eventName = "LogPayback(address,uint256,uint256,uint256,uint256)"; + _eventParam = abi.encode(token, _amt, rateMode, getId, setId); + } + + /** + * @dev Payback borrowed ETH/ERC20_Token using aTokens. + * @notice Repays a borrowed `amount` on a specific reserve using the reserve aTokens, burning the equivalent debt tokens. + * @param token The address of the token to payback.(For ETH: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) + * @param amt The amount of the token to payback. (For max: `uint256(-1)`) + * @param rateMode The type of debt paying back. (For Stable: 1, Variable: 2) + * @param getId ID to retrieve amt. + * @param setId ID stores the amount of tokens paid back. + */ + function paybackWithATokens( + address token, + uint256 amt, + uint256 rateMode, + uint256 getId, + uint256 setId + ) + external + payable + returns (string memory _eventName, bytes memory _eventParam) + { + uint256 _amt = getUint(getId, amt); + + AaveInterface aave = AaveInterface(aaveProvider.getPool()); + + bool isEth = token == ethAddr; + address _token = isEth ? wethAddr : token; + + TokenInterface tokenContract = TokenInterface(_token); + + _amt = _amt == uint256(-1) ? getPaybackBalance(_token, rateMode) : _amt; + + if (isEth) convertEthToWeth(isEth, tokenContract, _amt); + + approve(tokenContract, address(aave), _amt); + + aave.repayWithATokens(_token, _amt, rateMode); + + setUint(setId, _amt); + + _eventName = "LogPayback(address,uint256,uint256,uint256,uint256)"; + _eventParam = abi.encode(token, _amt, rateMode, getId, setId); + } + + /** + * @dev Enable collateral + * @notice Enable an array of tokens as collateral + * @param tokens Array of tokens to enable collateral + */ + function enableCollateral(address[] calldata tokens) + external + payable + returns (string memory _eventName, bytes memory _eventParam) + { + uint256 _length = tokens.length; + require(_length > 0, "0-tokens-not-allowed"); + + AaveInterface aave = AaveInterface(aaveProvider.getPool()); + + for (uint256 i = 0; i < _length; i++) { + address token = tokens[i]; + if (getCollateralBalance(token) > 0 && !getIsColl(token)) { + aave.setUserUseReserveAsCollateral(token, true); + } + } + + _eventName = "LogEnableCollateral(address[])"; + _eventParam = abi.encode(tokens); + } + + /** + * @dev Swap borrow rate mode + * @notice Swaps user borrow rate mode between variable and stable + * @param token The address of the token to swap borrow rate.(For ETH: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) + * @param rateMode Desired borrow rate mode. (Stable = 1, Variable = 2) + */ + function swapBorrowRateMode(address token, uint256 rateMode) + external + payable + returns (string memory _eventName, bytes memory _eventParam) + { + AaveInterface aave = AaveInterface(aaveProvider.getPool()); + + uint256 currentRateMode = rateMode == 1 ? 2 : 1; + + if (getPaybackBalance(token, currentRateMode) > 0) { + aave.swapBorrowRateMode(token, rateMode); + } + + _eventName = "LogSwapRateMode(address,uint256)"; + _eventParam = abi.encode(token, rateMode); + } + + /** + * @dev Set user e-mode + * @notice Updates the user's e-mode category + * @param categoryId The category Id of the e-mode user want to set + */ + function setUserEMode(uint8 categoryId) + external + returns (string memory _eventName, bytes memory _eventParam) + { + AaveInterface aave = AaveInterface(aaveProvider.getPool()); + + aave.setUserEMode(categoryId); + + _eventName = "LogSetUserEMode(uint8)"; + _eventParam = abi.encode(categoryId); + } +} + +contract ConnectV2AaveV3 is AaveResolver { + string public constant name = "AaveV3-v1.0"; +} diff --git a/contracts/optimism/connectors/aave/v3/events.sol b/contracts/optimism/connectors/aave/v3/events.sol new file mode 100644 index 00000000..9f60f22b --- /dev/null +++ b/contracts/optimism/connectors/aave/v3/events.sol @@ -0,0 +1,33 @@ +pragma solidity ^0.7.0; + +contract Events { + event LogDeposit( + address indexed token, + uint256 tokenAmt, + uint256 getId, + uint256 setId + ); + event LogWithdraw( + address indexed token, + uint256 tokenAmt, + uint256 getId, + uint256 setId + ); + event LogBorrow( + address indexed token, + uint256 tokenAmt, + uint256 indexed rateMode, + uint256 getId, + uint256 setId + ); + event LogPayback( + address indexed token, + uint256 tokenAmt, + uint256 indexed rateMode, + uint256 getId, + uint256 setId + ); + event LogEnableCollateral(address[] tokens); + event LogSwapRateMode(address indexed token, uint256 rateMode); + event LogSetUserEMode(uint8 categoryId); +} diff --git a/contracts/optimism/connectors/aave/v3/helpers.sol b/contracts/optimism/connectors/aave/v3/helpers.sol new file mode 100644 index 00000000..f0fd9188 --- /dev/null +++ b/contracts/optimism/connectors/aave/v3/helpers.sol @@ -0,0 +1,66 @@ +pragma solidity ^0.7.0; + +import { DSMath } from "../../../common/math.sol"; +import { Basic } from "../../../common/basic.sol"; +import { AavePoolProviderInterface, AaveDataProviderInterface } from "./interface.sol"; + +abstract contract Helpers is DSMath, Basic { + /** + * @dev Aave Pool Provider + */ + AavePoolProviderInterface internal constant aaveProvider = + AavePoolProviderInterface(0xa97684ead0e402dC232d5A977953DF7ECBaB3CDb); // Optimism address - PoolAddressesProvider + + /** + * @dev Aave Pool Data Provider + */ + AaveDataProviderInterface internal constant aaveData = + AaveDataProviderInterface(0x69FA688f1Dc47d4B5d8029D5a35FB7a548310654); // Optimism address - PoolDataProvider + + /** + * @dev Aave Referral Code + */ + uint16 internal constant referralCode = 3228; + + /** + * @dev Checks if collateral is enabled for an asset + * @param token token address of the asset.(For ETH: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) + */ + + function getIsColl(address token) internal view returns (bool isCol) { + (, , , , , , , , isCol) = aaveData.getUserReserveData( + token, + address(this) + ); + } + + /** + * @dev Get total debt balance & fee for an asset + * @param token token address of the debt.(For ETH: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) + * @param rateMode Borrow rate mode (Stable = 1, Variable = 2) + */ + function getPaybackBalance(address token, uint256 rateMode) + internal + view + returns (uint256) + { + (, uint256 stableDebt, uint256 variableDebt, , , , , , ) = aaveData + .getUserReserveData(token, address(this)); + return rateMode == 1 ? stableDebt : variableDebt; + } + + /** + * @dev Get total collateral balance for an asset + * @param token token address of the collateral.(For ETH: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) + */ + function getCollateralBalance(address token) + internal + view + returns (uint256 bal) + { + (bal, , , , , , , , ) = aaveData.getUserReserveData( + token, + address(this) + ); + } +} diff --git a/contracts/optimism/connectors/aave/v3/interface.sol b/contracts/optimism/connectors/aave/v3/interface.sol new file mode 100644 index 00000000..8ae14716 --- /dev/null +++ b/contracts/optimism/connectors/aave/v3/interface.sol @@ -0,0 +1,91 @@ +pragma solidity ^0.7.0; + +interface AaveInterface { + function supply( + address asset, + uint256 amount, + address onBehalfOf, + uint16 referralCode + ) external; + + function withdraw( + address asset, + uint256 amount, + address to + ) external returns (uint256); + + function borrow( + address asset, + uint256 amount, + uint256 interestRateMode, + uint16 referralCode, + address onBehalfOf + ) external; + + function repay( + address asset, + uint256 amount, + uint256 interestRateMode, + address onBehalfOf + ) external returns (uint256); + + function repayWithATokens( + address asset, + uint256 amount, + uint256 interestRateMode + ) external returns (uint256); + + function setUserUseReserveAsCollateral(address asset, bool useAsCollateral) + external; + + function swapBorrowRateMode(address asset, uint256 interestRateMode) + external; + + function setUserEMode(uint8 categoryId) external; +} + +interface AavePoolProviderInterface { + function getPool() external view returns (address); +} + +interface AaveDataProviderInterface { + function getReserveTokensAddresses(address _asset) + external + view + returns ( + address aTokenAddress, + address stableDebtTokenAddress, + address variableDebtTokenAddress + ); + + function getUserReserveData(address _asset, address _user) + external + view + returns ( + uint256 currentATokenBalance, + uint256 currentStableDebt, + uint256 currentVariableDebt, + uint256 principalStableDebt, + uint256 scaledVariableDebt, + uint256 stableBorrowRate, + uint256 liquidityRate, + uint40 stableRateLastUpdated, + bool usageAsCollateralEnabled + ); + + function getReserveEModeCategory(address asset) + external + view + returns (uint256); +} + +interface AaveAddressProviderRegistryInterface { + function getAddressesProvidersList() + external + view + returns (address[] memory); +} + +interface ATokenInterface { + function balanceOf(address _user) external view returns (uint256); +} diff --git a/contracts/optimism/connectors/aave/v3/main.sol b/contracts/optimism/connectors/aave/v3/main.sol new file mode 100644 index 00000000..62be7a41 --- /dev/null +++ b/contracts/optimism/connectors/aave/v3/main.sol @@ -0,0 +1,296 @@ +pragma solidity ^0.7.0; + +/** + * @title Aave v3. + * @dev Lending & Borrowing. + */ + +import { TokenInterface } from "../../../common/interfaces.sol"; +import { Stores } from "../../../common/stores.sol"; +import { Helpers } from "./helpers.sol"; +import { Events } from "./events.sol"; +import { AaveInterface } from "./interface.sol"; + +abstract contract AaveResolver is Events, Helpers { + /** + * @dev Deposit ETH/ERC20_Token. + * @notice Deposit a token to Aave v3 for lending / collaterization. + * @param token The address of the token to deposit.(For ETH: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) + * @param amt The amount of the token to deposit. (For max: `uint256(-1)`) + * @param getId ID to retrieve amt. + * @param setId ID stores the amount of tokens deposited. + */ + function deposit( + address token, + uint256 amt, + uint256 getId, + uint256 setId + ) + external + payable + returns (string memory _eventName, bytes memory _eventParam) + { + uint256 _amt = getUint(getId, amt); + + AaveInterface aave = AaveInterface(aaveProvider.getPool()); + + bool isEth = token == ethAddr; + address _token = isEth ? wethAddr : token; + + TokenInterface tokenContract = TokenInterface(_token); + + if (isEth) { + _amt = _amt == uint256(-1) ? address(this).balance : _amt; + convertEthToWeth(isEth, tokenContract, _amt); + } else { + _amt = _amt == uint256(-1) + ? tokenContract.balanceOf(address(this)) + : _amt; + } + + approve(tokenContract, address(aave), _amt); + + aave.supply(_token, _amt, address(this), referralCode); + + if (!getIsColl(_token)) { + aave.setUserUseReserveAsCollateral(_token, true); + } + + setUint(setId, _amt); + + _eventName = "LogDeposit(address,uint256,uint256,uint256)"; + _eventParam = abi.encode(token, _amt, getId, setId); + } + + /** + * @dev Withdraw ETH/ERC20_Token. + * @notice Withdraw deposited token from Aave v3 + * @param token The address of the token to withdraw.(For ETH: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) + * @param amt The amount of the token to withdraw. (For max: `uint256(-1)`) + * @param getId ID to retrieve amt. + * @param setId ID stores the amount of tokens withdrawn. + */ + function withdraw( + address token, + uint256 amt, + uint256 getId, + uint256 setId + ) + external + payable + returns (string memory _eventName, bytes memory _eventParam) + { + uint256 _amt = getUint(getId, amt); + + AaveInterface aave = AaveInterface(aaveProvider.getPool()); + bool isEth = token == ethAddr; + address _token = isEth ? wethAddr : token; + + TokenInterface tokenContract = TokenInterface(_token); + + uint256 initialBal = tokenContract.balanceOf(address(this)); + aave.withdraw(_token, _amt, address(this)); + uint256 finalBal = tokenContract.balanceOf(address(this)); + + _amt = sub(finalBal, initialBal); + + convertWethToEth(isEth, tokenContract, _amt); + + setUint(setId, _amt); + + _eventName = "LogWithdraw(address,uint256,uint256,uint256)"; + _eventParam = abi.encode(token, _amt, getId, setId); + } + + /** + * @dev Borrow ETH/ERC20_Token. + * @notice Borrow a token using Aave v3 + * @param token The address of the token to borrow.(For ETH: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) + * @param amt The amount of the token to borrow. + * @param rateMode The type of borrow debt. (For Stable: 1, Variable: 2) + * @param getId ID to retrieve amt. + * @param setId ID stores the amount of tokens borrowed. + */ + function borrow( + address token, + uint256 amt, + uint256 rateMode, + uint256 getId, + uint256 setId + ) + external + payable + returns (string memory _eventName, bytes memory _eventParam) + { + uint256 _amt = getUint(getId, amt); + + AaveInterface aave = AaveInterface(aaveProvider.getPool()); + + bool isEth = token == ethAddr; + address _token = isEth ? wethAddr : token; + + aave.borrow(_token, _amt, rateMode, referralCode, address(this)); + convertWethToEth(isEth, TokenInterface(_token), _amt); + + setUint(setId, _amt); + + _eventName = "LogBorrow(address,uint256,uint256,uint256,uint256)"; + _eventParam = abi.encode(token, _amt, rateMode, getId, setId); + } + + /** + * @dev Payback borrowed ETH/ERC20_Token. + * @notice Payback debt owed. + * @param token The address of the token to payback.(For ETH: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) + * @param amt The amount of the token to payback. (For max: `uint256(-1)`) + * @param rateMode The type of debt paying back. (For Stable: 1, Variable: 2) + * @param getId ID to retrieve amt. + * @param setId ID stores the amount of tokens paid back. + */ + function payback( + address token, + uint256 amt, + uint256 rateMode, + uint256 getId, + uint256 setId + ) + external + payable + returns (string memory _eventName, bytes memory _eventParam) + { + uint256 _amt = getUint(getId, amt); + + AaveInterface aave = AaveInterface(aaveProvider.getPool()); + + bool isEth = token == ethAddr; + address _token = isEth ? wethAddr : token; + + TokenInterface tokenContract = TokenInterface(_token); + + _amt = _amt == uint256(-1) ? getPaybackBalance(_token, rateMode) : _amt; + + if (isEth) convertEthToWeth(isEth, tokenContract, _amt); + + approve(tokenContract, address(aave), _amt); + + aave.repay(_token, _amt, rateMode, address(this)); + + setUint(setId, _amt); + + _eventName = "LogPayback(address,uint256,uint256,uint256,uint256)"; + _eventParam = abi.encode(token, _amt, rateMode, getId, setId); + } + + /** + * @dev Payback borrowed ETH/ERC20_Token using aTokens. + * @notice Repays a borrowed `amount` on a specific reserve using the reserve aTokens, burning the equivalent debt tokens. + * @param token The address of the token to payback.(For ETH: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) + * @param amt The amount of the token to payback. (For max: `uint256(-1)`) + * @param rateMode The type of debt paying back. (For Stable: 1, Variable: 2) + * @param getId ID to retrieve amt. + * @param setId ID stores the amount of tokens paid back. + */ + function paybackWithATokens( + address token, + uint256 amt, + uint256 rateMode, + uint256 getId, + uint256 setId + ) + external + payable + returns (string memory _eventName, bytes memory _eventParam) + { + uint256 _amt = getUint(getId, amt); + + AaveInterface aave = AaveInterface(aaveProvider.getPool()); + + bool isEth = token == ethAddr; + address _token = isEth ? wethAddr : token; + + TokenInterface tokenContract = TokenInterface(_token); + + _amt = _amt == uint256(-1) ? getPaybackBalance(_token, rateMode) : _amt; + + if (isEth) convertEthToWeth(isEth, tokenContract, _amt); + + approve(tokenContract, address(aave), _amt); + + aave.repayWithATokens(_token, _amt, rateMode); + + setUint(setId, _amt); + + _eventName = "LogPayback(address,uint256,uint256,uint256,uint256)"; + _eventParam = abi.encode(token, _amt, rateMode, getId, setId); + } + + /** + * @dev Enable collateral + * @notice Enable an array of tokens as collateral + * @param tokens Array of tokens to enable collateral + */ + function enableCollateral(address[] calldata tokens) + external + payable + returns (string memory _eventName, bytes memory _eventParam) + { + uint256 _length = tokens.length; + require(_length > 0, "0-tokens-not-allowed"); + + AaveInterface aave = AaveInterface(aaveProvider.getPool()); + + for (uint256 i = 0; i < _length; i++) { + address token = tokens[i]; + if (getCollateralBalance(token) > 0 && !getIsColl(token)) { + aave.setUserUseReserveAsCollateral(token, true); + } + } + + _eventName = "LogEnableCollateral(address[])"; + _eventParam = abi.encode(tokens); + } + + /** + * @dev Swap borrow rate mode + * @notice Swaps user borrow rate mode between variable and stable + * @param token The address of the token to swap borrow rate.(For ETH: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) + * @param rateMode Desired borrow rate mode. (Stable = 1, Variable = 2) + */ + function swapBorrowRateMode(address token, uint256 rateMode) + external + payable + returns (string memory _eventName, bytes memory _eventParam) + { + AaveInterface aave = AaveInterface(aaveProvider.getPool()); + + uint256 currentRateMode = rateMode == 1 ? 2 : 1; + + if (getPaybackBalance(token, currentRateMode) > 0) { + aave.swapBorrowRateMode(token, rateMode); + } + + _eventName = "LogSwapRateMode(address,uint256)"; + _eventParam = abi.encode(token, rateMode); + } + + /** + * @dev Set user e-mode + * @notice Updates the user's e-mode category + * @param categoryId The category Id of the e-mode user want to set + */ + function setUserEMode(uint8 categoryId) + external + returns (string memory _eventName, bytes memory _eventParam) + { + AaveInterface aave = AaveInterface(aaveProvider.getPool()); + + aave.setUserEMode(categoryId); + + _eventName = "LogSetUserEMode(uint8)"; + _eventParam = abi.encode(categoryId); + } +} + +contract ConnectV2AaveV3Optimism is AaveResolver { + string public constant name = "AaveV3-v1.0"; +} diff --git a/contracts/polygon/connectors/aave/v2-to-v3-import/events.sol b/contracts/polygon/connectors/aave/v2-to-v3-import/events.sol new file mode 100644 index 00000000..84bb146f --- /dev/null +++ b/contracts/polygon/connectors/aave/v2-to-v3-import/events.sol @@ -0,0 +1,15 @@ +pragma solidity ^0.7.0; + +contract Events { + event LogAaveImportV2ToV3( + address indexed user, + bool doImport, + bool convertStable, + address[] supplyTokens, + address[] borrowTokens, + uint256[] flashLoanFees, + uint256[] supplyAmts, + uint256[] stableBorrowAmts, + uint256[] variableBorrowAmts + ); +} diff --git a/contracts/polygon/connectors/aave/v2-to-v3-import/helpers.sol b/contracts/polygon/connectors/aave/v2-to-v3-import/helpers.sol new file mode 100644 index 00000000..5da70943 --- /dev/null +++ b/contracts/polygon/connectors/aave/v2-to-v3-import/helpers.sol @@ -0,0 +1,328 @@ +pragma solidity ^0.7.0; + +import { DSMath } from "../../../common/math.sol"; +import { Basic } from "../../../common/basic.sol"; +import { TokenInterface, AccountInterface } from "../../../common/interfaces.sol"; +import "./events.sol"; +import "./interfaces.sol"; + +abstract contract Helper is DSMath, Basic { + /** + * @dev Aave referal code + */ + uint16 internal constant referalCode = 3228; + + /** + * @dev AaveV2 Lending Pool Provider + */ + AaveV2LendingPoolProviderInterface internal constant aaveV2Provider = + AaveV2LendingPoolProviderInterface( + 0xd05e3E715d945B59290df0ae8eF85c1BdB684744 // v2 address + ); + + /** + * @dev AaveV3 Lending Pool Provider + */ + AaveV3PoolProviderInterface internal constant aaveV3Provider = + AaveV3PoolProviderInterface( + 0xa97684ead0e402dC232d5A977953DF7ECBaB3CDb // Polygon address - PoolAddressesProvider + ); + + /** + * @dev Aave Protocol Data Provider + */ + AaveV2DataProviderInterface internal constant aaveV2Data = + AaveV2DataProviderInterface(0x7551b5D2763519d4e37e8B81929D336De671d46d); // v2 address + + function getIsColl(address token, address user) + internal + view + returns (bool isCol) + { + (, , , , , , , , isCol) = aaveV2Data.getUserReserveData(token, user); + } + + struct ImportData { + address[] _supplyTokens; + address[] _borrowTokens; + ATokenV2Interface[] aTokens; + uint256[] supplyAmts; + uint256[] variableBorrowAmts; + uint256[] variableBorrowAmtsWithFee; + uint256[] stableBorrowAmts; + uint256[] stableBorrowAmtsWithFee; + uint256[] totalBorrowAmts; + uint256[] totalBorrowAmtsWithFee; + bool convertStable; + } + + struct ImportInputData { + address[] supplyTokens; + address[] borrowTokens; + bool convertStable; + uint256[] flashLoanFees; + } +} + +contract _AaveHelper is Helper { + function getBorrowAmountV2(address _token, address userAccount) + internal + view + returns (uint256 stableBorrow, uint256 variableBorrow) + { + ( + , + address stableDebtTokenAddress, + address variableDebtTokenAddress + ) = aaveV2Data.getReserveTokensAddresses(_token); + + stableBorrow = ATokenV2Interface(stableDebtTokenAddress).balanceOf( + userAccount + ); + variableBorrow = ATokenV2Interface(variableDebtTokenAddress).balanceOf( + userAccount + ); + } + + function getBorrowAmountsV2( + address userAccount, + AaveV2Interface aaveV2, + ImportInputData memory inputData, + ImportData memory data + ) internal returns (ImportData memory) { + if (inputData.borrowTokens.length > 0) { + data._borrowTokens = new address[](inputData.borrowTokens.length); + data.variableBorrowAmts = new uint256[]( + inputData.borrowTokens.length + ); + data.stableBorrowAmts = new uint256[]( + inputData.borrowTokens.length + ); + data.totalBorrowAmts = new uint256[](inputData.borrowTokens.length); + for (uint256 i = 0; i < inputData.borrowTokens.length; i++) { + for (uint256 j = i; j < inputData.borrowTokens.length; j++) { + if (j != i) { + require( + inputData.borrowTokens[i] != + inputData.borrowTokens[j], + "token-repeated" + ); + } + } + } + for (uint256 i = 0; i < inputData.borrowTokens.length; i++) { + address _token = inputData.borrowTokens[i] == maticAddr + ? wmaticAddr + : inputData.borrowTokens[i]; + data._borrowTokens[i] = _token; + + ( + data.stableBorrowAmts[i], + data.variableBorrowAmts[i] + ) = getBorrowAmountV2(_token, userAccount); + + if (data.variableBorrowAmts[i] != 0) { + data.variableBorrowAmtsWithFee[i] = add( + data.variableBorrowAmts[i], + inputData.flashLoanFees[i] + ); + data.stableBorrowAmtsWithFee[i] = data.stableBorrowAmts[i]; + } else { + data.stableBorrowAmtsWithFee[i] = add( + data.stableBorrowAmts[i], + inputData.flashLoanFees[i] + ); + } + + data.totalBorrowAmts[i] = add( + data.stableBorrowAmts[i], + data.variableBorrowAmts[i] + ); + data.totalBorrowAmtsWithFee[i] = add( + data.stableBorrowAmtsWithFee[i], + data.variableBorrowAmtsWithFee[i] + ); + + if (data.totalBorrowAmts[i] > 0) { + uint256 _amt = data.totalBorrowAmts[i]; + TokenInterface(_token).approve(address(aaveV2), _amt); + } + } + } + return data; + } + + function getSupplyAmountsV2( + address userAccount, + ImportInputData memory inputData, + ImportData memory data + ) internal view returns (ImportData memory) { + data.supplyAmts = new uint256[](inputData.supplyTokens.length); + data._supplyTokens = new address[](inputData.supplyTokens.length); + data.aTokens = new ATokenV2Interface[](inputData.supplyTokens.length); + + for (uint256 i = 0; i < inputData.supplyTokens.length; i++) { + for (uint256 j = i; j < inputData.supplyTokens.length; j++) { + if (j != i) { + require( + inputData.supplyTokens[i] != inputData.supplyTokens[j], + "token-repeated" + ); + } + } + } + for (uint256 i = 0; i < inputData.supplyTokens.length; i++) { + address _token = inputData.supplyTokens[i] == maticAddr + ? wmaticAddr + : inputData.supplyTokens[i]; + (address _aToken, , ) = aaveV2Data.getReserveTokensAddresses( + _token + ); + data._supplyTokens[i] = _token; + data.aTokens[i] = ATokenV2Interface(_aToken); + data.supplyAmts[i] = data.aTokens[i].balanceOf(userAccount); + } + + return data; + } + + function _paybackBehalfOneV2( + AaveV2Interface aaveV2, + address token, + uint256 amt, + uint256 rateMode, + address user + ) private { + aaveV2.repay(token, amt, rateMode, user); + } + + function _PaybackStableV2( + uint256 _length, + AaveV2Interface aaveV2, + address[] memory tokens, + uint256[] memory amts, + address user + ) internal { + for (uint256 i = 0; i < _length; i++) { + if (amts[i] > 0) { + _paybackBehalfOneV2(aaveV2, tokens[i], amts[i], 1, user); + } + } + } + + function _PaybackVariableV2( + uint256 _length, + AaveV2Interface aaveV2, + address[] memory tokens, + uint256[] memory amts, + address user + ) internal { + for (uint256 i = 0; i < _length; i++) { + if (amts[i] > 0) { + _paybackBehalfOneV2(aaveV2, tokens[i], amts[i], 2, user); + } + } + } + + function _TransferAtokensV2( + uint256 _length, + AaveV2Interface aaveV2, + ATokenV2Interface[] memory atokenContracts, + uint256[] memory amts, + address[] memory tokens, + address userAccount + ) internal { + for (uint256 i = 0; i < _length; i++) { + if (amts[i] > 0) { + uint256 _amt = amts[i]; + require( + atokenContracts[i].transferFrom( + userAccount, + address(this), + _amt + ), + "allowance?" + ); + + if (!getIsColl(tokens[i], address(this))) { + aaveV2.setUserUseReserveAsCollateral(tokens[i], true); + } + } + } + } + + function _WithdrawTokensFromV2( + uint256 _length, + AaveV2Interface aaveV2, + uint256[] memory amts, + address[] memory tokens + ) internal { + for (uint256 i = 0; i < _length; i++) { + if (amts[i] > 0) { + uint256 _amt = amts[i]; + address _token = tokens[i]; + aaveV2.withdraw(_token, _amt, address(this)); + } + } + } + + function _depositTokensV3( + uint256 _length, + AaveV3Interface aaveV3, + uint256[] memory amts, + address[] memory tokens + ) internal { + for (uint256 i = 0; i < _length; i++) { + if (amts[i] > 0) { + uint256 _amt = amts[i]; + address _token = tokens[i]; + TokenInterface tokenContract = TokenInterface(_token); + require( + tokenContract.balanceOf(address(this)) >= _amt, + "Insufficient funds to deposit in v3" + ); + approve(tokenContract, address(aaveV3), _amt); + aaveV3.supply(_token, _amt, address(this), referalCode); + + if (!getIsColl(_token, address(this))) { + aaveV3.setUserUseReserveAsCollateral(_token, true); + } + } + } + } + + function _BorrowVariableV3( + uint256 _length, + AaveV3Interface aaveV3, + address[] memory tokens, + uint256[] memory amts + ) internal { + for (uint256 i = 0; i < _length; i++) { + if (amts[i] > 0) { + _borrowOneV3(aaveV3, tokens[i], amts[i], 2); + } + } + } + + function _BorrowStableV3( + uint256 _length, + AaveV3Interface aaveV3, + address[] memory tokens, + uint256[] memory amts + ) internal { + for (uint256 i = 0; i < _length; i++) { + if (amts[i] > 0) { + _borrowOneV3(aaveV3, tokens[i], amts[i], 1); + } + } + } + + function _borrowOneV3( + AaveV3Interface aaveV3, + address token, + uint256 amt, + uint256 rateMode + ) private { + aaveV3.borrow(token, amt, rateMode, referalCode, address(this)); + } +} diff --git a/contracts/polygon/connectors/aave/v2-to-v3-import/interfaces.sol b/contracts/polygon/connectors/aave/v2-to-v3-import/interfaces.sol new file mode 100644 index 00000000..b28f49e0 --- /dev/null +++ b/contracts/polygon/connectors/aave/v2-to-v3-import/interfaces.sol @@ -0,0 +1,150 @@ +pragma solidity ^0.7.0; +pragma experimental ABIEncoderV2; + +// aave v2 +interface AaveV2Interface { + function withdraw( + address _asset, + uint256 _amount, + address _to + ) external; + + function borrow( + address _asset, + uint256 _amount, + uint256 _interestRateMode, + uint16 _referralCode, + address _onBehalfOf + ) external; + + function repay( + address _asset, + uint256 _amount, + uint256 _rateMode, + address _onBehalfOf + ) external; + + function setUserUseReserveAsCollateral( + address _asset, + bool _useAsCollateral + ) external; + + function getUserAccountData(address user) + external + view + returns ( + uint256 totalCollateralETH, + uint256 totalDebtETH, + uint256 availableBorrowsETH, + uint256 currentLiquidationThreshold, + uint256 ltv, + uint256 healthFactor + ); +} + +interface AaveV2LendingPoolProviderInterface { + function getLendingPool() external view returns (address); +} + +// Aave Protocol Data Provider +interface AaveV2DataProviderInterface { + function getUserReserveData(address _asset, address _user) + external + view + returns ( + uint256 currentATokenBalance, + uint256 currentStableDebt, + uint256 currentVariableDebt, + uint256 principalStableDebt, + uint256 scaledVariableDebt, + uint256 stableBorrowRate, + uint256 liquidityRate, + uint40 stableRateLastUpdated, + bool usageAsCollateralEnabled + ); + + // function getReserveConfigurationData(address asset) + // external + // view + // returns ( + // uint256 decimals, + // uint256 ltv, + // uint256 liquidationThreshold, + // uint256 liquidationBonus, + // uint256 reserveFactor, + // bool usageAsCollateralEnabled, + // bool borrowingEnabled, + // bool stableBorrowRateEnabled, + // bool isActive, + // bool isFrozen + // ); + + function getReserveTokensAddresses(address asset) + external + view + returns ( + address aTokenAddress, + address stableDebtTokenAddress, + address variableDebtTokenAddress + ); +} + +interface ATokenV2Interface { + function scaledBalanceOf(address _user) external view returns (uint256); + + function isTransferAllowed(address _user, uint256 _amount) + external + view + returns (bool); + + function balanceOf(address _user) external view returns (uint256); + + function transferFrom( + address, + address, + uint256 + ) external returns (bool); + + function allowance(address, address) external returns (uint256); +} + +// aave v3 +interface AaveV3Interface { + function supply( + address asset, + uint256 amount, + address onBehalfOf, + uint16 referralCode + ) external; + + function withdraw( + address asset, + uint256 amount, + address to + ) external returns (uint256); + + function borrow( + address asset, + uint256 amount, + uint256 interestRateMode, + uint16 referralCode, + address onBehalfOf + ) external; + + function repay( + address asset, + uint256 amount, + uint256 interestRateMode, + address onBehalfOf + ) external returns (uint256); + + function setUserUseReserveAsCollateral(address asset, bool useAsCollateral) + external; + + function swapBorrowRateMode(address asset, uint256 interestRateMode) + external; +} + +interface AaveV3PoolProviderInterface { + function getPool() external view returns (address); +} diff --git a/contracts/polygon/connectors/aave/v2-to-v3-import/main.sol b/contracts/polygon/connectors/aave/v2-to-v3-import/main.sol new file mode 100644 index 00000000..06a7d43b --- /dev/null +++ b/contracts/polygon/connectors/aave/v2-to-v3-import/main.sol @@ -0,0 +1,160 @@ +pragma solidity ^0.7.0; +pragma experimental ABIEncoderV2; + +/** + * @title Aave v2 to v3 import connector . + * @dev migrate aave V2 position to aave v3 position + */ + +import { TokenInterface, AccountInterface } from "../../../common/interfaces.sol"; +import "./interfaces.sol"; +import "./helpers.sol"; +import "./events.sol"; + +contract _AaveV2ToV3MigrationResolver is _AaveHelper { + /** + * @dev Import aave position . + * @notice Import EOA's or DSA's aave V2 position to DSA's aave v3 position + * @param userAccount The address of the EOA from which aave position will be imported + * @param inputData The struct containing all the neccessary input data + * @param doImport boolean, to support DSA v2->v3 migration + */ + function _importAave( + address userAccount, + ImportInputData memory inputData, + bool doImport + ) internal returns (string memory _eventName, bytes memory _eventParam) { + if (doImport) { + // check only when we are importing from user's address + require( + AccountInterface(address(this)).isAuth(userAccount), + "user-account-not-auth" + ); + } + + require(inputData.supplyTokens.length > 0, "0-length-not-allowed"); + + ImportData memory data; + + AaveV2Interface aaveV2 = AaveV2Interface( + aaveV2Provider.getLendingPool() + ); + AaveV3Interface aaveV3 = AaveV3Interface(aaveV3Provider.getPool()); + + data = getBorrowAmountsV2(userAccount, aaveV2, inputData, data); + data = getSupplyAmountsV2(userAccount, inputData, data); + + // payback borrowed amount; + _PaybackStableV2( + data._borrowTokens.length, + aaveV2, + data._borrowTokens, + data.stableBorrowAmts, + userAccount + ); + _PaybackVariableV2( + data._borrowTokens.length, + aaveV2, + data._borrowTokens, + data.variableBorrowAmts, + userAccount + ); + + if (doImport) { + // transfer atokens to user's DSA address; + _TransferAtokensV2( + data._supplyTokens.length, + aaveV2, + data.aTokens, + data.supplyAmts, + data._supplyTokens, + userAccount + ); + } + + // withdraw v2 supplied tokens + _WithdrawTokensFromV2( + data._supplyTokens.length, + aaveV2, + data.supplyAmts, + data._supplyTokens + ); + // deposit tokens in v3 + _depositTokensV3( + data._supplyTokens.length, + aaveV3, + data.supplyAmts, + data._supplyTokens + ); + + // borrow assets in aave v3 after migrating position + if (data.convertStable) { + _BorrowVariableV3( + data._borrowTokens.length, + aaveV3, + data._borrowTokens, + data.totalBorrowAmtsWithFee + ); + } else { + _BorrowStableV3( + data._borrowTokens.length, + aaveV3, + data._borrowTokens, + data.stableBorrowAmtsWithFee + ); + _BorrowVariableV3( + data._borrowTokens.length, + aaveV3, + data._borrowTokens, + data.variableBorrowAmtsWithFee + ); + } + + _eventName = "LogAaveImportV2ToV3(address,bool,bool,address[],address[],uint256[],uint256[],uint256[],uint256[])"; + _eventParam = abi.encode( + userAccount, + doImport, + inputData.convertStable, + inputData.supplyTokens, + inputData.borrowTokens, + inputData.flashLoanFees, + data.supplyAmts, + data.stableBorrowAmts, + data.variableBorrowAmts + ); + } + + /** + * @dev Import aave position . + * @notice Import EOA's aave V2 position to DSA's aave v3 position + * @param userAccount The address of the EOA from which aave position will be imported + * @param inputData The struct containing all the neccessary input data + */ + function importAaveV2ToV3( + address userAccount, + ImportInputData memory inputData + ) + external + payable + returns (string memory _eventName, bytes memory _eventParam) + { + (_eventName, _eventParam) = _importAave(userAccount, inputData, true); + } + + /** + * @dev Migrate aave position . + * @notice Migrate DSA's aave V2 position to DSA's aave v3 position + * @param inputData The struct containing all the neccessary input data + */ + function migrateAaveV2ToV3(ImportInputData memory inputData) + external + payable + returns (string memory _eventName, bytes memory _eventParam) + { + (_eventName, _eventParam) = _importAave(msg.sender, inputData, false); + } +} + +contract ConnectV2AaveV2ToV3MigrationPolygon is _AaveV2ToV3MigrationResolver { + string public constant name = "Aave-Import-v2-to-v3"; +} diff --git a/contracts/polygon/connectors/aave/v3/events.sol b/contracts/polygon/connectors/aave/v3/events.sol new file mode 100644 index 00000000..9f60f22b --- /dev/null +++ b/contracts/polygon/connectors/aave/v3/events.sol @@ -0,0 +1,33 @@ +pragma solidity ^0.7.0; + +contract Events { + event LogDeposit( + address indexed token, + uint256 tokenAmt, + uint256 getId, + uint256 setId + ); + event LogWithdraw( + address indexed token, + uint256 tokenAmt, + uint256 getId, + uint256 setId + ); + event LogBorrow( + address indexed token, + uint256 tokenAmt, + uint256 indexed rateMode, + uint256 getId, + uint256 setId + ); + event LogPayback( + address indexed token, + uint256 tokenAmt, + uint256 indexed rateMode, + uint256 getId, + uint256 setId + ); + event LogEnableCollateral(address[] tokens); + event LogSwapRateMode(address indexed token, uint256 rateMode); + event LogSetUserEMode(uint8 categoryId); +} diff --git a/contracts/polygon/connectors/aave/v3/helpers.sol b/contracts/polygon/connectors/aave/v3/helpers.sol new file mode 100644 index 00000000..28447ee0 --- /dev/null +++ b/contracts/polygon/connectors/aave/v3/helpers.sol @@ -0,0 +1,66 @@ +pragma solidity ^0.7.0; + +import { DSMath } from "../../../common/math.sol"; +import { Basic } from "../../../common/basic.sol"; +import { AavePoolProviderInterface, AaveDataProviderInterface } from "./interface.sol"; + +abstract contract Helpers is DSMath, Basic { + /** + * @dev Aave Pool Provider + */ + AavePoolProviderInterface internal constant aaveProvider = + AavePoolProviderInterface(0xa97684ead0e402dC232d5A977953DF7ECBaB3CDb); // Polygon address - PoolAddressesProvider + + /** + * @dev Aave Pool Data Provider + */ + AaveDataProviderInterface internal constant aaveData = + AaveDataProviderInterface(0x69FA688f1Dc47d4B5d8029D5a35FB7a548310654); // Polygon address - PoolDataProvider + + /** + * @dev Aave Referral Code + */ + uint16 internal constant referralCode = 3228; + + /** + * @dev Checks if collateral is enabled for an asset + * @param token token address of the asset.(For ETH: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) + */ + + function getIsColl(address token) internal view returns (bool isCol) { + (, , , , , , , , isCol) = aaveData.getUserReserveData( + token, + address(this) + ); + } + + /** + * @dev Get total debt balance & fee for an asset + * @param token token address of the debt.(For ETH: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) + * @param rateMode Borrow rate mode (Stable = 1, Variable = 2) + */ + function getPaybackBalance(address token, uint256 rateMode) + internal + view + returns (uint256) + { + (, uint256 stableDebt, uint256 variableDebt, , , , , , ) = aaveData + .getUserReserveData(token, address(this)); + return rateMode == 1 ? stableDebt : variableDebt; + } + + /** + * @dev Get total collateral balance for an asset + * @param token token address of the collateral.(For ETH: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) + */ + function getCollateralBalance(address token) + internal + view + returns (uint256 bal) + { + (bal, , , , , , , , ) = aaveData.getUserReserveData( + token, + address(this) + ); + } +} diff --git a/contracts/polygon/connectors/aave/v3/interface.sol b/contracts/polygon/connectors/aave/v3/interface.sol new file mode 100644 index 00000000..8ae14716 --- /dev/null +++ b/contracts/polygon/connectors/aave/v3/interface.sol @@ -0,0 +1,91 @@ +pragma solidity ^0.7.0; + +interface AaveInterface { + function supply( + address asset, + uint256 amount, + address onBehalfOf, + uint16 referralCode + ) external; + + function withdraw( + address asset, + uint256 amount, + address to + ) external returns (uint256); + + function borrow( + address asset, + uint256 amount, + uint256 interestRateMode, + uint16 referralCode, + address onBehalfOf + ) external; + + function repay( + address asset, + uint256 amount, + uint256 interestRateMode, + address onBehalfOf + ) external returns (uint256); + + function repayWithATokens( + address asset, + uint256 amount, + uint256 interestRateMode + ) external returns (uint256); + + function setUserUseReserveAsCollateral(address asset, bool useAsCollateral) + external; + + function swapBorrowRateMode(address asset, uint256 interestRateMode) + external; + + function setUserEMode(uint8 categoryId) external; +} + +interface AavePoolProviderInterface { + function getPool() external view returns (address); +} + +interface AaveDataProviderInterface { + function getReserveTokensAddresses(address _asset) + external + view + returns ( + address aTokenAddress, + address stableDebtTokenAddress, + address variableDebtTokenAddress + ); + + function getUserReserveData(address _asset, address _user) + external + view + returns ( + uint256 currentATokenBalance, + uint256 currentStableDebt, + uint256 currentVariableDebt, + uint256 principalStableDebt, + uint256 scaledVariableDebt, + uint256 stableBorrowRate, + uint256 liquidityRate, + uint40 stableRateLastUpdated, + bool usageAsCollateralEnabled + ); + + function getReserveEModeCategory(address asset) + external + view + returns (uint256); +} + +interface AaveAddressProviderRegistryInterface { + function getAddressesProvidersList() + external + view + returns (address[] memory); +} + +interface ATokenInterface { + function balanceOf(address _user) external view returns (uint256); +} diff --git a/contracts/polygon/connectors/aave/v3/main.sol b/contracts/polygon/connectors/aave/v3/main.sol new file mode 100644 index 00000000..c7782667 --- /dev/null +++ b/contracts/polygon/connectors/aave/v3/main.sol @@ -0,0 +1,296 @@ +pragma solidity ^0.7.0; + +/** + * @title Aave v3. + * @dev Lending & Borrowing. + */ + +import { TokenInterface } from "../../../common/interfaces.sol"; +import { Stores } from "../../../common/stores.sol"; +import { Helpers } from "./helpers.sol"; +import { Events } from "./events.sol"; +import { AaveInterface } from "./interface.sol"; + +abstract contract AaveResolver is Events, Helpers { + /** + * @dev Deposit Matic/ERC20_Token. + * @notice Deposit a token to Aave v3 for lending / collaterization. + * @param token The address of the token to deposit.(For Matic: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) + * @param amt The amount of the token to deposit. (For max: `uint256(-1)`) + * @param getId ID to retrieve amt. + * @param setId ID stores the amount of tokens deposited. + */ + function deposit( + address token, + uint256 amt, + uint256 getId, + uint256 setId + ) + external + payable + returns (string memory _eventName, bytes memory _eventParam) + { + uint256 _amt = getUint(getId, amt); + + AaveInterface aave = AaveInterface(aaveProvider.getPool()); + + bool isMatic = token == maticAddr; + address _token = isMatic ? wmaticAddr : token; + + TokenInterface tokenContract = TokenInterface(_token); + + if (isMatic) { + _amt = _amt == uint256(-1) ? address(this).balance : _amt; + convertMaticToWmatic(isMatic, tokenContract, _amt); + } else { + _amt = _amt == uint256(-1) + ? tokenContract.balanceOf(address(this)) + : _amt; + } + + approve(tokenContract, address(aave), _amt); + + aave.supply(_token, _amt, address(this), referralCode); + + if (!getIsColl(_token)) { + aave.setUserUseReserveAsCollateral(_token, true); + } + + setUint(setId, _amt); + + _eventName = "LogDeposit(address,uint256,uint256,uint256)"; + _eventParam = abi.encode(token, _amt, getId, setId); + } + + /** + * @dev Withdraw matic/ERC20_Token. + * @notice Withdraw deposited token from Aave v3 + * @param token The address of the token to withdraw.(For matic: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) + * @param amt The amount of the token to withdraw. (For max: `uint256(-1)`) + * @param getId ID to retrieve amt. + * @param setId ID stores the amount of tokens withdrawn. + */ + function withdraw( + address token, + uint256 amt, + uint256 getId, + uint256 setId + ) + external + payable + returns (string memory _eventName, bytes memory _eventParam) + { + uint256 _amt = getUint(getId, amt); + + AaveInterface aave = AaveInterface(aaveProvider.getPool()); + bool isMatic = token == maticAddr; + address _token = isMatic ? wmaticAddr : token; + + TokenInterface tokenContract = TokenInterface(_token); + + uint256 initialBal = tokenContract.balanceOf(address(this)); + aave.withdraw(_token, _amt, address(this)); + uint256 finalBal = tokenContract.balanceOf(address(this)); + + _amt = sub(finalBal, initialBal); + + convertWmaticToMatic(isMatic, tokenContract, _amt); + + setUint(setId, _amt); + + _eventName = "LogWithdraw(address,uint256,uint256,uint256)"; + _eventParam = abi.encode(token, _amt, getId, setId); + } + + /** + * @dev Borrow matic/ERC20_Token. + * @notice Borrow a token using Aave v3 + * @param token The address of the token to borrow.(For matic: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) + * @param amt The amount of the token to borrow. + * @param rateMode The type of borrow debt. (For Stable: 1, Variable: 2) + * @param getId ID to retrieve amt. + * @param setId ID stores the amount of tokens borrowed. + */ + function borrow( + address token, + uint256 amt, + uint256 rateMode, + uint256 getId, + uint256 setId + ) + external + payable + returns (string memory _eventName, bytes memory _eventParam) + { + uint256 _amt = getUint(getId, amt); + + AaveInterface aave = AaveInterface(aaveProvider.getPool()); + + bool isMatic = token == maticAddr; + address _token = isMatic ? wmaticAddr : token; + + aave.borrow(_token, _amt, rateMode, referralCode, address(this)); + convertWmaticToMatic(isMatic, TokenInterface(_token), _amt); + + setUint(setId, _amt); + + _eventName = "LogBorrow(address,uint256,uint256,uint256,uint256)"; + _eventParam = abi.encode(token, _amt, rateMode, getId, setId); + } + + /** + * @dev Payback borrowed matic/ERC20_Token. + * @notice Payback debt owed. + * @param token The address of the token to payback.(For matic: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) + * @param amt The amount of the token to payback. (For max: `uint256(-1)`) + * @param rateMode The type of debt paying back. (For Stable: 1, Variable: 2) + * @param getId ID to retrieve amt. + * @param setId ID stores the amount of tokens paid back. + */ + function payback( + address token, + uint256 amt, + uint256 rateMode, + uint256 getId, + uint256 setId + ) + external + payable + returns (string memory _eventName, bytes memory _eventParam) + { + uint256 _amt = getUint(getId, amt); + + AaveInterface aave = AaveInterface(aaveProvider.getPool()); + + bool isMatic = token == maticAddr; + address _token = isMatic ? wmaticAddr : token; + + TokenInterface tokenContract = TokenInterface(_token); + + _amt = _amt == uint256(-1) ? getPaybackBalance(_token, rateMode) : _amt; + + if (isMatic) convertMaticToWmatic(isMatic, tokenContract, _amt); + + approve(tokenContract, address(aave), _amt); + + aave.repay(_token, _amt, rateMode, address(this)); + + setUint(setId, _amt); + + _eventName = "LogPayback(address,uint256,uint256,uint256,uint256)"; + _eventParam = abi.encode(token, _amt, rateMode, getId, setId); + } + + /** + * @dev Payback borrowed matic/ERC20_Token using aTokens. + * @notice Repays a borrowed `amount` on a specific reserve using the reserve aTokens, burning the equivalent debt tokens. + * @param token The address of the token to payback.(For matic: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) + * @param amt The amount of the token to payback. (For max: `uint256(-1)`) + * @param rateMode The type of debt paying back. (For Stable: 1, Variable: 2) + * @param getId ID to retrieve amt. + * @param setId ID stores the amount of tokens paid back. + */ + function paybackWithATokens( + address token, + uint256 amt, + uint256 rateMode, + uint256 getId, + uint256 setId + ) + external + payable + returns (string memory _eventName, bytes memory _eventParam) + { + uint256 _amt = getUint(getId, amt); + + AaveInterface aave = AaveInterface(aaveProvider.getPool()); + + bool isMatic = token == maticAddr; + address _token = isMatic ? wmaticAddr : token; + + TokenInterface tokenContract = TokenInterface(_token); + + _amt = _amt == uint256(-1) ? getPaybackBalance(_token, rateMode) : _amt; + + if (isMatic) convertMaticToWmatic(isMatic, tokenContract, _amt); + + approve(tokenContract, address(aave), _amt); + + aave.repayWithATokens(_token, _amt, rateMode); + + setUint(setId, _amt); + + _eventName = "LogPayback(address,uint256,uint256,uint256,uint256)"; + _eventParam = abi.encode(token, _amt, rateMode, getId, setId); + } + + /** + * @dev Enable collateral + * @notice Enable an array of tokens as collateral + * @param tokens Array of tokens to enable collateral + */ + function enableCollateral(address[] calldata tokens) + external + payable + returns (string memory _eventName, bytes memory _eventParam) + { + uint256 _length = tokens.length; + require(_length > 0, "0-tokens-not-allowed"); + + AaveInterface aave = AaveInterface(aaveProvider.getPool()); + + for (uint256 i = 0; i < _length; i++) { + address token = tokens[i]; + if (getCollateralBalance(token) > 0 && !getIsColl(token)) { + aave.setUserUseReserveAsCollateral(token, true); + } + } + + _eventName = "LogEnableCollateral(address[])"; + _eventParam = abi.encode(tokens); + } + + /** + * @dev Swap borrow rate mode + * @notice Swaps user borrow rate mode between variable and stable + * @param token The address of the token to swap borrow rate.(For matic: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) + * @param rateMode Desired borrow rate mode. (Stable = 1, Variable = 2) + */ + function swapBorrowRateMode(address token, uint256 rateMode) + external + payable + returns (string memory _eventName, bytes memory _eventParam) + { + AaveInterface aave = AaveInterface(aaveProvider.getPool()); + + uint256 currentRateMode = rateMode == 1 ? 2 : 1; + + if (getPaybackBalance(token, currentRateMode) > 0) { + aave.swapBorrowRateMode(token, rateMode); + } + + _eventName = "LogSwapRateMode(address,uint256)"; + _eventParam = abi.encode(token, rateMode); + } + + /** + * @dev Set user e-mode + * @notice Updates the user's e-mode category + * @param categoryId The category Id of the e-mode user want to set + */ + function setUserEMode(uint8 categoryId) + external + returns (string memory _eventName, bytes memory _eventParam) + { + AaveInterface aave = AaveInterface(aaveProvider.getPool()); + + aave.setUserEMode(categoryId); + + _eventName = "LogSetUserEMode(uint8)"; + _eventParam = abi.encode(categoryId); + } +} + +contract ConnectV2AaveV3Polygon is AaveResolver { + string public constant name = "AaveV3-v1.0"; +} diff --git a/hardhat.config.ts b/hardhat.config.ts index 694d715e..9b7e4eb6 100644 --- a/hardhat.config.ts +++ b/hardhat.config.ts @@ -25,7 +25,7 @@ const chainIds = { polygon: 137, arbitrum: 42161, optimism: 10, - fantom:250 + fantom: 250 }; const alchemyApiKey = process.env.ALCHEMY_API_KEY; @@ -39,13 +39,8 @@ const POLYGONSCAN_API = process.env.POLYGON_API_KEY; const ARBISCAN_API = process.env.ARBISCAN_API_KEY; const SNOWTRACE_API = process.env.SNOWTRACE_API_KEY; const FANTOMSCAN_API = process.env.FANTOM_API_KEY; -<<<<<<< HEAD +const OPTIMISM_API = process.env.OPTIMISM_API_KEY; const mnemonic = process.env.MNEMONIC ?? "test test test test test test test test test test test junk"; -======= -const mnemonic = - process.env.MNEMONIC ?? - "test test test test test test test test test test test junk"; ->>>>>>> 2a009cc8da9682a1e82ec3119909e6dbaf30f11e const networkGasPriceConfig: Record = { mainnet: "160", @@ -57,30 +52,17 @@ const networkGasPriceConfig: Record = { function createConfig(network: string) { return { url: getNetworkUrl(network), - accounts: !!PRIVATE_KEY ? [`0x${PRIVATE_KEY}`] : { mnemonic }, - gasPrice: 220000000000 // 0.0001 GWEI + accounts: !!PRIVATE_KEY ? [`0x${PRIVATE_KEY}`] : { mnemonic } + // gasPrice: 1000000, // 0.0001 GWEI }; } function getNetworkUrl(networkType: string) { -<<<<<<< HEAD if (networkType === "avalanche") return "https://api.avax.network/ext/bc/C/rpc"; else if (networkType === "polygon") return `https://polygon-mainnet.g.alchemy.com/v2/${alchemyApiKey}`; else if (networkType === "arbitrum") return `https://arb-mainnet.g.alchemy.com/v2/${alchemyApiKey}`; else if (networkType === "optimism") return `https://opt-mainnet.g.alchemy.com/v2/${alchemyApiKey}`; else if (networkType === "fantom") return `https://rpc.ftm.tools/`; -======= - if (networkType === "avalanche") - return "https://api.avax.network/ext/bc/C/rpc"; - else if (networkType === "polygon") - return `https://polygon-mainnet.g.alchemy.com/v2/${alchemyApiKey}`; - else if (networkType === "arbitrum") - return `https://arb-mainnet.g.alchemy.com/v2/${alchemyApiKey}`; - else if (networkType === "optimism") - return `https://opt-mainnet.g.alchemy.com/v2/${alchemyApiKey}`; - else if(networkType === "fantom") - return `https://rpc.ftm.tools/` ->>>>>>> 2a009cc8da9682a1e82ec3119909e6dbaf30f11e else return `https://eth-mainnet.alchemyapi.io/v2/${alchemyApiKey}`; } @@ -88,12 +70,9 @@ function getScanApiKey(networkType: string) { if (networkType === "avalanche") return SNOWTRACE_API; else if (networkType === "polygon") return POLYGONSCAN_API; else if (networkType === "arbitrum") return ARBISCAN_API; -<<<<<<< HEAD else if (networkType === "fantom") return FANTOMSCAN_API; -======= - else if(networkType === "fantom") return FANTOMSCAN_API; + else if (networkType === "fantom") return FANTOMSCAN_API; else if (networkType === "optimism") return OPTIMISM_API; ->>>>>>> 2a009cc8da9682a1e82ec3119909e6dbaf30f11e else return ETHERSCAN_API; } @@ -138,7 +117,7 @@ const config: HardhatUserConfig = { avalanche: createConfig("avalanche"), arbitrum: createConfig("arbitrum"), optimism: createConfig("optimism"), - fantom: createConfig("fantom"), + fantom: createConfig("fantom") }, paths: { artifacts: "./artifacts", diff --git a/scripts/deployment/deployConnectorsFromCmd.ts b/scripts/deployment/deployConnectorsFromCmd.ts index 60fb880a..9ed56c14 100644 --- a/scripts/deployment/deployConnectorsFromCmd.ts +++ b/scripts/deployment/deployConnectorsFromCmd.ts @@ -24,8 +24,8 @@ async function deployRunner() { name: "chain", message: "What chain do you want to deploy on?", type: "list", - choices: ["mainnet", "polygon", "avalanche", "arbitrum"], - }, + choices: ["mainnet", "polygon", "avalanche", "arbitrum", "optimism"] + } ]); // let connector = await connectorSelect(chain); @@ -48,8 +48,8 @@ async function deployRunner() { { name: "connector", message: "Enter the connector contract name? (ex: ConnectV2Paraswap)", - type: "input", - }, + type: "input" + } ]); let { choice } = await inquirer.prompt([ @@ -57,39 +57,29 @@ async function deployRunner() { name: "choice", message: "Do you wanna try deploy on hardhat first?", type: "list", - choices: ["yes", "no"], - }, + choices: ["yes", "no"] + } ]); runchain = choice === "yes" ? "hardhat" : chain; - console.log( - `Deploying ${connector} on ${runchain}, press (ctrl + c) to stop` - ); + console.log(`Deploying ${connector} on ${runchain}, press (ctrl + c) to stop`); start = Date.now(); await execScript({ cmd: "npx", - args: [ - "hardhat", - "run", - "scripts/deployment/deploy.ts", - "--network", - `${runchain}`, - ], + args: ["hardhat", "run", "scripts/deployment/deploy.ts", "--network", `${runchain}`], env: { connectorName: connector, - networkType: chain, - }, + networkType: chain + } }); end = Date.now(); } deployRunner() .then(() => { - console.log( - `Done successfully, total time taken: ${(end - start) / 1000} sec` - ); + console.log(`Done successfully, total time taken: ${(end - start) / 1000} sec`); process.exit(0); }) .catch((err) => { diff --git a/scripts/tests/addLiquidity.ts b/scripts/tests/addLiquidity.ts index a18d172f..a1250bcc 100644 --- a/scripts/tests/addLiquidity.ts +++ b/scripts/tests/addLiquidity.ts @@ -1,4 +1,4 @@ -import { ethers } from "hardhat"; +import { ethers, network } from "hardhat"; import { impersonateAccounts } from "./impersonate"; import { tokenMapping as mainnetMapping } from "./mainnet/tokens"; @@ -12,7 +12,7 @@ const mineTx = async (tx: any) => { const tokenMapping: Record> = { mainnet: mainnetMapping, polygon: polygonMapping, - avalanche: avalancheMapping, + avalanche: avalancheMapping }; export async function addLiquidity(tokenName: string, address: any, amt: any) { @@ -20,20 +20,16 @@ export async function addLiquidity(tokenName: string, address: any, amt: any) { tokenName = tokenName.toLowerCase(); const chain = String(process.env.networkType); if (!tokenMapping[chain][tokenName]) { - throw new Error( - `Add liquidity doesn't support the following token: ${tokenName}` - ); + throw new Error(`Add liquidity doesn't support the following token: ${tokenName}`); } const token = tokenMapping[chain][tokenName]; - const [impersonatedSigner] = await impersonateAccounts([ - token.impersonateSigner, - ]); + const [impersonatedSigner] = await impersonateAccounts([token.impersonateSigner]); // send 2 eth to cover any tx costs. await network.provider.send("hardhat_setBalance", [ impersonatedSigner.address, - ethers.utils.parseEther("2").toHexString(), + ethers.utils.parseEther("2").toHexString() ]); await token.process(impersonatedSigner, address, amt);