> ## 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.

# M2 Scope

> M2 (External Testnet) on Ethereum Sepolia (L1) + Arbitrum Sepolia (L2): identical EUR/USD + USD/JPY forwards, 6 tenors (1D-1Y), MockUSDC collateral, Pyth oracle, subgraph indexer, MCP server (23 tools), x402 API, CLI tool, and public documentation

<Warning>
  M2 is deployed on two **testnets** — Ethereum Sepolia (L1) and Arbitrum Sepolia (L2). This is not a production
  system. All tokens are test tokens with no monetary value. Do not use real funds. Contract addresses,
  parameters, and behaviors may change between deployments.
</Warning>

## Two testnets, complementary coverage

<Columns cols={2}>
  <Card title="Ethereum Sepolia — L1 fidelity" icon="ethereum">
    * chainId `11155111`, \~12 s block time
    * Mainnet-shape gas market dynamics — useful for validating behavior under L1 fee variance
    * The canonical L1 testnet for ecosystem integrations (Pyth, Graph Studio, third-party tooling)
    * Block explorer: `sepolia.etherscan.io`
  </Card>

  <Card title="Arbitrum Sepolia — L2 fidelity" icon="bolt">
    * chainId `421614`, sub-second blocks
    * Low and steady L2 fee market — useful for validating long-running scenarios and frequent operations
    * Sub-second confirmation latency suits agent integrations that chain many transactions
    * Block explorer: `sepolia.arbiscan.io`
  </Card>
</Columns>

Both networks run **identical** contracts with **identical** protocol parameters. The choice between them
is about what you are validating, not about feature differences.

## Which testnet should I use?

* **Use Sepolia (L1)** when you need: mainnet-shape gas validation, L1 confirmation cadence, ecosystems
  that already treat Sepolia as canonical, or to validate behavior under L1 fee variance.
* **Use Arbitrum Sepolia (L2)** when you need: rapid iteration on agent / MCP / x402 / CLI flows
  (sub-second confirmation), steady fee dynamics for long-running tests, or L2 cost dynamics in your
  integration tests.

Switch between them by setting `NETWORK=sepolia` / `NETWORK=arbitrumSepolia` in the CLI, or
`?network=` in the MCP / x402 query parameter, or by switching chains in the connected wallet.

## Network trade-offs

| Property                | Ethereum Sepolia (L1)                      | Arbitrum Sepolia (L2)                                        |
| ----------------------- | ------------------------------------------ | ------------------------------------------------------------ |
| chainId                 | 11155111                                   | 421614                                                       |
| Block time              | \~12 s                                     | \~0.25 s                                                     |
| Tx confirmation latency | \~12–24 s                                  | sub-second                                                   |
| Gas fee dynamics        | Mirrors mainnet — high variance under load | Lower, steadier; rollup batches amortize fee                 |
| Settlement model        | L1 native                                  | L2 rollup, settled to Ethereum with batch + challenge window |
| Block explorer          | sepolia.etherscan.io                       | sepolia.arbiscan.io                                          |
| Native gas faucet       | arbitrum.faucet.dev/Sepolia                | arbitrum.faucet.dev/ArbSepolia                               |

## Deployment overview

| Property            | Value                                             |
| ------------------- | ------------------------------------------------- |
| **Networks**        | Ethereum Sepolia + Arbitrum Sepolia               |
| **Version**         | v0.3.2                                            |
| **Milestone**       | M2 (External Testnet)                             |
| **Collateral**      | MockUSDC (test ERC-20, 6 decimals) on both chains |
| **Supported Pairs** | EUR/USD, USD/JPY                                  |
| **Oracle**          | Pyth Network (per-chain Pyth deployments)         |

M2 is the first externally accessible deployment of the Open Nile Protocol. The full protocol feature
set is deployed on both testnets with real Pyth oracle prices and automated keeper operations on each.

## Smart Contracts

Eight core contracts plus a Protocol registry are deployed on each testnet:

<Columns cols={2}>
  <Card title="Shared Infrastructure" icon="server">
    * **Protocol** — Root registry and access control
    * **Config** — All configurable parameters (fees, margins, caps)
    * **OracleModule** — Pyth spot prices + publisher-pushed forward prices
    * **ModeController** — 4-mode operating state machine
    * **RiskManager** — Position, account, and pool-level risk caps
  </Card>

  <Card title="Pool Contracts" icon="database">
    * **MarginAccounts** — Collateral deposits, margin locking, fee collection
    * **PoolVault** — ERC-4626 liquidity pool for LP deposits
    * **PositionManager** — Position lifecycle (open, increase, close, reduce)
    * **SettlementEngine** — Batch settlement, liquidation, early termination
  </Card>
</Columns>

<Note>
  All contracts are immutable (no proxy upgrades). Protocol parameters are adjustable via the Config
  contract by the admin role. Contract source is verified on each chain's block explorer.
</Note>

## Supported Features

<Tabs>
  <Tab title="Trading">
    * **NDF trading on EUR/USD and USD/JPY** -- LONG or SHORT positions
    * **6 tenors per chain**: 1D (86,400s), 1W (604,800s), 1M (2,592,000s), 3M (7,776,000s), 6M (15,552,000s), 1Y (31,536,000s). Tenors are a dynamic uint32-second registry; admins can add or remove via `Config.registerTenor`/`unregisterTenor`.
    * **Isolated margin model** -- each position's risk is contained to its own locked margin
    * **Variable leverage** up to 50x (2% initial margin requirement)
    * **Position operations**: open, increase, close early, reduce, add/remove margin
    * **Permissionless settlement** -- anyone can settle matured positions or liquidate
  </Tab>

  <Tab title="Liquidity">
    * **ERC-4626 vault** for LP deposits and withdrawals
    * **Share price** reflects cumulative pool performance (fees + trader PnL)
    * **Utilization cap** (80%) restricts withdrawals to maintain reserve liquidity
    * **Optional LP allowlist** for controlled deposit access
    * **Fee distribution**: 70% to pool, 30% to treasury
  </Tab>

  <Tab title="Oracle & Pricing">
    * **Pyth Network** integration for real-time spot prices on EUR/USD and USD/JPY
    * **Forward price publisher** using interest rate parity formula, per pair
    * **Bid/ask spread** with configurable basis point spread per mode
    * **Per-pair oracle health** — `OracleModule.isOracleValid(pairId)` reports per-pair, and the DEGRADED watchdog drives mode escalation per pair, not globally
    * **Staleness checks** on both spot and forward prices
    * **Fixing price recording** from Pyth for maturity settlement (gated on `PUBLISHER_ROLE`)
  </Tab>

  <Tab title="Risk Management">
    * **4-mode state machine**: Normal, Degraded, Reduce-Only, Paused
    * **Pool exposure caps**: max net exposure, max gross notional
    * **Position caps**: max notional per position, per account
    * **Maintenance margin**: positions liquidatable below MM threshold
    * **Rate-of-change limits** (configurable, disabled by default)
  </Tab>
</Tabs>

## Off-Chain Services

<Steps>
  <Step title="Publisher">
    Fetches real EUR/USD and USD/JPY spot prices from Pyth Hermes, computes forward prices using
    interest rate parity, and publishes them onchain via `OracleModule.publishRound` (gated on
    `PUBLISHER_ROLE`). Deployed per-network — each chain runs an independent publisher targeting
    that chain's `OracleModule`. The publish cadence aligns to the chain's block-time grid.
  </Step>

  <Step title="Keeper">
    Monitors for matured and liquidatable positions and calls the permissionless
    `SettlementEngine.settle{Position,Batch}` / `liquidate` entry points. Deployed per-network —
    each chain runs an independent keeper. Poll cadence matches the chain's block time
    (\~12 s on Sepolia, \~1 s on Arbitrum Sepolia) so liquidation reaction time matches the chain's
    confirmation cadence.
  </Step>

  <Step title="Frontend (Next.js)">
    Trading UI built with Next.js, wagmi, viem, and shadcn/ui. Supports wallet connection via
    RainbowKit, switching between Sepolia and Arbitrum Sepolia, real-time position monitoring,
    LP deposit/withdraw, and protocol state display.
  </Step>

  <Step title="Subgraph (The Graph)">
    Per-chain subgraph deployment indexes all onchain protocol events into a queryable GraphQL API.
    Provides historical data, position lifecycle tracking, fee accounting, and pool state history.
  </Step>
</Steps>

## Integration Paths

M2 supports multiple ways to interact with the protocol on either testnet:

| Integration        | Description                                                                          | Status    |
| ------------------ | ------------------------------------------------------------------------------------ | --------- |
| **TypeScript SDK** | Type-safe ABIs, enums, and constants (`@nile-markets/sdk`)                           | Available |
| **Subgraph API**   | Per-chain GraphQL queries for positions, accounts, pool state, history               | Available |
| **CLI Tool**       | Command-line interface (`nile`) — `--network arbitrumSepolia` or `--network sepolia` | Available |
| **MCP Server**     | Model Context Protocol server for AI agents — `network` parameter per tool call      | Available |
| **x402 API**       | Pay-per-call HTTP API — `?network=` query parameter                                  | Available |
| **llms.txt**       | Machine-readable protocol summary for LLM consumption                                | Available |

## Known Limitations

The following limitations apply to the M2 deployment and are planned for resolution in future milestones:

<AccordionGroup>
  <Accordion title="Two currency pairs">
    EUR/USD and USD/JPY are registered on both testnets. The contract architecture supports
    arbitrary multi-pair registration via `OracleModule.registerPair()`; additional pairs
    (GBP/USD, USD/CHF, …) are deferred to a later M2 patch or M3.
  </Accordion>

  <Accordion title="Isolated margin only">
    All positions use isolated margin (MarginMode.ISOLATED). Cross-margin support
    (MarginMode.CROSS) is defined in the enum but not implemented. Planned for M3.
  </Accordion>

  <Accordion title="No holiday calendar">
    Fixing dates do not account for FX market holidays. Only weekends are excluded from the tenor
    duration calculation. A proper holiday calendar is planned for M3.
  </Accordion>

  <Accordion title="Admin-controlled mode transitions">
    Mode changes (Normal, Degraded, Reduce-Only, Paused) are triggered by the admin role. Automated
    mode escalation based on oracle health or pool metrics is planned for M3.
  </Accordion>

  <Accordion title="No formal audit">
    The M2 contracts have not undergone a professional security audit. A professional audit with 1-2
    independent firms is planned for M3. Audit scope will cover the contracts deployed on both
    Sepolia and Arbitrum Sepolia — bytecode is identical. The test suite includes 550 Foundry tests
    with 95%+ line coverage.
  </Accordion>

  <Accordion title="MockUSDC collateral">
    M2 uses a test ERC-20 (MockUSDC) on both testnets rather than canonical USDC. Integration with
    canonical USDC on mainnet is planned for M3.
  </Accordion>

  <Accordion title="No keeper economic incentives">
    The keeper service operates without onchain economic incentives (no liquidation rewards or gas
    reimbursement). Keeper incentive design is planned for M3.
  </Accordion>

  <Accordion title="Single publisher per chain">
    Forward prices on each chain are published by a single authorized publisher. There is no
    publisher redundancy or decentralized publisher network. Multi-publisher support is planned for M3.
  </Accordion>
</AccordionGroup>

## Related Pages

<Columns cols={3}>
  <Card title="Architecture Decision" icon="diagram-project" href="/ai-agents/architecture-decision">
    Why M2 supports two testnets, and the L1 vs L2 trade-offs in long form.
  </Card>

  <Card title="Contract Addresses" icon="link" href="/build/contract-addresses">
    Current deployment addresses per chain.
  </Card>

  <Card title="Quick Start" icon="bolt" href="/build/quick-start">
    Get started interacting with the M2 deployment.
  </Card>
</Columns>
