# Auto Rebalancing

#### **Objective**

The **Auto Rebalancing Strategy** automates yield optimization across multiple predefined strategies — each representing a specific capital deployment method such as lending, LP farming, leveraged looping, or vault aggregation.

It continuously:

* **Activates pending deposits** into the most profitable strategy.
* **Rebalances or deactivates** positions when better yields are found or performance declines.
* **Processes withdrawals** safely by prioritizing liquidity sources to minimize friction.
* **Maintains tokenized vault interoperability** via [**ERC-4626**](https://docs.openzeppelin.com/contracts/5.x/erc4626) and [**ERC-7540**](https://eips.ethereum.org/EIPS/eip-7540) standards

***

### **1. Automation Overview**

#### **Trigger**

* **Frequency:** Every 1 hour (Cron)
* **Data fetched:**
  * Current and historical APYs per strategy
  * TVL and liquidity
  * Historical volatility metrics
  * Transaction costs (gas, slippage)

***

### **2. Opportunity Discovery**

Each **strategy** is a predefined configuration (asset pair, protocol, or vault).\
The rebalancing process evaluates all strategies to find the **best net yield** after accounting for risks and costs.

For each strategy:

1. Fetch performance metrics:
   * `supplyAPY`, `borrowAPY` (if relevant)
   * `TVL`, `liquidity`, `volatility`, `fees`
2. Compute **Net APY**:\
   $$APY\_{\text{net}} = APY\_{\text{gross}} - \left( C\_{\text{gas}} + C\_{\text{slippage}} + C\_{\text{fee}} \right)$$<br>
3. Store opportunities with all metadata for guard evaluation.

***

### **3. Independent Guard Checks**

Each candidate opportunity passes through independent guard checks before being eligible for activation or rebalancing.

Each guard can be toggled or weighted differently depending on strategy type.

* **Minimum Pending Amount**\
  Avoid activating small deposits.\
  \&#xNAN;*Example:* `pendingAssets ≥ 5000`
* **APY Improvement**\
  Ensure yield gain exceeds the threshold.\
  \&#xNAN;*Example:* `ΔAPY ≥ 0.2%`
* **APY Stability**\
  Avoid pools or vaults with volatile APYs.\
  \&#xNAN;*Example:* `volatility ≤ 0.5%`
* **Profit vs Gas**\
  Rebalance only if expected profit exceeds gas costs.\
  \&#xNAN;*Example:* `(ΔAPY × balance × freqEst) > gasCost`
* **Slippage Profitability**\
  Require at least 10 days of additional yield to offset slippage.\
  \&#xNAN;*Example:* `10-day profit > slippageCost`
* **TVL Capacity**\
  Limit exposure to small or illiquid pools.\
  \&#xNAN;*Example:* `strategyTVL × maxShare = vaultLimit`
* **TVL Stability**\
  Ensure liquidity is stable and not fluctuating excessively.\
  \&#xNAN;*Example:* `stdev(TVL)/mean(TVL) < 0.1`

***

### **4. Decision Engine**

The automation evaluates all eligible opportunities and selects the one with the **highest net APY** that passes all guards.

```python
best_opportunity = None

for opp in opportunities:
    if not check_apy_boost(opp.apy, currentAPY): continue
    if not check_apy_stability(opp.historicalAPY): continue
    if not check_profit_vs_gas(opp.apy, currentAPY, balance, freqEst, gasCost): continue
    if not check_slippage(opp.apy, currentAPY, balance, opp.slippageCost): continue
    if not check_tvl_capacity(opp.totalSupply, opp.poolTVL): continue
    if not check_tvl_stability(opp.historicalTVL): continue

    if not best_opportunity or opp.apy > best_opportunity.apy:
        best_opportunity = opp
```

***

### **5. Execution Logic**

| Condition                              | Action                                                  |
| -------------------------------------- | ------------------------------------------------------- |
| **Better strategy found**              | `IStrategy.rebalance()` into target strategy            |
| **No better yield & current APY < 0**  | `IStrategy.deactivate()` or shift to a safe asset       |
| **Pending deposits ≥ MIN\_ACTIVATION** | `IStrategy.activate()` (enter current or best strategy) |
| **Otherwise**                          | No action (wait for next cycle)                         |

***

### **6. Strategy Interface**

Every strategy integrates with the **Automation Controller** via a unified interface.\
This allows the rebalancer to manage any strategy type through standardized calls.

```solidity
interface IStrategy {
    function activate(bytes calldata params) external;
    function deactivate(bytes calldata params) external;
    function rebalance(bytes calldata oldParams, bytes calldata newParams) external;
    function getCurrentYield() external view returns (uint256);
    function getExpectedYield(bytes calldata params) external view returns (uint256);
    function getTVL() external view returns (uint256);
}
```

> Implementations of `IStrategy` may wrap looping, LP vaults, money markets, or any structured yield product.

***

### **7. Withdrawal Automation**

Withdrawals follow a prioritized flow to minimize capital movement:

1. **Pending Deposits First**\
   Serve withdrawal requests from unactivated deposits (instant runtime match).
2. **Idle Liquidity Second**\
   If insufficient, use liquidity already in the **redeemVault**.
3. **Deactivation (Last Resort)**\
   If the above sources can’t satisfy withdrawals, call\
   `IStrategy.deactivate()` to unwind positions and release liquidity.

This creates a **natural netting effect** between new deposits and redemptions.

***

### **8. Risk Framework**

* Yield improvement threshold (≥0.2%)
* APY stability filters
* Gas and slippage profitability guards
* TVL capacity and liquidity stability
* Minimum activation size
* Auto deactivation if APY < 0

All checks operate independently and can be updated without redeploying strategy contracts.

***

### **9. Yield Comparison Model**

To compare yields across heterogeneous strategies, normalize all metrics to a **net annualized APY**:

$$
APY\_{\text{net}} = APY\_{\text{strategy}} - C\_{\text{gas}} - C\_{\text{slippage}} - C\_{\text{risk}}
$$

A rebalance is triggered when:

$$
\Delta APY = APY\_{\text{net,new}} - APY\_{\text{net,current}}
$$

***

### **10. Rebalance Flow**

1. Detect better opportunity (ΔAPY > threshold).
2. Validate all guard checks.
3. Execute:

   ```solidity
   IStrategy.rebalance(oldParams, newParams);
   ```
4. Rebalance transaction redistributes capital from the underperforming strategy to the target one.
5. Updated positions are stored in the Automation Controller state.

***

#### **Key Takeaway**

The **Auto Rebalancing Strategy** acts as a **universal yield optimizer** for any **ERC-4626 or ERC-7540-compatible vault**, using **Ditto’s secure automation** to maximize returns while maintaining safety and composability.

It provides a unified framework for automated capital deployment, rebalancing, and withdrawals — built for reliability, modularity, and cross-protocol interoperability.
