> For the complete documentation index, see [llms.txt](https://docs.fermi.trade/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.fermi.trade/02-architecture.md).

# 02 architecture

This page explains how Fermi-v1 is built, what each component does, how they interact, and why the design delivers something that is usually a trade-off: **a fair, fully on-chain order book that still feels as fast as a centralized exchange.**

It is written for two audiences at once — engineers who need the mental model before reading the mechanics chapters, and evaluators (prospective large users, market makers etc.) who need to judge whether the system is sound and viable.

## The problem Fermi-v1 solves

A perpetual-futures exchange has to do four things well:

1. **Match orders fairly** — earlier orders should get filled first, and nobody should be able to jump the queue or front-run.
2. **Execute trustlessly** — users should never have to hand custody, matching, or risk enforcement to an operator.
3. **Feel fast** — traders expect millisecond feedback, not block-time feedback.
4. **Stay live** — the exchange should keep working even when individual off-chain services fail or misbehave.

On-chain order books usually get (1) and (2) but fail (3): every action waits for block confirmation. Centralized exchanges get (3) but fail (1) and (2): you trust the operator's matching engine, sequencing, risk database, and custody. Fermi-v1 is architected so you do not have to choose.

## The four components

```
        ┌───────────────────────────────────────────────────────────┐
        │                  Trader (wallet / SDK / UI / bot)          │
        └───┬───────────────────────┬──────────────────────┬─────────┘
            │ 1. sign + submit      │ 4. read state        │ 5. stream
            │    signed intent      │    (optimistic +     │    fills /
            ▼                       │     confirmed)       │    events
   ┌─────────────────┐              │                      │
   │   POSq / RELAYER │             ▼                      ▼
   │  (encrypted VDF  │     ┌──────────────────┐   ┌────────────────┐
   │   tick ordering) │     │ OPTIMISTIC HARNESS│   │    FANOUT       │
   │                  │     │ (off-chain read / │   │ (SSE broadcast) │
   │ - validate       │     │  optimistic layer)│   │                 │
   │ - assign seq     │     └────────▲──────────┘   └───────▲────────┘
   │ - commit hash    │              │ reads               │ events
   └────────┬─────────┘              │                      │
            │ 2. commit              │                      │
            │    + 3. reveal         │                      │
            ▼                        │                      │
   ┌──────────────────────────────────────────────────────────────────┐
   │                FERMI-V1 ON-CHAIN EXCHANGE PROGRAM                  │
   │                                                                    │
   │   ExecutionQueueV5  →  matching engine  →  risk engine            │
   │   (AMQ FIFO queue)     (FIFO order book)   (cross-margin health)  │
   │                                                                    │
   │   Group · Bank · FermiAccount · PerpMarket · BookSide · EventQueue │
   └──────────────────────────────────────────────────────────────────┘
                  ▲                                       │
                  │ 6. EXECUTOR drives reveal/execute      │ events
                  └───────────────────────────────────────┘
                              Solana mainnet-beta
```

### 1. The on-chain exchange program

This is the **only authority**. It is a Solana program that owns:

* The **execution queue** (`ExecutionQueueV5`) — a per-market, AMQ-style queue that enforces first-come-first-served execution on chain.
* The **matching engine** — a price-time-priority FIFO order book.
* The **order actions** — placement, cancels, matching, event consumption, and book mutation.
* The **risk engine** — cross-margin health, funding, liquidation, bankruptcy resolution.
* All **value-bearing state** — `Group`, `Bank` (collateral), `FermiAccount` (your positions), `PerpMarket`, `BookSide`, `EventQueue`.

Every order placement, cancel, match, fill, funding payment, and liquidation happens here, in a transaction recorded on the public ledger. Nothing off-chain can move your funds, change a fill, or execute a trade. The off-chain components exist to make the on-chain program **fast to use**, **explicitly sequenced**, and **fast to observe** — they have no matching authority.

The execution queue is the on-chain primitive that makes the FIFO claim real. It follows the Asynchronous Market Queue (AMQ) pattern: market actions are admitted into program state, tagged with a market sequence, and later executed by the program in the application's chosen order. In Fermi's case, that chosen order is strict per-market FIFO over the POSq-produced sequence. See [20 - Execution Queue v5](broken://pages/be48c90533e062fae8818e133338dcf126bb706d).

This is the bedrock of the trust model: if every off-chain component disappeared tomorrow, your funds, orders, and positions would be exactly where the chain says they are, and you could still interact with the program directly (see [21 - Direct Fallback Pool](broken://pages/31cdbebbf779c24c05fcc4cf4188188d5f306bc7)).

### 2. POSq and the relayer

The fast path combines [POSq sequencing](broken://pages/ac31e9ddbaaf6ba0dc00cd9026f42e08117ea99d) with relayer plumbing. The relayer turns a trader's signed intent into an on-chain queue entry, but the ordering claim is not "trust the relayer." POSq sequences encrypted transactions over VDF ticks, then the relayer commits that ordered stream to the on-chain queue.

{% stepper %}
{% step %}

## Receive a signed intent

The fast path receives a signed *intent* — the order payload plus the trader's Ed25519 signature plus the exact account list the order will touch.
{% endstep %}

{% step %}

## Validate off-chain

It validates off-chain:

* signature correctness
* account freshness
* oracle freshness
* margin/health pre-check
* reduce-only rules

This is a courtesy fast-fail — it spares the trader a wasted on-chain transaction — not a security boundary.
{% endstep %}

{% step %}

## Sequence via POSq

It sequences via POSq for that market. In v1 this is single sequencer mode: encrypted transactions are ordered over VDF ticks, making reordering detectable rather than hidden in an opaque sequencer.
{% endstep %}

{% step %}

## Commit the hash

It commits a *hash* of the intent to the on-chain queue, batched with up to 64 other commits for efficiency.
{% endstep %}

{% step %}

## Return the sequence and signature

It returns the assigned sequence and the commit transaction signature to the trader, immediately.
{% endstep %}
{% endstepper %}

The v1 POSq sequencer is **not fully decentralized**, but it is also not a black-box sequencer. As covered in the [POSq page](broken://pages/ac31e9ddbaaf6ba0dc00cd9026f42e08117ea99d), it emits a VDF-tick ordering trail before reveal; once the relayer commits that order, the sequence and a hash of the payload are locked on chain. The fast path **cannot**:

* Change your order's contents after you signed it — the reveal step re-hashes the payload and checks your signature.
* Silently reorder same-market intents relative to the emitted POSq sequence — the VDF-tick/commit trail makes that detectable, and the on-chain queue enforces the committed order.
* Substitute account lists — the account list is bound into the signed intent.
* Replay your order — the on-chain replay cache rejects duplicate intent hashes.
* Move your funds — every state change requires your signature, verified inside the program.

The remaining v1 gap is availability and pre-admission censorship: a single sequencer can be down, slow, or refuse an intent before it enters the POSq log. The direct fallback pool mitigates that today. The [v2 POSq roadmap](broken://pages/ac31e9ddbaaf6ba0dc00cd9026f42e08117ea99d#v2-consensus-level-safeguards) adds voting, leader rotation, and permissionless participation to reduce that single-sequencer liveness/admission assumption.

### 3. The executor (off-chain crank)

A committed intent is just a hash on chain; it has not executed yet. The **executor** is the off-chain worker that finishes the job.

{% stepper %}
{% step %}

## Pick up committed intents

It picks up committed intents in sequence order.
{% endstep %}

{% step %}

## Build the reveal transaction

It builds a **reveal** transaction containing the full intent payload and account list.
{% endstep %}

{% step %}

## Submit the reveal

It submits the reveal. The on-chain program then re-hashes the payload, verifies it matches the commit, verifies the trader's signature, checks the replay cache, and **dispatches the order into the matching engine**.
{% endstep %}

{% step %}

## Advance the queue head

It advances the queue head so the next sequence can execute.
{% endstep %}
{% endstepper %}

The executor is also **unprivileged**. If it builds a wrong reveal, the hash check fails and the transaction reverts. If it stalls, a watchdog ("autodrop") advances the queue past the stuck item so a single failure cannot wedge a market. Anyone can run an executor; in production the operator runs the relayer and executor together in one service for low latency.

> Commit/reveal in one sentence: the relayer **locks the order (sequence + hash)** first, and the executor **opens it (payload)** second. Locking before opening is what makes the ordering provably fair — see "Why commit/reveal" below.

### 4. The optimistic harness

The harness is the component that makes Fermi-v1 *feel* fast. It is an off-chain service that maintains a continuously-updated mirror of all on-chain state — every order book, every account, every oracle — and serves it over plain HTTP and Server-Sent Events.

Crucially, the harness publishes **two views**:

* **Confirmed view** — state derived purely from finalized on-chain transactions. This is ground truth; it is what you reconcile against.
* **Optimistic view** — the confirmed view *plus* the intents the POSq/relayer has already accepted but which have not yet been finalized on chain. Because ordering is fixed by POSq, enforced by the on-chain AMQ-style queue, and matched by deterministic program logic, the harness can replay an accepted intent against its mirror and predict the on-chain outcome **before the block lands**.

The optimistic view is what gives a trader sub-second feedback: "your order is sequenced at position N and, against the current book, it fills 1.4 SOL at $150.2." Confirmation follows a beat later and — because the same deterministic queue and matcher run in both places — matches the prediction. This optimistic pre-play is unavailable on venues where ordering is discretionary, hidden, or mutable after the off-chain preview has been computed.

The **fanout** service sits in front of the harness's event stream and re-broadcasts it to many subscribers at once, so thousands of traders and bots can stream fills without overloading the core harness. It is purely a scaling layer.

Like the relayer and executor, the harness has **no authority**. It cannot change state; it can only read and predict it. A wrong harness can mislead a UI for a moment, but the on-chain program will not honor anything the harness says — it only honors signed, sequenced, revealed intents.

## How a trade flows through all four

```
  t0   Trader signs an intent (order + signature + account list).
  t0   SDK sends it to POSq / RELAYER.
  t0+  POSq orders the encrypted intent over VDF ticks; relayer commits seq 4711.
       → Relayer returns (seq 4711, commit tx sig) to the trader.
       → Harness sees the accepted intent and updates the
         OPTIMISTIC view: the trader's UI shows the (predicted) fill
         in well under a second.
  t1   EXECUTOR builds the REVEAL for seq 4711 and submits it.
  t1   On-chain program re-hashes payload, checks signature, checks
       replay cache, DISPATCHES into the matching engine.
       → Order matches; FillEvent written; queue head advances.
  t2   Fill is finalized on chain. Harness CONFIRMED view now
       matches what the optimistic view already showed.
       → Fanout broadcasts the FillEvent over SSE.
```

The trader experiences `t0+` — milliseconds. The chain reaches finality at `t2` — a second or two later. The gap between them is bridged by the optimistic view, and it is *safe* to bridge because the prediction is made from the same deterministic order, queue, and matcher that the chain will run.

## Why commit/reveal — the fairness mechanism

The execution queue uses a two-step **commit then reveal** protocol. POSq first orders encrypted intents over VDF ticks. The relayer then commits only a *hash* of the intent and its sequence number; the full payload is revealed later by the executor. This ordering — encrypted sequence first, lock on chain second, open later — is what makes Fermi-v1's fairness auditable rather than merely promised:

* **First-come-first-served (FCFS) is enforced against the POSq log.** Each market has one monotonically increasing sequence. Orders execute in sequence order, period. In v1, POSq's single sequencer emits an encrypted VDF-tick order; once committed, the choice is public and immutable. There is no room for a privileged actor to slip an order in front of yours after seeing it.
* **No payload-based reordering.** When the relayer commits, it only publishes a hash. Nobody — not the relayer, not a validator, not another trader — can see *what* your order is until it is already locked into its sequence position. So ordering cannot be influenced by order contents. This neutralizes the most common on-chain MEV: reordering a block to extract value from pending trades.
* **No tampering.** At reveal, the program recomputes the hash from the payload and account list. Any change — price, size, account, a single bit — produces a different hash and the transaction reverts.
* **No replay.** Each consumed intent hash is recorded in an on-chain cache. A signed order cannot be fired twice.
* **No silent drops.** Every stage of an intent emits a structured, queryable event. Given `(market, sequence)` you can ask the harness exactly where an order is and why — accepted, committed, revealed, executed, or dropped, with the reason.

The result is an order book where **time priority is a property of the protocol**, the same way it is on a traditional exchange's matching engine — except here it is publicly verifiable and nobody has to be trusted to honor it.

## Why this combination is powerful

Taken together, the four components give Fermi-v1 a profile that is hard to get any other way:

| Property                     | How the architecture delivers it                                                                                                                                                                                                                                                                  |
| ---------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Fair ordering (FCFS)**     | [POSq](broken://pages/ac31e9ddbaaf6ba0dc00cd9026f42e08117ea99d) encrypted VDF ticks produce an auditable order; one on-chain sequence per market enforces it; commit-before-reveal hides payloads until ordering is locked.                                                                       |
| **Low perceived latency**    | The optimistic harness pre-plays accepted intents in milliseconds; deterministic ordering, AMQ enforcement, and deterministic matching make the prediction meaningful.                                                                                                                            |
| **Fully on-chain execution** | The on-chain program is the sole authority for order placement, cancels, matching, fills, risk, and accounting; off-chain components have zero custody and no matching authority.                                                                                                                 |
| **Censorship resistance**    | In v1, direct fallback lets you enter the queue on chain if the single fast-path sequencer is unavailable or refusing admission; [v2 POSq](broken://pages/ac31e9ddbaaf6ba0dc00cd9026f42e08117ea99d#v2-consensus-level-safeguards) adds voting, leader rotation, and permissionless participation. |
| **Throughput**               | Per-market queues are independent, so markets commit and execute in parallel; commits are batched up to 64 at a time.                                                                                                                                                                             |
| **Capital efficiency**       | A single cross-margin `FermiAccount` backs positions across every market; collateral is not fragmented per market.                                                                                                                                                                                |
| **Operational transparency** | Every intent leaves an auditable trail; `GET /trace/sequence/{market}/{seq}` answers "where is my order" in seconds.                                                                                                                                                                              |
| **Verifiability**            | Matching engine, risk engine, and queue are open-source on-chain code; anyone can audit or re-derive every fill.                                                                                                                                                                                  |

The headline is the pairing of the last two rows of the trade-flow diagram: **FCFS fairness from the on-chain queue, plus centralized-exchange-like responsiveness from the optimistic harness.** On-chain books are usually fair but slow to interact with; centralized books are fast but require trust. Fermi-v1's separation of concerns — execution on chain, POSq sequencing in an auditable encrypted VDF-tick log plus verifiable queue, speed in a powerless read layer — is what lets it offer both at once.

## The trust model, stated plainly

For an evaluator, the single most important question is "what can each party do to me?" The answer:

| Party                          | Can do                                                                                                                                                                         | Cannot do                                                                                         |
| ------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------- |
| **On-chain program**           | Order placement, cancels, matching, fills, risk, accounting, and liquidation — it is the authority. It is open-source and audited; its behavior is fixed by deployed bytecode. | Act outside its code. Upgrades are governance-gated.                                              |
| **POSq / relayer v1**          | Sequence encrypted intents over VDF ticks; commit the resulting order; refuse or delay pre-admission service.                                                                  | Alter, silently reorder an emitted sequence, replay, forge, execute, or touch your funds.         |
| **Executor**                   | Drive reveals; choose timing.                                                                                                                                                  | Change payloads (hash check); wedge a market (autodrop watchdog); move funds.                     |
| **Harness / fanout**           | Read and predict state; serve it fast.                                                                                                                                         | Change any state; force the program to honor a prediction.                                        |
| **Another trader / validator** | Submit their own orders; build blocks.                                                                                                                                         | See your order contents before sequencing; reorder same-market intents; front-run committed flow. |
| **You**                        | Sign and submit your own intents; withdraw your own funds; liquidate undercollateralized accounts.                                                                             | Affect anyone else's account without their signature.                                             |

Every off-chain component is **replaceable and unprivileged**. The operator runs them for convenience and speed; a sufficiently motivated trader can run their own, or bypass them entirely via the direct path. That is the property that makes the "feels like a CEX" speed safe to rely on: the speed layer cannot betray you, because it has nothing to betray you *with*.

## Liveness — what happens when things fail

| Failure             | Effect                                 | Mitigation                                                                                                       |
| ------------------- | -------------------------------------- | ---------------------------------------------------------------------------------------------------------------- |
| POSq / relayer down | New orders can't take the fast path.   | Direct fallback pool: submit intents on chain yourself. Cancels can also be sent as plain on-chain instructions. |
| Executor down       | Committed intents don't reveal.        | Any party can run an executor; the autodrop watchdog advances past stalled items.                                |
| Harness down        | Optimistic reads unavailable.          | Read confirmed state directly from any Solana RPC; trading is unaffected.                                        |
| Fanout down         | Event streaming degraded.              | Subscribe to the harness directly, or poll.                                                                      |
| Oracle stale        | Affected market pauses (reads revert). | Anyone can push a fresh oracle update; other markets unaffected.                                                 |
| Solana congestion   | Higher confirmation latency.           | Optimistic view still serves; priority fees; per-market isolation.                                               |

No single off-chain failure can cause loss of funds or rewrite on-chain execution. In v1, the single POSq sequencer can still be an availability or pre-admission bottleneck. The worst case is degraded latency or a temporary inability to *enter* new orders via the fast path — and even then the direct on-chain path remains open.

## Where to read more

* [30 - POSq Sequencing](broken://pages/ac31e9ddbaaf6ba0dc00cd9026f42e08117ea99d) — the v1 single-sequencer model, the v2 roadmap, and how sequencing differs from on-chain execution.
* [10 - FIFO Order Book](broken://pages/c22a8887caeab589a71645012a2e3efda04843ea) and [11 - Matching Engine](broken://pages/0f0463f601862e7cb23b3633eab97633d590c2f9) — the on-chain matcher in detail.
* [15 - Margin & Health](broken://pages/854a94521c8968d1ac32269b054622c7369c60d5) — the cross-margin risk engine.
* [20 - Execution Queue v5](broken://pages/be48c90533e062fae8818e133338dcf126bb706d) — the commit/reveal queue, sequencing, and recovery, with on-chain data structures.
* [21 - Direct Fallback Pool](broken://pages/31cdbebbf779c24c05fcc4cf4188188d5f306bc7) — the censorship-resistant submission path.
* [25 - HTTP & SSE API](broken://pages/cde6fe8b251bf446b6350f65563e1ee1a7083b1f) and [26 - gRPC API](broken://pages/0e7a840819337d746ed8e882c2eb48f78a789e68) — the harness and relayer interfaces.


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## 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, and the optional `goal` query parameter:

```
GET https://docs.fermi.trade/02-architecture.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

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.
