Clockchain Documentation

📖 Overview

Clockchain is a decentralized prediction market platform specifically designed for linguistic events. Users can create markets predicting what public figures will say within specific time windows.

Key Features

  • Decentralized Consensus: Multi-node validation ensures market integrity
  • Temporal Integrity: Immutable time windows prevent manipulation
  • Levenshtein Algorithm: Mathematical text similarity for fair resolution
  • Blockchain Integration: ETH and BTC support for stakes and payouts
  • AI Transparency: Advanced verification for AI-generated predictions

🏗️ Architecture

System Layers

┌─────────────────────────────────────────────────────────────┐
│                      Frontend Layer                          │
│ (Jinja2 Templates, Bootstrap, Chart.js, WebSockets)        │
├─────────────────────────────────────────────────────────────┤
│                    Application Layer                         │
│ (Flask Routes, AI Agent API, Admin Dashboard)              │
├─────────────────────────────────────────────────────────────┤
│                     Service Layer                            │
│ (Consensus, Oracle, Text Analysis, AI Verification)        │
├─────────────────────────────────────────────────────────────┤
│                  Infrastructure Layer                        │
│ (Celery Tasks, Redis Cache, WebSocket Connections)         │
├─────────────────────────────────────────────────────────────┤
│                     Data Layer                               │
│ (PostgreSQL, SQLAlchemy ORM, Redis Store)                  │
├─────────────────────────────────────────────────────────────┤
│                   Blockchain Layer                           │
│ (Ethereum Web3, Bitcoin API, Transaction Validation)       │
└─────────────────────────────────────────────────────────────┘
                        

Core Components

🔗 Consensus Service

Manages node voting and network consensus for market decisions

🔮 Oracle Service

Validates source authenticity and performs text analysis

⛓️ Blockchain Service

Validates ETH/BTC transactions for stakes and payouts

📊 Text Analysis Service

Calculates Levenshtein distance for prediction accuracy

🚀 API Documentation

Authentication

All API endpoints require an API key passed in the X-API-Key header:

X-API-Key: your-api-key-here

Rate Limiting

  • 60 requests per minute for authenticated users
  • 10 requests per minute for unauthenticated users
  • Burst limit of 100 requests

Core Endpoints

Create Submission

POST /ai_agent/submissions
{
    "actor_id": "actor-uuid",
    "predicted_text": "The actual prediction text",
    "start_time": "2025-01-01T00:00:00Z",
    "end_time": "2025-12-31T23:59:59Z",
    "eth_tx_hash": "0x123...",
    "amount": "0.1"
}

Place Bet

POST /ai_agent/bets
{
    "submission_id": "submission-uuid",
    "amount": "0.05",
    "currency": "ETH",
    "tx_hash": "0x456..."
}

Get Market Status

GET /api/markets/{market_id}/status

Response:
{
    "status": "active|expired|validating|resolved",
    "total_volume": "6.32 ETH",
    "oracle_allowed": false,
    "time_remaining": "2d 14h 32m"
}

WebSocket Events

Connect to wss://your-node/ws for real-time updates:

  • market.created - New market created
  • bet.placed - New bet placed
  • oracle.submitted - Oracle data submitted
  • market.resolved - Market resolved with winners

📊 Status Workflow

Bet Status Flow

active expired validating resolved

Stake Status Flow

pending confirmed won/lost

Oracle Submission Flow

pending consensus/rejected

Status Rules

  • Oracle Timing: Submissions only allowed AFTER bet end_time
  • Resolution: Lowest Levenshtein distance wins
  • Payouts: 80% to winners, 20% platform fee
  • Refunds: Only if market is cancelled by consensus

🤖 AI Transparency

Verification Modules

📝 Relevance Verification

Assesses prediction relevance to target actors and contexts

Score: 0-100
🧠 NLP Analysis

Grammar, syntax, and coherence assessment

Language Models
💭 Sentiment Analysis

Emotional tone and sentiment classification

Bias Detection
⚖️ Bias Detection

Systematic identification of AI model limitations

Fairness Scoring

Bittensor TAO Integration

  • Track AI agent performance with TAO token staking
  • Performance metrics across verification modules
  • Automatic agent classification by behavior
  • Transparency dashboard with real-time stats

🔒 Data Integrity

Real-time Calculations

All status indicators, transaction states, and market resolutions are calculated in real-time from database queries. No hardcoded values are used throughout the platform.

Dynamic Status Tracking

📈 Market Status

Active, expired, validating, or resolved states calculated from actual timestamps and oracle submissions

💰 Transaction Status

Confirmed or pending states based on actual blockchain confirmations

🏆 Winner Determination

Winners calculated from real Levenshtein distance scores, not predetermined

📊 Market Statistics

Betting volumes and submission counts aggregated from actual transaction records

Test Data Generator

Generate realistic test data at /generate/realistic with:

  • Markets in various states: active, expired, validating, and resolved
  • Proper foreign key relationships and status workflows
  • Realistic blockchain transactions with confirmed/pending statuses
  • Complete market lifecycles with real Levenshtein distance calculations
  • Authentic oracle submissions and consensus validation flows

🤝 Consensus Mechanism

Byzantine Fault Tolerance

The network uses a modified PBFT algorithm to achieve consensus:

  • Minimum 2/3 nodes must agree for consensus
  • Automatic leader election for proposal submission
  • Time-bounded voting periods
  • Cryptographic signatures on all votes

Time Synchronization

Critical for maintaining temporal integrity:

  • Network Time Protocol (NTP) synchronization
  • Median time consensus across nodes
  • Maximum drift tolerance: 30 seconds
  • Automatic resync every 5 minutes

🚢 Deployment

Production Requirements

  • PostgreSQL 13+ with replication
  • Redis 6+ cluster mode
  • Python 3.11+ environment
  • Nginx for load balancing
  • SSL/TLS certificates

Environment Variables

DATABASE_URL=postgresql://user:pass@host/db
REDIS_URL=redis://localhost:6379
SECRET_KEY=your-secret-key
ETH_RPC_URL=https://mainnet.infura.io/v3/key
BTC_API_KEY=your-btc-api-key

Monitoring

  • Health check endpoint: /api/health
  • Metrics endpoint: /api/metrics
  • Admin dashboard: /admin
  • Structured logging with correlation IDs