The MaxApyVault is an ERC4626-compatible vault contract that serves as the core component of the MaxAPY Protocol. It manages user deposits and strategy allocations to generate yield. The vault accepts deposits of a specific underlying asset, issues share to depositors, and allocates the funds across various yield-generating strategies.
Constants
uint256publicconstant MAXIMUM_STRATEGIES =20;// Maximum number of strategies the vault can manageuint256publicconstant MAX_BPS =10_000;// Base points scale (100%)uint256publicconstant SECS_PER_YEAR =31_556_952;// Seconds in a year (365.2425 days)uint256publicconstant AUTOPILOT_HARVEST_INTERVAL =1weeks;// Interval between automated harvests
errorQueueIsFull();// Withdrawal queue has reached maximum capacityerrorVaultInEmergencyShutdownMode();// Operation not allowed during emergency shutdownerrorStrategyInEmergencyExitMode();// Strategy is in emergency exit modeerrorInvalidZeroAddress();// Zero address provided where not allowederrorStrategyAlreadyActive();// Attempt to add already active strategyerrorStrategyNotActive();// Operation attempted on inactive strategyerrorInvalidStrategyVault();// Strategy's vault address doesn't matcherrorInvalidStrategyUnderlying();// Strategy's underlying asset doesn't matcherrorInvalidDebtRatio();// Debt ratio exceeds maximum allowederrorInvalidMinDebtPerHarvest();// Invalid minimum debt per harvest valueerrorInvalidPerformanceFee();// Performance fee exceeds maximum allowederrorInvalidManagementFee();// Management fee exceeds maximum allowederrorStrategyDebtRatioAlreadyZero();// Strategy's debt ratio is already zeroerrorInvalidQueueOrder();// Invalid withdrawal queue orderingerrorVaultDepositLimitExceeded();// Deposit would exceed vault's limiterrorInvalidZeroAmount();// Zero amount provided where not allowederrorInvalidZeroShares();// Zero shares amount where not allowederrorLossGreaterThanStrategyTotalDebt();// Reported loss exceeds strategy's total debterrorInvalidReportedGainAndDebtPayment();// Invalid gain and debt payment reportederrorFeesAlreadyAssesed();// Fees have already been assessed
Events
Strategy Management Events
Configuration Events
Operation Events
State Variables
Functions
Basic View Functions
name
Returns the name of the vault shares token.
Returns:
The token name
symbol
Returns the symbol of the vault shares token.
Returns:
The token symbol
asset
Returns the address of the underlying token that the vault accepts.
Returns:
The underlying asset address
totalAssets
Returns total assets managed by vault, including idle funds and assets deployed in strategies.
Returns:
The total assets under management
totalDeposits
Returns the sum of idle assets and debt allocated to strategies.
Returns:
The total accounted assets
sharePrice
Returns the current price of one vault share regarding the underlying asset.
Returns:
The current share price
Asset/Share Conversion Functions
convertToShares
Calculates how many shares would be minted for a given amount of assets.
Parameters:
assets: Amount of underlying assets to convert
Returns:
The equivalent amount of shares
convertToAssets
Calculates how many underlying assets a given amount of shares represents.
Parameters:
shares: Amount of shares to convert
Returns:
The equivalent amount of assets
Deposit Limit Functions
maxDeposit
Calculates the maximum amount of assets that can be deposited.
Parameters:
to: Address that would receive the shares (unused in calculation)
Returns:
Maximum deposit amount allowed
maxMint
Calculates the maximum amount of shares that can be minted.
Parameters:
to: Address that would receive the shares (unused in calculation)
Returns:
Maximum shares that can be minted
maxWithdraw
Returns the maximum amount of assets that an address can withdraw.
Parameters:
owner: Address of the shares owner
Returns:
Maximum assets that can be withdrawn
Preview Functions
previewMint
Simulates the amount of assets needed to mint a specific amount of shares.
Parameters:
shares: The amount of shares to mint
Returns:
The amount of assets required
previewWithdraw
Simulates the amount of shares needed to withdraw a specific amount of assets.
Parameters:
assets: The amount of assets to withdraw
Returns:
The amount of shares required
previewRedeem
Simulates the amount of assets that would be received when redeeming shares.
Parameters:
shares: The amount of shares to redeem
Returns:
The amount of assets that would be received
Strategy View Functions
creditAvailable
Returns the amount of additional funds a strategy can borrow from the vault.
Parameters:
strategy: The strategy address to check
Returns:
The amount of credit available
debtOutstanding
Returns the amount of debt that a strategy needs to repay to the vault.
Parameters:
strategy: The strategy address to check
Returns:
The amount of outstanding debt
getStrategyTotalDebt
Returns the total debt allocated to a strategy.
Parameters:
strategy: The strategy address to check
Returns:
The strategy's total debt
Deposit Functions
deposit
Deposits underlying assets into the vault and mints shares to the receiver. Only possible when vault is not in emergency shutdown.
Parameters:
assets: Amount of underlying assets to deposit
receiver: Address to receive the minted shares
Returns:
Amount of shares minted
depositWithPermit
Deposits assets using an EIP-2612 permit for approval. Prevents extra approve transaction.
Parameters:
owner: Owner of the assets
assets: Amount of assets to deposit
deadline: Timestamp until which the permit is valid
v: Signature parameter
r: Signature parameter
s: Signature parameter
receiver: Address to receive the shares
Returns:
Amount of shares minted
mint
Mints an exact amount of shares by depositing the necessary amount of assets.
Parameters:
shares: Amount of shares to mint
receiver: Address to receive the shares
Returns:
Amount of assets deposited
mintWithPermit
Mints exact shares using an EIP-2612 permit for approval.
Parameters:
owner: Owner of the assets
shares: Amount of shares to mint
deadline: Timestamp until which the permit is valid
v: Signature parameter
r: Signature parameter
s: Signature parameter
receiver: Address to receive the shares
Returns:
Amount of assets deposited
Withdrawal Functions
withdraw
Withdraws exact assets by burning the required amount of shares.
Parameters:
assets: Amount of assets to withdraw
receiver: Address to receive the assets
owner: Owner of the shares
Returns:
Amount of shares burned
redeem
Burns exact shares for underlying assets.
Parameters:
shares: Amount of shares to redeem
receiver: Address to receive the assets
owner: Owner of the shares
Returns:
Amount of assets withdrawn
Strategy Management Functions
addStrategy
Adds a new strategy to the vault. Can only be called by admin and not during emergency shutdown.
Parameters:
strategy: Address of the strategy to add
debtRatio: Percentage of vault's total assets that strategy can manage (in BPS)
maxDebtPerHarvest: Maximum debt the strategy can take on in a single harvest
minDebtPerHarvest: Minimum debt the strategy should take in a single harvest
performanceFee: Performance fee for the strategy (in BPS)
removeStrategy
Removes a strategy from the vault's withdrawal queue. Can only be called by admin and not during emergency shutdown.
Parameters:
strategy: Address of the strategy to remove
revokeStrategy
Revokes a strategy by setting its debt ratio to 0 and preventing future deposits. Can only be called by admin.
Parameters:
strategy: Address of the strategy to revoke
exitStrategy
Fully exits a strategy by liquidating all positions and removing it from the withdrawal queue. Can only be called by admin.
Parameters:
strategy: Address of the strategy to exit
updateStrategyData
Updates a strategy's configuration parameters. Can only be called by admin.
Parameters:
strategy: Address of the strategy to update
newDebtRatio: New debt ratio (in BPS)
newMaxDebtPerHarvest: New maximum debt per harvest
newMinDebtPerHarvest: New minimum debt per harvest
newPerformanceFee: New performance fee (in BPS)
Reporting Functions
report
Reports strategy performance and handles profit/loss accounting. Can only be called by strategies.
Parameters:
realizedGain: Realized profit
unrealizedGain: Unrealized profit
loss: Amount of losses
debtPayment: Amount of debt being repaid
managementFeeReceiver: Address to receive management fees
Returns:
Updated debt outstanding
Configuration Functions
setWithdrawalQueue
Sets the order of strategies for withdrawals. Can only be called by admin.
Parameters:
queue: Array of strategy addresses in withdrawal order
setPerformanceFee
Updates the vault's performance fee. Can only be called by admin.
Parameters:
_performanceFee: New performance fee (in BPS)
setManagementFee
Updates the vault's management fee. Can only be called by admin.
Parameters:
_managementFee: New management fee (in BPS)
setDepositLimit
Sets the maximum total assets the vault can accept. Can only be called by admin.
Parameters:
_depositLimit: New deposit limit
setEmergencyShutdown
Enables/disables emergency shutdown mode. Can only be called by emergency admin.
Parameters:
_emergencyShutdown: True to enable shutdown, false to disable
setTreasury
Updates the treasury address that receives fees. Can only be called by admin.
Parameters:
_treasury: New treasury address
setAutopilotEnabled
Enables/disables automated strategy harvesting. Can only be called by admin.
Parameters:
_autoPilotEnabled: True to enable autopilot, false to disable
setAutoPilot
Sets autopilot mode for a specific strategy. Can only be called by strategies.
Parameters:
_autoPilot: True to enable autopilot for the strategy
Internal Functions
_forceOneHarvest
Forces a harvest of the next strategy in autopilot mode.
Parameters:
harvester: Address that will receive extra shares for harvesting
Returns:
strategy: Address of the harvested strategy
success: Whether the harvest was successful
reason: Error reason if harvest failed
_reportLoss
Handles strategy loss reporting by adjusting debt ratios and total debt.
Parameters:
strategy: Strategy reporting the loss
loss: Amount of loss to report
_assessFees
Calculates and distributes performance, management, and strategist fees.
Parameters:
strategy: Strategy the fees are being assessed for
gain: Amount of profit to assess fees on
managementFeeReceiver: Address to receive management fees
Returns:
Total amount of fees assessed
_creditAvailable
Calculates available credit line for a strategy.
Parameters:
strategy: Strategy to check credit for
Returns:
Amount of credit available
_computeDebtLimit
Calculates maximum debt limit based on debt ratio and total assets.
Parameters:
_debtRatio: Debt ratio to use (in BPS)
totalAssets_: Total assets to base calculation on
Returns:
Calculated debt limit
_debtOutstanding
Calculates how much debt a strategy needs to pay back.
Parameters:
strategy: Strategy to check debt for
Returns:
Amount of outstanding debt
_organizeWithdrawalQueue
Reorganizes withdrawal queue by removing gaps and maintaining relative order.
_revokeStrategy
Internal function to revoke a strategy and update debt ratios.
Parameters:
strategy: Strategy to revoke
strategyDebtRatio: Current debt ratio of the strategy
_issueSharesForAmount
Calculates and mints shares for a given amount of assets.
Parameters:
to: Address to receive shares
amount: Amount of assets to convert to shares
Returns:
Amount of shares minted
Helper Functions
eitherIsZero
Checks if either of two values is zero.
Parameters:
a: First value to check
b: Second value to check
Returns:
True if either value is zero
inc
Returns value plus one.
Parameters:
x: Value to increment
Returns:
Incremented value
_sub0
Safely subtracts b from a, returning 0 if result would be negative.
Parameters:
a: Value to subtract from
b: Value to subtract
Returns:
Result of subtraction or 0
ERC4626 Override Functions
_underlyingDecimals
Returns decimals of the underlying token.
Returns:
Number of decimals
_decimalsOffset
Returns decimal offset used to prevent inflation attacks.
Returns:
Decimal offset value (6)
_totalAssets
Calculates total assets including idle funds and strategy positions.
Returns:
Total assets under management
_totalDeposits
Returns sum of idle assets and total debt.
Returns:
Total deposited assets
_deposit
Internal deposit implementation with additional checks.
bool public emergencyShutdown; // Emergency shutdown state
bool public autoPilotEnabled; // Automated harvesting state
uint8 private immutable _decimals; // Underlying token decimals
uint8 public nexHarvestStrategyIndex; // Next strategy index to harvest
uint256 public depositLimit; // Maximum total assets limit
uint256 public debtRatio; // Total debt ratio across strategies (in BPS)
uint256 public totalIdle; // Tokens held in vault
uint256 public totalDebt; // Total tokens allocated to strategies
uint256 public lastReport; // Timestamp of last strategy report
uint256 public performanceFee; // Performance fee rate (in BPS)
uint256 public managementFee; // Management fee rate (in BPS)
address public treasury; // Fee recipient address
mapping(address => StrategyData) public strategies; // Strategy data mapping
address[MAXIMUM_STRATEGIES] public withdrawalQueue; // Strategy withdrawal order
string private _name; // Vault shares token name
string private _symbol; // Vault shares token symbol
address private immutable _underlyingAsset; // Underlying asset address
function name() public view override returns (string memory)
function symbol() public view override returns (string memory)
function asset() public view override returns (address)
function totalAssets() public view override returns (uint256)
function totalDeposits() public view returns (uint256)
function sharePrice() external view returns (uint256)
function convertToShares(uint256 assets) public view override returns (uint256)
function convertToAssets(uint256 shares) public view override returns (uint256)
function maxDeposit(address to) public view override returns (uint256)
function maxMint(address to) public view override returns (uint256)
function maxWithdraw(address owner) public view override returns (uint256)
function previewMint(uint256 shares) public view override returns (uint256)
function previewWithdraw(uint256 assets) public view override returns (uint256)
function previewRedeem(uint256 shares) public view override returns (uint256)
function creditAvailable(address strategy) external view returns (uint256)
function debtOutstanding(address strategy) external view returns (uint256)
function getStrategyTotalDebt(address strategy) external view returns (uint256)
function deposit(uint256 assets, address receiver) public returns (uint256 shares)