AavePM - Aave Position Manager


🧪 ALPHA TESTING PHASE 🧪


1. Overview

Docs Site: https://eridianalpha.github.io/aave-position-manager

A smart contract manager for Aave positions.

  1. Set a desired Health Factor.
  2. Send assets (ETH, WETH, wstETH, or USDC) to the contract.
  3. Reinvest and rebalance the position to maintain the desired Health Factor, either manually or with a bot.
  4. Borrow and withdraw USDC from the position while maintaining the desired Health Factor.

1.1. Key Functions

1.1.1. Owner Functions

FunctionRestrictionsDescription
upgradeToAndCallOWNER_ROLEUpgrade the contract.
updateContractAddressOWNER_ROLEUpdate the specified contract address.
updateTokenAddressOWNER_ROLEUpdate the specified token address.
updateUniswapV3PoolOWNER_ROLEUpdate the specified Uniswap V3 pool.
updateManagerDailyInvocationLimitOWNER_ROLEUpdate the daily invocation limit for the manager role.

1.1.2. Manager Functions

FunctionRestrictionsDescription
rebalanceMANAGER_ROLERebalance the Aave position to the desired Health Factor.
reinvestMANAGER_ROLEReinvest the Aave position to the desired Health Factor target.
deleverageMANAGER_ROLEDeleverage the Aave position by paying back all reinvested debt.
aaveSupplyFromContractBalanceMANAGER_ROLESupply all the collateral from the contract balance to Aave.
aaveRepayUSDCFromContractBalanceMANAGER_ROLERepay Aave position debt using all the USDC from the contract balance.
withdrawTokensFromContractBalanceMANAGER_ROLEWithdraw all the specified tokens from the contract to the specified owner.
aaveBorrowAndWithdrawUSDCMANAGER_ROLEBorrow USDC from Aave and withdraw to the specified owner.
aaveWithdrawWstETHMANAGER_ROLEWithdraw wstETH collateral from the Aave position to the specified owner.
aaveClosePositionMANAGER_ROLEClose the Aave position by repaying all debt and withdrawing all collateral to the specified owner.
updateHealthFactorTargetMANAGER_ROLESet the desired Health Factor target.
updateSlippageToleranceMANAGER_ROLESet the slippage tolerance for Uniswap V3 swaps.
rescueEthMANAGER_ROLERescue ETH from the contract to the specified owner.
delegateCallHelperMANAGER_ROLEExecute 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.

ChainCommand
Anvilmake deploy anvil
Base Sepoliamake deploy base-sepolia
Base Mainnetmake 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.

ChainCommand
Anvilmake upgrade anvil
Base Sepoliamake upgrade base-sepolia
Base Mainnetmake 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....

ChainCommand
Anvilmake grantRole anvil
Base Sepoliamake grantRole base-sepolia
Base Mainnetmake 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....

ChainCommand
Anvilmake revokeRole anvil
Base Sepoliamake revokeRole base-sepolia
Base Mainnetmake revokeRole base-mainnet

7.3. Fund contract with ETH

Input value in ETH e.g. 0.15.

ChainCommand
Anvilmake send-ETH anvil
Base Mainnetmake 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.

ChainCommand
Anvilmake update-hft anvil
Base Mainnetmake 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%.

ChainCommand
Anvilmake update-st anvil
Base Mainnetmake 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.

ChainCommand
Anvilmake rebalance anvil
Base Mainnetmake 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.

ChainCommand
Anvilmake reinvest anvil
Base Mainnetmake reinvest base-mainnet

7.8. Supply from contract balance to Aave

Supplies any ETH, WETH, wstETH, or USDC in the contract to Aave.

ChainCommand
Anvilmake supply anvil
Base Mainnetmake supply base-mainnet

7.9. Repay USDC from contract balance

Repay any USDC debt in the contract to repay Aave position debt.

ChainCommand
Anvilmake repay anvil
Base Mainnetmake 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....

ChainCommand
Anvilmake closePosition anvil
Base Mainnetmake 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....

ChainCommand
Anvilmake withdrawWstETH anvil
Base Mainnetmake 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....

ChainCommand
Anvilmake withdrawToken anvil
Base Mainnetmake 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....

ChainCommand
Anvilmake borrowUSDC anvil
Base Mainnetmake borrowUSDC base-mainnet

7.14. Get Contract Balance

Input value as token identifier e.g. USDC.

ChainCommand
Anvilmake getContractBalance anvil
Base Mainnetmake getContractBalance base-mainnet

7.15. Get Aave Account Data

Returns the Aave account data for the contract.

ChainCommand
Anvilmake getAaveAccountData anvil
Base Mainnetmake 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

MIT

Contents

IAaveFunctionsModule

Git Source

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

Git Source

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

Git Source

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

Git Source

Inherits: IERC20

This interface extends the ERC20 interface with the decimals function.

Functions

decimals

function decimals() external view returns (uint8);

IRebalanceModule

Git Source

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

Git Source

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

Git Source

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

Git Source

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

Git Source

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

NameTypeDescription
_aavePMProxyAddressaddressThe 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

NameTypeDescription
aavePoolAddressaddressThe address of the Aave pool contract.
tokenAddressaddressThe address of the token to deposit.
tokenBalanceuint256The 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

NameTypeDescription
aavePoolAddressaddressThe address of the Aave pool contract.
tokenAddressaddressThe address of the token to withdraw.
withdrawAmountuint256The 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

NameTypeDescription
aavePoolAddressaddressThe address of the Aave pool contract.
tokenAddressaddressThe address of the token to borrow.
borrowAmountuint256The 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

NameTypeDescription
aavePoolAddressaddressThe address of the Aave pool contract.
tokenAddressaddressThe address of the token to repay.
repayAmountuint256The 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

NameTypeDescription
aavePMIAavePMThe Aave Position Manager contract.

Returns

NameTypeDescription
initialCollateralBaseuint256The initial collateral in USD base unit with 8 decimals to the dollar.
totalDebtBaseuint256The total debt in USD base unit with 8 decimals to the dollar.
currentLiquidationThresholduint256The current liquidation threshold.
initialHealthFactorScaleduint256The initial health factor scaled to 2 decimal places.
healthFactorTargetuint16The health factor target.
aavePoolAddressaddressThe address of the Aave pool contract.
wstETHAddressaddressThe address of the wstETH token.
usdcAddressaddressThe 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

NameTypeDescription
totalCollateralBaseuint256The total collateral in USD base unit with 8 decimals to the dollar.
totalDebtBaseuint256The total debt in USD base unit with 8 decimals to the dollar.
availableBorrowsBaseuint256The available borrows in USD base unit with 8 decimals to the dollar.
currentLiquidationThresholduint256The current liquidation threshold.
ltvuint256The loan to value ratio.
healthFactoruint256The 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

NameTypeDescription
totalCollateralBaseuint256The total collateral in USD base unit with 8 decimals to the dollar.
reinvestedDebtTotaluint256The reinvested debt total in USD base unit with 8 decimals to the dollar.
suppliedCollateralTotaluint256The supplied collateral total in USD base unit with 8 decimals to the dollar.

Returns

NameTypeDescription
deltauint256The total collateral delta.
isPositiveboolA 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

NameTypeDescription
suppliedCollateraluint256The 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

NameTypeDescription
totalCollateralBaseuint256The total collateral in USD base unit with 8 decimals to the dollar.
totalDebtBaseuint256The total debt in USD base unit with 8 decimals to the dollar.
currentLiquidationThresholduint256The current liquidation threshold.
healthFactorTargetuint16The health factor target.

BorrowAndWithdrawUSDCModule

Git Source

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

NameTypeDescription
_aavePMProxyAddressaddressThe 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

NameTypeDescription
borrowAmountUSDCuint256The amount of USDC to borrow.
_owneraddressThe address to withdraw the USDC to.

Returns

NameTypeDescription
repaidReinvestedDebtuint256The 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

NameTypeDescription
totalCollateralBaseuint256The total collateral base in the Aave pool.
totalDebtBaseuint256The total debt base in the Aave pool.
currentLiquidationThresholduint256The current liquidation threshold in the Aave pool.
borrowAmountUSDCuint256The amount of USDC to borrow.
healthFactorTargetuint256The target Health Factor.

Returns

NameTypeDescription
repaidReinvestedDebtuint256The amount of reinvested debt repaid to increase the Health Factor.

RebalanceModule

Git Source

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

NameTypeDescription
_aavePMProxyAddressaddressThe 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

NameTypeDescription
totalDebtBaseuint256The total debt in base units.
aavePoolAddressaddressThe address of the Aave pool.
usdcAddressaddressThe address of the USDC token.
totalCollateralBaseuint256The total collateral in base units.
currentLiquidationThresholduint256The current liquidation threshold.
healthFactorTargetuint16The target health factor.

Returns

NameTypeDescription
repaymentAmountUSDCuint256The amount of USDC repaid.

ReinvestModule

Git Source

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

NameTypeDescription
_aavePMProxyAddressaddressThe 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

NameTypeDescription
reinvestedDebtuint256The 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

NameTypeDescription
aavePMIAavePMThe Aave Position Manager contract.
totalDebtBaseuint256The total debt in base units.
aavePoolAddressaddressThe address of the Aave pool.
usdcAddressaddressThe address of the USDC token.
wstETHAddressaddressThe address of the wstETH token.
initialCollateralBaseuint256The initial collateral in base units.
currentLiquidationThresholduint256The current liquidation threshold.
healthFactorTargetuint16The target health factor.

Returns

NameTypeDescription
borrowAmountUSDCuint256The amount of USDC borrowed.

TokenSwapsModule

Git Source

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

NameTypeDescription
_aavePMProxyAddressaddressThe 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

NameTypeDescription
_uniswapV3PoolIdentifierstringThe identifier of the UniswapV3 pool to use for the swap.
_tokenInIdentifierstringThe identifier of the token to swap.
_tokenOutIdentifierstringThe identifier of the token to receive from the swap.

Returns

NameTypeDescription
tokenOutIdentifierstringThe identifier of the token received from the swap.
amountOutuint256The 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

NameTypeDescription
aavePMIAavePMThe Aave Position Manager contract.
paramsIV3SwapRouter.ExactInputSingleParamsThe swap parameters.
currentBalanceuint256The current balance of the token to swap.

Returns

NameTypeDescription
amountOutuint256The 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

NameTypeDescription
aavePMIAavePMThe Aave Position Manager contract.
_currentBalanceuint256The current balance of the token to swap.
_uniswapV3PoolAddressaddressThe address of the UniswapV3 pool to use for the swap.
tokenOutAddressaddressThe address of the token to receive from the swap.

Returns

NameTypeDescription
minOutuint256The 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

NameTypeDescription
identifierstringThe identifier to check.

Returns

NameTypeDescription
<none>boolisETH True if the identifier is for ETH.

AavePM

Git Source

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

NameTypeDescription
_owneraddressThe 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

NameTypeDescription
owneraddressThe address of the owner of the contract.
contractAddressesContractAddress[]An array of ContractAddress structures containing addresses of related contracts.
tokenAddressesTokenAddress[]An array of TokenAddress structures containing addresses of relevant ERC-20 tokens.
uniswapV3PoolsUniswapV3Pool[]An array of UniswapV3Pool structures containing the address and fee of the UniswapV3 pools.
initialHealthFactorTargetuint16The initial target health factor, used to manage risk.
initialSlippageToleranceuint16The initial slippage tolerance for token swaps.
initialManagerDailyInvocationLimituint16

_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

NameTypeDescription
owneraddressThe initial address of the owner of the contract.
contractAddressesContractAddress[]An array of ContractAddress structures containing addresses of related contracts.
tokenAddressesTokenAddress[]An array of TokenAddress structures containing addresses of relevant ERC-20 tokens.
uniswapV3PoolsUniswapV3Pool[]An array of UniswapV3Pool structures containing the address and fee of the UniswapV3 pools.
initialHealthFactorTargetuint16The initial target health factor, used to manage risk.
initialSlippageToleranceuint16The initial slippage tolerance for token swaps.
initialManagerDailyInvocationLimituint16The 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

NameTypeDescription
_identifierstringThe identifier for the contract address.
_newContractAddressaddressThe 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

NameTypeDescription
_identifierstringThe identifier for the token address.
_newTokenAddressaddressThe 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

NameTypeDescription
_healthFactorTargetuint16The 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

NameTypeDescription
_slippageToleranceuint16The 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

NameTypeDescription
_managerDailyInvocationLimituint16The 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

NameTypeDescription
repaymentAmountUSDCuint256The 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

NameTypeDescription
reinvestedDebtuint256The 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

NameTypeDescription
suppliedCollateraluint256The 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

NameTypeDescription
_targetIdentifierstringThe identifier of the target contract.
_databytesThe data to send to the target contract.

Returns

NameTypeDescription
<none>bytesresult 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

NameTypeDescription
_targetIdentifierstringThe identifier of the target contract.
_databytesThe data to send to the target contract.

Returns

NameTypeDescription
resultbytesThe 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

NameTypeDescription
_rescueAddressaddressThe 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

NameTypeDescription
_identifierstringThe identifier of the token to withdraw.
_owneraddressThe 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

NameTypeDescription
_amountuint256The amount of wstETH to withdraw in wstETH units.
_owneraddressThe address to send the withdrawn wstETH to.

Returns

NameTypeDescription
collateralDeltaBaseuint256The 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

NameTypeDescription
_amountuint256The amount of USDC to borrow and withdraw.
_owneraddressThe 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

NameTypeDescription
_owneraddressThe 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

NameTypeDescription
creatoraddressThe 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

NameTypeDescription
<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

NameTypeDescription
versionstringThe 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

NameTypeDescription
_identifierstringThe identifier for the contract address.

Returns

NameTypeDescription
contractAddressaddressThe 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

NameTypeDescription
_identifierstringThe identifier for the contract address.

Returns

NameTypeDescription
tokenAddressaddressThe 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

NameTypeDescription
_identifierstringThe identifier for the UniswapV3 pool.

Returns

NameTypeDescription
uniswapV3PoolAddressaddressThe UniswapV3 pool address.
uniswapV3PoolFeeuint24The 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

NameTypeDescription
healthFactorTargetuint16The 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

NameTypeDescription
healthFactorTargetMinimumuint16The 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

NameTypeDescription
slippageToleranceuint16The 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

NameTypeDescription
slippageToleranceMaximumuint16The 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

NameTypeDescription
managerDailyInvocationLimituint16The 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

NameTypeDescription
<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

NameTypeDescription
_identifierstringThe identifier for the token address.

Returns

NameTypeDescription
contractBalanceuint256The 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

NameTypeDescription
_roleStringstringThe identifier for the role.

Returns

NameTypeDescription
<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

NameTypeDescription
withdrawnUSDCTotaluint256The 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

NameTypeDescription
reinvestedDebtTotaluint256The 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

NameTypeDescription
totalCollateralDeltauint256The total collateral delta.
isPositiveboolA 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

NameTypeDescription
suppliedCollateralTotaluint256The 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

NameTypeDescription
maxBorrowAndWithdrawUSDCAmountuint256The 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

NameTypeDescription
reinvestableAmountuint256The 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

NameTypeDescription
rolebytes32The role to get the member from in a bytes32 format keccak256("ROLE_NAME").
indexuint256The 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

NameTypeDescription
rolebytes32The 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

NameTypeDescription
rolebytes32The role to get the admin role from in a bytes32 format keccak256("ROLE_NAME").

Returns

NameTypeDescription
<none>bytes32The 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

NameTypeDescription
rolebytes32The role to grant in a bytes32 format keccak256("ROLE_NAME").
accountaddressThe 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

NameTypeDescription
rolebytes32The role to check in a bytes32 format keccak256("ROLE_NAME").
accountaddressThe account to check if they have the role.

Returns

NameTypeDescription
<none>boolTrue 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

NameTypeDescription
rolebytes32The role to renounce in a bytes32 format keccak256("ROLE_NAME").
callerConfirmationaddressThe 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

NameTypeDescription
rolebytes32The role to revoke in a bytes32 format keccak256("ROLE_NAME").
accountaddressThe 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

NameTypeDescription
interfaceIdbytes4The interface ID to check.

Returns

NameTypeDescription
<none>boolTrue 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

NameTypeDescription
_newImplementationaddressAddress 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

NameTypeDescription
newImplementationaddressAddress of the new contract implementation.
databytesData 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

NameTypeDescription
assetaddressThe address of the asset being flash loaned.
amountuint256The amount of the asset being flash loaned.
premiumuint256The fee charged for the flash loan.
initiatoraddressThe address of the contract that initiated the flash loan.
paramsbytesThe parameters for the flash loan operation.

Returns

NameTypeDescription
<none>boolbool True if the operation was successful.

FlashLoan

Git Source

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

NameTypeDescription
assetaddressThe address of the asset being flash loaned.
amountuint256The amount of the asset being flash loaned.
premiumuint256The fee charged for the flash loan.
initiatoraddressThe address of the contract that initiated the flash loan.
<none>bytes

Returns

NameTypeDescription
<none>boolbool True if the operation was successful.

FunctionChecks

Git Source

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

NameTypeDescription
_owneraddressThe 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

NameTypeDescription
managerInvocationsuint64[]The array of manager invocations.