AavePM - Aave Position Manager
🧪 ALPHA TESTING PHASE 🧪
- 1. Overview
- 2. WebApp
- 3. Installation
- 4. Testing
- 5. Deployment
- 6. Upgrades
- 7. Interactions
- 7.1. Grant Role
- 7.2. Revoke Role
- 7.3. Fund contract with ETH
- 7.4. Update Health Factor Target
- 7.5. Update Slippage Tolerance
- 7.6. Rebalance Aave Position
- 7.7. Reinvest collateral
- 7.8. Supply from contract balance to Aave
- 7.9. Repay USDC from contract balance
- 7.10. Close Position
- 7.11. Withdraw wstETH to owner
- 7.12. Withdraw Token to owner
- 7.13. Borrow USDC and send it to an owner
- 7.14. Get Contract Balance
- 7.15. Get Aave Account Data
- 8. Build and Deploy Documentation
- 9. License
1. Overview
Docs Site: https://eridianalpha.github.io/aave-position-manager
A smart contract manager for Aave positions.
- Set a desired Health Factor.
- Send assets (ETH, WETH, wstETH, or USDC) to the contract.
- Reinvest and rebalance the position to maintain the desired Health Factor, either manually or with a bot.
- Borrow and withdraw USDC from the position while maintaining the desired Health Factor.
1.1. Key Functions
1.1.1. Owner Functions
Function | Restrictions | Description |
---|---|---|
upgradeToAndCall | OWNER_ROLE | Upgrade the contract. |
updateContractAddress | OWNER_ROLE | Update the specified contract address. |
updateTokenAddress | OWNER_ROLE | Update the specified token address. |
updateUniswapV3Pool | OWNER_ROLE | Update the specified Uniswap V3 pool. |
updateManagerDailyInvocationLimit | OWNER_ROLE | Update the daily invocation limit for the manager role. |
1.1.2. Manager Functions
Function | Restrictions | Description |
---|---|---|
rebalance | MANAGER_ROLE | Rebalance the Aave position to the desired Health Factor. |
reinvest | MANAGER_ROLE | Reinvest the Aave position to the desired Health Factor target. |
deleverage | MANAGER_ROLE | Deleverage the Aave position by paying back all reinvested debt. |
aaveSupplyFromContractBalance | MANAGER_ROLE | Supply all the collateral from the contract balance to Aave. |
aaveRepayUSDCFromContractBalance | MANAGER_ROLE | Repay Aave position debt using all the USDC from the contract balance. |
withdrawTokensFromContractBalance | MANAGER_ROLE | Withdraw all the specified tokens from the contract to the specified owner. |
aaveBorrowAndWithdrawUSDC | MANAGER_ROLE | Borrow USDC from Aave and withdraw to the specified owner. |
aaveWithdrawWstETH | MANAGER_ROLE | Withdraw wstETH collateral from the Aave position to the specified owner. |
aaveClosePosition | MANAGER_ROLE | Close the Aave position by repaying all debt and withdrawing all collateral to the specified owner. |
updateHealthFactorTarget | MANAGER_ROLE | Set the desired Health Factor target. |
updateSlippageTolerance | MANAGER_ROLE | Set the slippage tolerance for Uniswap V3 swaps. |
rescueEth | MANAGER_ROLE | Rescue ETH from the contract to the specified owner. |
delegateCallHelper | MANAGER_ROLE | Execute a delegate call to the specified module. |
2. WebApp
A WebApp is being developed to allow easy interaction with the smart contract and will be linked here when available.
3. Installation
3.1. Clone repository
git clone https://github.com/EridianAlpha/aave-position-manager.git
3.2. Install Dependencies
This should happen automatically when first running a command, but the installation can be manually triggered with the following commands:
git submodule init
git submodule update
make install
3.3. Create the .env
file
Use the .env.example
file as a template to create a .env
file.
3.4. Configure Ethernal (optional)
Configure an Ethernal account to interact with the smart contract through a UI. Ethernal is like Etherscan but for a custom network.
https://docs.eridianalpha.com/ethereum-dev/useful-tools/ethernal
make ethernal
4. Testing
4.1. Tests (Fork)
make test-fork
make test-fork-v
make test-fork-summary
4.2. Coverage (Fork)
make coverage
make coverage-report
5. Deployment
Deploys AavePM and all modules to the Anvil chain specified in the .env
file.
Chain | Command |
---|---|
Anvil | make deploy anvil |
Base Sepolia | make deploy base-sepolia |
Base Mainnet | make deploy base-mainnet |
6. Upgrades
Upgrade the contract to a new logic implementation while maintaining the same proxy address. This also redeploys all modules and updates their contract addresses on AavePM.
Chain | Command |
---|---|
Anvil | make upgrade anvil |
Base Sepolia | make upgrade base-sepolia |
Base Mainnet | make upgrade base-mainnet |
7. Interactions
Interactions are defined in ./script/Interactions.s.sol
If DEPLOYED_CONTRACT_ADDRESS
is set in the .env
file, that contract address will be used for interactions.
If that variable is not set, the latest deployment on the specified chain will be used.
7.1. Grant Role
Grant a role to an address. Requires the caller to be an admin of the role being granted.
Input value 1 as a role e.g. MANAGER_ROLE
.
Input value 2 as an address e.g. 0x123...
.
Combined input value e.g. MANAGER_ROLE,0x123...
.
Chain | Command |
---|---|
Anvil | make grantRole anvil |
Base Sepolia | make grantRole base-sepolia |
Base Mainnet | make grantRole base-mainnet |
7.2. Revoke Role
Revoke a role from an address. Requires the caller to be an admin of the role being revoked.
Input value 1 as a role e.g. MANAGER_ROLE
.
Input value 2 as an address e.g. 0x123...
.
Combined input value e.g. MANAGER_ROLE,0x123...
.
Chain | Command |
---|---|
Anvil | make revokeRole anvil |
Base Sepolia | make revokeRole base-sepolia |
Base Mainnet | make revokeRole base-mainnet |
7.3. Fund contract with ETH
Input value in ETH e.g. 0.15
.
Chain | Command |
---|---|
Anvil | make send-ETH anvil |
Base Mainnet | make send-ETH base-mainnet |
7.4. Update Health Factor Target
Input value to 2 decimal places e.g. 225
for a Health Factor target of 2.25
.
Chain | Command |
---|---|
Anvil | make update-hft anvil |
Base Mainnet | make update-hft base-mainnet |
7.5. Update Slippage Tolerance
Input value to 2 decimal places e.g. 200
for a Slippage Tolerance of 0.5%
.
Chain | Command |
---|---|
Anvil | make update-st anvil |
Base Mainnet | make update-st base-mainnet |
7.6. Rebalance Aave Position
Rebalances the Aave position to maintain the desired Health Factor target.
REBALANCE_HFT_BUFFER
is a constant in the module that determines if a rebalance is required.
Chain | Command |
---|---|
Anvil | make rebalance anvil |
Base Mainnet | make rebalance base-mainnet |
7.7. Reinvest collateral
Reinvests any collateral above the Health Factor target.
REINVEST_HFT_BUFFER
is a constant in the module that determines if a reinvest is required.
Chain | Command |
---|---|
Anvil | make reinvest anvil |
Base Mainnet | make reinvest base-mainnet |
7.8. Supply from contract balance to Aave
Supplies any ETH, WETH, wstETH, or USDC in the contract to Aave.
Chain | Command |
---|---|
Anvil | make supply anvil |
Base Mainnet | make supply base-mainnet |
7.9. Repay USDC from contract balance
Repay any USDC debt in the contract to repay Aave position debt.
Chain | Command |
---|---|
Anvil | make repay anvil |
Base Mainnet | make repay base-mainnet |
7.10. Close Position
Close the Aave position by repaying all debt and withdrawing all collateral.
Input value as an owner address. e.g. 0x123...
.
Chain | Command |
---|---|
Anvil | make closePosition anvil |
Base Mainnet | make closePosition base-mainnet |
7.11. Withdraw wstETH to owner
Withdraw wstETH collateral from the Aave position to the specified owner.
Input value 1 in ETH e.g. 0.15
.
Input value 2 as an owner address e.g. 0x123...
.
Combined input value e.g. 0.15,0x123...
.
Chain | Command |
---|---|
Anvil | make withdrawWstETH anvil |
Base Mainnet | make withdrawWstETH base-mainnet |
7.12. Withdraw Token to owner
Withdraw the specified token from the contract to the specified owner.
Input value 1 in token identifier e.g. USDC
.
Input value 2 as an owner address e.g. 0x123...
.
Combined input value e.g. USDC,0x123...
.
Chain | Command |
---|---|
Anvil | make withdrawToken anvil |
Base Mainnet | make withdrawToken base-mainnet |
7.13. Borrow USDC and send it to an owner
Borrow USDC from Aave and withdraw to the specified owner.
Input value 1 in USDC e.g. 200
for $200 USDC.
Input value 2 as an owner address e.g. 0x123...
.
Combined input value e.g. 200,0x123...
.
Chain | Command |
---|---|
Anvil | make borrowUSDC anvil |
Base Mainnet | make borrowUSDC base-mainnet |
7.14. Get Contract Balance
Input value as token identifier e.g. USDC
.
Chain | Command |
---|---|
Anvil | make getContractBalance anvil |
Base Mainnet | make getContractBalance base-mainnet |
7.15. Get Aave Account Data
Returns the Aave account data for the contract.
Chain | Command |
---|---|
Anvil | make getAaveAccountData anvil |
Base Mainnet | make getAaveAccountData base-mainnet |
8. Build and Deploy Documentation
Instructions on how to build and deploy the documentation book are detailed here: https://docs.eridianalpha.com/ethereum-dev/foundry-notes/docs-and-github-pages
9. License
Contents
- IAaveFunctionsModule
- IAavePM
- IBorrowAndWithdrawUSDCModule
- IERC20Extended
- IRebalanceModule
- IReinvestModule
- ITokenSwapsModule
- IWETH9
IAaveFunctionsModule
This interface defines the essential structures and functions for the AaveFunctionsModule contract.
Functions
VERSION
function VERSION() external pure returns (string memory version);
aavePMProxyAddress
function aavePMProxyAddress() external view returns (address aavePMProxyAddress);
aaveSupply
function aaveSupply(address aavePoolAddress, address tokenAddress, uint256 tokenBalance) external;
aaveWithdrawCollateral
function aaveWithdrawCollateral(address aavePoolAddress, address tokenAddress, uint256 withdrawAmount) external;
aaveBorrow
function aaveBorrow(address aavePoolAddress, address tokenAddress, uint256 borrowAmount) external;
aaveRepayDebt
function aaveRepayDebt(address aavePoolAddress, address tokenAddress, uint256 repayAmount) external;
getCurrentPositionValues
function getCurrentPositionValues(IAavePM aavePM)
external
view
returns (
uint256 initialCollateralBase,
uint256 totalDebtBase,
uint256 currentLiquidationThreshold,
uint256 initialHealthFactorScaled,
uint16 healthFactorTarget,
address aavePoolAddress,
address wstETHAddress,
address usdcAddress
);
checkHealthFactorAboveMinimum
function checkHealthFactorAboveMinimum()
external
view
returns (
uint256 totalCollateralBase,
uint256 totalDebtBase,
uint256 availableBorrowsBase,
uint256 currentLiquidationThreshold,
uint256 ltv,
uint256 healthFactor
);
getTotalCollateralDelta
function getTotalCollateralDelta(
uint256 totalCollateralBase,
uint256 reinvestedDebtTotal,
uint256 suppliedCollateralTotal
) external pure returns (uint256 delta, bool isPositive);
convertExistingBalanceToWstETHAndSupplyToAave
function convertExistingBalanceToWstETHAndSupplyToAave() external returns (uint256 suppliedCollateral);
calculateMaxBorrowUSDC
function calculateMaxBorrowUSDC(
uint256 totalCollateralBase,
uint256 totalDebtBase,
uint256 currentLiquidationThreshold,
uint16 healthFactorTarget
) external pure returns (uint256 maxBorrowUSDC);
Errors
AaveFunctionsModule__InvalidAavePMProxyAddress
error AaveFunctionsModule__InvalidAavePMProxyAddress();
IAavePM
This interface defines the essential structures and functions for the AavePM contract.
Functions
initialize
function initialize(
address owner,
ContractAddress[] memory contractAddresses,
TokenAddress[] memory tokenAddresses,
UniswapV3Pool[] memory uniswapV3Pools,
uint16 initialHealthFactorTarget,
uint16 initialSlippageTolerance,
uint16 initialManagerDailyInvocationLimit
) external;
updateContractAddress
function updateContractAddress(string memory identifier, address newContractAddress) external;
updateTokenAddress
function updateTokenAddress(string memory identifier, address newTokenAddress) external;
updateUniswapV3Pool
function updateUniswapV3Pool(string memory identifier, address newUniswapV3PoolAddress, uint24 newUniswapV3PoolFee)
external;
updateHealthFactorTarget
function updateHealthFactorTarget(uint16 healthFactorTarget) external;
updateSlippageTolerance
function updateSlippageTolerance(uint16 slippageTolerance) external;
updateManagerDailyInvocationLimit
function updateManagerDailyInvocationLimit(uint16 _managerDailyInvocationLimit) external;
rebalance
function rebalance() external returns (uint256 repaymentAmountUSDC);
reinvest
function reinvest() external payable returns (uint256 reinvestedDebt);
deleverage
function deleverage() external;
aaveSupplyFromContractBalance
function aaveSupplyFromContractBalance() external payable returns (uint256 suppliedCollateral);
aaveRepayUSDCFromContractBalance
function aaveRepayUSDCFromContractBalance() external;
delegateCallHelper
function delegateCallHelper(string memory _targetIdentifier, bytes memory _data) external returns (bytes memory);
rescueEth
function rescueEth(address ownerAddress) external;
withdrawTokensFromContractBalance
function withdrawTokensFromContractBalance(string memory identifier, address ownerAddress) external;
aaveWithdrawWstETH
function aaveWithdrawWstETH(uint256 withdrawAmount, address ownerAddress)
external
returns (uint256 collateralDeltaBase);
aaveBorrowAndWithdrawUSDC
function aaveBorrowAndWithdrawUSDC(uint256 borrowAmount, address ownerAddress) external;
aaveClosePosition
function aaveClosePosition(address ownerAddress) external;
getCreator
function getCreator() external view returns (address creator);
getEventBlockNumbers
function getEventBlockNumbers() external view returns (uint64[] memory);
getVersion
function getVersion() external pure returns (string memory version);
getContractAddress
function getContractAddress(string memory) external view returns (address contractAddress);
getTokenAddress
function getTokenAddress(string memory) external view returns (address tokenAddress);
getUniswapV3Pool
function getUniswapV3Pool(string memory)
external
view
returns (address uniswapV3PoolAddress, uint24 uniswapV3PoolFee);
getHealthFactorTarget
function getHealthFactorTarget() external view returns (uint16 healthFactorTarget);
getHealthFactorTargetMinimum
function getHealthFactorTargetMinimum() external pure returns (uint16 healthFactorTargetMinimum);
getSlippageTolerance
function getSlippageTolerance() external view returns (uint16 slippageTolerance);
getSlippageToleranceMaximum
function getSlippageToleranceMaximum() external pure returns (uint16 slippageToleranceMaximum);
getManagerDailyInvocationLimit
function getManagerDailyInvocationLimit() external view returns (uint16 managerDailyInvocationLimit);
getManagerInvocationTimestamps
function getManagerInvocationTimestamps() external view returns (uint64[] memory);
getContractBalance
function getContractBalance(string memory identifier) external view returns (uint256 contractBalance);
getRoleMembers
function getRoleMembers(string memory roleString) external view returns (address[] memory);
getWithdrawnUSDCTotal
function getWithdrawnUSDCTotal() external view returns (uint256 withdrawnUSDCTotal);
getReinvestedDebtTotal
function getReinvestedDebtTotal() external view returns (uint256 reinvestedDebtTotal);
getTotalCollateralDelta
function getTotalCollateralDelta() external returns (uint256 totalCollateralDelta, bool isPositive);
getSuppliedCollateralTotal
function getSuppliedCollateralTotal() external view returns (uint256 depositedCollateralTotal);
getMaxBorrowAndWithdrawUSDCAmount
function getMaxBorrowAndWithdrawUSDCAmount() external view returns (uint256 maxBorrowAndWithdrawUSDCAmount);
getReinvestableAmount
function getReinvestableAmount() external returns (uint256 reinvestableAmount);
getRoleAdmin
function getRoleAdmin(bytes32 role) external view returns (bytes32);
getRoleMember
function getRoleMember(bytes32 role, uint256 index) external view returns (address);
getRoleMemberCount
function getRoleMemberCount(bytes32 role) external view returns (uint256);
grantRole
function grantRole(bytes32 role, address account) external;
hasRole
function hasRole(bytes32 role, address account) external view returns (bool);
renounceRole
function renounceRole(bytes32 role, address callerConfirmation) external;
revokeRole
function revokeRole(bytes32 role, address account) external;
supportsInterface
function supportsInterface(bytes4 interfaceId) external view returns (bool);
upgradeToAndCall
function upgradeToAndCall(address newImplementation, bytes memory data) external payable;
executeOperation
function executeOperation(address asset, uint256 amount, uint256 premium, address initiator, bytes calldata params)
external
returns (bool);
Events
AavePMInitialized
event AavePMInitialized(address indexed creator);
ContractAddressUpdated
event ContractAddressUpdated(
string identifier, address indexed previousContractAddress, address indexed newContractAddress
);
TokenAddressUpdated
event TokenAddressUpdated(string identifier, address indexed previousTokenAddress, address indexed newTokenAddress);
UniswapV3PoolUpdated
event UniswapV3PoolUpdated(string identifier, address indexed newUniswapV3PoolAddress, uint24 newUniswapV3PoolFee);
HealthFactorTargetUpdated
event HealthFactorTargetUpdated(uint16 previousHealthFactorTarget, uint16 newHealthFactorTarget);
SlippageToleranceUpdated
event SlippageToleranceUpdated(uint16 previousSlippageTolerance, uint16 newSlippageTolerance);
ManagerDailyInvocationLimitUpdated
event ManagerDailyInvocationLimitUpdated(
uint16 previousManagerDailyInvocationLimit, uint16 newManagerDailyInvocationLimit
);
Rebalanced
event Rebalanced(uint256 repaymentAmountUSDC);
Reinvested
event Reinvested(uint256 reinvestedDebt);
Deleveraged
event Deleveraged(uint256 repaymentAmountUSDC);
AaveSuppliedFromContractBalance
event AaveSuppliedFromContractBalance(uint256 suppliedCollateral);
AaveRepayedUSDCFromContractBalance
event AaveRepayedUSDCFromContractBalance(uint256 usdcBalance);
EthRescued
event EthRescued(address indexed to, uint256 amount);
TokensWithdrawnFromContractBalance
event TokensWithdrawnFromContractBalance(string identifier, uint256 tokenBalance);
AaveWithdrawnWstETH
event AaveWithdrawnWstETH(address indexed ownerAddress, uint256 amount);
AaveBorrowedAndWithdrawnUSDC
event AaveBorrowedAndWithdrawnUSDC(address indexed ownerAddress, uint256 amount);
AaveClosedPosition
event AaveClosedPosition(address indexed ownerAddress);
AavePMUpgraded
event AavePMUpgraded(address indexed previousImplementation, address indexed newImplementation);
FlashLoanExecuted
event FlashLoanExecuted(address indexed asset, uint256 amount, uint256 premium);
Errors
AavePM__NoDebtToRepay
error AavePM__NoDebtToRepay();
AavePM__RescueEthFailed
error AavePM__RescueEthFailed();
AavePM__ZeroBorrowAmount
error AavePM__ZeroBorrowAmount();
AavePM__AddressNotAnOwner
error AavePM__AddressNotAnOwner();
AavePM__DelegateCallFailed
error AavePM__DelegateCallFailed();
AavePM__NoTokensToWithdraw
error AavePM__NoTokensToWithdraw();
AavePM__ReinvestNotRequired
error AavePM__ReinvestNotRequired();
AavePM__RebalanceNotRequired
error AavePM__RebalanceNotRequired();
AavePM__FunctionDoesNotExist
error AavePM__FunctionDoesNotExist();
AavePM__NegativeInterestCalc
error AavePM__NegativeInterestCalc();
AavePM__HealthFactorUnchanged
error AavePM__HealthFactorUnchanged();
AavePM__NoCollateralToWithdraw
error AavePM__NoCollateralToWithdraw();
AavePM__InvalidWithdrawalToken
error AavePM__InvalidWithdrawalToken();
AavePM__HealthFactorBelowMinimum
error AavePM__HealthFactorBelowMinimum();
AavePM__SlippageToleranceUnchanged
error AavePM__SlippageToleranceUnchanged();
AavePM__SlippageToleranceAboveMaximum
error AavePM__SlippageToleranceAboveMaximum();
AavePM__ZeroBorrowAndWithdrawUSDCAvailable
error AavePM__ZeroBorrowAndWithdrawUSDCAvailable();
AavePM__ManagerDailyInvocationLimitReached
error AavePM__ManagerDailyInvocationLimitReached();
AaveFunctions__FlashLoanMsgSenderUnauthorized
error AaveFunctions__FlashLoanMsgSenderUnauthorized();
AaveFunctions__FlashLoanInitiatorUnauthorized
error AaveFunctions__FlashLoanInitiatorUnauthorized();
TokenSwaps__NotEnoughTokensForSwap
error TokenSwaps__NotEnoughTokensForSwap(string tokenInIdentifier);
Structs
ContractAddress
struct ContractAddress {
string identifier;
address contractAddress;
}
TokenAddress
struct TokenAddress {
string identifier;
address tokenAddress;
}
UniswapV3Pool
struct UniswapV3Pool {
string identifier;
address poolAddress;
uint24 fee;
}
IBorrowAndWithdrawUSDCModule
This interface defines the essential structures and functions for the BorrowAndWithdrawUSDCModule contract.
Functions
VERSION
function VERSION() external pure returns (string memory version);
aavePMProxyAddress
function aavePMProxyAddress() external view returns (address aavePMProxyAddress);
borrowAndWithdrawUSDC
function borrowAndWithdrawUSDC(uint256 borrowAmountUSDC, address _owner)
external
returns (uint256 repaidReinvestedDebt);
Errors
BorrowAndWithdrawUSDCModule__InvalidAavePMProxyAddress
error BorrowAndWithdrawUSDCModule__InvalidAavePMProxyAddress();
IERC20Extended
Inherits: IERC20
This interface extends the ERC20 interface with the decimals function.
Functions
decimals
function decimals() external view returns (uint8);
IRebalanceModule
This interface defines the essential structures and functions for the RebalanceModule contract.
Functions
VERSION
function VERSION() external pure returns (string memory version);
aavePMProxyAddress
function aavePMProxyAddress() external view returns (address aavePMProxyAddress);
rebalance
function rebalance() external returns (uint256 repaymentAmountUSDC);
Errors
RebalanceModule__InvalidAavePMProxyAddress
error RebalanceModule__InvalidAavePMProxyAddress();
IReinvestModule
This interface defines the essential structures and functions for the ReinvestModule contract.
Functions
VERSION
function VERSION() external pure returns (string memory version);
aavePMProxyAddress
function aavePMProxyAddress() external view returns (address aavePMProxyAddress);
reinvest
function reinvest() external returns (uint256 reinvestedDebt);
Errors
ReinvestModule__InvalidAavePMProxyAddress
error ReinvestModule__InvalidAavePMProxyAddress();
ITokenSwapsModule
This interface defines the essential structures and functions for the TokenSwapsModule contract.
Functions
VERSION
function VERSION() external pure returns (string memory version);
aavePMProxyAddress
function aavePMProxyAddress() external view returns (address aavePMProxyAddress);
swapTokens
function swapTokens(
string memory _uniswapV3PoolIdentifier,
string memory _tokenInIdentifier,
string memory _tokenOutIdentifier
) external returns (string memory tokenOutIdentifier, uint256 amountOut);
wrapETHToWETH
function wrapETHToWETH() external payable;
Errors
TokenSwapsModule__InvalidAavePMProxyAddress
error TokenSwapsModule__InvalidAavePMProxyAddress();
IWETH9
This interface enables the wrapping and unwrapping of ETH to WETH.
Functions
deposit
function deposit() external payable;
withdraw
function withdraw(uint256 wad) external;
Contents
AaveFunctionsModule
Inherits: IAaveFunctionsModule
Author: EridianAlpha
This contract contains the functions for AavePM to interact with the Aave protocol.
State Variables
VERSION
The version of the contract.
Contract is upgradeable so the version is a constant set on each implementation contract.
string public constant VERSION = "0.0.1";
aavePMProxyAddress
The address of the AavePM proxy contract.
The AavePM proxy address is set on deployment and is immutable.
address public immutable aavePMProxyAddress;
HFT_MINIMUM_BUFFER
The buffer for the Health Factor Target minimum calculation
uint16 public constant HFT_MINIMUM_BUFFER = 1;
Functions
constructor
Contract constructor to set the AavePM proxy address.
The AavePM proxy address is set on deployment and is immutable.
constructor(address _aavePMProxyAddress);
Parameters
Name | Type | Description |
---|---|---|
_aavePMProxyAddress | address | The address of the AavePM proxy contract. |
onlyAavePM
Modifier to check that only the AavePM contract is the caller.
Uses address(this)
since this contract is called by the AavePM contract using delegatecall.
modifier onlyAavePM();
aaveSupply
Deposit all wstETH into Aave.
This function is used to deposit all wstETH into Aave.
function aaveSupply(address aavePoolAddress, address tokenAddress, uint256 tokenBalance) public onlyAavePM;
Parameters
Name | Type | Description |
---|---|---|
aavePoolAddress | address | The address of the Aave pool contract. |
tokenAddress | address | The address of the token to deposit. |
tokenBalance | uint256 | The contract balance of the token to deposit. |
aaveWithdrawCollateral
Withdraw wstETH from Aave.
This function is used to withdraw wstETH from Aave.
function aaveWithdrawCollateral(address aavePoolAddress, address tokenAddress, uint256 withdrawAmount)
public
onlyAavePM;
Parameters
Name | Type | Description |
---|---|---|
aavePoolAddress | address | The address of the Aave pool contract. |
tokenAddress | address | The address of the token to withdraw. |
withdrawAmount | uint256 | The amount of the token to withdraw. |
aaveBorrow
Borrow USDC from Aave.
This function is used to borrow USDC from Aave.
function aaveBorrow(address aavePoolAddress, address tokenAddress, uint256 borrowAmount) public onlyAavePM;
Parameters
Name | Type | Description |
---|---|---|
aavePoolAddress | address | The address of the Aave pool contract. |
tokenAddress | address | The address of the token to borrow. |
borrowAmount | uint256 | The amount of USDC to borrow. 8 decimal places to the dollar. e.g. 100000000 = $1.00. |
aaveRepayDebt
Repay USDC debt to Aave.
This function is used to repay USDC debt to Aave.
function aaveRepayDebt(address aavePoolAddress, address tokenAddress, uint256 repayAmount) public onlyAavePM;
Parameters
Name | Type | Description |
---|---|---|
aavePoolAddress | address | The address of the Aave pool contract. |
tokenAddress | address | The address of the token to repay. |
repayAmount | uint256 | The amount of USDC to repay. 8 decimal places to the dollar. e.g. 100000000 = $1.00. |
getCurrentPositionValues
Getter function to get the current position values.
This function is used to avoid code duplication in the Reinvest and Rebalance contracts.
function getCurrentPositionValues(IAavePM aavePM)
public
view
returns (
uint256 initialCollateralBase,
uint256 totalDebtBase,
uint256 currentLiquidationThreshold,
uint256 initialHealthFactorScaled,
uint16 healthFactorTarget,
address aavePoolAddress,
address wstETHAddress,
address usdcAddress
);
Parameters
Name | Type | Description |
---|---|---|
aavePM | IAavePM | The Aave Position Manager contract. |
Returns
Name | Type | Description |
---|---|---|
initialCollateralBase | uint256 | The initial collateral in USD base unit with 8 decimals to the dollar. |
totalDebtBase | uint256 | The total debt in USD base unit with 8 decimals to the dollar. |
currentLiquidationThreshold | uint256 | The current liquidation threshold. |
initialHealthFactorScaled | uint256 | The initial health factor scaled to 2 decimal places. |
healthFactorTarget | uint16 | The health factor target. |
aavePoolAddress | address | The address of the Aave pool contract. |
wstETHAddress | address | The address of the wstETH token. |
usdcAddress | address | The address of the USDC token. |
checkHealthFactorAboveMinimum
Check if the health factor is above the minimum.
This function is used to check if the health factor is above the minimum.
function checkHealthFactorAboveMinimum()
public
view
returns (
uint256 totalCollateralBase,
uint256 totalDebtBase,
uint256 availableBorrowsBase,
uint256 currentLiquidationThreshold,
uint256 ltv,
uint256 healthFactor
);
Returns
Name | Type | Description |
---|---|---|
totalCollateralBase | uint256 | The total collateral in USD base unit with 8 decimals to the dollar. |
totalDebtBase | uint256 | The total debt in USD base unit with 8 decimals to the dollar. |
availableBorrowsBase | uint256 | The available borrows in USD base unit with 8 decimals to the dollar. |
currentLiquidationThreshold | uint256 | The current liquidation threshold. |
ltv | uint256 | The loan to value ratio. |
healthFactor | uint256 | The health factor. |
getTotalCollateralDelta
Getter function to get the total collateral delta.
This function is used to calculate the total collateral delta.
function getTotalCollateralDelta(
uint256 totalCollateralBase,
uint256 reinvestedDebtTotal,
uint256 suppliedCollateralTotal
) public pure returns (uint256 delta, bool isPositive);
Parameters
Name | Type | Description |
---|---|---|
totalCollateralBase | uint256 | The total collateral in USD base unit with 8 decimals to the dollar. |
reinvestedDebtTotal | uint256 | The reinvested debt total in USD base unit with 8 decimals to the dollar. |
suppliedCollateralTotal | uint256 | The supplied collateral total in USD base unit with 8 decimals to the dollar. |
Returns
Name | Type | Description |
---|---|---|
delta | uint256 | The total collateral delta. |
isPositive | bool | A boolean to indicate if the delta is positive. |
convertExistingBalanceToWstETHAndSupplyToAave
Convert existing balance to wstETH and supply to Aave.
This function is used to convert the existing balance to wstETH and supply to Aave.
function convertExistingBalanceToWstETHAndSupplyToAave() public onlyAavePM returns (uint256 suppliedCollateral);
Returns
Name | Type | Description |
---|---|---|
suppliedCollateral | uint256 | The amount of wstETH supplied to Aave. |
calculateMaxBorrowUSDC
Calculate the minimum amount of tokens received from a Uniswap V3 swap.
This function is used to calculate the minimum amount of tokens received from a Uniswap V3 swap.
function calculateMaxBorrowUSDC(
uint256 totalCollateralBase,
uint256 totalDebtBase,
uint256 currentLiquidationThreshold,
uint16 healthFactorTarget
) public pure returns (uint256 maxBorrowUSDC);
Parameters
Name | Type | Description |
---|---|---|
totalCollateralBase | uint256 | The total collateral in USD base unit with 8 decimals to the dollar. |
totalDebtBase | uint256 | The total debt in USD base unit with 8 decimals to the dollar. |
currentLiquidationThreshold | uint256 | The current liquidation threshold. |
healthFactorTarget | uint16 | The health factor target. |
BorrowAndWithdrawUSDCModule
Inherits: IBorrowAndWithdrawUSDCModule
Author: EridianAlpha
This contract contains the functions for AavePM to borrow and withdraw USDC from the Aave protocol.
State Variables
VERSION
The version of the contract.
Contract is upgradeable so the version is a constant set on each implementation contract.
string public constant VERSION = "0.0.1";
aavePMProxyAddress
The address of the AavePM proxy contract.
The AavePM proxy address is set on deployment and is immutable.
address public immutable aavePMProxyAddress;
HFT_BUFFER
The buffer for the Health Factor Target calculation
uint16 public constant HFT_BUFFER = 2;
Functions
constructor
Contract constructor to set the AavePM proxy address.
The AavePM proxy address is set on deployment and is immutable.
constructor(address _aavePMProxyAddress);
Parameters
Name | Type | Description |
---|---|---|
_aavePMProxyAddress | address | The address of the AavePM proxy contract. |
onlyAavePM
Modifier to check that only the AavePM contract is the caller.
Uses address(this)
since this contract is called by the AavePM contract using delegatecall.
modifier onlyAavePM();
borrowAndWithdrawUSDC
Borrow USDC from the Aave protocol and withdraw it to the specified owner.
This function borrows USDC from the Aave protocol and withdraws it to the specified owner.
function borrowAndWithdrawUSDC(uint256 borrowAmountUSDC, address _owner)
public
onlyAavePM
returns (uint256 repaidReinvestedDebt);
Parameters
Name | Type | Description |
---|---|---|
borrowAmountUSDC | uint256 | The amount of USDC to borrow. |
_owner | address | The address to withdraw the USDC to. |
Returns
Name | Type | Description |
---|---|---|
repaidReinvestedDebt | uint256 | The amount of reinvested debt repaid (if any) to increase the Health Factor. |
_borrowCalculation
Calculate the amount of reinvested debt to repay to increase the Health Factor.
This function calculates the amount of reinvested debt to repay to increase the Health Factor.
function _borrowCalculation(
uint256 totalCollateralBase,
uint256 totalDebtBase,
uint256 currentLiquidationThreshold,
uint256 borrowAmountUSDC,
uint256 healthFactorTarget
) private pure returns (uint256 repaidReinvestedDebt);
Parameters
Name | Type | Description |
---|---|---|
totalCollateralBase | uint256 | The total collateral base in the Aave pool. |
totalDebtBase | uint256 | The total debt base in the Aave pool. |
currentLiquidationThreshold | uint256 | The current liquidation threshold in the Aave pool. |
borrowAmountUSDC | uint256 | The amount of USDC to borrow. |
healthFactorTarget | uint256 | The target Health Factor. |
Returns
Name | Type | Description |
---|---|---|
repaidReinvestedDebt | uint256 | The amount of reinvested debt repaid to increase the Health Factor. |
RebalanceModule
Inherits: IRebalanceModule
Author: EridianAlpha
This contract contains the functions for AavePM to rebalance the Aave position by repaying debt to increase the health factor.
State Variables
VERSION
The version of the contract.
Contract is upgradeable so the version is a constant set on each implementation contract.
string public constant VERSION = "0.0.1";
aavePMProxyAddress
The address of the AavePM proxy contract.
The AavePM proxy address is set on deployment and is immutable.
address public immutable aavePMProxyAddress;
REBALANCE_HFT_BUFFER
The buffer for the Health Factor Target rebalance calculation
uint16 public constant REBALANCE_HFT_BUFFER = 10;
Functions
constructor
Contract constructor to set the AavePM proxy address.
The AavePM proxy address is set on deployment and is immutable.
constructor(address _aavePMProxyAddress);
Parameters
Name | Type | Description |
---|---|---|
_aavePMProxyAddress | address | The address of the AavePM proxy contract. |
onlyAavePM
Modifier to check that only the AavePM contract is the caller.
Uses address(this)
since this contract is called by the AavePM contract using delegatecall.
modifier onlyAavePM();
rebalance
Rebalance the Aave position.
Caller must have MANAGER_ROLE
.
The function rebalances the Aave position.
If the health factor is below the target, it repays debt to increase the health factor.
function rebalance() public onlyAavePM returns (uint256 repaymentAmountUSDC);
_repayDebt
Repay debt to increase the health factor.
This function repays debt to increase the health factor.
function _repayDebt(
uint256 totalDebtBase,
address aavePoolAddress,
address usdcAddress,
uint256 totalCollateralBase,
uint256 currentLiquidationThreshold,
uint16 healthFactorTarget
) private returns (uint256 repaymentAmountUSDC);
Parameters
Name | Type | Description |
---|---|---|
totalDebtBase | uint256 | The total debt in base units. |
aavePoolAddress | address | The address of the Aave pool. |
usdcAddress | address | The address of the USDC token. |
totalCollateralBase | uint256 | The total collateral in base units. |
currentLiquidationThreshold | uint256 | The current liquidation threshold. |
healthFactorTarget | uint16 | The target health factor. |
Returns
Name | Type | Description |
---|---|---|
repaymentAmountUSDC | uint256 | The amount of USDC repaid. |
ReinvestModule
Inherits: IReinvestModule
Author: EridianAlpha
This contract contains the functions for AavePM to borrow USDC, swap to wstETH, and supply to Aave maintaining the target health factor.
State Variables
VERSION
The version of the contract.
Contract is upgradeable so the version is a constant set on each implementation contract.
string public constant VERSION = "0.0.1";
aavePMProxyAddress
The address of the AavePM proxy contract.
The AavePM proxy address is set on deployment and is immutable.
address public immutable aavePMProxyAddress;
REINVEST_HFT_BUFFER
The buffer for the Health Factor Target reinvest calculation
uint16 public constant REINVEST_HFT_BUFFER = 10;
Functions
constructor
Contract constructor to set the AavePM proxy address.
The AavePM proxy address is set on deployment and is immutable.
constructor(address _aavePMProxyAddress);
Parameters
Name | Type | Description |
---|---|---|
_aavePMProxyAddress | address | The address of the AavePM proxy contract. |
onlyAavePM
Modifier to check that only the AavePM contract is the caller.
Uses address(this)
since this contract is called by the AavePM contract using delegatecall.
modifier onlyAavePM();
reinvest
Reinvest the Aave position.
This function reinvests the Aave position by borrowing USDC, swapping to wstETH, and supplying it back to Aave.
function reinvest() public onlyAavePM returns (uint256 reinvestedDebt);
Returns
Name | Type | Description |
---|---|---|
reinvestedDebt | uint256 | The amount of debt reinvested. |
_reinvestAction
Reinvest the Aave position.
This function actions the reinvestment of the Aave position.
function _reinvestAction(
IAavePM aavePM,
uint256 totalDebtBase,
address aavePoolAddress,
address usdcAddress,
address wstETHAddress,
uint256 initialCollateralBase,
uint256 currentLiquidationThreshold,
uint16 healthFactorTarget
) private returns (uint256 borrowAmountUSDC);
Parameters
Name | Type | Description |
---|---|---|
aavePM | IAavePM | The Aave Position Manager contract. |
totalDebtBase | uint256 | The total debt in base units. |
aavePoolAddress | address | The address of the Aave pool. |
usdcAddress | address | The address of the USDC token. |
wstETHAddress | address | The address of the wstETH token. |
initialCollateralBase | uint256 | The initial collateral in base units. |
currentLiquidationThreshold | uint256 | The current liquidation threshold. |
healthFactorTarget | uint16 | The target health factor. |
Returns
Name | Type | Description |
---|---|---|
borrowAmountUSDC | uint256 | The amount of USDC borrowed. |
TokenSwapsModule
Inherits: ITokenSwapsModule
Author: EridianAlpha
This contract contains the functions for AavePM to swap tokens using UniswapV3.
State Variables
VERSION
The version of the contract.
Contract is upgradeable so the version is a constant set on each implementation contract.
string public constant VERSION = "0.0.1";
aavePMProxyAddress
The address of the AavePM proxy contract.
The AavePM proxy address is set on deployment and is immutable.
address public immutable aavePMProxyAddress;
Functions
constructor
Contract constructor to set the AavePM proxy address.
The AavePM proxy address is set on deployment and is immutable.
constructor(address _aavePMProxyAddress);
Parameters
Name | Type | Description |
---|---|---|
_aavePMProxyAddress | address | The address of the AavePM proxy contract. |
onlyAavePM
Modifier to check that only the AavePM contract is the caller.
Uses address(this)
since this contract is called by the AavePM contract using delegatecall.
modifier onlyAavePM();
swapTokens
Swaps the entire specified token balance of the contract using a UniswapV3 pool.
Calculates the minimum amount that should be received based on the
current pool price ratio and a predefined slippage tolerance.
Reverts if there are no tokens in the contract or if the transaction does not
meet the amountOutMinimum
criteria due to price movements.
function swapTokens(
string memory _uniswapV3PoolIdentifier,
string memory _tokenInIdentifier,
string memory _tokenOutIdentifier
) public onlyAavePM returns (string memory tokenOutIdentifier, uint256 amountOut);
Parameters
Name | Type | Description |
---|---|---|
_uniswapV3PoolIdentifier | string | The identifier of the UniswapV3 pool to use for the swap. |
_tokenInIdentifier | string | The identifier of the token to swap. |
_tokenOutIdentifier | string | The identifier of the token to receive from the swap. |
Returns
Name | Type | Description |
---|---|---|
tokenOutIdentifier | string | The identifier of the token received from the swap. |
amountOut | uint256 | The amount tokens received from the swap. |
approveAndExecuteSwap
Approves and executes the swap using the UniswapV3 router.
Approves the swapRouter to spend the tokenIn and executes the swap.
function approveAndExecuteSwap(
IAavePM aavePM,
IV3SwapRouter.ExactInputSingleParams memory params,
uint256 currentBalance
) private returns (uint256 amountOut);
Parameters
Name | Type | Description |
---|---|---|
aavePM | IAavePM | The Aave Position Manager contract. |
params | IV3SwapRouter.ExactInputSingleParams | The swap parameters. |
currentBalance | uint256 | The current balance of the token to swap. |
Returns
Name | Type | Description |
---|---|---|
amountOut | uint256 | The amount of tokens received from the swap. |
wrapETHToWETH
Wraps all ETH in the contract to WETH.
Wraps all ETH in the contract to WETH even if the amount is 0.
function wrapETHToWETH() public payable onlyAavePM;
uniswapV3CalculateMinOut
Calculates the minimum amount of tokens to receive from a UniswapV3 swap.
Uses the current pool price ratio and a predefined slippage tolerance to calculate the minimum amount.
function uniswapV3CalculateMinOut(
IAavePM aavePM,
uint256 _currentBalance,
address _uniswapV3PoolAddress,
address tokenOutAddress
) private view returns (uint256 minOut);
Parameters
Name | Type | Description |
---|---|---|
aavePM | IAavePM | The Aave Position Manager contract. |
_currentBalance | uint256 | The current balance of the token to swap. |
_uniswapV3PoolAddress | address | The address of the UniswapV3 pool to use for the swap. |
tokenOutAddress | address | The address of the token to receive from the swap. |
Returns
Name | Type | Description |
---|---|---|
minOut | uint256 | The minimum amount of tokens to receive from the swap. |
_isIdentifierETH
Checks if the identifier is for ETH.
Compares the identifier to the ETH identifier and returns true if they match.
function _isIdentifierETH(string memory identifier) private pure returns (bool);
Parameters
Name | Type | Description |
---|---|---|
identifier | string | The identifier to check. |
Returns
Name | Type | Description |
---|---|---|
<none> | bool | isETH True if the identifier is for ETH. |
AavePM
Inherits: IAavePM, FunctionChecks, FlashLoan, Initializable, AccessControlEnumerableUpgradeable, UUPSUpgradeable
Author: EridianAlpha
A contract to manage positions on Aave.
State Variables
s_creator
address internal s_creator;
s_contractAddresses
mapping(string => address) internal s_contractAddresses;
s_tokenAddresses
mapping(string => address) internal s_tokenAddresses;
s_uniswapV3Pools
mapping(string => UniswapV3Pool) internal s_uniswapV3Pools;
s_healthFactorTarget
uint16 internal s_healthFactorTarget;
s_slippageTolerance
uint16 internal s_slippageTolerance;
s_withdrawnUSDCTotal
uint256 internal s_withdrawnUSDCTotal = 0;
s_reinvestedDebtTotal
uint256 internal s_reinvestedDebtTotal = 0;
s_suppliedCollateralTotal
uint256 internal s_suppliedCollateralTotal = 0;
s_eventBlockNumbers
uint64[] internal s_eventBlockNumbers;
s_managerDailyInvocationLimit
uint16 internal s_managerDailyInvocationLimit;
s_managerInvocationTimestamps
uint64[] internal s_managerInvocationTimestamps;
VERSION
The version of the contract.
Contract is upgradeable so the version is a constant set on each implementation contract.
string internal constant VERSION = "0.0.1";
OWNER_ROLE
The role hashes for the contract.
Two independent roles are defined: OWNER_ROLE
and MANAGER_ROLE
.
bytes32 internal constant OWNER_ROLE = keccak256("OWNER_ROLE");
MANAGER_ROLE
bytes32 internal constant MANAGER_ROLE = keccak256("MANAGER_ROLE");
HEALTH_FACTOR_TARGET_MINIMUM
The minimum Health Factor target.
The value is hardcoded in the contract to prevent the position from being liquidated cause by accidentally setting a low target. A contract upgrade is required to change this value.
uint16 internal constant HEALTH_FACTOR_TARGET_MINIMUM = 200;
SLIPPAGE_TOLERANCE_MAXIMUM
The maximum Slippage Tolerance.
The value is hardcoded in the contract to prevent terrible trades from occurring due to a high slippage tolerance. A contract upgrade is required to change this value.
uint16 internal constant SLIPPAGE_TOLERANCE_MAXIMUM = 100;
Functions
checkOwner
Modifier to check if the caller is the owner.
The function checks if the caller has the OWNER_ROLE
.
modifier checkOwner(address _owner);
Parameters
Name | Type | Description |
---|---|---|
_owner | address | The address to check if it has the OWNER_ROLE . |
checkManagerInvocationLimit
Function to check the manager invocation limit.
The function checks if the manager has exceeded the daily invocation limit and updates the timestamp array.
function checkManagerInvocationLimit() internal;
constructor
Constructor implemented but unused.
Contract is upgradeable and therefore the constructor is not used.
constructor();
receive
Function to receive ETH when no function matches the call data.
receive() external payable;
fallback
Fallback function to revert calls to functions that do not exist when the msg.data is empty.
fallback() external payable;
initialize
Initializes contract with the owner and relevant addresses and parameters for operation.
This function sets up all necessary state variables for the contract and can only be called once due to the initializer
modifier.
function initialize(
address owner,
ContractAddress[] memory contractAddresses,
TokenAddress[] memory tokenAddresses,
UniswapV3Pool[] memory uniswapV3Pools,
uint16 initialHealthFactorTarget,
uint16 initialSlippageTolerance,
uint16 initialManagerDailyInvocationLimit
) public initializer;
Parameters
Name | Type | Description |
---|---|---|
owner | address | The address of the owner of the contract. |
contractAddresses | ContractAddress[] | An array of ContractAddress structures containing addresses of related contracts. |
tokenAddresses | TokenAddress[] | An array of TokenAddress structures containing addresses of relevant ERC-20 tokens. |
uniswapV3Pools | UniswapV3Pool[] | An array of UniswapV3Pool structures containing the address and fee of the UniswapV3 pools. |
initialHealthFactorTarget | uint16 | The initial target health factor, used to manage risk. |
initialSlippageTolerance | uint16 | The initial slippage tolerance for token swaps. |
initialManagerDailyInvocationLimit | uint16 |
_initializeState
Internal function to initialize the state of the contract.
This function sets up all necessary state variables for the contract.
function _initializeState(
address owner,
ContractAddress[] memory contractAddresses,
TokenAddress[] memory tokenAddresses,
UniswapV3Pool[] memory uniswapV3Pools,
uint16 initialHealthFactorTarget,
uint16 initialSlippageTolerance,
uint16 initialManagerDailyInvocationLimit
) internal;
Parameters
Name | Type | Description |
---|---|---|
owner | address | The initial address of the owner of the contract. |
contractAddresses | ContractAddress[] | An array of ContractAddress structures containing addresses of related contracts. |
tokenAddresses | TokenAddress[] | An array of TokenAddress structures containing addresses of relevant ERC-20 tokens. |
uniswapV3Pools | UniswapV3Pool[] | An array of UniswapV3Pool structures containing the address and fee of the UniswapV3 pools. |
initialHealthFactorTarget | uint16 | The initial target health factor, used to manage risk. |
initialSlippageTolerance | uint16 | The initial slippage tolerance for token swaps. |
initialManagerDailyInvocationLimit | uint16 | The initial limit for the number of manager invocations per day. |
updateContractAddress
Generic update function to set the contract address for a given identifier.
Caller must have OWNER_ROLE
.
Emits a ContractAddressUpdated
event.
function updateContractAddress(string memory _identifier, address _newContractAddress) external onlyRole(OWNER_ROLE);
Parameters
Name | Type | Description |
---|---|---|
_identifier | string | The identifier for the contract address. |
_newContractAddress | address | The new contract address. |
updateTokenAddress
Generic update function to set the token address for a given identifier.
Caller must have OWNER_ROLE
.
Emits a TokenAddressUpdated
event.
function updateTokenAddress(string memory _identifier, address _newTokenAddress) external onlyRole(OWNER_ROLE);
Parameters
Name | Type | Description |
---|---|---|
_identifier | string | The identifier for the token address. |
_newTokenAddress | address | The new token address. |
updateUniswapV3Pool
Update UniSwapV3 pool details.
Caller must have OWNER_ROLE
.
Emits a UniswapV3PoolUpdated
event.
function updateUniswapV3Pool(string memory _identifier, address _newUniswapV3PoolAddress, uint24 _newUniswapV3PoolFee)
external
onlyRole(OWNER_ROLE);
updateHealthFactorTarget
Update the Health Factor target.
Caller must have MANAGER_ROLE
.
Emits a HealthFactorTargetUpdated
event.
function updateHealthFactorTarget(uint16 _healthFactorTarget) external onlyRole(MANAGER_ROLE);
Parameters
Name | Type | Description |
---|---|---|
_healthFactorTarget | uint16 | The new Health Factor target. |
updateSlippageTolerance
Update the Slippage Tolerance.
Caller must have MANAGER_ROLE
.
Emits a SlippageToleranceUpdated
event.
function updateSlippageTolerance(uint16 _slippageTolerance) external onlyRole(MANAGER_ROLE);
Parameters
Name | Type | Description |
---|---|---|
_slippageTolerance | uint16 | The new Slippage Tolerance. |
updateManagerDailyInvocationLimit
Update the Manager Daily Invocation Limit.
Caller must have OWNER_ROLE
.
Emits a ManagerDailyInvocationLimitUpdated
event.
function updateManagerDailyInvocationLimit(uint16 _managerDailyInvocationLimit) external onlyRole(OWNER_ROLE);
Parameters
Name | Type | Description |
---|---|---|
_managerDailyInvocationLimit | uint16 | The new Manager Daily Invocation Limit. |
_storeEventBlockNumber
Stores the block number of an event.
This function is called after an event is emitted to store the block number. Duplicates are not stored even if multiple events are emitted in the same block.
function _storeEventBlockNumber() private;
rebalance
Rebalance the Aave position.
The function rebalances the Aave position by converting any ETH to WETH, then WETH to wstETH.
It then deposits the wstETH into Aave.
If the health factor is below the target, it repays debt to increase the health factor.
Caller must have MANAGER_ROLE
.
Emits a Rebalanced
event.
function rebalance() public onlyRole(MANAGER_ROLE) returns (uint256 repaymentAmountUSDC);
Returns
Name | Type | Description |
---|---|---|
repaymentAmountUSDC | uint256 | The amount of debt repaid. |
reinvest
Reinvest any excess debt or collateral.
The function reinvests any excess collateral by converting any ETH to WETH, then WETH to wstETH.
It then deposits the wstETH into Aave.
If the health factor is below the target, outside of the allowed range, this function will fail.
Caller must have MANAGER_ROLE
.
Emits a Reinvested
event.
function reinvest() public payable onlyRole(MANAGER_ROLE) returns (uint256 reinvestedDebt);
Returns
Name | Type | Description |
---|---|---|
reinvestedDebt | uint256 | The amount of debt reinvested. |
deleverage
Deleverage the position by repaying all debt.
The function deleverages the position by taking out a flashloan to repay all debt
after setting the Health Factor target to the maximum value.
Caller must have MANAGER_ROLE
.
Emits a Deleveraged
event.
function deleverage() public onlyRole(MANAGER_ROLE);
aaveSupplyFromContractBalance
Convert any tokens in the contract to wstETH and supply to Aave.
The function converts any tokens in the contract to wstETH and supplies them to Aave.
Caller must have MANAGER_ROLE
.
Emits a AaveSuppliedFromContractBalance
event.
function aaveSupplyFromContractBalance() public payable onlyRole(MANAGER_ROLE) returns (uint256 suppliedCollateral);
Returns
Name | Type | Description |
---|---|---|
suppliedCollateral | uint256 | The amount of collateral supplied to Aave. |
aaveRepayUSDCFromContractBalance
Repay USDC debt from the contract balance.
The function repays USDC debt using all the USDC in the contract.
Caller must have MANAGER_ROLE
.
Emits a AaveRepayedUSDCFromContractBalance
event.
function aaveRepayUSDCFromContractBalance() public onlyRole(MANAGER_ROLE);
_delegateCallHelper
Delegate call helper function.
The internal function is used to delegate calls to other contracts.
function _delegateCallHelper(string memory _targetIdentifier, bytes memory _data) internal returns (bytes memory);
Parameters
Name | Type | Description |
---|---|---|
_targetIdentifier | string | The identifier of the target contract. |
_data | bytes | The data to send to the target contract. |
Returns
Name | Type | Description |
---|---|---|
<none> | bytes | result The result of the delegate call. |
delegateCallHelper
Delegate call helper function for the manager to call any function.
The public function is used to delegate calls to other contracts.
Caller must have MANAGER_ROLE
.
As the manager can only use identifiers already set in the contract,
it cannot call a contract that is not set (e.g. a malicious contract).
function delegateCallHelper(string memory _targetIdentifier, bytes memory _data)
public
onlyRole(MANAGER_ROLE)
returns (bytes memory result);
Parameters
Name | Type | Description |
---|---|---|
_targetIdentifier | string | The identifier of the target contract. |
_data | bytes | The data to send to the target contract. |
Returns
Name | Type | Description |
---|---|---|
result | bytes | The result of the delegate call. |
rescueEth
Rescue all ETH from the contract.
This function is intended for emergency use.
In normal operation, the contract shouldn't hold ETH,
as it is used to swap for wstETH.
It is called without an argument to rescue the entire balance.
Caller must have MANAGER_ROLE
.
The use of nonReentrant isn't required due to the rescueAddress
check for the OWNER_ROLE
and it drains 100% of the ETH balance anyway.
Throws AavePM__RescueEthFailed
if the ETH transfer fails.
Emits a RescueEth
event.
function rescueEth(address _rescueAddress) external onlyRole(MANAGER_ROLE) checkOwner(_rescueAddress);
Parameters
Name | Type | Description |
---|---|---|
_rescueAddress | address | The address to send the rescued ETH to. |
withdrawTokensFromContractBalance
Withdraw specified tokens from the contract balance.
The function withdraws the specified tokens from the contract balance to the owner.
Caller must have MANAGER_ROLE
.
Throws AavePM__InvalidWithdrawalToken
if the token is awstETH.
Throws AavePM__NoTokensToWithdraw
if there are no tokens to withdraw.
Emits a TokensWithdrawnFromContractBalance
event.
function withdrawTokensFromContractBalance(string memory _identifier, address _owner)
public
onlyRole(MANAGER_ROLE)
checkOwner(_owner);
Parameters
Name | Type | Description |
---|---|---|
_identifier | string | The identifier of the token to withdraw. |
_owner | address | The address to send the withdrawn tokens to. |
aaveWithdrawWstETH
Withdraw wstETH from Aave.
The function withdraws wstETH from Aave and sends it to the specified owner.
Caller must have MANAGER_ROLE
.
Throws AavePM__NoCollateralToWithdraw
if there is no collateral to withdraw.
Emits a AaveWithdrawnWstETH
event.
function aaveWithdrawWstETH(uint256 _amount, address _owner)
public
onlyRole(MANAGER_ROLE)
checkOwner(_owner)
returns (uint256 collateralDeltaBase);
Parameters
Name | Type | Description |
---|---|---|
_amount | uint256 | The amount of wstETH to withdraw in wstETH units. |
_owner | address | The address to send the withdrawn wstETH to. |
Returns
Name | Type | Description |
---|---|---|
collateralDeltaBase | uint256 | The change in collateral base value after withdrawing. |
aaveBorrowAndWithdrawUSDC
Borrow and withdraw USDC from Aave.
The function borrows USDC from Aave and withdraws it to the specified owner.
Caller must have MANAGER_ROLE
.
Throws AavePM__ZeroBorrowAmount
if the requested borrow amount is 0.
Throws AavePM__ZeroBorrowAndWithdrawUSDCAvailable
if the available borrow and withdraw amount is 0.
Emits a AaveBorrowedAndWithdrawnUSDC
event.
function aaveBorrowAndWithdrawUSDC(uint256 _amount, address _owner) public onlyRole(MANAGER_ROLE) checkOwner(_owner);
Parameters
Name | Type | Description |
---|---|---|
_amount | uint256 | The amount of USDC to borrow and withdraw. |
_owner | address | The address to send the borrowed and withdrawn USDC to. |
aaveClosePosition
Close the Aave position.
The function closes the Aave position by repaying all debt and withdrawing all wstETH to the specified owner.
Caller must have MANAGER_ROLE
.
Emits a AaveClosedPosition
event.
function aaveClosePosition(address _owner) public onlyRole(MANAGER_ROLE) checkOwner(_owner);
Parameters
Name | Type | Description |
---|---|---|
_owner | address | The address to send the withdrawn wstETH to. |
getCreator
Getter function to get the i_creator address.
Public function to allow anyone to view the contract creator.
function getCreator() public view returns (address creator);
Returns
Name | Type | Description |
---|---|---|
creator | address | The address of the creator. |
getEventBlockNumbers
Getter function to get the block numbers of all the contract events.
Public function to allow anyone to view the block numbers of all the contract events.
function getEventBlockNumbers() public view returns (uint64[] memory);
Returns
Name | Type | Description |
---|---|---|
<none> | uint64[] | eventBlockNumbers The array of event block numbers. |
getVersion
Getter function to get the contract version.
Public function to allow anyone to view the contract version.
function getVersion() public pure returns (string memory version);
Returns
Name | Type | Description |
---|---|---|
version | string | The contract version. |
getContractAddress
Generic getter function to get the contract address for a given identifier.
Public function to allow anyone to view the contract address for the given identifier.
function getContractAddress(string memory _identifier) public view returns (address contractAddress);
Parameters
Name | Type | Description |
---|---|---|
_identifier | string | The identifier for the contract address. |
Returns
Name | Type | Description |
---|---|---|
contractAddress | address | The contract address corresponding to the given identifier. |
getTokenAddress
Generic getter function to get the token address for a given identifier.
Public function to allow anyone to view the token address for the given identifier.
function getTokenAddress(string memory _identifier) public view returns (address tokenAddress);
Parameters
Name | Type | Description |
---|---|---|
_identifier | string | The identifier for the contract address. |
Returns
Name | Type | Description |
---|---|---|
tokenAddress | address | The token address corresponding to the given identifier. |
getUniswapV3Pool
Getter function to get the UniswapV3 pool address and fee.
Public function to allow anyone to view the UniswapV3 pool address and fee.
function getUniswapV3Pool(string memory _identifier)
public
view
returns (address uniswapV3PoolAddress, uint24 uniswapV3PoolFee);
Parameters
Name | Type | Description |
---|---|---|
_identifier | string | The identifier for the UniswapV3 pool. |
Returns
Name | Type | Description |
---|---|---|
uniswapV3PoolAddress | address | The UniswapV3 pool address. |
uniswapV3PoolFee | uint24 | The UniswapV3 pool fee. |
getHealthFactorTarget
Getter function to get the Health Factor target.
Public function to allow anyone to view the Health Factor target value.
function getHealthFactorTarget() public view returns (uint16 healthFactorTarget);
Returns
Name | Type | Description |
---|---|---|
healthFactorTarget | uint16 | The Health Factor target. |
getHealthFactorTargetMinimum
Getter function to get the Health Factor Target minimum.
Public function to allow anyone to view the Health Factor Target minimum value.
function getHealthFactorTargetMinimum() public pure returns (uint16 healthFactorTargetMinimum);
Returns
Name | Type | Description |
---|---|---|
healthFactorTargetMinimum | uint16 | The Health Factor Target minimum value. |
getSlippageTolerance
Getter function to get the Slippage Tolerance.
Public function to allow anyone to view the Slippage Tolerance value.
function getSlippageTolerance() public view returns (uint16 slippageTolerance);
Returns
Name | Type | Description |
---|---|---|
slippageTolerance | uint16 | The Slippage Tolerance value. |
getSlippageToleranceMaximum
Getter function to get the Slippage Tolerance maximum.
Public function to allow anyone to view the Slippage Tolerance maximum value.
function getSlippageToleranceMaximum() public pure returns (uint16 slippageToleranceMaximum);
Returns
Name | Type | Description |
---|---|---|
slippageToleranceMaximum | uint16 | The Slippage Tolerance maximum value. |
getManagerDailyInvocationLimit
Getter function to get the manager role daily invocation limit.
Public function to allow anyone to view the manager role daily invocation limit.
function getManagerDailyInvocationLimit() public view returns (uint16 managerDailyInvocationLimit);
Returns
Name | Type | Description |
---|---|---|
managerDailyInvocationLimit | uint16 | The manager role daily invocation limit. |
getManagerInvocationTimestamps
Getter function to get the manager invocation timestamps.
Public function to allow anyone to view the manager invocation timestamps.
function getManagerInvocationTimestamps() public view returns (uint64[] memory);
Returns
Name | Type | Description |
---|---|---|
<none> | uint64[] | managerInvocationTimestamps The array of manager invocation timestamps. |
getContractBalance
Getter function to get the balance of the provided identifier.
Public function to allow anyone to view the balance of the provided identifier.
function getContractBalance(string memory _identifier) public view returns (uint256 contractBalance);
Parameters
Name | Type | Description |
---|---|---|
_identifier | string | The identifier for the token address. |
Returns
Name | Type | Description |
---|---|---|
contractBalance | uint256 | The balance of the specified token identifier. |
getRoleMembers
Getter function to get all the members of a role.
Public function to allow anyone to view the members of a role.
function getRoleMembers(string memory _roleString) public view returns (address[] memory);
Parameters
Name | Type | Description |
---|---|---|
_roleString | string | The identifier for the role. |
Returns
Name | Type | Description |
---|---|---|
<none> | address[] | members The array of addresses that are members of the role. |
getWithdrawnUSDCTotal
Getter function to get the total amount of USDC withdrawn.
Public function to allow anyone to view the total amount of USDC withdrawn.
function getWithdrawnUSDCTotal() public view returns (uint256 withdrawnUSDCTotal);
Returns
Name | Type | Description |
---|---|---|
withdrawnUSDCTotal | uint256 | The total amount of USDC withdrawn. |
getReinvestedDebtTotal
Getter function to get the total amount of reinvested debt.
Public function to allow anyone to view the total amount of reinvested debt.
function getReinvestedDebtTotal() public view returns (uint256 reinvestedDebtTotal);
Returns
Name | Type | Description |
---|---|---|
reinvestedDebtTotal | uint256 | The total amount of reinvested debt. |
getTotalCollateralDelta
Getter function to get the total collateral delta.
Public function to allow anyone to view the total collateral delta.
function getTotalCollateralDelta() public returns (uint256 totalCollateralDelta, bool isPositive);
Returns
Name | Type | Description |
---|---|---|
totalCollateralDelta | uint256 | The total collateral delta. |
isPositive | bool | A boolean indicating if the total collateral delta is positive. |
getSuppliedCollateralTotal
Getter function to get the total amount of supplied collateral.
Public function to allow anyone to view the total amount of supplied collateral.
function getSuppliedCollateralTotal() public view returns (uint256 suppliedCollateralTotal);
Returns
Name | Type | Description |
---|---|---|
suppliedCollateralTotal | uint256 | The total amount of supplied collateral. |
getMaxBorrowAndWithdrawUSDCAmount
Getter function to get the maximum amount of USDC that can be borrowed and withdrawn.
Public function to allow anyone to view the maximum amount of USDC that can be borrowed and withdrawn.
function getMaxBorrowAndWithdrawUSDCAmount() public view returns (uint256 maxBorrowAndWithdrawUSDCAmount);
Returns
Name | Type | Description |
---|---|---|
maxBorrowAndWithdrawUSDCAmount | uint256 | The maximum amount of USDC that can be borrowed and withdrawn. |
getReinvestableAmount
Getter function to get the reinvestable amount.
Public function to allow anyone to view the reinvestable amount.
function getReinvestableAmount() public returns (uint256 reinvestableAmount);
Returns
Name | Type | Description |
---|---|---|
reinvestableAmount | uint256 | The reinvestable amount. |
getRoleMember
Getter function to get the role member at the specified index.
Public function to allow anyone to view the role member at the specified index.
function getRoleMember(bytes32 role, uint256 index)
public
view
override(IAavePM, AccessControlEnumerableUpgradeable)
returns (address);
Parameters
Name | Type | Description |
---|---|---|
role | bytes32 | The role to get the member from in a bytes32 format keccak256("ROLE_NAME"). |
index | uint256 | The index of the member. |
getRoleMemberCount
Getter function to get the number of members in a role.
Public function to allow anyone to view the number of members in a role.
function getRoleMemberCount(bytes32 role)
public
view
override(IAavePM, AccessControlEnumerableUpgradeable)
returns (uint256);
Parameters
Name | Type | Description |
---|---|---|
role | bytes32 | The role to get the member count from in a bytes32 format keccak256("ROLE_NAME"). |
getRoleAdmin
Getter function to get the role admin role.
Public function to allow anyone to view the role admin role.
function getRoleAdmin(bytes32 role)
public
view
override(IAavePM, IAccessControl, AccessControlUpgradeable)
returns (bytes32);
Parameters
Name | Type | Description |
---|---|---|
role | bytes32 | The role to get the admin role from in a bytes32 format keccak256("ROLE_NAME"). |
Returns
Name | Type | Description |
---|---|---|
<none> | bytes32 | The role admin role. |
grantRole
Grant a role to an account.
Caller must be an admin for the role.
function grantRole(bytes32 role, address account) public override(IAavePM, IAccessControl, AccessControlUpgradeable);
Parameters
Name | Type | Description |
---|---|---|
role | bytes32 | The role to grant in a bytes32 format keccak256("ROLE_NAME"). |
account | address | The account to grant the role to. |
hasRole
Check if an account has a role.
Public function to allow anyone to check if an account has a role.
function hasRole(bytes32 role, address account)
public
view
override(IAavePM, IAccessControl, AccessControlUpgradeable)
returns (bool);
Parameters
Name | Type | Description |
---|---|---|
role | bytes32 | The role to check in a bytes32 format keccak256("ROLE_NAME"). |
account | address | The account to check if they have the role. |
Returns
Name | Type | Description |
---|---|---|
<none> | bool | True if the account has the role, otherwise false. |
renounceRole
Renounce a role from an account.
Caller must have the role.
function renounceRole(bytes32 role, address callerConfirmation)
public
override(IAavePM, IAccessControl, AccessControlUpgradeable);
Parameters
Name | Type | Description |
---|---|---|
role | bytes32 | The role to renounce in a bytes32 format keccak256("ROLE_NAME"). |
callerConfirmation | address | The account to renounce the role from. |
revokeRole
Revoke a role from an account.
Caller must be an admin for the role.
function revokeRole(bytes32 role, address account) public override(IAavePM, IAccessControl, AccessControlUpgradeable);
Parameters
Name | Type | Description |
---|---|---|
role | bytes32 | The role to revoke in a bytes32 format keccak256("ROLE_NAME"). |
account | address | The account to revoke the role from. |
supportsInterface
Supports interface.
Public function to allow anyone to check if the contract supports the interface.
function supportsInterface(bytes4 interfaceId)
public
view
override(IAavePM, AccessControlEnumerableUpgradeable)
returns (bool);
Parameters
Name | Type | Description |
---|---|---|
interfaceId | bytes4 | The interface ID to check. |
Returns
Name | Type | Description |
---|---|---|
<none> | bool | True if the contract supports the interface, otherwise false. |
_authorizeUpgrade
Internal function to authorize an upgrade.
Caller must have OWNER_ROLE
.
function _authorizeUpgrade(address _newImplementation) internal override onlyRole(OWNER_ROLE);
Parameters
Name | Type | Description |
---|---|---|
_newImplementation | address | Address of the new contract implementation. |
upgradeToAndCall
Upgrade the contract to a new implementation.
Caller must have OWNER_ROLE
.
function upgradeToAndCall(address newImplementation, bytes memory data)
public
payable
override(IAavePM, UUPSUpgradeable);
Parameters
Name | Type | Description |
---|---|---|
newImplementation | address | Address of the new contract implementation. |
data | bytes | Data to send to the new implementation. |
executeOperation
Flash loan callback function.
This function is called by the Aave pool contract after the flash loan is executed. It is used to repay the flash loan and execute the operation. The function is called by the Aave pool contract and is not intended to be called directly.
function executeOperation(address asset, uint256 amount, uint256 premium, address initiator, bytes calldata params)
external
returns (bool);
Parameters
Name | Type | Description |
---|---|---|
asset | address | The address of the asset being flash loaned. |
amount | uint256 | The amount of the asset being flash loaned. |
premium | uint256 | The fee charged for the flash loan. |
initiator | address | The address of the contract that initiated the flash loan. |
params | bytes | The parameters for the flash loan operation. |
Returns
Name | Type | Description |
---|---|---|
<none> | bool | bool True if the operation was successful. |
FlashLoan
Author: EridianAlpha
This contract contains the functions for AavePM to execute a flash loan to repay debt and withdraw collateral.
Functions
_executeOperation
Flash loan callback function.
This function is called by the Aave pool contract after the flash loan is executed. It is used to repay the flash loan and execute the operation. The function is called by the Aave pool contract and is not intended to be called directly.
function _executeOperation(address asset, uint256 amount, uint256 premium, address initiator, bytes calldata)
internal
returns (bool);
Parameters
Name | Type | Description |
---|---|---|
asset | address | The address of the asset being flash loaned. |
amount | uint256 | The amount of the asset being flash loaned. |
premium | uint256 | The fee charged for the flash loan. |
initiator | address | The address of the contract that initiated the flash loan. |
<none> | bytes |
Returns
Name | Type | Description |
---|---|---|
<none> | bool | bool True if the operation was successful. |
FunctionChecks
Author: EridianAlpha
This contract contains the functions used inside AavePM modifiers.
Functions
_checkOwner
Check if the caller has the OWNER_ROLE
.
This function checks if the caller has the OWNER_ROLE
and reverts if it does not.
function _checkOwner(address _owner) internal view;
Parameters
Name | Type | Description |
---|---|---|
_owner | address | The address to check if it has the OWNER_ROLE . |
_checkManagerInvocationLimit
Check if manager invocations are within the daily limit.
This function checks if the manager invocations are within the daily limit and reverts if the limit is reached.
function _checkManagerInvocationLimit(uint64[] memory managerInvocations) internal view;
Parameters
Name | Type | Description |
---|---|---|
managerInvocations | uint64[] | The array of manager invocations. |