# `MorfaRebalancer` Contract Spec

**`MorfaRebalancer.sol`** is the immutable, non-upgradeable Solidity `0.8.28` (Cancun EVM) smart contract that powers **Mode A (`Direct Wallet`)** automated rebalancing on Morpho Blue.

* **Ethereum Mainnet Address:** [`0x2135195643CCC32513Da3baDC6394FbaB8Fb9cfA`](https://etherscan.io/address/0x2135195643CCC32513Da3baDC6394FbaB8Fb9cfA#code) (deployed at block `#26570409`, verified on Etherscan V2 & Sourcify `exact_match`)
* **Verified Source Code:** [`Rolaman/morfa-contracts/contracts/MorfaRebalancer.sol`](https://github.com/Rolaman/morfa-contracts/blob/main/contracts/MorfaRebalancer.sol)
* **Automated Security Scan:** [Nethermind AuditAgent Scan #3 PDF](https://github.com/Rolaman/morfa-contracts/blob/main/audits/auditagent-scan-3-2026-12-06.pdf) ([summary & finding disposition](https://github.com/Rolaman/morfa-contracts/blob/main/audits/README.md))

***

## Immutable On-Chain Constants

These values are compiled directly into the deployed bytecode and **cannot be changed by any governance role**:

| Constant | Value | Meaning |
| --- | --- | --- |
| `MORPHO` | `0xBBBBBbbBBb9cC5e90e3b3Af64bdAF62C37EEFFCb` | Immutable Morpho Blue core contract. |
| `USDC` | `0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48` | Immutable Circle Ethereum USDC (`6` decimals). |
| `TIMELOCK_DELAY` | `48 hours` (`172,800s`) | Mandatory wait before executing queued market additions, fee increases, or fee recipient changes. |
| `MAX_FEE_BPS` | `100` (`1.00%`) | Absolute hard ceiling on protocol rebalance fee (`feeBps`). Initial fee at deployment: `5 bps` (`0.05%`). |
| `MIN_MARKET_SUPPLY` | `100_000e6` (`100,000 USDC`) | Minimum pre-supply target Morpho Blue market `totalSupplyAssets` required before deposit. |
| `MAX_TARGET_UTILIZATION_WAD` | `0.95e18` (`95.00%`) | Maximum pre-supply target market utilization allowed before deposit. |
| `FEE_PERIOD_DURATION` | `30 days` (`2,592,000s`) | Resetting fee-cap window anchored on a user's first non-zero fee rebalance. |
| `MAX_ROUNDING_LOSS` | `2` (`2 wei USDC`) | Maximum acceptable rounding loss between `netAssets` supplied and resulting `sharesOut` asset value. |

***

## User Configuration Storage (`UserConfig`)

Each Mode A wallet's personal guardrails and accounting live in a compact 2-slot `UserConfig` struct:

```solidity
struct UserConfig {
    bool enabled;           // Master opt-in switch
    uint16 maxFeeBps;       // Max acceptable rebalance fee (0..100 bps)
    uint32 cooldown;        // Min seconds between completed rebalances
    uint48 lastRebalanceAt; // Timestamp of last rebalance
    uint48 periodStart;     // Anchor timestamp of current 30-day fee period
    uint32 configVersion;   // Monotonic version incremented on every config/disable write
    uint64 nonce;           // Monotonic per-user rebalance nonce
    uint128 periodFeeCap;   // Max total USDC fees (6 dec) per 30-day period
    uint128 periodFeeSpent; // USDC fees spent so far in current 30-day period
}
```

***

## Primary User-Facing Functions

All user configuration functions below are **always callable, even when `MorfaRebalancer` is paused**.

### `enableWithSig` (EOA 1-Transaction Onboarding)

Atomically submits a user's EIP-712 Morpho `Authorization` signature to Morpho Blue and enables their personal guardrails in a single transaction.

```solidity
function enableWithSig(
    uint16 maxFeeBps,
    uint32 cooldown,
    uint128 periodFeeCap,
    Authorization calldata auth,
    Signature calldata sig
) external
```

* Requires `auth.authorizer == msg.sender`, `auth.authorized == address(this)`, and `auth.isAuthorized == true`.
* Front-run resilient: skips `MORPHO.setAuthorizationWithSig` only if the caller is already authorized **and** `auth.nonce < MORPHO.nonce(sender)`, preventing post-revocation replay while surviving mempool front-running.

### `setConfig` (Update Guardrails / Smart Account Onboarding)

Configures or updates automation guardrails for `msg.sender`. Used by Smart Accounts after `Morpho.setAuthorization(rebalancer, true)` and by any wallet updating limits later.

```solidity
function setConfig(
    bool enabled,
    uint16 maxFeeBps,
    uint32 cooldown,
    uint128 periodFeeCap
) external
```

* Requires `maxFeeBps <= MAX_FEE_BPS` (`100`).
* Increments `configVersion` and emits `UserConfigUpdated`.
* **Never resets** `periodFeeSpent`, `periodStart`, `lastRebalanceAt`, or `nonce`.

### `disable` (1-Call Off-Switch)

Immediately disables automated rebalancing for `msg.sender` and increments `configVersion`, invalidating any queued keeper call.

```solidity
function disable() external
```

*(For full protocol-level revocation on Morpho Blue, call `Morpho.setAuthorization(0x2135195643CCC32513Da3baDC6394FbaB8Fb9cfA, false)` directly on `0xBBBBBbbBBb9cC5e90e3b3Af64bdAF62C37EEFFCb`.)*

### View Helpers

```solidity
function getUserConfig(address user) external view returns (UserConfig memory);

function getRemainingPeriodFeeBudget(address user)
    external
    view
    returns (uint256 remaining, uint256 spentInWindow, bool windowWillReset);

function getActiveMarkets() external view returns (bytes32[] memory);
function isActiveMarket(bytes32 marketId) external view returns (bool);
```

***

## Keeper, Sentinel, Admin & Fee Boundaries (Summary)

For the full Solidity ABI, custom errors, and queue identifiers, see the verified source code at [Rolaman/morfa-contracts (`contracts/MorfaRebalancer.sol`)](https://github.com/Rolaman/morfa-contracts/blob/main/contracts/MorfaRebalancer.sol).

| Role | Functions | Hard Boundaries |
| --- | --- | --- |
| **`KEEPER_ROLE`** | `rebalance(RebalanceParams)`, `rebalanceBatch(RebalanceParams[])` | Requires `!paused`, valid deadline, `expectedVersion`/`expectedNonce` match, `MORPHO.isAuthorized(user, this)`, `currentFeeBps <= cfg.maxFeeBps`, cooldown elapsed (exempt on `WithdrawOnly` exits), `periodFeeSpent + fee <= periodFeeCap`, target `Active` with pre-supply `TVL ≥ 100k USDC` & `util ≤ 95%`, `sharesOut ≥ minSharesOut`, `≤ 2 wei` rounding, and `USDC.balanceOf(this) == usdcBefore + res.fee`. Rebalances exiting a `WithdrawOnly` market automatically enforce `currentFeeBps = 0`. |
| **`SENTINEL_ROLE`** | `disableMarketDeposits(marketId)`, `pause()` | Emergency defense only: sets `Active → WithdrawOnly` (`0 bps` cooldown-exempt exit) or pauses keeper calls. Cannot unpause, add markets, or touch fees. |
| **`DEFAULT_ADMIN_ROLE`** (`AccessControlDefaultAdminRules`, 48h 2-step transfer) | `queueAddMarket` / `executeAddMarket` / `cancelAddMarket`, `queueSetFeeBps` / `executeSetFeeBps` / `cancelSetFeeBps`, `queueSetFeeRecipient` / `executeSetFeeRecipient` / `cancelSetFeeRecipient`, `reduceFeeBps`, `disableMarketDeposits`, `pause`, `unpause`, `claimFees` | All market additions, fee increases, and recipient updates require the immutable `48h` timelock. `reduceFeeBps` is instant and downward-only. Role can be held by any Ethereum wallet. |
| **`feeRecipient`** | `claimFees()` | Pulls only accrued protocol fees; callable even while paused; never touches user principal. |

### Key Events for Indexing & Verification

* `UserConfigUpdated(address indexed user, bool enabled, uint32 configVersion, uint16 maxFeeBps, uint32 cooldown, uint128 periodFeeCap)`
* `Rebalanced(address indexed user, bytes32 indexed fromMarketId, bytes32 indexed toMarketId, uint256 withdrawnAssets, uint256 fee, uint256 suppliedAssets, uint256 sharesOut, uint64 nonce)`
* `BatchItemFailed(uint256 indexed index, address indexed user, bytes32 fromMarketId, bytes32 toMarketId, bytes reason)`
* `MarketStatusUpdated(bytes32 indexed marketId, MarketStatus oldStatus, MarketStatus newStatus)`
* `FeesClaimed(address indexed recipient, uint256 amount)`
