Comprehensive architecture documentation for the PredictIQ prediction market platform.
- System Overview
- Architecture Principles
- Smart Contract Architecture
- Module Design
- Data Flow
- Oracle Integration
- Security Architecture
- Scalability Considerations
PredictIQ is a decentralized prediction market platform built on Stellar's Soroban smart contract platform. The system enables users to create and participate in prediction markets with hybrid resolution mechanisms combining oracle data and community voting.
┌─────────────────────────────────────────────────────────────┐
│ Frontend Layer │
│ (Web App, Mobile App, Third-party Integrations) │
└────────────────────┬────────────────────────────────────────┘
│
│ JSON-RPC / REST API
│
┌────────────────────▼────────────────────────────────────────┐
│ Stellar Blockchain │
│ ┌──────────────────────────────────────────────────────┐ │
│ │ PredictIQ Smart Contract │ │
│ │ ┌────────┐ ┌────────┐ ┌────────┐ ┌────────┐ │ │
│ │ │Markets │ │ Bets │ │Oracles │ │ Voting │ │ │
│ │ └────────┘ └────────┘ └────────┘ └────────┘ │ │
│ │ ┌────────┐ ┌────────┐ ┌────────┐ ┌────────┐ │ │
│ │ │Disputes│ │ Fees │ │ Admin │ │Circuit │ │ │
│ │ └────────┘ └────────┘ └────────┘ │Breaker │ │ │
│ │ └────────┘ │ │
│ └──────────────────────────────────────────────────────┘ │
└────────────────────┬────────────────────────────────────────┘
│
│ Oracle Feeds
│
┌────────────────────▼────────────────────────────────────────┐
│ Oracle Providers │
│ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ │
│ │Pyth Network │ │ Reflector │ │Custom Oracles│ │
│ └──────────────┘ └──────────────┘ └──────────────┘ │
└─────────────────────────────────────────────────────────────┘
- Smart Contract Layer: Soroban smart contracts handling all business logic
- Oracle Layer: External data providers (Pyth, Reflector)
- Storage Layer: On-chain persistent storage
- Event Layer: Contract events for off-chain indexing
- Frontend Layer: User interfaces and integrations
The contract is organized into independent modules, each responsible for a specific domain:
- Separation of Concerns: Each module handles one aspect of functionality
- Loose Coupling: Modules interact through well-defined interfaces
- High Cohesion: Related functionality is grouped together
- Access Control: Role-based permissions for sensitive operations
- Input Validation: All inputs validated before processing
- Circuit Breaker: Emergency pause mechanism for critical issues
- Fail-Safe Defaults: Secure defaults for all configurations
- Efficient Storage: Minimized storage operations
- Batch Operations: Support for batching where possible
- Lazy Loading: Data loaded only when needed
- Event-Driven: Use events instead of storage for historical data
- Plugin Architecture: Easy to add new oracle providers
- Upgradeable Design: Support for future enhancements
- Configurable Parameters: Admin-adjustable settings
PredictIQContract
├── Storage
│ ├── Markets (Map<u64, Market>)
│ ├── Bets (Map<(u64, Address), Bet>)
│ ├── Votes (Map<(u64, Address), Vote>)
│ ├── Config (Admin, Fees, etc.)
│ └── Monitoring (Error counts, metrics)
├── Modules
│ ├── admin.rs # Admin functions
│ ├── markets.rs # Market management
│ ├── bets.rs # Betting logic
│ ├── oracles.rs # Oracle integration
│ ├── voting.rs # Voting system
│ ├── disputes.rs # Dispute resolution
│ ├── fees.rs # Fee management
│ ├── governance.rs # Governance functions
│ ├── circuit_breaker.rs # Emergency controls
│ ├── monitoring.rs # System monitoring
│ └── events.rs # Event definitions
└── Types
├── Market # Market data structure
├── Bet # Bet data structure
├── Vote # Vote data structure
└── ErrorCode # Error definitionspub struct Market {
pub id: u64,
pub creator: Address,
pub title: String,
pub description: String,
pub outcomes: Vec<String>,
pub deadline: u64,
pub status: MarketStatus,
pub resolution_source: ResolutionSource,
pub winning_outcome: Option<u32>,
pub total_volume: i128,
pub outcome_volumes: Vec<i128>,
pub created_at: u64,
pub resolved_at: Option<u64>,
}
pub enum MarketStatus {
Active,
Closed,
PendingResolution,
Disputed,
Resolved,
Cancelled,
}
pub enum ResolutionSource {
Oracle,
Voting,
Hybrid,
}pub struct Bet {
pub bettor: Address,
pub market_id: u64,
pub outcome: u32,
pub amount: i128,
pub odds: u32,
pub placed_at: u64,
pub claimed: bool,
}pub struct Vote {
pub voter: Address,
pub market_id: u64,
pub outcome: u32,
pub weight: i128,
pub voted_at: u64,
}Responsibility: Market creation, lifecycle management, and queries
Key Functions:
create_market(): Create new prediction marketget_market(): Retrieve market dataclose_market(): Close market for bettingcancel_market(): Cancel market (admin only)
State Transitions:
Active → Closed → PendingResolution → Resolved
↓
Disputed → Resolved
Responsibility: Bet placement, tracking, and payout calculation
Key Functions:
place_bet(): Place bet on market outcomeget_bet(): Retrieve bet informationcalculate_payout(): Calculate potential winningsclaim_winnings(): Claim winnings after resolution
Bet Lifecycle:
Placed → Active → (Market Resolved) → Claimable → Claimed
Responsibility: Oracle integration and data fetching
Supported Oracles:
- Pyth Network: High-frequency price feeds
- Reflector: Stellar-native oracle
- Custom: Extensible for additional providers
Key Functions:
fetch_oracle_result(): Get result from oracleregister_oracle(): Add new oracle providerset_oracle_priority(): Configure fallback order
Oracle Resolution Flow:
1. Query Primary Oracle (Pyth)
↓ (if fails)
2. Query Secondary Oracle (Reflector)
↓ (if fails)
3. Fallback to Community Voting
Responsibility: Community voting for disputed markets
Key Functions:
cast_vote(): Cast vote on disputed marketget_vote_results(): Get current vote tallyfinalize_vote(): Finalize voting and resolve market
Voting Mechanism:
- Weight: Based on reputation or stake
- Duration: Configurable voting period
- Threshold: Majority required for resolution
- Incentives: Rewards for correct votes
Responsibility: Dispute filing and resolution
Key Functions:
file_dispute(): Challenge market resolutionget_dispute_status(): Check dispute stateresolve_dispute(): Finalize dispute resolution
Dispute Process:
1. Market Resolved (Oracle)
↓
2. User Files Dispute (within window)
↓
3. Voting Period Opens
↓
4. Community Votes
↓
5. Dispute Resolved (majority wins)
Responsibility: Emergency pause mechanism
States:
Open: Normal operationPartialFreeze: Limited operations (withdrawals only)FullFreeze: All operations paused
Triggers:
- Manual (admin)
- Automatic (error threshold exceeded)
- Governance vote
User → create_market()
↓
Validate inputs
↓
Check authorization
↓
Generate market ID
↓
Store market data
↓
Emit MarketCreated event
↓
Return market ID
User → place_bet()
↓
Validate market exists & active
↓
Check deadline not passed
↓
Validate outcome index
↓
Transfer tokens from user
↓
Calculate odds
↓
Store bet data
↓
Update market volumes
↓
Emit BetPlaced event
↓
Return success
Deadline Passed
↓
close_market() → Status: Closed
↓
resolve_market()
↓
Query Oracle
↓
┌─────────────┬─────────────┐
│ Success │ Failure │
↓ ↓
Set outcome Open voting
↓ ↓
Status: Status:
Resolved PendingResolution
↓ ↓
Emit event Wait for votes
↓
Finalize vote
↓
Status: Resolved
Market Resolved
↓
User files dispute (within window)
↓
Status: Disputed
↓
Voting period opens
↓
Users cast votes
↓
Voting period ends
↓
Tally votes
↓
Majority outcome wins
↓
Update market outcome
↓
Status: Resolved
↓
Emit DisputeResolved event
┌─────────────────────────────────────────┐
│ PredictIQ Contract │
│ ┌───────────────────────────────────┐ │
│ │ Oracle Manager │ │
│ │ ┌─────────┐ ┌─────────┐ │ │
│ │ │Priority │ │Fallback │ │ │
│ │ │ Queue │ │ Logic │ │ │
│ │ └─────────┘ └─────────┘ │ │
│ └───────────────────────────────────┘ │
└─────────────────────────────────────────┘
│ │ │
▼ ▼ ▼
┌────────┐ ┌────────┐ ┌────────┐
│ Pyth │ │Reflect.│ │Custom │
│Network │ │ Oracle │ │Oracles │
└────────┘ └────────┘ └────────┘
- Primary: Pyth Network (high-frequency, institutional-grade)
- Secondary: Reflector (Stellar-native, reliable)
- Tertiary: Custom oracles (market-specific)
- Fallback: Community voting
pub struct OracleResult {
pub source: String, // Oracle identifier
pub outcome: u32, // Winning outcome index
pub confidence: u32, // Confidence score (0-100)
pub timestamp: u64, // Result timestamp
pub signature: BytesN<64>, // Cryptographic signature
}┌─────────────────────────────────────┐
│ Access Control │
├─────────────────────────────────────┤
│ Admin │
│ - Set fees │
│ - Pause contract │
│ - Update config │
│ - Emergency actions │
├─────────────────────────────────────┤
│ Market Creator │
│ - Create markets │
│ - Cancel own markets (conditions) │
├─────────────────────────────────────┤
│ Users │
│ - Place bets │
│ - Cast votes │
│ - File disputes │
│ - Claim winnings │
└─────────────────────────────────────┘
- Input Validation: All inputs sanitized and validated
- Authorization Checks: Role-based access control
- Reentrancy Protection: State updates before external calls
- Integer Overflow Protection: Safe math operations
- Circuit Breaker: Emergency pause mechanism
- Rate Limiting: Prevent spam and abuse
- Monitoring: Automatic error detection
| Threat | Mitigation |
|---|---|
| Oracle Manipulation | Multiple oracle sources, voting fallback |
| Front-running | Commit-reveal scheme (future) |
| Spam Markets | Market creation fee, reputation system |
| Vote Manipulation | Weighted voting, stake requirements |
| Reentrancy | Checks-effects-interactions pattern |
| Integer Overflow | Checked arithmetic operations |
| Unauthorized Access | Role-based access control |
| DoS Attacks | Rate limiting, gas limits |
- Minimal Storage: Only essential data on-chain
- Event-Driven: Historical data via events
- Pagination: Large datasets paginated
- Archival: Old markets archived off-chain
- Batch Operations: Multiple operations in one transaction
- Efficient Data Structures: Optimized storage layout
- Lazy Evaluation: Compute only when needed
- Caching: Frequently accessed data cached
| Metric | Target |
|---|---|
| Market Creation | < 0.5s |
| Bet Placement | < 0.3s |
| Market Query | < 0.1s |
| Vote Casting | < 0.3s |
| Resolution | < 1.0s |
- Multiple Markets: Unlimited concurrent markets
- Sharding: Future consideration for extreme scale
- Off-chain Indexing: Event indexing for queries
- CDN: Static content delivery
-
Advanced Market Types
- Scalar markets (price ranges)
- Combinatorial markets
- Conditional markets
-
Enhanced Oracle Integration
- More oracle providers
- Oracle reputation system
- Decentralized oracle network
-
Governance
- DAO structure
- Token-based voting
- Protocol upgrades
-
Layer 2 Integration
- State channels for high-frequency trading
- Rollups for scalability
-
Cross-chain Support
- Bridge to other blockchains
- Multi-chain markets
Current: v1.0 (Monolithic Contract)
↓
v2.0: Modular Contracts
↓
v3.0: DAO Governance
↓
v4.0: Cross-chain Support
┌──────────┐ ┌──────────┐ ┌──────────┐
│ Users │────▶│PredictIQ │────▶│ Stellar │
└──────────┘ │ Frontend │ │Blockchain│
└──────────┘ └──────────┘
│ │
▼ ▼
┌──────────┐ ┌──────────┐
│Analytics │ │ Oracles │
└──────────┘ └──────────┘
┌─────────────────────────────────────────┐
│ PredictIQ Contract │
│ │
│ ┌────────┐ ┌────────┐ ┌────────┐ │
│ │Markets │ │ Bets │ │Oracles │ │
│ └───┬────┘ └───┬────┘ └───┬────┘ │
│ │ │ │ │
│ └───────────┼────────────┘ │
│ │ │
│ ┌─────▼─────┐ │
│ │ Storage │ │
│ └───────────┘ │
└─────────────────────────────────────────┘
For implementation details, see DEVELOPMENT.md.
For contribution guidelines, see CONTRIBUTING.md.