# Smart Contract Architecture

The protocol is composed of several **interconnected smart contracts** and modules, each optimized for MegaETH’s environment:

* **Order Book Contract:** Responsible for storing and managing limit orders. Likely organized by price levels, each with a linked list of orders (for FIFO matching). Functions include `placeOrder(price, size, side)`, `cancelOrder(orderId)`, and an internal `matchOrder()` that finds matching opposite orders. In MegaETH, this can be done efficiently with its high TPS and possibly using innovative data structures in storage (like a balanced BST or skip list of price->volume). All order placements and cancellations are on-chain transactions (unlike off-chain order books), ensuring full transparency and composability.
* **AMM Pool Contract:** Implements the AMM logic (virtual AMM or actual liquidity pools). It holds the pool’s reserves of assets (could be real reserves for spot; for perps these might be virtual, backed by LP collateral held elsewhere). It provides a function `executeSwap(amount, direction)` that the matching engine calls to fill residual orders. This function computes the new price and output using the invariant formula (e.g., constant product or Liquidity Book mechanism) and updates pool state. If using virtual liquidity, it also adjusts LP’s debt or PnL records accordingly.
* **Clearinghouse / Risk Engine Contract:** The core **clearinghouse** coordinates trades, margin, and risk checks:
  * Maintains **user account balances** (collateral deposits, open positions, PnL).
  * Enforces **margin requirements**: e.g., initial and maintenance margin for each position. On each trade, ensures the user has enough collateral (cross-margined across all positions if applicable) to support the position. If not, the trade is rejected.
  * Updates **funding payments**: has logic for updating funding indices each interval, and for settling funding when positions are closed or periodically for long-running positions.
  * Handles **liquidations**: if a user’s account falls below maintenance margin, the clearinghouse triggers liquidation of that account’s positions. Given MegaETH’s composability, this can be done by a flash auction or by third-party liquidators calling a `liquidate(account)` function that closes positions at market (using the CLOB/AMM) at a small discount in exchange for a reward.
  * Integrates with an **insurance fund**: If liquidation losses exceed collateral (creating bad debt), the insurance fund (a pool of assets funded by a portion of fees or external backstop) covers the shortfall. If insurance fund is exhausted, as a last resort, we could have a socialized loss or auto-deleveraging mechanism, but we aim to avoid this via conservative risk parameters.
* **Margin Asset Vaults:** There will be vault contracts for holding collateral assets (e.g., a vault for USDC, one for stETH, etc.). When users deposit margin, funds go into these vaults. The vaults might be integrated with yield strategies for idle funds (e.g., auto-deposit USDC into a compound-like protocol to earn interest when not needed – this effectively makes $r\_{quote}$ non-zero). The vault provides an interface to quickly withdraw or reallocate margin when needed for trade settlement.
* **Oracle Module:** Reliable price oracles are crucial. We use a **dual oracle** scheme:

  1. **On-Chain TWAP Oracle:** For the underlying asset (if it’s a DeFi token like stETH or cToken), use a time-weighted average price from a large AMM (if available) or from our own AMM over short intervals. This resists manipulation by averaging price over (say) 5-15 minutes.
  2. **Off-Chain Oracle (Chainlink or Similar):** Pull a trusted price feed for the asset. For something like stETH/ETH or stETH/USD, Chainlink feed or a network of MegaETH oracles can provide periodic updates.

  The clearinghouse uses a **combination**: for marking positions and checking liquidation, we might use the lower of the two (to be safe on long positions) or some median. Perp index price is primarily from the external oracle with TWAP as fallback if oracle update is stale. This mitigates oracle manipulation: an attacker can’t easily trick both oracles at once.
* **Funding Calculator Module:** A sub-contract or library that calculates the funding rate each interval (as per the formula above) and stores the `fundingIndex`. This may also handle the increment of the index over time for continuous funding. It is called by the clearinghouse at set intervals (e.g., via a MegaETH native scheduler or by anyone calling a `poke()` function, or automatically each block if integrated with block production).
* **Liquidation Module:** A dedicated component (could be part of clearinghouse) to find and liquidate under-margined accounts. On MegaETH, this can be automated by a network of bots or a built-in scheduler that scans accounts. Because MegaETH allows **atomic multi-leg transactions**, a liquidator could, in one transaction, take over an account’s position and simultaneously place covering orders or use the AMM to offset it, thereby earning a fee. The protocol can also offer a **Dutch auction** mechanism where liquidators bid on the right to liquidate, ensuring competition yields the best prices (minimizing user losses).
* **Cross-Margin & Portfolio Manager:** The cross-margin system means one account can hold multiple positions against a shared collateral pool. This module computes the **account equity = collateral + PnL + funding accruals** in real time. It also allows **portfolio margin** where different asset positions offset each other’s risk. For example, if a user is long stETH-PERP and short ETH-PERP, the risk engine recognizes the correlation and gives a margin credit (because stETH and ETH are correlated assets, the net risk is lower). MegaETH’s composability might even let users hold yield-bearing collateral that auto-adjusts margin (e.g., collateral that grows in value gradually provides increasing margin headroom, which the engine accounts for).
* **Governance & Parameters:** A configuration module controlled by governance can adjust parameters like: trading fees, funding rate caps, max leverage, maintenance margin %, interest rate inputs ($r\_{base}, r\_{quote}$ can be set here or fetched from external data like current staking yield), and emergency controls (pausing a market, etc.).

**MegaETH-Specific Optimizations:**

* **Parallel Transaction Processing:** If MegaETH supports parallel execution, we can have the CLOB order matching and AMM swap logic run in parallel threads, only syncing up at the end for final state. This means even complex orders can be processed without slowing block production.
* **Sub-Second Block Times:** With \~0.5s block times, we achieve near real-time order book updates. If needed, the matching engine can also batch multiple orders in one block (like a micro-batch auction), though likely not necessary with such speed.
* **Atomic Composability Examples:** A user could atomically:

  * Borrow against stETH in a lending protocol, then use the borrowed funds to trade perps in one transaction (leveraged yield farming strategies).
  * Place a limit order and simultaneously deposit additional margin from their wallet if that order happens to execute (two actions in one tx).
  * LPs could adjust their liquidity range based on a price move and claim accrued fees all in one go.

  These complex interactions are enabled by MegaETH’s design and greatly enhance user strategies and protocol integration.

**Module Interaction Flow:**

1. **Placing an Order:** User calls OrderBook.placeOrder. The order is stored. If it’s a market order, the Clearinghouse actually invokes the matching engine process described earlier, which will call OrderBook.matchOrder and AMM.executeSwap as needed. The Clearinghouse then updates user balances, calling MarginVaults to escrow any needed collateral or release any received assets.
2. **Periodic Funding Update:** A keeper or scheduler calls Clearinghouse.updateFunding(). This calls Oracle for index price, Funding module for rate calc, then updates each open position’s funding PnL (or updates a global accumulator). The funding payment transfers are not actually moved asset-by-asset at each interval; rather, the `fundingIndex` is updated and each position’s PnL is implicitly affected. Traders see their **unrealized PnL** change due to funding: longs decrease, shorts increase when funding is positive (and vice versa).
3. **Liquidation:** Liquidator calls Clearinghouse.liquidate(accountX). The contract verifies accountX is below maintenance margin via current oracle prices. It then calculates the size to close (could be full position or partial). It uses the order book or AMM to close positions: the simplest implementation is to treat it as the liquidator placing counter-orders that execute immediately. Alternatively, the protocol can take over the position and allow the liquidator to directly claim collateral minus a discount. After closing, any remaining collateral (if any) is returned to the user, a penalty fee goes to the liquidator, and insurance fund covers any shortfall.
4. **Fee Distribution:** Trading fees collected (from both CLOB fills and AMM swaps) are split perhaps as follows: X% to LPs (AMM LPs get a base share of all AMM trade fees; order book makers get rebates or the spread they earned), Y% to insurance fund, Z% to protocol treasury or governance stakers. These are tallied in the Clearinghouse and distributed periodically or on each trade.

###


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.nunchi.trade/smart-contract-architecture.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
