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

# Architecture

> Offchain and onchain components, and the lifecycle of orders, deposits, withdrawals, and settlements.

## Components

Tplus' offchain components run inside Intel TDX TEEs, connected over an encrypted overlay network where every connection is bound to a hardware attestation quote.

The offchain components split into two tiers:

* **Hot tier** - OMS (order management system), orderbooks, interest engine. Fast, minimally replicated, and can only *propose* state changes.
* **Cold tier** - the clearing engine network. Distributed system that re-validates every proposal, threshold-signs state changes, and authorizes movements of funds.

Onchain contracts custody funds and release them only against quorum-signed, nonce-bound, expiring approvals.

The full hierarchy, including external parties, is in the [trust model](/security/trust-model).

### Offchain Architecture

```mermaid theme={null}
flowchart TB
  Clients(["Clients: traders, frontends, API integrators"])

  subgraph HOT["HOT TIER - propose-only, replicated (hot-swap on failure)"]
    direction LR
    OMS["OMS<br/>horizontal replicas for load balancing"]
    OB["Orderbook<br/>markets horizontally distributed for load balancing"]
    IE["Interest engine"]
  end

  subgraph COLD["COLD TIER - Clearing Engine, MPC + TEE quorum"]
    direction LR
    OR["Oracle<br/>Chainlink, Pyth, CEX API"]
    subgraph Q["k-of-N quorum"]
      direction LR
      L(["leader"])
      P1(["peer"])
      P2(["peer"])
      L --- P1
      L --- P2
    end
    BC["Blockchain clients<br/>vault events"]
    OR -->|prices| L
    BC -->|events| L
  end

  Vaults[("Onchain vaults")]

  Clients -->|"orders & signed requests (REST / WS)"| OMS
  OMS -->|orders| OB
  OB -->|"match results"| OMS
  OB -->|"matched orders"| L
  IE -->|"rate proposals"| L
  L -.->|"confirmations, state (gossip)"| OMS
  L ==>|"quorum-signed approvals"| Vaults

  style L stroke:#e60000,stroke-width:2px
  style Vaults stroke:#e60000,stroke-width:2px
```

### Offchain components

Attested services running over the encrypted overlay network. The clearing engine is the only authoritative component; everything else proposes or serves data.

| Component                     | Role                                                                                                                                                                                                    |
| ----------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Order Management System (OMS) | REST + WebSocket API. Validates auth, signer identity, and margin before dispatching orders to the orderbook. Mirrors clearing-engine state. Spawns replicas for load balancing and colocation services |
| Orderbook                     | Price-time priority. Spawns replicas to distribute load by segregating markets to dedicated hardware.                                                                                                   |
| Clearing engine               | Authoritative ledger, run as an MPC+TEE quorum. Finalizes or rolls back every fill; processes deposits, withdrawals, settlements, and interest payments.                                                |
| Market data service           | Historical klines, depth, trades, and tickers over HTTP/WebSocket. Runs separately from order processing.                                                                                               |
| Oracle                        | Aggregates Chainlink, Pyth, and CEX prices through threshold RPC consensus.                                                                                                                             |
| Interest engine               | Computes hourly funding and borrow rates; the clearing engine validates them against parameterized bounds before applying.                                                                              |
| Blockchain clients            | Ingest vault events from [supported chains](/funds/deposits#chains-and-confirmation-times) using majority agreement across multiple RPC providers.                                                      |

### Onchain components

Smart contracts custody all funds and define the protocol's trust root (both authorized component images and state checkpoints). Contract addresses are defined in the Registry. Full reference: [Contracts](/contracts/overview).

| Contract                                            | Role                                                                                                                                                           |
| --------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| [Deposit Vault](/contracts/deposit-vault)           | Custodies all user funds - the only contract that moves them (deposits, settlements, withdrawals). One deployment per chain.                                   |
| [Registry](/contracts/registry)                     | Onchain source of listed (fungible or leverage-approved) assets, per-asset risk parameters, withdrawal-delay parameters, and the fee account.                  |
| [Credential Manager](/contracts/credential-manager) | Root of trust. Registers vaults, binds operators to attested keys, pins approved TEE code measurements, timelocks governance, and validates state checkpoints. |

## Order lifecycle

1. The client sends an order to the OMS over an authenticated session (a bearer token obtained by signing a login nonce). Each order also carries its own Ed25519 signature; the OMS checks that the authenticated user matches the signer, and the clearing engine verifies the signature itself before finalization (step 5).
2. The OMS checks rate limits, signer identity, [order ID rules](/trading/orders#order-fields), reduce-only constraints, and runs a [margin pre-flight](/trading/margin#trading-capacity-and-order-pressure).
3. The orderbook matches in price-time priority (FIFO within a price level). Trades execute at the maker's price; price improvement goes to the taker. The OMS returns the order-created or order-filled acknowledgment once the orderbook accepts the order.
4. Matched fills are forwarded to the clearing engine as proposals.
5. The clearing engine verifies each order's signature, then checks cumulative fill quantities (no overfill), order parameters, [protocol caps](/trading/margin#protocol-caps), reduce-only constraints, and post-trade IM for every counterparty, at both oracle and mark price. Valid fills commit atomically; invalid ones roll back.

A fill is hard-final only when the clearing engine confirms it, not when the orderbook matches it. In practice, an orderbook match is a **soft finalization**: because orders are validated and margin-checked before they reach the book, the quorum confirms the vast majority of fills unchanged. You can act on a match immediately and treat it as confirmed for most purposes; wait for clearing confirmation only before an irreversible action against the fill (for example, releasing value off-platform). The mechanics:

* WebSocket trade-event streams carry pending, confirmed, and rolled-back states; REST trade history returns confirmed trades only.
* Rollbacks are per-party: if a maker is rolled back for failing margin, its quantity is removed from the book and the taker's restored quantity is re-matched against remaining liquidity. Rollback reasons are disclosed only to the at-fault party; counterparties see `CounterpartyAtFault`.
* Fill-or-kill is atomic across the whole batch: if any maker leg fails clearing, the entire batch rolls back.
* Fills that reach clearing more than 5 minutes after matching are rolled back as a stale match.

## Market-maker order lifecycle

Market-maker accounts are a designated account type. They run the standard [order lifecycle](#order-lifecycle), with these differences:

* **Dedicated colocated OMS.** Market makers are typically provisioned a dedicated OMS colocated with the orderbooks, that accepts only posts and cancels. The standard shared OMS serves the full REST/WebSocket API and sits behind a longer network path. This creates an implicit taker speed bump.
* **Post-only orders skip the OMS margin pre-flight check** (step 2); other order types still run it. Clearing still checks post-trade IM on every fill, so a fill that would leave the maker below IM still rolls back.
* **Exempt from [auto-reduce](/trading/orders#auto-reduce):** negative trading capacity never auto-cancels a maker's resting orders.
* **[Synchronous making](/composability#synchronous-making).** On market-maker-only sync orderbooks, an order bundles a delegated settlement request. The OMS checks that request's signature and expiry before matching, and at fill the underlying is sourced from onchain liquidity in the same atomic step - so the maker can quote an asset it holds no inventory in. Sync books are spot-only and limited to the spot sub-accounts.

## Deposit lifecycle

1. **Deposit onchain.** Call `deposit(...)` on the chain's vault contract. Funds stay in the vault throughout.
2. **Ingest.** Blockchain clients pick up the `Deposited` event, confirmed by majority agreement across independent RPC providers.
3. **Credit.** Once the chain's confirmation policy is met, the balance is credited and normalized to 18 decimals.

**Finality.** Each deposit is credited exactly once, tracked by a per-user, per-chain nonce. A canonical-block check drops events on orphaned blocks and re-ingests from the canonical chain, so a reorg can delay a credit but never double-credits or loses one. Confirmation thresholds and waits per chain, decimals, caps, and fungibility: [Deposits](/funds/deposits).

## Withdrawal lifecycle

1. **Request.** Submit a signed request specifying asset, amount (18-decimal), and destination.
2. **Lock and margin check.** The withdrawal amount is locked. Solvency is checked against the amount plus any dynamic rebalancing fee; a request that would leave the account under-margined is rejected with nothing locked.
3. **Delay queue.** The request waits a delay derived from the user's recent withdrawal-capacity usage for that asset, mapped through configured delay tiers and clamped to onchain minimum and maximum bounds.
4. **Fill.** After the delay, it is filled from vault liquidity, FIFO per asset.
5. **Approve and execute.** At the next [checkpoint](/security/trust-model#slot-lifecycle), the protocol issues a quorum-signed, nonce-bound, expiring approval. The user calls `withdraw(...)` and the vault verifies the quorum, nonce, and expiry.

**Finality.** The withdrawal is final once the onchain `withdraw(...)` executes. Approvals are single-use, nonce-bound, and expire at `validUntil`. If an approval lapses before the user executes it - the protocol first confirms onchain that the withdrawal was never executed, then unlocks the locked funds, so a withdrawal can never be both executed and refunded. Fees, partial-fill rules, cancellation, and the escape hatch: [Withdrawals](/funds/withdrawals).

## Settlement lifecycle

1. **Request and margin check.** Submit a signed request specifying `asset_out`/`asset_in`, amounts, sub-account, and settler. The clearing engine runs an initial-margin check at both oracle and mark price; the settlement must not decrease the IM surplus, though accounts with no borrows always pass.
2. **Lock.** The outgoing amount moves into a settlement lock keyed by chain and nonce.
3. **Approve.** The protocol signs a time-bound approval and delivers it to the settler, encrypted to the settler's key.
4. **Execute.** The settler calls `executeAtomicSettlement(...)` within the 10-second validity window; the vault verifies signature, nonce, and expiry.
5. **Confirm or expire.** A confirmed event credits `asset_in`. If execution does not land in time or reverts, the lock expires and the outgoing funds are restored.

**Finality.** Settlement is atomic: either `asset_in` is credited or the lock expires and the outgoing funds are restored - never a partial state. Once `validUntil` passes or the nonce is consumed, the vault rejects late or replayed execution. Lock mechanics, nonce scoping, and approval encryption: [Settlement](/funds/settlement). Cross-margining: [Funds](/funds/cross-margining). Synchronous making: [Composability](/composability#synchronous-making).
