> ## Documentation Index
> Fetch the complete documentation index at: https://docs.nilemarkets.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Architecture

> Three-layer architecture: eight Solidity contracts around a central ProtocolRegistry, off-chain services (Pyth publisher, keeper, subgraph indexer), and external integrations (MCP, x402, CLI).

The protocol combines onchain smart contracts with off-chain services to deliver non-deliverable FX forward (NDF) trading with full collateral transparency and deterministic settlement.

## System Architecture

Three layers work together: **external services** (Pyth oracle, The Graph indexer) provide market data and event indexing, **off-chain services** (publisher, keeper, frontend) bridge data to the chain, and **onchain contracts** enforce all trading rules, margin, and settlement.

```mermaid theme={null}
graph TB
    subgraph external["External Services"]
        pyth["Pyth Network<br/>EUR/USD Spot"]
        thegraph["The Graph<br/>Subgraph Indexer"]
    end
    subgraph offchain["Off-Chain Services"]
        publisher["Publisher<br/>Forward Prices"]
        keeper["Keeper<br/>Settle & Liquidate"]
        gateway["Gateway API<br/>CF Worker"]
        frontend["Frontend<br/>Web App"]
    end
    subgraph onchain["Onchain · Ethereum Sepolia"]
        oracle["OracleModule"]
        pm["PositionManager"]
        se["SettlementEngine"]
        vault["PoolVault"]
        margin["MarginAccounts"]
    end
    pyth -- "spot price" --> publisher
    publisher -- "publishRound() (Pyth bytes + forwards)" --> oracle
    keeper -- "batchSettle / batchLiquidate" --> se
    onchain -- "events" --> thegraph
    gateway -- "GraphQL" --> thegraph
    gateway -- "RPC reads" --> onchain
    frontend -- "wagmi / viem" --> onchain
    frontend -- "GraphQL" --> thegraph
```

For step-by-step interaction flows, see [Trading Flows](/protocol/trading-flows) and [System Flows](/protocol/system-flows).

## Contract Architecture

The Protocol Registry is the root — all contracts discover each other through it rather than storing direct addresses. Solid arrows show ownership, dotted arrows show runtime reads.

```mermaid theme={null}
graph TB
    protocol["Protocol Registry"]
    protocol --> config["Config<br/>Parameters"]
    protocol --> oracle["OracleModule<br/>Spot + Forward Prices"]
    protocol --> mode["ModeController<br/>Operating Mode"]
    protocol --> risk["RiskManager<br/>Risk Caps"]
    protocol --> pool
    subgraph pool["Pool 0 — USDC"]
        margin["MarginAccounts"]
        vault["PoolVault · ERC-4626"]
        pm["PositionManager"]
        se["SettlementEngine"]
        feelib["FeeLib<br/>(shared library)"]
    end
    config -. "reads" .-> pm & se
    oracle -. "prices" .-> pm & se
    risk -. "validates" .-> pm
    pm & se & vault --> margin
    pm -- "uses" --> feelib
    se -- "uses" --> feelib
    feelib -- "30% treasury<br/>70% pool" --> vault
    margin --> usdc["USDC (ERC-20)"]
```

Each pool can have its own operating mode. M2 deploys a single USDC pool; the architecture supports future multi-collateral pools.

### Shared Infrastructure

Singleton contracts that serve all pools:

* **Config** — Stores all tunable parameters: margin factors, fee rates, tenor durations, risk caps, and oracle thresholds. The admin can adjust parameters without redeploying contracts.
* **OracleModule** — Manages two price feeds: Pyth spot prices (read onchain) and publisher-submitted forward prices (with safeguard checks on staleness, deviation, and price movement).
* **ModeController** — Implements a four-state operating mode machine (NORMAL → DEGRADED → REDUCE\_ONLY → PAUSED) that progressively restricts protocol operations during adverse conditions.
* **RiskManager** — Enforces per-position, per-account, and pool-level risk caps, plus rate-of-change throttling to prevent sudden large exposures.

### Pool Contracts

Instantiated per collateral token (currently USDC only):

* **MarginAccounts** — Holds trader collateral. Manages deposits, withdrawals, and per-position margin locking so that each position's risk is isolated.
* **PoolVault** — ERC-4626 vault for LP deposits. Serves as the counterparty to all trader positions, paying out trader profits and absorbing trader losses.
* **PositionManager** — Handles the full position lifecycle: opening new positions, increasing existing ones, reducing exposure, and managing margin adjustments.
* **SettlementEngine** — Executes settlement at maturity, liquidation of underwater positions, and early termination requests.

For contract API details and function signatures, see the [Build tab](/build/position-manager).

<Note>For design rationale (zero-sum pool model, immutable contracts, isolated margin, ERC-4626 vault), see [Core Design](/protocol/core-design).</Note>

## Access Control

| Role                 | Capabilities                                            |
| -------------------- | ------------------------------------------------------- |
| `DEFAULT_ADMIN_ROLE` | Full admin — set config, manage roles, mode transitions |
| `PAUSER_ROLE`        | Emergency pause/unpause only                            |
| `PUBLISHER_ROLE`     | Submit forward prices via OracleModule                  |
| `ORACLE_ADMIN_ROLE`  | Configure oracle safeguard parameters                   |
| `RISK_ADMIN_ROLE`    | Configure risk caps and rate-of-change limits           |

For operation restrictions by mode (which actions are allowed in NORMAL vs DEGRADED vs REDUCE\_ONLY vs PAUSED), see [Mode Escalation](/protocol/mode-escalation).

## Technology Stack

| Layer                | Technology                                                   | Purpose                                          |
| -------------------- | ------------------------------------------------------------ | ------------------------------------------------ |
| **Contracts**        | Solidity 0.8.34, OpenZeppelin 5.6.1                          | Core protocol logic                              |
| **Upgradeability**   | None (immutable bytecode)                                    | All contracts are deployed without proxies       |
| **Oracle (Spot)**    | Pyth Network                                                 | EUR/USD spot price                               |
| **Oracle (Forward)** | Custom ForwardPublisher                                      | Computed forward prices via interest rate parity |
| **Indexer**          | The Graph (Subgraph)                                         | Event indexing and GraphQL API                   |
| **API Gateway**      | Cloudflare Workers                                           | Read-only REST API over subgraph + RPC           |
| **Publisher**        | Rust + Tokio + alloy-rs                                      | Forward price computation and onchain publishing |
| **Keeper**           | Rust + Tokio + alloy-rs                                      | Batch settlement and liquidation                 |
| **Risk**             | RiskManager                                                  | Position, account, and pool exposure caps        |
| **Frontend**         | Next.js 16 + shadcn/ui + Tailwind 4.x + wagmi 3.x + viem 2.x | User interface                                   |
| **Network**          | Ethereum Sepolia                                             | Testnet deployment                               |

## Next Steps

<Columns cols={3}>
  <Card title="Trading Flows" icon="arrow-right-arrow-left" href="/protocol/trading-flows">
    Sequence diagrams for open, increase, reduce, margin adjust, and settlement.
  </Card>

  <Card title="System Flows" icon="gears" href="/protocol/system-flows">
    Oracle publishing, keeper automation, fee distribution, and LP deposits.
  </Card>

  <Card title="Core Design" icon="compass-drafting" href="/protocol/core-design">
    Zero-sum pool model, immutable contracts, and design principles.
  </Card>
</Columns>
