# Protocol Flow

This document describes the complete lifecycle of a BaseCase prediction market, from creation through resolution.

***

## Market Lifecycle Overview

{% @mermaid/diagram content="flowchart LR
Creation\["CREATION<br/>─────────<br/>Market Initialization<br/>Parameters"]
Bonding\["BONDING<br/>─────────<br/>Shadow share<br/>trading"]
Graduation\["GRADUATION<br/>─────────<br/>Real tokens<br/>Order book"]
Resolution\["RESOLUTION<br/>─────────<br/>Oracle<br/>Settlement"]

```
Creation --> Bonding
Bonding --> Graduation
Graduation --> Resolution

style Creation fill:#f0fdf4,stroke:#22c55e,stroke-width:2px,color:#000000
style Bonding fill:#eff6ff,stroke:#3b82f6,stroke-width:2px,color:#000000
style Graduation fill:#fef3c7,stroke:#f59e0b,stroke-width:2px,color:#000000
style Resolution fill:#fce7f3,stroke:#ec4899,stroke-width:2px,color:#000000" %}
```

***

## Phase 1: Market Creation

### Initialization Parameters

| Parameter       | Description             | Example                        |
| --------------- | ----------------------- | ------------------------------ |
| Question        | Binary yes/no question  | "Will BTC hit $150k by Jan 1?" |
| End Time        | When trading stops      | January 1, 2025 00:00 UTC      |
| Bonding Period  | Duration of curve phase | 7 days                         |
| Virtual Reserve | Initial vYES and vNO    | 1,000 each                     |

### Initial State

```
vYES = 1,000
vNO = 1,000
k = vYES × vNO = 1,000,000

YES Price = vNO / (vYES + vNO) = 50%
NO Price = vYES / (vYES + vNO) = 50%

Vault = $0
Shadow YES = 0
Shadow NO = 0
```

***

## Phase 2: Bonding Curve Trading

### Trading Mechanics

During the bonding phase, users trade against a virtual Constant Product Market Maker (CPMM).

**Buy Operation:**

```
Input: USDC amount (A)

For YES purchase:
1. vNO_new = vNO + A
2. vYES_new = k / vNO_new
3. Shares = vYES_old - vYES_new
4. Vault += A
```

**Sell Operation:**

```
Input: Share quantity (S)

For YES sale:
1. vYES_new = vYES + S
2. vNO_new = k / vYES_new
3. cpmmPayout = vNO_old - vNO_new
4. Payout = MIN(cpmmPayout, S)  ← $1 CAP
5. Vault -= Payout
```

> \[!TIP] **Winner Profit Guarantee**: Buy operations include a $1 ceiling (min 1 share per $1), and sell operations have a $1 cap (max $1 payout per share). This ensures the vault can always pay $1/share to winners.

### Example Trading Sequence

| Action   | Trader  | Amount | Shares | Price | Vault  |
| -------- | ------- | ------ | ------ | ----- | ------ |
| Buy YES  | Alice   | $500   | 500    | $1.00 | $500   |
| Buy NO   | Bob     | $300   | 300    | $1.00 | $800   |
| Buy YES  | Charlie | $1,000 | 1,000  | $1.00 | $1,800 |
| Buy YES  | Dave    | $2,000 | 2,000  | $1.00 | $3,800 |
| Sell YES | Charlie | 1,000  | -      | $0.95 | $2,850 |
| Buy NO   | Eve     | $2,000 | 2,150  | $0.93 | $4,850 |

### Solvency Tracking

The protocol continuously monitors solvency:

```
Solvency = Vault Balance / MAX(Total Shadow YES, Total Shadow NO)
```

| Checkpoint    | Shadow YES | Shadow NO | Vault  | Solvency |
| ------------- | ---------- | --------- | ------ | -------- |
| After trade 3 | 2,305      | 294       | $1,800 | 78.1%    |
| After trade 4 | 4,125      | 294       | $3,800 | 92.1%    |
| After trade 5 | 3,175      | 294       | $2,765 | 87.1%    |
| After trade 6 | 3,175      | 2,444     | $4,765 | 150.1% ✓ |

### Graduation Trigger

When solvency reaches 100%, the market qualifies for graduation:

```
Solvency >= 100% → Graduation eligible
```

Graduation can be triggered by any user calling the `graduate()` function.

***

## Phase 3: Graduation

### Graduation Sequence

```
Step 1: FREEZE
├── Disable bonding curve trading
├── Snapshot shadow balances
└── Lock current state

Step 2: CALCULATE
├── Total YES claims = Shadow YES total
├── Total NO claims = Shadow NO total
├── Required collateral = MAX(YES, NO)
└── Excess = Vault - Required

Step 3: MINT
├── Lock required USDC in vault as collateral
├── Mint ERC-20 YES and NO tokens
├── Total tokens = MAX(Shadow YES, Shadow NO)
└── Collateral locked in vault contract

Step 4: DISTRIBUTE
├── Transfer YES tokens to shadow YES holders (1:1)
├── Transfer NO tokens to shadow NO holders (1:1)
├── Excess tokens retained by protocol
└── Excess USDC to treasury

Step 5: OPEN ORDER BOOK
├── Initialize YES/USDC order book
├── Initialize NO/USDC order book
├── Enable limit order placement
└── Enable order matching
```

### Example Graduation

**Pre-Graduation State:**

```
Shadow YES: 8,285 shares
Shadow NO: 3,024 shares
Vault: $12,259
Solvency: 148%
```

**Graduation Execution:**

```
Required sets: MAX(8,285, 3,024) = 8,285
Collateral locked: $8,285
Graduation fee (2%): $165

Token minting:
├── 8,285 YES tokens created
└── 8,285 NO tokens created

Distribution:
├── 8,285 YES → Shadow YES holders
├── 3,024 NO → Shadow NO holders
├── 5,261 NO → Protocol treasury
└── $3,809 USDC → Protocol treasury
```

***

## Phase 4: Order Book Trading

### Order Book Structure

Post-graduation, trading occurs on a Central Limit Order Book (CLOB):

```
YES/USDC Order Book
──────────────────────────────────────
ASKS (Sell orders)
├── $0.68 × 500 shares
├── $0.67 × 200 shares
├── $0.66 × 800 shares
────────────────────── Spread: $0.02
BIDS (Buy orders)
├── $0.64 × 1,000 shares
├── $0.62 × 500 shares
└── $0.60 × 2,000 shares
```

### Order Types

| Order Type | Description                    |
| ---------- | ------------------------------ |
| Limit      | Place order at specific price  |
| Market     | Execute against best available |
| Cancel     | Remove unfilled order          |

### No Liquidity Required

Unlike AMM-based post-graduation:

| Aspect            | AMM (Uniswap V3)     | Order Book        |
| ----------------- | -------------------- | ----------------- |
| LP capital needed | Yes (protocol seeds) | No                |
| Price discovery   | Formula-based        | Supply/demand     |
| Spread control    | Tick ranges          | Maker competition |
| Limit orders      | Indirect             | Native            |

### Price Constraint

Order books enforce the binary outcome constraint:

```
YES_price + NO_price = $1.00

Valid:   YES @ $0.65 implies NO @ $0.35
Invalid: YES @ $0.65 with NO @ $0.40 (sum = $1.05)
```

***

## Phase 5: Resolution

### Oracle Process

```
Step 1: Market end time reached
├── Trading continues until resolution
└── No new information restrictions

Step 2: Assertion
├── Any user can propose outcome
├── Bond required: $100 USDC
└── Assertion: "YES" or "NO"

Step 3: Dispute Window
├── Duration: 2 hours
├── Disputers can challenge with counter-bond
└── If disputed → UMA DVM vote

Step 4: Settlement
├── If undisputed → Assertion accepted
├── If disputed → DVM determines outcome
└── Winning asserter receives bond back + reward
```

### Token Redemption (Fixed $1 + OG Bonus)

```
Resolution: YES wins

Base Payout = User YES Shares × $1.00
OG Bonus = (User OG Shares / Total OG Shares) × OG Bonus Pool
Total Payout = Base Payout + OG Bonus

NO token value: $0.00

Redemption:
├── User calls claimWinnings()
├── Contract calculates: shares × $1 + OG bonus
├── Transfers USDC to user
└── Burns claimed tokens
```

### Collateral Flow

```
Initial:  Vault holds $8,285 collateral
          8,285 YES tokens outstanding
          8,285 NO tokens outstanding

If YES wins:
├── 8,285 YES × $1.00 = $8,285 claimed
├── 8,285 NO × $0.00 = $0 claimed
└── Collateral exactly matches payouts

If NO wins:
├── 8,285 YES × $0.00 = $0 claimed
├── 8,285 NO × $1.00 = $8,285 claimed
└── Collateral exactly matches payouts
```

***

## Fee Structure Summary

| Phase              | Fee    | Distribution                             |
| ------------------ | ------ | ---------------------------------------- |
| Bonding - Buy      | **0%** | —                                        |
| Bonding - Sell     | **0%** | —                                        |
| Graduation         | **2%** | 50% Protocol / 25% Stakers / 25% Creator |
| Order Book - Maker | 0%     | —                                        |
| Order Book - Taker | \~0.2% | TBD                                      |
| Resolution         | 0%     | —                                        |

> \[!NOTE] Bonding phase has **zero trading fees**. Solvency is maintained through CPMM slippage mechanics, not fees.

### Creator Rewards Example

```
Market graduates with $10,000 vault:

Graduation fee: 2% × $10,000 = $200
├── Protocol: $100 (50%)
├── Stakers:  $50  (25%)
└── Creator:  $50  (25%)

Post-graduation trading volume: $50,000
Taker fees: ~0.2% × $50,000 = ~$100
├── (Distribution TBD)

Total Creator Earnings (graduation only): $50
```

***

## Risk Analysis

### Solvency Guarantee

The protocol guarantees payout solvency through:

1. **CPMM Slippage**: Large one-sided trades pay premium prices
2. **Natural Accumulation**: Vault grows through buyer deposits
3. **Graduation Threshold**: Cannot graduate below 100% solvency + 20% each side
4. **Collateral Lock**: Vault holds required amount at graduation

### Failure Modes

| Scenario          | Trigger                     | Resolution      |
| ----------------- | --------------------------- | --------------- |
| Failed graduation | Solvency < 100% at deadline | Pro-rata refund |
| Oracle dispute    | Challenged assertion        | UMA DVM vote    |
| Invalid market    | Ambiguous question          | Refund mode     |

***

## Contract Interactions

### User Actions by Phase

**Bonding Phase:**

```solidity
function buyShadowYes(uint256 usdcAmount) external;
function buyShadowNo(uint256 usdcAmount) external;
function sellShadowYes(uint256 shares) external;
function sellShadowNo(uint256 shares) external;
```

**Graduation:**

```solidity
function graduate() external;  // Anyone can call when eligible
function claimTokens() external;  // Shadow → Real tokens
```

**Order Book:**

```solidity
function placeLimitOrder(bool isYes, bool isBuy, uint256 price, uint256 amount) external;
function cancelOrder(uint256 orderId) external;
function matchOrders(uint256[] orderIds) external;
```

**Resolution:**

```solidity
function assertOutcome(bool outcome) external;  // Requires bond
function disputeAssertion() external;  // Requires counter-bond
function redeemWinnings() external;  // Claim USDC
```
