# System & Data Architecture

Morfa is structured as a modular TypeScript and Solidity monorepo where **on-chain custody and invariants live strictly in Ethereum Mainnet smart contracts**, while off-chain services handle market indexing, rate math, telemetry, and transaction preparation.

> Diagram (System Architecture): morfa-app prepares user-signed Ethereum Mainnet transactions client-side with wagmi/viem and @morpho-org/morpho-sdk v10 (VaultBundlesV1 / BlueBundlesV1) and reads live state through Next.js API routes (/api/vault, /api/markets, /api/user/\[address], /api/merkl/\[address], /api/history) backed by Morpho Core REST, Merkl v4, and optional PostgreSQL. morfa-worker shares deterministic math via morfa-shared, logs snapshots and crash-recovery state to PostgreSQL, and broadcasts keeper/allocator transactions via Private RPC to Ethereum Mainnet.

***

## Monorepo Components

| Package | Stack | Responsibility |
| --- | --- | --- |
| **`morfa-contracts`** | Solidity `0.8.28` (Cancun EVM), Hardhat 3, OpenZeppelin v5 | Immutable `MorfaRebalancer.sol`, deployment scripts, and unit/fuzz/Ethereum Mainnet fork test suites covering both Mode A and Mode B. |
| **`morfa-shared`** | TypeScript (`viem`) | Deterministic shared library used by both the web app and worker: Morpho `AdaptiveCurveIRM` math, Merkl v4 6-hour coverage-weighted APR parsing, Morpho Core REST adapters, and risk/decision models. |
| **`morfa-worker`** | Node.js / TypeScript, PostgreSQL | Autonomous background service executing periodic market scans, single-block RPC verification, Mode B `VaultV2.multicall` allocations, Mode A `rebalanceBatch` moves, Smart Emergency Evacuations, Private RPC submission, and crash-recovery tx reconciliation. |
| **`morfa-app`** | Next.js (App Router), React, `wagmi` / `viem`, `@morpho-org/morpho-sdk` v10 | Noncustodial web interface (`https://morfa.finance` & `/portfolio`), client-side transaction preparation, mandatory legal acknowledgment gate, and server-side read API routes. |
| **`morfa-docs`** | Vocs v2 (MDX) | Official documentation site (`https://docs.morfa.finance`), full-text search index, and machine-readable `llms.txt` / `llms-full.txt` exports. |
| **`morfa-infra`** | Reverse proxy & deployment config | TLS termination, routing, and service orchestration for `morfa.finance` and `docs.morfa.finance`. |

***

## Client-Side Transaction Architecture (`morfa-app`)

`morfa-app` never handles private keys and never routes user assets through proprietary custody contracts:

1. **SDK-native bundles:** Mode B deposits, withdrawals, and zero-dust redemptions are prepared with `@morpho-org/morpho-sdk` v10 (`VaultBundlesV1`). Mode A direct Morpho Blue supplies and withdrawals use `BlueBundlesV1`.
2. **Smart Account detection:** On wallet connection, `morfa-app` calls `publicClient.getCode(address)` to distinguish EOAs from contract Smart Accounts, automatically selecting EIP-2612 permits + `enableWithSig` for EOAs versus ERC-20 `approve` + 2-step `setAuthorization` / `setConfig` for Smart Accounts.
3. **Pre-flight simulation & validity guards:** Every user action runs `eth_call` simulation before prompting the wallet, enforces a **1-hour** deadline (refusing to submit with `< 60s` remaining), and applies `0.03%` default `maxSharePrice` tolerance on vault deposits.
4. **Block-watermark reconciliation:** After a user transaction confirms, `morfa-app` immediately refreshes on-chain balances and polls Morpho Core REST until the upstream indexer's block watermark catches up to the confirmed transaction's `blockNumber`, preventing stale UI flash-backs.

***

## Server-Side Read API Routes

`morfa-app` exposes read-only Next.js API routes that aggregate upstream Morpho Core REST (`https://api.morpho.org`), Merkl v4 (`https://api.merkl.xyz`), Ethereum RPC, and optional PostgreSQL history:

| Route | Data Served |
| --- | --- |
| `/api/vault` | Live Morfa Vault V2 (`mfUSDC`) telemetry: total assets, idle assets, Liquidity Adapter capacity, dynamic fees, curated allocations, caps, 6h Native APY, and 6h Merkl APR. |
| `/api/markets` | Full set of monitored Ethereum Mainnet Morpho Blue USDC markets with live 6h rates, utilization, LLTV, oracle addresses, and Eligible vs. Filtered screening status. |
| `/api/user/[address]` | Connected wallet's `mfUSDC` balance, ordinary withdrawable limit, direct Morpho Blue USDC supply positions, open borrow/collateral detection, and `MorfaRebalancer` guardrail config. |
| `/api/merkl/[address]` | Connected wallet's Ethereum Merkl rewards split into Claimable Now, Pending (Not in Root), Earned to Date, and `Ready (TREE)` vs. excluded claim status. |
| `/api/history` | Recent worker market snapshots, rebalance decision records, and executed transactions logged in PostgreSQL. |

***

## Resilience & Graceful Degradation

* **Optional PostgreSQL for the UI:** PostgreSQL stores historical worker snapshots, decision logs, and emergency persistence streaks. If the database is temporarily unreachable, `morfa.finance` continues serving live vault balances, markets, deposits, withdrawals, and Merkl claims directly from Ethereum RPC, Morpho Core REST, and Merkl v4.
* **Worker crash recovery:** Before sending any new on-chain transaction, `morfa-worker` reconciles any previously `submitted` transactions stored in PostgreSQL against live Ethereum receipts so process restarts never double-submit moves.
* **Zero-dependency user exits:** Even if every Morfa off-chain service were permanently offline, users retain direct on-chain access to their USDC and rewards via [Independent Exit (Without Morfa)](/guides/independent-exit).
