You can query how much you can withdraw from an asset you supplied by querying your AToken
balance that represents your position for a specific token.
The AToken
balance get minted when you call the supply()
function and gets burnt when you call withdraw()
. Simply query how much ATokens you have by calling the balanceOf()
function and that will be the maximum amount of token you can withdraw.
The hard part part knowing the AToken
address. You can get the address by calling the getReserveData()
function like this:
address aTokenAddress = IPool(AAVE_POOL_ADDRESS).getReserveData(STAKED_TOKEN_ADDRESS).aTokenAddress;
Where AAVE_POOL_ADDRESS
is the Aave Pool Address, unique for each Aave deployment and STAKED_TOKEN_ADDRESS
is the token address you supplied (DAI or USDC for example).
To call this you will need to add references to DataTypes library and to IPool:
library DataTypes {
struct ReserveConfigurationMap {
uint256 data;
}
struct ReserveData {
ReserveConfigurationMap configuration;
uint128 liquidityIndex;
uint128 currentLiquidityRate;
uint128 variableBorrowIndex;
uint128 currentVariableBorrowRate;
uint128 currentStableBorrowRate;
uint40 lastUpdateTimestamp;
uint16 id;
address aTokenAddress;
address stableDebtTokenAddress;
address variableDebtTokenAddress;
address interestRateStrategyAddress;
uint128 accruedToTreasury;
uint128 unbacked;
uint128 isolationModeTotalDebt;
}
}
interface IPool {
function getReserveData(
address asset) external view returns (DataTypes.ReserveData memory);
}
Once you have the AToken
address, you can know how much you're able to withdraw by calling the balanceOf()
function. For example you can withdraw all your supplied tokens the following way, assuming the tokens were staked by the smart contract:
IPool(AAVE_POOL_ADDRESS).withdraw(
IERC20(aTokenAddress).balanceOf(address(this)),
amount,
msg.sender
);