diff --git a/README.md b/README.md index 620788fa..bb9159e7 100644 --- a/README.md +++ b/README.md @@ -28,34 +28,27 @@ This repository contains smart contracts for Stellar's Soroban platform, organiz --- -## 📚 API Documentation +## 📚 Documentation -For comprehensive API documentation, including versioning information, integration examples, and troubleshooting guides, please refer to: +For comprehensive documentation, please refer to our organized documentation structure: -**📖 [API_DOCUMENTATION.md](./API_DOCUMENTATION.md)** +**📖 [Documentation Index](./docs/README.md)** -This dedicated documentation file contains: -- **API Versioning**: Semantic versioning, compatibility matrix, upgrade strategies -- **Core API Reference**: Function signatures, parameters, and examples -- **Data Structures**: Complete type definitions and usage -- **Error Codes**: Comprehensive error reference with solutions -- **Integration Examples**: Real-world usage patterns and best practices -- **Troubleshooting Guide**: Common issues and debugging tools -- **Support Resources**: Community channels and getting help +### 🚀 API Documentation +Complete API reference and integration guides: **[API Documentation](./docs/api/API_DOCUMENTATION.md)** ---- +### ⛽ Gas Optimization +Performance optimization and cost analysis: **[Gas Documentation](./docs/gas/)** + +### 🔒 Security +Security audits, best practices, and threat analysis: **[Security Documentation](./docs/security/)** -## ⚡ Gas Optimization Documentation +### 🛠️ Operations +Deployment, maintenance, and incident management: **[Operations Documentation](./docs/operations/)** + +--- -- Gas Guide and Best Practices: [GAS_OPTIMIZATION.md](./GAS_OPTIMIZATION.md) -- Per-Function Cost Analysis (catalog + templates): [GAS_COST_ANALYSIS.md](./GAS_COST_ANALYSIS.md) -- Benchmarking Procedures: [GAS_BENCHMARKING.md](./GAS_BENCHMARKING.md) -- Testing Guidelines (prevent regressions): [GAS_TESTING_GUIDELINES.md](./GAS_TESTING_GUIDELINES.md) -- Usage Monitoring & Ops: [GAS_MONITORING.md](./GAS_MONITORING.md) -- Case Studies (Predictify-specific): [GAS_CASE_STUDIES.md](./GAS_CASE_STUDIES.md) -- Troubleshooting Guide: [GAS_TROUBLESHOOTING.md](./GAS_TROUBLESHOOTING.md) -These documents provide practical steps to measure, monitor, and reduce fees for Soroban contracts in this repo. --- diff --git a/contracts/predictify-hybrid/VOTING_SYSTEM.md b/contracts/predictify-hybrid/VOTING_SYSTEM.md deleted file mode 100644 index 0519ecba..00000000 --- a/contracts/predictify-hybrid/VOTING_SYSTEM.md +++ /dev/null @@ -1 +0,0 @@ - \ No newline at end of file diff --git a/docs/README.md b/docs/README.md new file mode 100644 index 00000000..7b6a352d --- /dev/null +++ b/docs/README.md @@ -0,0 +1,79 @@ +# 📚 Predictify Contracts Documentation + +Welcome to the Predictify Contracts documentation! This directory contains comprehensive documentation for the Predictify Hybrid prediction market smart contract system. + +## 📁 Documentation Structure + +### 🚀 [API Documentation](./api/API_DOCUMENTATION.md) +Complete API reference for the Predictify Hybrid contract, including: +- Contract functions and their parameters +- Return types and error handling +- Integration examples +- Client usage patterns + +### 🔒 [Security Documentation](./security/) +Comprehensive security documentation and guidelines: + +- **[Attack Vectors](./security/ATTACK-VECTORS.md)** - Known attack vectors and mitigation strategies +- **[Audit Checklist](./security/AUDIT_CHECKLIST.md)** - Security audit requirements and checklist +- **[Security Best Practices](./security/SECURITY_BEST_PRACTICES.md)** - Development and deployment security guidelines +- **[Security Considerations](./security/SECURITY_CONSIDERATIONS.md)** - Important security considerations for the system +- **[Security Testing Guide](./security/SECURITY_TESTING_GUIDE.md)** - Security testing procedures and tools + +### ⛽ [Gas Optimization Documentation](./gas/) +Complete gas optimization and cost analysis: + +- **[Gas Benchmarking](./gas/GAS_BENCHMARKING.md)** - Performance benchmarks and metrics +- **[Gas Case Studies](./gas/GAS_CASE_STUDIES.md)** - Real-world gas optimization examples +- **[Gas Cost Analysis](./gas/GAS_COST_ANALYSIS.md)** - Detailed cost breakdown and analysis +- **[Gas Monitoring](./gas/GAS_MONITORING.md)** - Tools and techniques for monitoring gas usage +- **[Gas Optimization](./gas/GAS_OPTIMIZATION.md)** - Strategies and best practices for gas optimization +- **[Gas Testing Guidelines](./gas/GAS_TESTING_GUIDELINES.md)** - Testing procedures for gas optimization +- **[Gas Troubleshooting](./gas/GAS_TROUBLESHOOTING.md)** - Common gas-related issues and solutions + +### 🛠️ [Operations Documentation](./operations/) +Operational procedures and incident management: + +- **[Incident Response](./operations/INCIDENT_RESPONSE.md)** - Incident response procedures and protocols + +### 📋 [Contract Documentation](./contracts/) +Implementation-specific documentation for the Predictify Hybrid contract: + +- **[Types System](./contracts/TYPES_SYSTEM.md)** - Comprehensive type system and data structures +- **[Voting System](./contracts/VOTING_SYSTEM.md)** - Voting mechanism and dispute resolution + +## 🎯 Quick Start + +1. **For Developers**: Start with [API Documentation](./api/API_DOCUMENTATION.md) +2. **For Contract Contributors**: Review [Contract Documentation](./contracts/) +3. **For Security Auditors**: Review [Security Documentation](./security/) +4. **For Gas Optimization**: Check [Gas Optimization](./gas/GAS_OPTIMIZATION.md) +5. **For Operations**: Read [Incident Response](./operations/INCIDENT_RESPONSE.md) + +## 🔗 Related Resources + +- **[Main Project README](../README.md)** - Project overview and setup instructions +- **[Contracts Directory](../contracts/)** - Source code for all smart contracts +- **[GitHub Repository](https://github.com/your-org/predictify-contracts)** - Source code repository + +## 📝 Contributing to Documentation + +When adding new documentation: + +1. **Choose the appropriate category** based on the content type +2. **Follow the naming convention** (UPPERCASE_WITH_UNDERSCORES.md) +3. **Update this index** to include the new document +4. **Add cross-references** to related documents where appropriate + +## 🏷️ Documentation Categories + +- **API**: Contract interfaces, function references, and integration guides +- **Contracts**: Implementation-specific documentation for contract systems +- **Security**: Security audits, best practices, and threat analysis +- **Gas**: Performance optimization, cost analysis, and monitoring +- **Operations**: Deployment, maintenance, and incident management + +--- + +*Last updated: $(date)* +*For questions or suggestions about documentation, please open an issue in the repository.* \ No newline at end of file diff --git a/API_DOCUMENTATION.md b/docs/api/API_DOCUMENTATION.md similarity index 99% rename from API_DOCUMENTATION.md rename to docs/api/API_DOCUMENTATION.md index ff8c30fa..b2df7135 100644 --- a/API_DOCUMENTATION.md +++ b/docs/api/API_DOCUMENTATION.md @@ -216,7 +216,7 @@ const getContractVersion = async (contractId: string): Promise => { **Documentation:** - [v1.0.x API Reference](./docs/api/v1.0/) - [v0.9.x Legacy Docs](./docs/api/v0.9/) -- [Migration Guide v0.9 → v1.0](./docs/migration/v0.9-to-v1.0.md) +- [Migration Guide v0.9 → v1.0](./migration/v0.9-to-v1.0.md) **Contract Addresses:** - **v1.0.x Mainnet**: `CDLZFC3SYJYDZT7K67VZ75HPJVIEUVNIXF47ZG2FB2RMQQAHHAGK3HGU` diff --git a/contracts/predictify-hybrid/TYPES_SYSTEM.md b/docs/contracts/TYPES_SYSTEM.md similarity index 100% rename from contracts/predictify-hybrid/TYPES_SYSTEM.md rename to docs/contracts/TYPES_SYSTEM.md diff --git a/docs/contracts/VOTING_SYSTEM.md b/docs/contracts/VOTING_SYSTEM.md new file mode 100644 index 00000000..71594908 --- /dev/null +++ b/docs/contracts/VOTING_SYSTEM.md @@ -0,0 +1,412 @@ +# Predictify Hybrid Voting System + +## Overview + +The Predictify Hybrid contract features a sophisticated voting and dispute resolution system that combines community consensus with oracle-based resolution. This document outlines the architecture, components, and implementation details of the voting system. + +## Architecture + +### Core Components + +The voting system consists of several key components: + +1. **Voting Structures** - Data structures for votes, statistics, and payouts +2. **Voting Manager** - Core voting operations and state management +3. **Dispute System** - Stake-based dispute resolution with dynamic thresholds +4. **Validation System** - Input validation and business rule enforcement +5. **Analytics System** - Voting statistics and market insights +6. **Utility Functions** - Helper functions for common operations + +## Voting Structures + +### Vote Structure + +```rust +pub struct Vote { + pub user: Address, + pub outcome: String, + pub stake: i128, + pub timestamp: u64, +} +``` + +**Purpose**: Represents a user's vote on a prediction market outcome. + +**Fields**: +- `user`: The voter's address +- `outcome`: The chosen outcome (e.g., "yes", "no") +- `stake`: Amount staked in the vote (in stroops) +- `timestamp`: When the vote was cast + +### Voting Statistics + +```rust +pub struct VotingStats { + pub total_votes: u32, + pub total_staked: i128, + pub outcome_distribution: Map, + pub unique_voters: u32, +} +``` + +**Purpose**: Provides comprehensive analytics about voting activity. + +**Fields**: +- `total_votes`: Number of votes cast +- `total_staked`: Total amount staked across all votes +- `outcome_distribution`: Stake distribution by outcome +- `unique_voters`: Number of unique participants + +### Payout Data + +```rust +pub struct PayoutData { + pub user_stake: i128, + pub winning_total: i128, + pub total_pool: i128, + pub fee_percentage: i128, + pub payout_amount: i128, +} +``` + +**Purpose**: Calculates user payouts based on voting results. + +## Dispute System + +### Dynamic Dispute Thresholds + +The system implements sophisticated dispute thresholds that adjust based on market characteristics: + +```rust +pub struct DisputeThreshold { + pub market_id: Symbol, + pub base_threshold: i128, + pub adjusted_threshold: i128, + pub market_size_factor: i128, + pub activity_factor: i128, + pub complexity_factor: i128, + pub timestamp: u64, +} +``` + +### Threshold Adjustment Factors + +```rust +pub struct ThresholdAdjustmentFactors { + pub market_size_factor: i128, + pub activity_factor: i128, + pub complexity_factor: i128, + pub total_adjustment: i128, +} +``` + +**Adjustment Logic**: +- **Market Size**: Larger markets require higher dispute thresholds +- **Activity Level**: High-activity markets may need lower thresholds +- **Complexity**: Complex markets (multiple outcomes) require higher thresholds + +### Threshold History + +```rust +pub struct ThresholdHistoryEntry { + pub market_id: Symbol, + pub old_threshold: i128, + pub new_threshold: i128, + pub adjustment_reason: String, + pub adjusted_by: Address, + pub timestamp: u64, +} +``` + +**Purpose**: Tracks all threshold adjustments for transparency and auditability. + +## Voting Manager + +### Core Operations + +The `VotingManager` provides the main interface for voting operations: + +#### Process Vote +```rust +pub fn process_vote( + env: &Env, + user: Address, + market_id: Symbol, + outcome: String, + stake: i128, +) -> Result<(), Error> +``` + +**Functionality**: +- Validates user authentication +- Checks market state and voting eligibility +- Validates outcome and stake amount +- Records vote and updates market statistics +- Transfers stake from user to contract + +#### Process Dispute +```rust +pub fn process_dispute( + env: &Env, + user: Address, + market_id: Symbol, + stake: i128, +) -> Result<(), Error> +``` + +**Functionality**: +- Validates dispute eligibility +- Checks dispute threshold requirements +- Records dispute stake +- Extends market resolution period +- Triggers dispute resolution process + +#### Process Claim +```rust +pub fn process_claim( + env: &Env, + user: Address, + market_id: Symbol, +) -> Result +``` + +**Functionality**: +- Validates market resolution +- Calculates user payout +- Transfers winnings to user +- Marks payout as claimed +- Updates market statistics + +## Validation System + +### Voting Validator + +The `VotingValidator` ensures all voting operations comply with business rules: + +#### Authentication Validation +```rust +pub fn validate_user_authentication(user: &Address) -> Result<(), Error> +pub fn validate_admin_authentication(env: &Env, admin: &Address) -> Result<(), Error> +``` + +#### Market State Validation +```rust +pub fn validate_market_for_voting(env: &Env, market: &Market) -> Result<(), Error> +pub fn validate_market_for_dispute(env: &Env, market: &Market) -> Result<(), Error> +pub fn validate_market_for_claim(env: &Env, market: &Market, user: &Address) -> Result<(), Error> +``` + +#### Parameter Validation +```rust +pub fn validate_vote_parameters( + env: &Env, + outcome: &String, + valid_outcomes: &Vec, + stake: i128, +) -> Result<(), Error> +``` + +### Threshold Validator + +The `ThresholdValidator` manages dispute threshold rules: + +```rust +pub fn validate_threshold_limits(threshold: i128) -> Result<(), Error> +pub fn validate_threshold_adjustment_permissions(env: &Env, admin: &Address) -> Result<(), Error> +``` + +## Analytics System + +### Voting Analytics + +The `VotingAnalytics` provides insights into voting patterns: + +#### Participation Metrics +```rust +pub fn calculate_participation_rate(market: &Market) -> f64 +pub fn calculate_average_stake(market: &Market) -> i128 +``` + +#### Distribution Analysis +```rust +pub fn calculate_stake_distribution(market: &Market) -> Map +pub fn calculate_voting_power_concentration(market: &Market) -> f64 +``` + +#### Top Voters +```rust +pub fn get_top_voters(market: &Market, limit: usize) -> Vec<(Address, i128)> +``` + +## Utility Functions + +### Transfer Operations + +```rust +pub fn transfer_stake(env: &Env, user: &Address, stake: i128) -> Result<(), Error> +pub fn transfer_winnings(env: &Env, user: &Address, amount: i128) -> Result<(), Error> +pub fn transfer_fees(env: &Env, admin: &Address, amount: i128) -> Result<(), Error> +``` + +### Calculation Functions + +```rust +pub fn calculate_user_payout(env: &Env, market: &Market, user: &Address) -> Result +pub fn calculate_fee_amount(market: &Market) -> Result +``` + +### Query Functions + +```rust +pub fn has_user_voted(market: &Market, user: &Address) -> bool +pub fn get_user_vote(market: &Market, user: &Address) -> Option<(String, i128)> +pub fn has_user_claimed(market: &Market, user: &Address) -> bool +``` + +## Constants and Configuration + +### Voting Constants + +```rust +/// Minimum stake amount for voting (0.1 XLM) +pub const MIN_VOTE_STAKE: i128 = 100_000; + +/// Minimum stake amount for disputes (10 XLM) +pub const MIN_DISPUTE_STAKE: i128 = 10_000_000; + +/// Maximum dispute threshold (100 XLM) +pub const MAX_DISPUTE_THRESHOLD: i128 = 100_000_000; + +/// Base dispute threshold (10 XLM) +pub const BASE_DISPUTE_THRESHOLD: i128 = 10_000_000; + +/// Market size threshold for large markets (1000 XLM) +pub const LARGE_MARKET_THRESHOLD: i128 = 1_000_000_000; + +/// Activity level threshold for high activity (100 votes) +pub const HIGH_ACTIVITY_THRESHOLD: u32 = 100; + +/// Platform fee percentage (2%) +pub const FEE_PERCENTAGE: i128 = 2; + +/// Dispute extension period in hours +pub const DISPUTE_EXTENSION_HOURS: u32 = 24; +``` + +## Usage Examples + +### Creating a Vote + +```rust +use predictify_hybrid::voting::{Vote, VotingManager}; + +// User votes "yes" with 0.5 XLM stake +VotingManager::process_vote( + &env, + user_address, + market_id, + String::from_str(&env, "yes"), + 500_000, // 0.5 XLM +)?; +``` + +### Initiating a Dispute + +```rust +// User disputes market resolution with 15 XLM +VotingManager::process_dispute( + &env, + user_address, + market_id, + 15_000_000, // 15 XLM +)?; +``` + +### Claiming Winnings + +```rust +// User claims their winnings +let payout = VotingManager::process_claim( + &env, + user_address, + market_id, +)?; +``` + +### Getting Voting Statistics + +```rust +use predictify_hybrid::voting::VotingUtils; + +let stats = VotingUtils::get_voting_stats(&market); +println!("Total votes: {}", stats.total_votes); +println!("Total staked: {} stroops", stats.total_staked); +``` + +## Integration Points + +### Market System Integration + +The voting system integrates with the market system through: +- Market state validation +- Outcome validation +- Stake management +- Resolution coordination + +### Oracle System Integration + +Voting results combine with oracle data for hybrid resolution: +- 70% oracle weight +- 30% community consensus weight +- Dispute resolution when oracle and community disagree + +### Fee System Integration + +The voting system manages platform fees: +- 2% platform fee on all stakes +- Fee collection after market resolution +- Fee distribution to platform admin + +## Testing + +The voting system includes comprehensive testing utilities: + +```rust +pub mod testing { + pub fn create_test_vote(env: &Env, user: Address, outcome: String, stake: i128) -> Vote + pub fn create_test_voting_stats(env: &Env) -> VotingStats + pub fn create_test_payout_data() -> PayoutData + pub fn validate_vote_structure(vote: &Vote) -> Result<(), Error> + pub fn validate_voting_stats(stats: &VotingStats) -> Result<(), Error> +} +``` + +## Error Handling + +The voting system includes comprehensive error handling for: +- Invalid market states +- Insufficient stakes +- Authentication failures +- Threshold violations +- Duplicate operations +- Invalid parameters + +## Performance Considerations + +### Gas Optimization + +- Efficient data structures for vote storage +- Optimized threshold calculations +- Minimal storage operations +- Batch processing where possible + +### Scalability + +- Support for large numbers of voters +- Efficient dispute threshold calculations +- Optimized payout calculations +- Minimal on-chain computation + +--- + +*This voting system provides a robust foundation for prediction market operations with sophisticated dispute resolution and community consensus mechanisms.* \ No newline at end of file diff --git a/GAS_BENCHMARKING.md b/docs/gas/GAS_BENCHMARKING.md similarity index 94% rename from GAS_BENCHMARKING.md rename to docs/gas/GAS_BENCHMARKING.md index a2eeec28..297d8c45 100644 --- a/GAS_BENCHMARKING.md +++ b/docs/gas/GAS_BENCHMARKING.md @@ -54,5 +54,5 @@ Track optimized size and ensure below network limits. ### Reporting - Commit CSVs and a short summary per release under `benchmarks/`. -- Update `GAS_COST_ANALYSIS.md` with highlights (e.g., hot paths, bytes drivers). +- Update `../gas/GAS_COST_ANALYSIS.md` with highlights (e.g., hot paths, bytes drivers). diff --git a/GAS_CASE_STUDIES.md b/docs/gas/GAS_CASE_STUDIES.md similarity index 100% rename from GAS_CASE_STUDIES.md rename to docs/gas/GAS_CASE_STUDIES.md diff --git a/GAS_COST_ANALYSIS.md b/docs/gas/GAS_COST_ANALYSIS.md similarity index 98% rename from GAS_COST_ANALYSIS.md rename to docs/gas/GAS_COST_ANALYSIS.md index fc77611b..c289022e 100644 --- a/GAS_COST_ANALYSIS.md +++ b/docs/gas/GAS_COST_ANALYSIS.md @@ -76,7 +76,7 @@ env.storage().persistent().set(&market_id, &market); ### Analysis Template -Fill per method after running benchmarks (see GAS_BENCHMARKING.md): +Fill per method after running benchmarks (see ../gas/GAS_BENCHMARKING.md): - initialize - Reads: 0-1 (admin guard if re-init) diff --git a/GAS_MONITORING.md b/docs/gas/GAS_MONITORING.md similarity index 100% rename from GAS_MONITORING.md rename to docs/gas/GAS_MONITORING.md diff --git a/GAS_OPTIMIZATION.md b/docs/gas/GAS_OPTIMIZATION.md similarity index 100% rename from GAS_OPTIMIZATION.md rename to docs/gas/GAS_OPTIMIZATION.md diff --git a/GAS_TESTING_GUIDELINES.md b/docs/gas/GAS_TESTING_GUIDELINES.md similarity index 100% rename from GAS_TESTING_GUIDELINES.md rename to docs/gas/GAS_TESTING_GUIDELINES.md diff --git a/GAS_TROUBLESHOOTING.md b/docs/gas/GAS_TROUBLESHOOTING.md similarity index 100% rename from GAS_TROUBLESHOOTING.md rename to docs/gas/GAS_TROUBLESHOOTING.md diff --git a/INCIDENT_RESPONSE.md b/docs/operations/INCIDENT_RESPONSE.md similarity index 100% rename from INCIDENT_RESPONSE.md rename to docs/operations/INCIDENT_RESPONSE.md diff --git a/ATTACK-VECTORS.md b/docs/security/ATTACK-VECTORS.md similarity index 100% rename from ATTACK-VECTORS.md rename to docs/security/ATTACK-VECTORS.md diff --git a/AUDIT_CHECKLIST.md b/docs/security/AUDIT_CHECKLIST.md similarity index 100% rename from AUDIT_CHECKLIST.md rename to docs/security/AUDIT_CHECKLIST.md diff --git a/SECURITY_BEST_PRACTICES.md b/docs/security/SECURITY_BEST_PRACTICES.md similarity index 100% rename from SECURITY_BEST_PRACTICES.md rename to docs/security/SECURITY_BEST_PRACTICES.md diff --git a/SECURITY_CONSIDERATIONS.md b/docs/security/SECURITY_CONSIDERATIONS.md similarity index 100% rename from SECURITY_CONSIDERATIONS.md rename to docs/security/SECURITY_CONSIDERATIONS.md diff --git a/SECURITY_TESTING_GUIDE.md b/docs/security/SECURITY_TESTING_GUIDE.md similarity index 100% rename from SECURITY_TESTING_GUIDE.md rename to docs/security/SECURITY_TESTING_GUIDE.md