# Rebalancing & Allocation Engine

Morfa's automated off-chain worker (`morfa-worker`) continuously monitors Ethereum Mainnet USDC lending markets and executes reallocations across both **Mode B (`Morfa Vault`)** and **Mode A (`Direct Wallet`)** while respecting every Curator cap, user guardrail, and on-chain safety invariant.

> Diagram (Rebalancing Pipeline): Step 01 Scan & Verify (Morpho Core REST + Merkl v4 6h APR + single-block RPC check) -> Step 02 Risk & Emergency Filters (toxic APY, oracle, liquidity, fail-closed on missing data) -> Step 03 Optimize & Gate (post-move AdaptiveCurveIRM math, conservatively discounted Merkl, net gain > cost) -> Step 04 Simulate & Send (mandatory eth_call pre-flight, Private RPC MEV protection, crash-safe log) -> Step 05 On-Chain Enforcement (Vault V2 Curator caps via VaultV2.multicall for Mode B; user guardrails and zero-custody conservation via rebalanceBatch for Mode A).

***

## Shared Execution Pipeline

Every periodic scan cycle follows five strict stages:

1. **Multi-source market scan & single-block verification:** The worker fetches listed Ethereum USDC markets, caps, and 6-hour realized averages from Morpho Core REST, fetches 6-hour coverage-weighted incentive rates from Merkl v4, and verifies top candidate markets directly against **Ethereum Mainnet RPC pinned to a single block** (`Morpho.market` + `AdaptiveCurveIRM.borrowRateView`).
2. **Crash-recovery reconciliation:** Before broadcasting any new transaction, the worker checks its PostgreSQL execution log for previously submitted transactions and reconciles their on-chain receipt status so restarts never produce duplicate or conflicting moves.
3. **Risk & emergency screening:** Markets failing utilization, TVL, free liquidity, IRM, or oracle checks (or missing required live data) are filtered out (fail closed). Emergency conditions are prioritized ahead of normal yield optimization.
4. **Mandatory pre-flight simulation (`eth_call`):** Every candidate transaction is simulated against current chain state before signing. Reverting or unprofitable calls are discarded without spending gas.
5. **Private RPC MEV protection:** Approved transactions are broadcast through a **Private RPC** endpoint rather than the public mempool to mitigate sandwiching, front-running, and failed-tx gas waste.

***

## Mode B: Morfa Vault Allocator (`mfUSDC`)

In Mode B, the worker holds Morpho Vault V2's **`Allocator`** role. It can only move USDC between markets already approved by the **Curator** within strict on-chain absolute, relative, and collateral caps.

### Multi-Market Water-Filling Optimization

Rather than concentrating the entire vault into one market until its rate collapses, the Vault Allocator runs an iterative **multi-market water-filling optimizer** across deployable vault capital (idle USDC plus withdrawable market positions):

* **Marginal post-move yield:** Each allocation slice is routed to the curated market offering the highest marginal effective yield **after** accounting for how that slice shifts `AdaptiveCurveIRM` utilization and after conservatively discounting volatile Merkl incentives.
* **Strict cap compliance:** Allocations simultaneously respect each market's absolute cap, relative cap (with a protective safety buffer on partial relative caps), adapter cap, and shared collateral caps across markets using the same collateral asset.
* **Utilization ceiling:** Target allocations never push any curated market above the `95%` utilization ceiling.

### Dynamic Liquidity Adapter Selection

On Morpho Vault V2, ordinary user deposits and withdrawals route automatically through the vault's designated **Liquidity Adapter** (in addition to idle USDC). At the end of every rebalance, the allocator ensures the Liquidity Adapter points to a healthy, high-liquidity curated market with full relative cap eligibility, generous absolute cap headroom, and safe utilization, preventing ordinary user deposits or withdrawals from reverting due to tight caps or exhausted liquidity.

### Atomic Execution & Profitability Gate

To avoid wasteful churn, the allocator only executes when the moved volume and projected net yield improvement comfortably exceed Ethereum gas costs. Approved adjustments execute in a single atomic **`VaultV2.multicall`** combining deallocations, allocations, and any Liquidity Adapter update.

***

## Mode A: Direct Wallet Keeper (`MorfaRebalancer`)

In Mode A, the worker holds **`KEEPER_ROLE`** on `MorfaRebalancer.sol`. It indexes on-chain `UserConfigUpdated` events to track opted-in addresses and evaluates each user's Morpho Blue USDC positions against whitelisted active markets.

### Conservative Yield Valuation

When evaluating whether to move a user's position from Market A to Market B, the keeper models:

1. **Exact post-move native rate impact** on both the source market (utilization rises slightly upon exit) and the target market (utilization drops slightly upon entry) via `AdaptiveCurveIRM`.
2. **Conservatively discounted Merkl incentives**, applying a haircut for campaign volatility and subtracting amortized Ethereum claim gas relative to the user's principal so small positions are never churned for unclaimable micro-rewards.
3. **Persistence & net-gain margin:** A rebalance triggers only when the conservatively projected net gain over the evaluation window meaningfully beats the `5 bps` (`0.05%`) rebalance fee and meets minimum economic thresholds.

### Single Best Market & Zero-Dust Share Exits

To minimize user rebalance fees and Ethereum gas overhead, the Direct Wallet keeper consolidates a wallet's largest non-optimal Morpho Blue USDC position into the **single highest-scoring active eligible market** using a **100% share-based withdrawal** (`shares > 0`, `assets = 0`). Exiting by shares ensures zero residual dust is left stranded in the old market.

### Batched Execution with Per-User Rollback Isolation

Eligible user moves are grouped into `MorfaRebalancer.rebalanceBatch(...)` calls. Internally, `MorfaRebalancer` wraps each individual user move inside an isolated `try / catch` (`executeBatchItem`):

* If one wallet's conditions change in the same block (for example, the user manually withdrew, disabled automation, or hit their personal cooldown/fee cap), only that single item reverts cleanly and emits `BatchItemFailed`.
* Every other valid user move in the batch executes normally without being blocked.
* Every move enforces slippage protection (`minSharesOut`) and all on-chain user guardrails (`maxFeeBps`, `cooldown`, rolling 30-day `periodFeeCap`).
