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

# Engine Architecture

> Technical whitepaper on the 0x1 Rust-based mirror trading engine, contrasted with the serial-order and slippage pathologies of legacy copy-trading systems.

## Abstract

0x1 operates a Rust-native mirror trading engine built to replicate leader fills onto a heterogeneous population of follower accounts with sub-second latency, bounded slippage, and per-account risk isolation. This document specifies the architecture of that engine and contrasts it with the serial-execution and unbounded-slippage patterns that characterize conventional copy-trading stacks. The design choices below — per-mirror-trader concurrent pipelines, parallel fanout, orderbook-aware pre-checks, and non-custodial EIP-712 signing — are the mechanisms by which 0x1 compresses the leader-to-follower replication envelope and preserves the PnL shape a follower signed up for.

## 1. Problem Statement: Legacy Copy Trading

Most incumbent copy-trading implementations inherit an architecture that was not designed for high-frequency derivatives venues. The resulting execution pathologies fall into four recurring categories.

### 1.1 Serial order placement

Legacy systems iterate followers in a single-threaded loop. When a leader fills, the system enumerates `N` followers and submits orders one after another, blocking on each HTTP round trip and exchange acknowledgement before advancing to the next. In steady state the k-th follower observes a fill time of approximately:

$$
t_k \approx t_{\text{leader}} + k \cdot (t_{\text{rtt}} + t_{\text{match}})
$$

For `N = 500` followers, a 30 ms round trip, and a 10 ms matching delay, the last follower fills **20 seconds** after the leader — an eternity on a perpetuals venue.

### 1.2 Unbounded slippage

Because orders are sized from the leader's notional and submitted market-on-fill, later followers repeatedly walk their own book. Each fill consumes liquidity at progressively worse prices, and the system has no feedback loop that halts the fanout when realized slippage exceeds the follower's tolerance. The same leader trade produces a PnL distribution across followers that is heavily left-skewed.

### 1.3 Polling-based signal detection

Many systems detect leader activity by polling the exchange REST API every few seconds rather than subscribing to the user-data stream. The leader's fill therefore enters the replication pipeline with an already-stale timestamp, compounding the queueing delay above.

### 1.4 Shared-fate failure modes

A single malformed order, rate-limit block, or HTTP timeout in the serial loop stalls every follower behind it. There is no bulkhead isolating one leader's pipeline from another's, and no per-follower circuit breaker to prevent a bad moment for one account from cascading.

## 2. 0x1 Engine: Design Goals

The 0x1 engine targets four invariants:

| Invariant                   | Definition                                                                                              |
| --------------------------- | ------------------------------------------------------------------------------------------------------- |
| **Low replication latency** | Median follower fill lands within one second of the leader fill.                                        |
| **Bounded slippage**        | No follower fills outside their configured slippage tolerance.                                          |
| **Proportional sizing**     | Follower position delta is a fixed fraction of the leader's margin delta, not a mirrored absolute size. |
| **Fault isolation**         | A failure in one leader pipeline, or one follower account, never blocks any other.                      |

## 3. Architecture

### 3.1 Runtime

The hot path is implemented in Rust on top of the [Tokio](https://tokio.rs) asynchronous runtime. Each leader is served by an independent supervisor task, and each follower subscription is a lightweight task scheduled cooperatively on the Tokio executor. The engine holds zero synchronous locks on the critical path — all state handoffs use bounded MPSC channels, and backpressure is explicit.

### 3.2 Per-mirror-trader concurrent pipelines

Every followed mirror trader runs three concurrent streams that share nothing except the outbound signal channel:

```mermaid theme={"system"}
flowchart LR
  subgraph Leader pipeline
    OB["Orderbook stream<br/>(WebSocket)"]
    UA["User-account stream<br/>(WebSocket)"]
    EX["Executor task"]
  end
  UA -->|fill event| SG["Signal generator"]
  OB -->|top-of-book| SG
  SG --> RG["Risk guard"]
  RG -->|sized & validated| FA["Parallel fanout"]
  FA -. task .-> F1["Follower A<br/>signer task"]
  FA -. task .-> F2["Follower B<br/>signer task"]
  FA -. task .-> F3["Follower C<br/>signer task"]
```

Because the orderbook and user-account streams are independent WebSocket subscriptions, leader fills are observed in the push path rather than a poll cycle. The signal generator produces a typed `MirrorIntent` the moment Aster publishes the fill, not after the next REST tick.

### 3.3 Parallel fanout

The fanout step is implemented as `FuturesUnordered` over all eligible followers. Each follower is a distinct Tokio task that owns its own signer and its own outbound HTTP connection to Aster. The k-th follower no longer waits on the (k-1)-th — every signature, risk check, and order submission happens concurrently.

In the serial model the last follower's latency grows linearly in `N`. In the 0x1 model it grows logarithmically in `N` (scheduler + connection-pool bounded) and is dominated by a single RTT:

$$
t_k \approx t_{\text{leader}} + t_{\text{rtt}} + t_{\text{match}} \quad \forall k \text{ (up to concurrency ceiling)}
$$

### 3.4 Orderbook-aware pre-check

Before a follower task submits, the risk guard re-reads the live orderbook snapshot and computes the expected fill against the follower's configured slippage tolerance. Orders that would breach the tolerance are **skipped**, not sent — and the skip is written to the follower's activity log with a structured reason code. The legacy failure mode where 500 followers sequentially walk their own book cannot occur, because the order is never dispatched once the expected mark breaches the bound.

### 3.5 Proportional sizing

Follower size is a function of the follower's configured allocation and the leader's margin delta:

$$
\text{size}_{\text{follower}} = \text{size}_{\text{leader}} \cdot \frac{\text{alloc}_{\text{follower}}}{\text{margin}_{\text{leader}}}
$$

clamped by the follower's leverage cap and Aster's minimum order size. The engine does not mirror absolute notional; it mirrors the shape of the leader's risk commitment onto the follower's balance sheet.

### 3.6 Non-custodial signing

The engine never sees a raw follower private key on the hot path. Each follower provisions an agent key that signs EIP-712 ECDSA payloads scoped to the trading account; agent keys are encrypted at rest and rotated on demand. The follower retains custody of both their Aster balance and the master key that authorizes the agent.

## 4. Comparative Analysis

<Tabs>
  <Tab title="Fanout latency">
    | Property              | Legacy serial           | 0x1 engine      |
    | --------------------- | ----------------------- | --------------- |
    | k-th follower fill    | $O(k \cdot \text{RTT})$ | $O(\text{RTT})$ |
    | Last follower @ N=500 | ≈ 20 s                  | ≈ 1 s           |
    | Signal detection      | REST polling            | WebSocket push  |
  </Tab>

  <Tab title="Slippage profile">
    | Property               | Legacy serial       | 0x1 engine            |
    | ---------------------- | ------------------- | --------------------- |
    | Pre-dispatch check     | None                | Orderbook re-read     |
    | Slippage bound         | Implicit, unbounded | Per-follower explicit |
    | Late-follower PnL skew | Heavy left tail     | Bounded by tolerance  |
  </Tab>

  <Tab title="Fault isolation">
    | Property                | Legacy serial      | 0x1 engine          |
    | ----------------------- | ------------------ | ------------------- |
    | Cross-follower blocking | Yes                | No (per-task)       |
    | Cross-leader blocking   | Yes (shared loop)  | No (per-supervisor) |
    | Bad-order containment   | Whole batch stalls | Single task fails   |
  </Tab>

  <Tab title="Custody">
    | Property               | Legacy serial          | 0x1 engine               |
    | ---------------------- | ---------------------- | ------------------------ |
    | Key material on server | Plaintext / KMS-backed | Encrypted agent key only |
    | Signing scope          | Unscoped               | EIP-712 scoped payloads  |
    | Revocation             | Platform-side          | Follower-side            |
  </Tab>
</Tabs>

## 5. Operational Envelope

<AccordionGroup>
  <Accordion title="Leader goes silent">
    The supervisor does not synthesize exits. Open follower positions remain open until the leader closes them or the follower closes them manually from the dashboard. The engine never assumes intent from absence.
  </Accordion>

  <Accordion title="Follower margin exhausted">
    The risk guard returns a `MarginBreach` skip before any order is signed. No leveraged top-up is issued on the follower's behalf. The activity log records the breach with the attempted size and the configured cap.
  </Accordion>

  <Accordion title="Exchange rate limit">
    Each follower connection carries its own token-bucket rate limiter. When a follower hits its bucket, only that follower's tasks backpressure; other followers and other leaders are unaffected.
  </Accordion>

  <Accordion title="Partial fill on leader">
    The signal generator emits incremental `MirrorIntent` messages for each partial. Follower sizing is recomputed against the new leader margin delta on every emission.
  </Accordion>
</AccordionGroup>

## 6. Conclusion

Legacy copy-trading stacks are the product of batch-oriented, REST-polled, single-threaded assumptions that do not compose with modern perpetual venues. The 0x1 engine replaces that stack with a push-driven, per-mirror-trader concurrent, orderbook-aware design whose cost per additional follower is a task handle rather than an RTT. The result is a replication surface where the follower's realized PnL distribution tracks the leader's with bounded, explicit divergence — and where a bad moment for one account never becomes a crisis for the next.

<Note>
  The engine is non-custodial. All follower balances remain on Aster; all signing uses follower-scoped agent keys the follower can revoke at any time.
</Note>
