# How the Durian CLOB Works

## 📊 How the Durian CLOB Works

> **A trustless on-chain order book purpose-built for gaming tokens.** Real limit orders. Real market orders. Real maker rebates. No admin switches. No off-chain matching.

### Why a CLOB?

AMMs are great for bootstrapping a brand-new token with zero liquidity providers — but they're **inefficient** for mature markets:

* Constant-product pricing leaks value to arbitrageurs on every trade.
* Liquidity providers carry impermanent loss.
* There's no way to say *"sell at exactly 0.015 KUB, not a tick lower."*

For **gaming tokens** — where communities want fast execution, market-maker incentives, and tight spreads — a **Central Limit Order Book** is the right primitive.

The Durian CLOB gives you all of that, **fully on-chain**, with zero admin keys.

### Architecture at a Glance

```
┌─────────────────────────────────────────────────────────────┐
│                     CLOBFactory V2.5                        │
│  · Listing requests (5 KUB fee, 14-day escrow)              │
│  · Approver slots (5 hard-capped, transferable NFT-like)    │
│  · Deterministic pair deployment (CREATE2 clones)           │
└──────────────────────────┬──────────────────────────────────┘
                           │ spawns one pair per token/base
        ┌──────────────────┴──────────────────┐
        ▼                                     ▼
┌─────────────────┐                   ┌─────────────────┐
│  TOKEN / KUB    │                   │  TOKEN / kUSDT  │ ... (+ kUSDC)
│  CLOBPair       │                   │  CLOBPair       │
│  · Limit book   │                   │  · Limit book   │
│  · Matching     │                   │  · Matching     │
└─────────┬───────┘                   └─────────┬───────┘
          └─────────────┬─────────────────────┘
                        ▼
          ┌───────────────────────────────┐
          │    DurianSpotWallet (Vault)   │
          │  Singleton for ALL pairs      │
          │  free[user][token]            │
          │  locked[user][token][pair]    │
          └───────────────┬───────────────┘
                          │
                          ▼
          ┌───────────────────────────────┐
          │    InsuranceReserve           │
          │  10% of net fees accumulated  │
          └───────────────────────────────┘
```

### Three Pairs Per Token

Every listing automatically creates **three trading pairs** against the ecosystem bases:

* `TOKEN / KUB`
* `TOKEN / kUSDT`
* `TOKEN / kUSDC`

One listing fee, three venues — gaming communities can pay in whatever stable or native currency suits them.

### Order Types

| Order           | Function                                   | Description                                                         |
| --------------- | ------------------------------------------ | ------------------------------------------------------------------- |
| **Limit**       | `placeLimitOrder(isBuy, price, amount)`    | Set-and-forget at a specific price. Returns `orderId`. Cancellable. |
| **Market Buy**  | `placeMarketBuy(tokenAmount, maxBaseIn)`   | Buy up to `tokenAmount` at best ask. `maxBaseIn` caps slippage.     |
| **Market Sell** | `placeMarketSell(tokenAmount, minBaseOut)` | Sell `tokenAmount` into best bid. `minBaseOut` floors receipt.      |
| **Batch Limit** | `placeBatchLimit(BatchOrder[])`            | Atomic multi-order placement — great for market makers.             |

**GTC-only at launch.** Good-Till-Cancelled is the one time-in-force on V2.5. IOC / FOK / stop / post-only orders are deferred to future versions.

### The Matching Engine

Under the hood, the CLOB runs:

* **Per-tick linked lists** of orders (price levels).
* **Sorted linked list** of occupied ticks for O(log n) best-bid / best-ask lookup.
* **FIFO within price** — price-time priority, classical exchange semantics.
* **Partial fills** supported — any untilled remainder stays open.
* **Fill sweep cap:** up to **50 fills per transaction** to keep gas bounded.
* **Tick-hop cap:** `MAX_TICK_HOPS = 64` — prevents gas-bomb attacks from dust-level spam.

### The Vault — Where Your Funds Actually Live

All user balances are held by a **single shared vault contract** (`DurianSpotWallet`), not by individual pairs. This is a security-first design:

```
User flow:
  1. deposit(token, amount)  ─► free[user][token] += amount
  2. placeLimitOrder(...)    ─► pair calls pullAndLock:
                                  free[user][token]    -= amount
                                  locked[user][token]  += amount
  3. match fills             ─► pair calls settleLockedToFree:
                                  maker: locked → free of counterparty asset
                                  taker: balance moves directly
  4. withdraw(token, amount) ─► free[user][token] -= amount → wallet
```

Benefits:

* **One withdrawal surface.** Deposit once, trade across all pairs.
* **Isolation by token.** A bug in one pair can't drain others.
* **Pair auth via CREATE2.** The vault verifies the calling pair was deployed by the factory — no rogue pair can steal funds.

### Fee Structure

| Side                 | Fee                       | Where it goes                               |
| -------------------- | ------------------------- | ------------------------------------------- |
| **Taker**            | **0.20%**                 | Paid on the trade                           |
| **Maker**            | **+0.04%** rebate         | Direct to maker — incentivizes liquidity    |
| **Net protocol fee** | 0.20% − 0.04% = **0.16%** | Split: 90% Treasury · 10% Insurance Reserve |

#### Worked Example — 1,000 KUB Trade

```
Taker pays:     1,000 × 0.20% = 2.0 KUB
Maker earns:    1,000 × 0.04% = 0.4 KUB (rebate)
Net protocol:   2.0 − 0.4    = 1.6 KUB
  ├─ Treasury (90%):  1.44 KUB
  └─ Insurance (10%): 0.16 KUB
```

Fee constants are **bytecode immutable:**

* `TAKER_FEE_PPM = 2,000` (0.20%)
* `MAKER_REBATE_PPM = 400` (0.04%)
* `INSURANCE_BPS = 1,000` (10% of net)

Enforced invariant: `makerPpm × 10,000 ≤ takerPpm × rebateBps` — this was the **C-02 fix** (see Audit).

### Tick Sizing for Every Scale

Tick size is **chosen at listing** and **immutable** thereafter. Choose from **8 presets**:

| Preset | Tick | Best for                      |
| ------ | ---- | ----------------------------- |
| `1e9`  | 1e-9 | Meme tier, micro-price tokens |
| `1e11` | 1e-7 | Very high precision           |
| `1e12` | 1e-6 | High precision                |
| `1e13` | 1e-5 | Standard small-cap            |
| `1e14` | 1e-4 | Standard                      |
| `1e15` | 1e-3 | Large-cap tokens              |
| `1e16` | 0.01 | Big tokens                    |
| `1e17` | 0.1  | Highest-value tokens          |

Pick the one that gives you meaningful spreads without fragmenting liquidity across ticks nobody uses.

### What Makes It Gaming-Native

* **Low min notional** (0.001 base) → accommodates small-value gaming transactions.
* **Multiple base pairs** (KUB / kUSDT / kUSDC) → international gaming communities.
* **Maker rebates** → motivates game studios + their MM partners to seed books.
* **Zero admin** → no pause, no delist, no freeze. Studios can't be held hostage.
* **Microcap tick sizing** → launch tokens with 9-decimal prices without book fragmentation.

### Key Contracts (Mainnet V2.5)

| Contract                 | Address                                      |
| ------------------------ | -------------------------------------------- |
| CLOB Factory V2.5        | `0x1e963da022030D29D952e7e0c944F6bfAC50b0e7` |
| DurianSpotWallet (Vault) | `0xF5b0137F6dCEcE06C566FCae10694dD8645283B3` |
| Pair Implementation      | `0x6619496380EBD9FF50805E2e2637b48943875e00` |

All source-verified on [Kubscan](https://www.kubscan.com).

→ Next: **How to List Your Coin** — the 5-KUB request path and approver bypass. → Or: **Read the CLOB Audit** — six review rounds, R6 hard audit.


---

# 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:

```
GET https://durianandfun.gitbook.io/durianfun/durian-spot/spot-clob/how-the-durian-clob-works.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
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.
