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

# Contract Events

> Complete reference for all events emitted by the DelphAI contract

## Overview

DelphAI emits events for all important state changes. These events can be indexed by platforms for real-time updates, historical data, and user interfaces.

## Market Events

### MarketCreated

Emitted when a new prediction market is created.

```solidity theme={null}
event MarketCreated(
    uint256 indexed marketId,
    address indexed creator,
    string question,
    string description,
    string[] possibleOutcomes,
    uint256 createdAt,
    uint256 resolutionTimestamp
);
```

**Parameters**:

* `marketId` (indexed) - Unique market identifier
* `creator` (indexed) - Address that created the market
* `question` - The market question
* `description` - Additional context and resolution criteria
* `possibleOutcomes` - Array of possible outcome strings
* `createdAt` - Block timestamp when market was created
* `resolutionTimestamp` - When the market should be resolved

**Example Usage**:

```javascript theme={null}
// Listen for new markets
delphAI.on('MarketCreated', (marketId, creator, question, description, outcomes, createdAt, resolutionTime) => {
    console.log(`New market created: ${question}`);
    console.log(`Market ID: ${marketId}`);
    console.log(`Creator: ${creator}`);
    console.log(`Possible outcomes: ${outcomes.join(', ')}`);
    console.log(`Resolves at: ${new Date(resolutionTime * 1000)}`);
});
```

***

### MarketResolved

Emitted when the AI resolver resolves a market.

```solidity theme={null}
event MarketResolved(
    uint256 indexed marketId,
    uint256 outcomeIndex,
    string outcome,
    address indexed resolver,
    string resolutionData,
    string[] resolutionSources,
    uint8 resolutionConfidence,
    bytes proofData,
    uint256 resolvedAt
);
```

**Parameters**:

* `marketId` (indexed) - The market identifier
* `outcomeIndex` - Index of the winning outcome in `possibleOutcomes` array
* `outcome` - The actual outcome string that was selected
* `resolver` (indexed) - Address that resolved the market
* `resolutionData` - AI explanation and reasoning for the resolution
* `resolutionSources` - Array of source URLs used for resolution
* `resolutionConfidence` - Confidence level of the resolution (0-100)
* `proofData` - TEE attestation or cryptographic proof
* `resolvedAt` - Block timestamp when resolved

**Example Usage**:

```javascript theme={null}
// Listen for resolutions
delphAI.on('MarketResolved', (marketId, outcomeIndex, outcome, resolver, resolutionData, resolutionSources, resolutionConfidence, proofData, resolvedAt) => {
    console.log(`Market ${marketId} resolved!`);
    console.log(`Winning outcome: ${outcome} (index ${outcomeIndex})`);
    console.log(`AI explanation: ${resolutionData}`);
    console.log(`Sources used: ${resolutionSources.join(', ')}`);
    console.log(`Confidence: ${resolutionConfidence}%`);
    console.log(`Resolved by: ${resolver}`);

    // Trigger payout distribution on your platform
    distributeWinnings(marketId, outcomeIndex);
});
```

***

### MarketCancelled

Emitted when a market is cancelled before resolution.

```solidity theme={null}
event MarketCancelled(
    uint256 indexed marketId,
    address indexed cancelledBy,
    uint256 cancelledAt
);
```

**Parameters**:

* `marketId` (indexed) - The market identifier
* `cancelledBy` (indexed) - Address that cancelled the market (creator or owner)
* `cancelledAt` - Block timestamp when cancelled

**Example Usage**:

```javascript theme={null}
// Listen for cancellations
delphAI.on('MarketCancelled', (marketId, cancelledBy, cancelledAt) => {
    console.log(`Market ${marketId} was cancelled`);
    console.log(`Cancelled by: ${cancelledBy}`);

    // Return bets to users on your platform
    refundAllBets(marketId);
});
```

***

## Admin Events

### FeeUpdated

Emitted when the market creation fee is changed.

```solidity theme={null}
event FeeUpdated(
    uint256 oldFee,
    uint256 newFee
);
```

**Parameters**:

* `oldFee` - Previous fee amount in wei
* `newFee` - New fee amount in wei

**Example Usage**:

```javascript theme={null}
delphAI.on('FeeUpdated', (oldFee, newFee) => {
    console.log(`Fee updated from ${ethers.utils.formatEther(oldFee)} BNB to ${ethers.utils.formatEther(newFee)} BNB`);
    // Update your UI to show new fee
});
```

***

### ResolverUpdated

Emitted when the authorized resolver address is changed.

```solidity theme={null}
event ResolverUpdated(
    address indexed oldResolver,
    address indexed newResolver
);
```

**Parameters**:

* `oldResolver` (indexed) - Previous resolver address
* `newResolver` (indexed) - New resolver address

**Example Usage**:

```javascript theme={null}
delphAI.on('ResolverUpdated', (oldResolver, newResolver) => {
    console.log(`Resolver changed from ${oldResolver} to ${newResolver}`);
});
```

***

### FeesWithdrawn

Emitted when accumulated fees are withdrawn.

```solidity theme={null}
event FeesWithdrawn(
    address indexed to,
    uint256 amount
);
```

**Parameters**:

* `to` (indexed) - Recipient address
* `amount` - Amount withdrawn in wei

**Example Usage**:

```javascript theme={null}
delphAI.on('FeesWithdrawn', (to, amount) => {
    console.log(`${ethers.utils.formatEther(amount)} BNB withdrawn to ${to}`);
});
```

***

### TokensRecovered

Emitted when ERC20 tokens are recovered from the contract.

```solidity theme={null}
event TokensRecovered(
    address indexed token,
    address indexed to,
    uint256 amount
);
```

**Parameters**:

* `token` (indexed) - ERC20 token address
* `to` (indexed) - Recipient address
* `amount` - Amount recovered

**Example Usage**:

```javascript theme={null}
delphAI.on('TokensRecovered', (token, to, amount) => {
    console.log(`Recovered ${amount} of token ${token} to ${to}`);
});
```

***

## Querying Historical Events

### Get All Markets Created

```javascript theme={null}
// Get all markets created in a block range
const filter = delphAI.filters.MarketCreated();
const events = await delphAI.queryFilter(filter, fromBlock, toBlock);

events.forEach(event => {
    console.log(`Market ${event.args.marketId}: ${event.args.question}`);
});
```

### Get Markets by Creator

```javascript theme={null}
// Get all markets created by a specific address
const creatorAddress = "0x...";
const filter = delphAI.filters.MarketCreated(null, creatorAddress);
const events = await delphAI.queryFilter(filter);

console.log(`${creatorAddress} created ${events.length} markets`);
```

### Get All Resolutions

```javascript theme={null}
// Get all resolved markets
const filter = delphAI.filters.MarketResolved();
const events = await delphAI.queryFilter(filter, fromBlock, toBlock);

events.forEach(event => {
    console.log(`Market ${event.args.marketId} resolved to: ${event.args.outcome}`);
    console.log(`AI reasoning: ${event.args.resolutionData}`);
});
```

### Get Specific Market Resolution

```javascript theme={null}
// Get resolution for a specific market
const marketId = 12345;
const filter = delphAI.filters.MarketResolved(marketId);
const events = await delphAI.queryFilter(filter);

if (events.length > 0) {
    const resolution = events[0].args;
    console.log(`Winning outcome: ${resolution.outcome}`);
    console.log(`Explanation: ${resolution.resolutionData}`);
}
```

***

## Real-Time Monitoring

### Complete Event Listener Setup

```javascript theme={null}
import { ethers } from 'ethers';

// Connect to DelphAI contract
const provider = new ethers.providers.JsonRpcProvider('https://bsc-dataseed.binance.org/');
const delphAI = new ethers.Contract(
    '0xA95E99848a318e37F128aB841b0CF693c1f0b4D1',
    DELPHAI_ABI,
    provider
);

// Listen to all market events
delphAI.on('MarketCreated', handleMarketCreated);
delphAI.on('MarketResolved', handleMarketResolved);
delphAI.on('MarketCancelled', handleMarketCancelled);

// Listen to admin events
delphAI.on('FeeUpdated', handleFeeUpdated);
delphAI.on('ResolverUpdated', handleResolverUpdated);

function handleMarketCreated(marketId, creator, question, description, outcomes, createdAt, resolutionTime) {
    // Add new market to your database
    db.markets.insert({
        id: marketId.toNumber(),
        creator,
        question,
        description,
        outcomes,
        createdAt: createdAt.toNumber(),
        resolutionTime: resolutionTime.toNumber(),
        status: 'Open'
    });
}

function handleMarketResolved(marketId, outcomeIndex, outcome, resolver, resolutionData, proofData, resolvedAt) {
    // Update market in database
    db.markets.update(marketId.toNumber(), {
        status: 'Resolved',
        winningOutcome: outcomeIndex.toNumber(),
        aiExplanation: resolutionData,
        resolvedAt: resolvedAt.toNumber()
    });

    // Trigger payout distribution
    distributeWinnings(marketId.toNumber());
}

function handleMarketCancelled(marketId, cancelledBy, cancelledAt) {
    // Update market status
    db.markets.update(marketId.toNumber(), {
        status: 'Cancelled',
        cancelledAt: cancelledAt.toNumber()
    });

    // Refund all users
    refundMarket(marketId.toNumber());
}
```

***

## Event Indexing with The Graph

Example subgraph schema for indexing DelphAI events:

```graphql theme={null}
type Market @entity {
  id: ID!
  marketId: BigInt!
  creator: Bytes!
  question: String!
  description: String!
  possibleOutcomes: [String!]!
  createdAt: BigInt!
  resolutionTimestamp: BigInt!
  status: MarketStatus!
  outcomeIndex: BigInt
  outcome: String
  resolutionData: String
  resolvedAt: BigInt
  resolvedBy: Bytes
  cancelledAt: BigInt
  cancelledBy: Bytes
}

enum MarketStatus {
  Open
  Resolved
  Cancelled
}
```

***

## Next Steps

<CardGroup cols={2}>
  <Card title="Oracle Contract" icon="code" href="/contracts/oracle-contract">
    View complete contract API reference
  </Card>

  <Card title="Integration Guide" icon="book" href="/quickstart">
    Learn how to integrate DelphAI
  </Card>

  <Card title="Market Lifecycle" icon="circle-notch" href="/core-concepts/market-lifecycle">
    Understand the market lifecycle
  </Card>

  <Card title="Examples" icon="github" href="https://github.com/delphai-io/contracts">
    View example implementations
  </Card>
</CardGroup>
