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

# Market Lifecycle

> Understanding the complete lifecycle of a prediction market using delphAI

## Market Lifecycle Overview

A prediction market goes through several distinct phases from creation to settlement. Here's the complete lifecycle when using delphAI as the resolution oracle.

```mermaid theme={null}
graph LR
    A[Creation] --> B[Active Trading]
    B --> C[Market Close]
    C --> D[AI Resolution]
    D --> E[Settlement]
    E --> F[Archived]

    style D fill:#D4AF37
```

## Phase 1: Market Creation

**Who**: Prediction market platform
**Duration**: One transaction

The platform creates a market on delphAI by paying the creation fee:

```solidity theme={null}
// Platform calls delphAI to create market
function createMarket(
    string memory question,
    string memory description,
    string[] memory outcomes,
    uint256 resolutionTime
) external payable returns (uint256 marketId) {
    // Get creation fee from delphAI
    uint256 creationFee = delphAI.marketCreationFee();
    require(msg.value >= creationFee, "Insufficient fee");

    // Create market on delphAI (returns market ID)
    marketId = delphAI.createMarket{value: creationFee}(
        question,
        description,
        outcomes,
        resolutionTime
    );

    // Store market ID and your platform's betting data
    markets[marketId].delphAIMarketId = marketId;
    markets[marketId].closeTime = resolutionTime - 1 hours; // Trading closes before resolution

    return marketId;
}
```

**Key Parameters**:

* **Question**: The event to predict
* **Description**: Additional context and resolution criteria
* **Outcomes**: Array of possible results (e.g., \["Yes", "No"])
* **Resolution Time**: When delphAI AI will resolve

**What delphAI Does**:

* Creates and stores the market
* Schedules AI agent for resolution time
* Emits `MarketCreated` event
* Returns unique market ID

<Check>
  Market is now created on delphAI and scheduled for automatic AI resolution
</Check>

## Phase 2: Active Trading

**Who**: Users on the platform
**Duration**: From creation to close time

Users trade on your platform while the market is on delphAI:

### User Actions:

* Buy YES/NO positions
* Sell positions
* Provide liquidity
* Monitor prices

### Platform Responsibilities:

* Execute trades
* Update odds/prices
* Handle deposits/withdrawals
* Display market info
* Poll delphAI for market status

### Checking Market Status:

```solidity theme={null}
function getMarketStatus(uint256 marketId) public view returns (MarketStatus) {
    Market memory market = delphAI.getMarket(marketId);
    return market.status; // Open, Resolved, or Cancelled
}
```

### delphAI's Role:

<Note>
  **Waiting** - delphAI market is Open, waiting for resolution time
</Note>

### Market Status Tracking

| Timestamp                  | delphAI Status | Platform Action             |
| -------------------------- | -------------- | --------------------------- |
| Before closeTime           | Open           | Allow trading               |
| At closeTime               | Open           | Stop trading on platform    |
| Between close & resolution | Open           | Wait for delphAI resolution |
| After resolution           | Resolved       | Distribute winnings         |

## Phase 3: Market Close

**Who**: Platform (managed separately from delphAI)
**Duration**: Instant

Your platform closes trading before delphAI resolves:

```solidity theme={null}
function closeTrading(uint256 marketId) external {
    require(block.timestamp >= markets[marketId].closeTime, "Too early");

    // Check delphAI market is still open
    Market memory delphAIMarket = delphAI.getMarket(marketId);
    require(delphAIMarket.status == MarketStatus.Open, "Already resolved");

    markets[marketId].tradingClosed = true;
    emit TradingClosed(marketId);
}
```

**Effects**:

* No new bets allowed on your platform
* Positions are locked
* Market awaits delphAI resolution
* Users can view their positions

<Info>
  Gap between platform close time and delphAI resolution allows for:

  * Events to complete (e.g., game ends)
  * Data to be available (e.g., official results published)
  * AI to fetch accurate information
</Info>

## Phase 4: AI Resolution

**Who**: delphAI resolver (automatic)
**Duration**: Seconds to minutes

At the scheduled resolution time, delphAI's AI resolver activates:

<Steps>
  <Step title="Trigger">
    When block.timestamp reaches resolutionTimestamp, delphAI's resolver can resolve the market
  </Step>

  <Step title="AI Execution (Offchain)">
    AI agent performs resolution:

    1. Parse question and description (criteria)
    2. Query specified data sources
    3. Fetch relevant data
    4. Analyze against criteria
    5. Determine winning outcome
    6. Generate resolution explanation
  </Step>

  <Step title="Onchain Submission">
    Resolver calls delphAI contract:

    ```solidity theme={null}
    // Only authorized resolver can call this
    function resolveMarket(
        uint256 marketId,
        uint256 outcomeIndex,
        string memory resolutionData,
        string[] memory resolutionSources,
        uint8 resolutionConfidence,
        bytes memory proofData
    ) external onlyResolver {
        // Updates market on delphAI contract
        market.status = MarketStatus.Resolved;
        market.outcomeIndex = outcomeIndex;
        market.resolutionData = resolutionData;
        market.resolutionSources = resolutionSources;
        market.resolutionConfidence = resolutionConfidence;
        market.resolvedAt = block.timestamp;

        emit MarketResolved(marketId, outcomeIndex, outcome, resolutionData, resolutionSources, resolutionConfidence);
    }
    ```
  </Step>

  <Step title="Platform Queries Resolution">
    Your platform checks for resolution:

    ```solidity theme={null}
    function checkAndDistribute(uint256 marketId) external {
        // Query delphAI market
        Market memory delphAIMarket = delphAI.getMarket(marketId);

        // Check if resolved
        require(delphAIMarket.status == MarketStatus.Resolved, "Not resolved");
        require(!markets[marketId].distributed, "Already distributed");

        // Get winning outcome
        uint256 winningOutcome = delphAIMarket.outcomeIndex;
        string memory aiExplanation = delphAIMarket.resolutionData;

        // Mark as resolved and ready for claims
        markets[marketId].resolved = true;
        markets[marketId].winningOutcome = winningOutcome;

        emit MarketResolved(marketId, winningOutcome, aiExplanation);
    }
    ```
  </Step>
</Steps>

**Resolution Data Available**:

* **outcomeIndex**: Index of winning outcome in possibleOutcomes array
* **resolutionData**: AI's explanation of the resolution
* **proofData**: TEE attestation (future feature)
* **resolvedAt**: Timestamp when resolved
* **resolvedBy**: Address of the resolver

## Phase 5: Settlement

**Who**: Platform + Users
**Duration**: Ongoing (users claim when ready)

After delphAI resolves, the platform handles payouts:

### Platform Calculates Winnings:

```solidity theme={null}
function calculateWinnings(uint256 marketId, address user)
    public
    view
    returns (uint256)
{
    // Get resolution from delphAI
    Market memory delphAIMarket = delphAI.getMarket(marketId);
    require(delphAIMarket.status == MarketStatus.Resolved, "Not resolved");

    uint256 winningOutcome = delphAIMarket.outcomeIndex;
    uint256 userStake = markets[marketId].bets[user][winningOutcome];
    uint256 totalWinningStake = markets[marketId].totalBets[winningOutcome];
    uint256 totalPool = markets[marketId].totalPool;

    // Proportional payout
    return (userStake * totalPool) / totalWinningStake;
}
```

### Users Claim:

```solidity theme={null}
function claimWinnings(uint256 marketId) external {
    uint256 winnings = calculateWinnings(marketId, msg.sender);
    require(winnings > 0, "No winnings");
    require(!claimed[marketId][msg.sender], "Already claimed");

    claimed[marketId][msg.sender] = true;
    payable(msg.sender).transfer(winnings);

    emit WinningsClaimed(marketId, msg.sender, winnings);
}
```

<Note>
  **delphAI's role is complete** - market is resolved on delphAI, platforms query the result and handle payouts
</Note>

## Phase 6: Archived

**Who**: Platform
**Duration**: Permanent

Market is permanently resolved and archived:

**What's Available**:

* ✅ Historical data viewable on delphAI
* ✅ Resolution details preserved
* ✅ Trade history accessible on platform
* ✅ AI explanation permanently stored
* ❌ No further actions possible

## Timeline Example

Real-world example: "Will Lakers win vs Warriors on Feb 15, 2025?"

```
Jan 1, 2025 00:00 UTC    → Platform creates market on delphAI (pays fee)
                           → delphAI returns marketId
                           → Market is Open on delphAI
  ↓
[30 days of active trading on platform]
  ↓
Feb 15, 2025 15:00 UTC   → Game starts (platform still allows bets)
  ↓
Feb 15, 2025 17:30 UTC   → Game ends
  ↓
Feb 15, 2025 18:00 UTC   → Platform closes trading
                           → delphAI market still Open
  ↓
Feb 15, 2025 19:00 UTC   → Resolution Time reached
                           → delphAI AI resolver activates
                           → Queries ESPN API for final score
                           → Determines Lakers won 112-108
                           → Calls delphAI.resolveMarket()
                           → Market status = Resolved on delphAI
  ↓
Feb 15, 2025 19:02 UTC   → Platform queries delphAI.getMarket()
                           → Sees status = Resolved, outcomeIndex = 0 (YES)
                           → Reads resolutionData (AI explanation)
                           → Marks market as resolved on platform
                           → Winners can claim
  ↓
[Users claim over next days/weeks]
  ↓
Mar 1, 2025              → Market archived on platform
```

## State Transitions

### delphAI Market States:

```mermaid theme={null}
stateDiagram-v2
    [*] --> Open
    Open --> Resolved
    Open --> Cancelled
    Resolved --> [*]
    Cancelled --> [*]
```

**delphAI has 3 market states:**

* **Open**: Market created, waiting for resolution time
* **Resolved**: AI has resolved the market
* **Cancelled**: Market was cancelled before resolution

### Platform-Side States:

Your platform manages its own states separately:

* **Trading Open**: Users can place bets
* **Trading Closed**: Bets closed, waiting for delphAI resolution
* **Distributing**: delphAI resolved, calculating payouts
* **Settled**: Payouts complete
* **Archived**: Market finished

### Error States:

<Warning>
  **Edge cases that platforms must handle:**

  * **Resolution Delay**: Resolver hasn't resolved yet
    * Action: Wait or have backup manual resolution

  * **Data Source Unavailable**: APIs down during resolution
    * Action: Resolver uses fallback sources or delays

  * **Market Cancelled**: Market cancelled on delphAI
    * Action: Return all bets to users

  * **Query Failure**: Can't read delphAI market
    * Action: Retry queries, handle RPC failures
</Warning>

## Next Steps

<CardGroup cols={2}>
  <Card title="Resolution Process" icon="gears" href="/core-concepts/resolution-process">
    Deep dive into how delphAI resolves markets
  </Card>

  <Card title="Smart Contract Reference" icon="file-code" href="/contracts/market-contract">
    Explore the contract interfaces
  </Card>

  <Card title="Integration Guide" icon="plug" href="/guides/create-market">
    Step-by-step integration guide
  </Card>

  <Card title="Best Practices" icon="star" href="/guides/best-practices">
    Learn platform integration best practices
  </Card>
</CardGroup>
