# Chapter 1: Core Concepts of Exchanges

### 1. Centralized Exchanges (CEX)

#### 1.1 Definition & System Architecture

* **Definition:** A **custodial** trading platform operated by a single corporate entity. Matching, risk control, and clearing/settlement occur **off-chain**; blockchains are used mainly for deposits and withdrawals.
* **Core modules:**
  1. **Accounts & Custody**
     * **Hot/Cold wallet system** (hot wallets serve liquidity and small, frequent flows; cold wallets keep most funds offline long-term).
     * **Multisig / MPC** key management to reduce single-point key-exposure risk.
  2. **Matching Engine**
     * **Price–time priority** matching with nano–millisecond latency; supports **batch matching** and in-memory/on-disk snapshots of the matching core.
     * **Order types:** market, limit, stop-loss (SL), take-profit (TP), IOC/FOK, post-only, hidden/iceberg, reduce-only, etc.
  3. **Risk & Clearing**
     * **Spot:** T+0 real-time settlement; rollback strategies for abnormal matches.
     * **Perpetuals/Derivatives:**
       * **Margin modes:** isolated vs. cross; initial/maintenance margin curves;
       * **Risk engine:** stepwise deleveraging tiers, liquidation flows, **insurance fund** and **ADL (auto-deleveraging)**;
       * **Funding rate:** periodic fee balancing longs vs. shorts;
       * **Mark price / index price:** prevents unreasonable liquidations due to manipulation.
  4. **Fiat On/Off-Ramps**
     * Banking rails, card schemes, payment processors, compliant stablecoin rails (mint/redeem).
  5. **Risk & Compliance**
     * **KYC/AML/sanctions screening**, on-chain tracing/monitoring, suspicious activity reports (SARs), **Travel Rule** support, geo-fencing;
     * Monitoring for AML, wash-trading, market manipulation (layering, pump-and-dump, wash trades).

#### 1.2 Advantages & User Experience

* **High performance & deep liquidity:** Centralized matching and a unified order book lower spreads and market-impact costs.
* **Rich product suite:** Fiat rails, margin/derivatives, options, OTC/block trades, lending, staking, Earn, copy trading, etc.
* **Friendly UX:** One-click orders, unified settlement currency, customer support—newcomer-friendly.

#### 1.3 Key Risks & Mitigations

* **Counterparty risk**
  * Funds are **custodied** by the platform—**Not your keys, not your coins**.
  * **Mitigations:**
    * **PoR (Proof of Reserves):** on-chain reserve addresses + **Merkle-proofed** liabilities + third-party attestation;
    * **Limits:** point-in-time only; blind to external borrowing/off-balance-sheet liabilities; trust in auditor/process; rehypothecation risk.
* **Opacity**
  * Matching and settlement occur in a black box; **information asymmetry/insider-risk** (e.g., potential pre-trading, internalization).
  * **Mitigations:** trade surveillance, access-log retention, matching-engine isolation, bandwidth isolation, regulatory sandboxes/licensing constraints.
* **Operational & compliance risk**
  * Regulatory shifts, licensing hurdles, regional restrictions, service pauses and withdrawal throttling.
* **Security risk**
  * Hot-wallet compromise, privilege abuse, social engineering, supply-chain attacks;
  * **Mitigations:** MPC, multisig, withdrawal allowlists, withdrawal delays, risk thresholds, SOC 2/ISO 27001, bug bounties, incident drills.

#### 1.4 Engineering & Data Metrics to Assess a CEX

* **Market quality**
  * **Depth** (e.g., executable size within ±10 bps), **realized market-impact**, **slippage distribution**, **spread**, **order-gateway latency**, reject rate, matching lag / queue-jump incidence.
* **Reliability**
  * Peak QPS, matching jitter, availability (>99.9%), circuit breakers and rollback, active-active across regions.
* **Risk robustness**
  * Liquidation incident rate, ADL trigger rate, insurance fund size, continuity during extreme volatility.
* **Compliance & transparency**
  * Licensed jurisdictions, Travel Rule coverage, PoR disclosure cadence/method, availability of audit reports.

### 2. Decentralized Exchanges (DEX)

#### 2.1 Definition & Ecosystem Components

* **Definition:** **Non-custodial** trading protocols on blockchains. Assets remain in users’ wallets; **smart contracts** handle quoting, matching, and settlement.
* **Ecosystem components:**
  1. **Market-making mechanisms**
     * **AMMs:** **Constant product** `x*y=k` (Uniswap V2); **stable-swap curves** (near-constant-sum, Curve); **concentrated liquidity** (Uniswap V3—price-range LPing for capital efficiency).
     * **Order-book DEXs:** on-chain/off-chain order books with on-chain settlement (common on some L2s/specific chains).
     * **RFQ / Intent:** Users submit **intents**; **solvers/market makers** compete to fill, often via **batch auctions** to reduce MEV (the auction/solver route).
  2. **Routing & aggregation:** multi-pool paths, cross-protocol aggregation, **best-path search**, some support **split fills** and **RFQ hybrids**.
  3. **Oracles:** TWAP/in-pool pricing; external decentralized oracles with manipulation-resistance.
  4. **Governance & fees:** protocol fees, LP fees (static/dynamic), buybacks & treasury, incentive tokens.

#### 2.2 Trading Flow (typical AMM)

1. **Approve:** User `approve`s tokens (or uses Permit/EIP-2612 for gasless approval).
2. **Quote:** Front-end/aggregator reads pool reserves & fee, estimates slippage and minimum out.
3. **Submit:** User signs and sends the tx (L1 or L2); it enters the **mempool** awaiting inclusion.
4. **Settle:** Contract updates reserves per curve, swaps tokens, and emits logs.

#### 2.3 Advantages

* **Asset sovereignty:** Users keep their keys—**no custodial counterparty risk**.
* **Verifiable transparency:** Rules are in code; on-chain and auditable.
* **Censorship resistance:** Any address can interact with minimal permission (subject to base-chain/front-end constraints).

#### 2.4 Challenges & Technical Considerations

* **Performance & cost**
  * Constrained by L1 TPS/gas;
  * **L2 rollups** cut costs and latency; **EIP-4844/blobs** further reduce DA costs.
* **MEV & execution fairness**
  * Sandwiching, front-/back-running, liquidation races, arbitrage crowd-outs;
  * **Mitigations:** private mempools/protected RPC, **frequent batch auctions (FBA)**, intents+solvers, threshold encryption/delayed reveal, **dark auctions**, randomized routing, ZK-private transactions.
* **Smart-contract & oracle risk**
  * Reentrancy, price manipulation, flash-loan coupling, privilege misconfig, init-defects, arithmetic bugs, etc.;
  * **Mitigations:** multiple audits, formal verification, bug bounties, split privileges/timelocks, parameter caps, multi-source oracle aggregation.
* **LP risk & incentives**
  * **Impermanent loss (IL)**, **adverse selection / toxic flow**, **LVR** (loss vs. rebalancing / price-update lag);
  * **Mitigations:** stable-swap curves, dynamic fees, tight-range CLMM management, hedging, **MM-as-a-Service (MMaaS)**.
* **User experience**
  * Approvals/signing, gas settings, **slippage tolerance**, revert handling;
  * **Account abstraction (AA)**, **batching**, **paymasters**, **social recovery** improve usability.
* **Compliance pathways**
  * Whitelisted pools/restricted front-ends, compliant routing, on-chain credentials (VCs) and **optional KYC** scenarios.

#### 2.5 Engineering & Data Metrics to Assess a DEX

* **Liquidity & execution quality:** pool TVL, 30D/7D/24H volume, unit-size market impact, time-of-day slippage profiles.
* **Efficiency & cost:** average confirmation time, failure rate, average gas cost, L2 fees and withdrawal latency.
* **Security:** audit count/depth, bounty ceiling, incident history, proxy/upgrade permissions, oracle protections.
* **Sustainability:** LP APY (net of IL), protocol fee capture, incentive inflation, governance participation.

### 3. CEX vs. DEX: Dimensional Comparison

| Dimension           | CEX                                           | DEX                                                              |
| ------------------- | --------------------------------------------- | ---------------------------------------------------------------- |
| **Asset custody**   | Platform custody (hot/cold/MPC)               | Self-custody (user wallet signatures)                            |
| **Matching**        | Off-chain order book; millisecond latency     | AMM / order book / intent; constrained by base-chain performance |
| **Transparency**    | Low (black box); PoR helps but limited        | High (contracts and transactions auditable on-chain)             |
| **Perf/Cost**       | High performance; low unit execution cost     | L1-limited; L2s can approach CEX-like UX                         |
| **Product breadth** | Fiat, margin/derivatives, options, Earn, etc. | Mostly spot; derivatives/options maturing                        |
| **Key risks**       | Custody / operations / compliance             | Contract / oracle / MEV / IL                                     |
| **Compliance**      | Strong KYC/AML/licensing                      | Optional compliance modules / front-end gating                   |
| **Listing bar**     | Centralized reviews & MM arrangements         | Any contract can deploy; trust via community/audits              |
| **Composability**   | Weak (platform walled garden)                 | Strong (composable with other DeFi protocols)                    |
