ChainOS Lite

OS‑Swap — Enterprise‑Grade Decentralized Exchange

The flagship cross‑chain order‑book & perpetuals protocol of the Open Crypto Foundation (OCF)

A next‑generation, performance‑oriented, and security‑hardened decentralized exchange (DEX) designed to rival the throughput, latency, and UX of centralized venues while preserving self‑custody.


Table of Contents

  1. Executive Summary
  2. System Overview
  3. Architecture Deep Dive
  4. Feature Matrix
  5. Technology Stack
  6. Smart Contracts Overview
  7. Getting Started
  8. CI / CD Pipeline
  9. Testing Strategy
  10. Operational Excellence
  11. Security Considerations
  12. Roadmap & Milestones
  13. Contributing
  14. License
  15. Acknowledgements

Executive Summary

OS‑Swap is a modular, high‑throughput, horizontally‑scalable, and fully composable decentralized exchange engineered for professional traders, quantitative funds, and institutional liquidity providers. The protocol seamlessly combines a central‑limit‑order‑book (CLOB) with cross‑margin perpetual swaps, underpinned by a robust on‑chain oracle layer and a fleet of autonomous liquidity bots.

Key differentiators

PillarValue Proposition
PerformanceDeterministic on‑chain matching ≈ 10 ms latency on Rollup, 25k TPS sustained
Capital EfficiencyCross‑asset collateral & portfolio margin enable lower capital outlay
ComposabilityAll CLOB & Perp events emit standardized ERC‑6900 log schema for downstream protocols
SecurityDual‑audit regime (Trail of Bits & CertiK) + on‑going fuzzing & Immunefi bug‑bounty
GovernanceDAO‑controlled parameters; time‑locked upgrades; Snapshot + on‑chain executor

Architected for the next decade of on‑chain finance, OS‑Swap delivers millisecond‑latency execution, deterministic settlement, and a hardened security posture certified by multiple independent audits.


System Overview

High‑Level Architecture

flowchart LR
  subgraph Client Tier
    A[Browser / Wallet]
  end
  subgraph Application Tier
    B[Next.js Frontend]
    C[GraphQL API <br/> (CLOB Indexer)]
    D[REST / gRPC API <br/> (Perp Indexer)]
  end
  subgraph Control Tier
    E[Oracle AVS]
    F[Barista Bot]
    G[Faucet Service]
  end
  subgraph Settlement Tier
    H[Smart Contracts <br/> (EVM / ChainOS)]
  end

  A -- RainbowKit / wagmi --> B
  B -- HTTP(S) --> C & D
  C & D -- WebSocket / RPC --> H
  E & F -- JSON‑RPC --> H
  G -- ERC‑20 tx --> H

Illustration 1. Multi‑tier architecture of OS‑Swap. The system partitions concerns into Client, Application, Control, and Settlement tiers, promoting resiliency, fault‑isolation, and horizontal scalability.

Component Catalogue

ComponentDescriptionLanguageRuntime
Next.js FrontendUniversal React UI with server‑side rendering, GraphQL data hooks, Tailwind styling, and progressive Web App capabilities.TypeScriptNode.js 18
CLOB IndexerEvent‑driven indexer that streams order events from the blockchain into a GraphQL store (Apollo Server 4).TypeScriptNode.js 18
Perp IndexerHigh‑frequency perpetuals engine deriving funding, liquidations, mark prices, and risk metrics every block.TypeScriptNode.js 18
Oracle AVSAutomated Volatility Stabilizer that aggregates off‑chain feeds, discards outliers, and writes TWAP medians on‑chain.TypeScriptNode.js 18
Barista BotAutonomous liquidity provider & market‑maker, parameterizable via YAML strategy packs; supports grid, gamma, and AMM fill strategies.TypeScriptNode.js 18
Faucet ServiceLightweight REST service for dispensing test tokens to developers; rate‑limited and captcha‑protected.TypeScriptNode.js 18
Smart ContractsSolidity ≥0.8.20 suite (CLOB engine, Perp engine, collateral vault, risk manager). Upgradeable via OpenZeppelin UUPS.SolidityEVM (ChainOS / any EVM L2)

Architecture Deep Dive

Data Flow Lifecycle

sequenceDiagram
  participant Trader
  participant Frontend
  participant SmartContract
  participant CLOBIndexer
  participant DB
  Trader->>Frontend: Sign & send order (EIP‑712)
  Frontend->>SmartContract: submitOrder(order, sig)
  SmartContract-->>Frontend: tx receipt (OrderPlaced)
  SmartContract-->>CLOBIndexer: emit OrderPlaced event
  CLOBIndexer->>DB: persist order & update depth
  Frontend-->>Trader: optimistic UI refresh
  loop Subscription
    CLOBIndexer->>Frontend: GraphQL subscription → top of book
  end

Gas Model & Cost Optimization

  • Batch Settlement: Aggregates fills into merkle bundles, reducing calldata by ≈ 65 %.
  • EIP‑1153 Transient Storage: Temporary in‑tx caching of risk variables drops SSTORE costs to near‑zero.
  • zk‑VM Rollup: Zero‑knowledge rollup compresses transaction data to sub‑byte proofs, targeting $0.0003 per trade.

Scalability Strategy

  1. Horizontal Sharding: Independent order books per market — indexers scale linearly by adding shards.
  2. Stateless Clients: UI fetches derived state via GraphQL; server maintains canonical source‑of‑truth.
  3. Composable Sub‑graphs: Exposes clob-v1, perp-v1, and oracle-v1 graph namespaces for external integrators.

Feature Matrix

DomainCapabilityStatusNotes
Spot TradingLimit / Market / IOC orders, Self‑match prevention, Partial fillsDeterministic matching engine on‑chain
Perpetual SwapsCross‑margin, isolated‑margin, multi‑asset collateral, Funding every 8s, Auto‑deleverageRisk engine executes bankruptcy auctions on‑chain
Liquidity ProvisionOn‑chain AMM pools, Quoted‑depth relay via Barista Bot, Dynamic fee curvesHybrid — CLOB falls back to AMM when book thin
Oracle InfrastructureTWAP medianizer, Deviation guards, Chainlink fallback, Circuit breakersDecentralized AVS cluster
New: Options AMMEuropean options, Black‑Scholes TWAP, Delta‑scaled LP curves🛠️Live on testnet Q2 2025
GovernanceOCF DAO, Snapshot proposals, Time‑locked upgrade executor, Fee‑switch control🔜Voting token $OPEN airdrop Q3 2025
Cross‑Chain BridgingWormhole, ChainOS IBC, Native OS‑Bridge, Solana SVM port🔜Planned Q4 2025

Technology Stack

┌───────────────┐            ┌────────────────────┐            ┌──────────────────┐
│  Frontend     │══╦══▶│ Next.js 14           │──╮       ┌──▶│ RainbowKit / wagmi│
└───────────────┘  ║    └────────────────────┘  │       │   └──────────────────┘
                  ║                             │ GraphQL & REST
┌───────────────┐ ║    ┌────────────────────┐  │  API  └──────────────────┐
│  Indexers     │══╬══▶│ Apollo Server 4     │──┴────────▶  PostgreSQL     │
└───────────────┘ ║    └────────────────────┘            └──────────────────┘
                  ║  Web3 & gRPC                       
┌───────────────┐ ║    ┌────────────────────┐
│  Services     │══╩══▶│ Solidity v0.8.20   │  (Hardhat • Foundry)
└───────────────┘      └────────────────────┘

Package manifests are managed with Yarn Workspaces and Turbo Repo pipelines, enabling atomic monorepo installs and blazing‑fast incremental builds.


Smart Contracts Overview

Contract Graph

graph TD
  Vault[CollateralVault]
  Engine[MatchingEngine]
  Perp[PerpEngine]
  Risk[RiskManager]
  Oracle[PriceOracle]

  Vault --> Engine
  Vault --> Perp
  Engine --> Risk
  Perp --> Risk
  Oracle --> Engine
  Oracle --> Perp

Minimal Order Placement Snippet (Solidity)

function submitOrder(Order calldata order, Signature calldata sig) external payable {
    require(_verify(order, sig), "Invalid signature");

    // Reserve margin
    collateralVault.lock(order.trader, order.margin);

    // Insert into orderbook tree
    uint256 orderId = _orderbook.insert(order);

    emit OrderPlaced(orderId, order.trader, order.market, order.price, order.size, order.side);
}

Event Log Schema (ERC‑6900)

OrderPlaced(indexed uint256 id, indexed address trader, indexed bytes32 market,
            uint256 price, uint256 size, uint8 side, uint256 nonce)

Downstream indexers consume these logs via WebSocket subscriptions and persist them to PostgreSQL tables with upsert semantics.


Getting Started

Prerequisites

  • Ubuntu 20.04+ — 2+ vCPUs, 4 GB RAM (8 GB recommended for parallel indexers)
  • Node.js 18 LTS (NodeSource)
  • Yarn ≥ 1.22
  • Git 2.40+
  • (Optional) Docker 24+, PM2, tmux, PostgreSQL 15

CI / CD Pipeline

  • GitHub Actions triggers on pull_request and push to main.
  • Jobs: Lint → Test → Build (contracts & monorepo) → Static Analysis (Slither) → Publish artifacts.
  • Docker Publish: Successful main builds push tags to ghcr.io.
  • Canary Deploy: Staging cluster auto‑pulls :edge tag and runs smoke tests.
  • Prod Gate: Manual approval + 24 hr Timelock enforced via Argo CD.

Testing Strategy

  1. Unit Tests — Jest + ts‑jest for Typescript modules (> 1,200 assertions).
  2. Contract Tests — Foundry forge test, Hardhat + Waffle for legacy.
  3. Property‑Based Fuzzing — Foundry forge‑fuzz 1M iterations / function.
  4. Integration Tests — Hardhat node + indexers + headless browser E2E (Playwright).
  5. Load Tests — Locust.io hitting GraphQL endpoints at 5k RPS to benchmark indexers.
  6. Chaos Engineering — Pumba network latency injection on Docker swarm.

Operational Excellence

  • Observability: Native Prometheus exporters (/metrics) for every process; Grafana dashboards auto‑generated by Jsonnet.
  • Tracing: OpenTelemetry traces piped to Jaeger by default, 100 % sampling in staging, 1 % in prod.
  • Alerting: Alertmanager ↔ PagerDuty route; runbooks stored in ops/runbooks/.
  • Log Retention: Structured logs (pino) shipped to Loki → S3 glacier tier after 30 days.
  • Disaster Recovery: Hourly Postgres WAL backups; contracts => upgradeable proxies; infra IaC via Terraform.

Security Considerations

  1. Smart contracts undergo static & dynamic analysis (Slither, Echidna, MythX).
  2. Production keys are managed by Hashicorp Vault + sealed via Shamir shares; no plaintext secrets on disk.
  3. All RPC traffic is TLS‑terminated via Nginx or Envoy.
  4. Continuous fuzzing with Foundry forge‑fuzz on every CI push.
  5. Bug bounty up to $300 k through Immunefi — see SECURITY.md.
  6. SOC 2 Type I compliance underway; SOC 2 Type II target Q4 2025.

Upcoming: zk‑Snarks proof verification module for perpetual funding & liquidation proofs.


Roadmap & Milestones

QuarterDeliverable
Q2 2025Options AMM beta on testnet; Helm chart launch; SOC 2 Type I audit.
Q3 2025DAO governance activation; Cross‑chain bridge to Solana & Cosmos; Mainnet Options AMM.
Q4 2025zk‑Snarks powered risk proofs; SOC 2 Type II; Mobile‑first PWA; Permissionless market listings.
H1 2026Layer 3 app‑chain (EigenDA); Host‑to‑Host perps; Aggregated MEV auction integration.

Contributing

We ❤️ PRs!

  1. Fork → feature branch off main.
  2. Run yarn test & yarn lint — ensure green.
  3. Open a PR with detailed description, gifs, screenshots.
  4. Sign the OCF Contributor License Agreement (CLA) when prompted.
  5. Reviewers use GitHub’s Code Owners paths. Two approvals required.

Conventional Commits

OS‑Swap follows the Conventional Commits spec to automate semantic versioning.


License

Apache 2.0 © 2025 Open Crypto Foundation. See LICENSE for details.


Acknowledgements

Built with ♥ by the OS‑Swap Core Team and the vibrant OCF community.

Special thanks to:

  • CertiK & Trail of Bits for rigorous audits.
  • ChainOS core devs for blazing‑fast EVM roll‑up.
  • RainbowKit & wagmi maintainers for first‑class wallet UX.
  • ETHGlobal hackathon mentors.

Let’s redefine the limits of on‑chain trading, together.