# MaxApyHarvester

## Overview

The MaxApyHarvester contract serves as an internal mechanism to execute harvests atomically. It manages strategy allocations and harvests for the MaxApy protocol, handling batch operations for multiple strategies.

## Constants

```solidity
uint256 public constant ADMIN_ROLE = _ROLE_0;     // Role for administrative functions
uint256 public constant KEEPER_ROLE = _ROLE_1;    // Role for keeper functions
address public constant DEFAULT_HARVESTER = address(0);  // Default harvester address
```

## Errors

```solidity
error AddStrategyFailed();           // Strategy addition failed
error CantReceiveETH();             // Contract cannot receive ETH
error Fallback();                   // Fallback function called
error HarvestFailed();              // Harvest operation failed
error NotOwner();                   // Caller is not the owner
error MaximumStrategiesReached();   // Maximum strategy limit reached
```

## State Variables

```solidity
IStrategy strategy;    // Reference to the current strategy being processed
```

## Structs

```solidity
struct AllocationData {
    address strategyAddress;        // Address of the strategy
    uint256 debtRatio;             // Debt ratio for the strategy
    uint256 maxDebtPerHarvest;     // Maximum debt per harvest
    uint256 minDebtPerHarvest;     // Minimum debt per harvest
    uint256 performanceFee;        // Performance fee percentage
}

struct HarvestData {
    address strategyAddress;           // Strategy address to harvest
    uint256 minExpectedBalance;        // Minimum expected balance after harvest
    uint256 minOutputAfterInvestment;  // Minimum output after investment
    uint256 deadline;                  // Deadline for harvest operation
}
```

## Functions

### Constructor

```solidity
constructor(address admin, address[] memory keepers)
```

Initializes the contract with admin and keeper roles.

Parameters:

* `admin`: Address of the admin
* `keepers`: Array of keeper addresses to be granted roles

### Fallback Functions

### fallback

```solidity
fallback() external payable
```

Reverts any direct calls to the contract.

### receive

```solidity
receive() external payable
```

Reverts any ETH transfers to the contract.

### Core Functions

### batchAllocate

```solidity
function batchAllocate(IMaxApyVault vault, AllocationData[] calldata strategies) public checkRoles(KEEPER_ROLE)
```

Executes batch strategy allocation for the MaxApy protocol.

Parameters:

* `vault`: MaxApyVault contract instance
* `strategies`: Array of strategy allocation data

### batchHarvest

```solidity
function batchHarvest(IMaxApyVault vault, HarvestData[] calldata harvests) public checkRoles(KEEPER_ROLE)
```

Executes batch harvesting operations for multiple strategies.

Parameters:

* `vault`: MaxApyVault contract instance
* `harvests`: Array of harvest data for strategies

### batchAllocateAndHarvest

```solidity
function batchAllocateAndHarvest(
    IMaxApyVault vault,
    AllocationData[] calldata allocations,
    HarvestData[] calldata harvests
) external returns (bool)
```

Combines batch allocation and harvesting in a single transaction.

Parameters:

* `vault`: MaxApyVault contract instance
* `allocations`: Array of strategy allocation data
* `harvests`: Array of harvest data

Returns:

* Boolean indicating success

### Simulation Functions

### \_simulateBatchAllocateAndHarvest

```solidity
solidityCopyfunction _simulateBatchAllocateAndHarvest(
    IMaxApyVault vault,
    AllocationData[] calldata allocations,
    HarvestData[] calldata harvests
) public
```

Internal function that performs a dry-run of batch allocation and harvest operations. It simulates the entire process of adding new strategies and harvesting, capturing the state changes without permanently altering the blockchain state.

This function works by:

1. Recording initial total assets
2. Simulating strategy allocations
3. Simulating harvests for each strategy
4. Collecting detailed simulation results
5. Reverting with encoded data containing all simulation outcomes

Parameters:

* `vault`: MaxApyVault contract instance
* `allocations`: Array of strategy allocation data
* `harvests`: Array of harvest data

### simulateBatchAllocateAndHarvest

```solidity
solidityCopyfunction simulateBatchAllocateAndHarvest(
    IMaxApyVault vault,
    AllocationData[] calldata allocations,
    HarvestData[] calldata harvests
) external returns (
    uint256 totalAssetsBefore,
    uint256 totalAssetsAfter,
    bytes[] memory simulationResults
)
```

An external function that provides a safe way to preview the outcomes of strategy changes and harvests before actually executing them. This function is crucial for risk management and optimization of strategy allocations.

Key benefits:

* Allows analysis of potential returns before committing funds
* It helps in comparing different strategy combinations
* Provides insights into expected asset value changes
* Enables validation of allocation decisions before execution
* Assists in optimizing harvest parameters

Parameters:

* `vault`: MaxApyVault contract instance
* `allocations`: Array of strategy allocation data
* `harvests`: Array of harvest data

Returns:

* `totalAssetsBefore`: Total vault assets before simulated operations
* `totalAssetsAfter`: Projected total assets after operations
* `simulationResults`: Detailed results for each strategy, including:
  * Expected balances
  * Investment outputs
  * Intended vs actual invest/divest amounts
  * Strategy-specific performance metrics

Usage: This simulation mechanism is essential for protocol management, allowing operators to:

1. Test new strategy combinations safely
2. Validate allocation ratios
3. Preview harvest outcomes
4. Optimize timing and parameters of operations
5. Minimize risks when adjusting strategy allocations

### Modifiers

### checkRoles

```solidity
modifier checkRoles(uint256 roles)
```

Ensures caller has required roles.

Parameters:

* `roles`: Required role permissions
