From 791db8bef6e2b08f3d556b0f85572aa64e96ea0d Mon Sep 17 00:00:00 2001 From: 1nonlypiece Date: Sun, 10 Aug 2025 16:08:30 +0530 Subject: [PATCH 01/20] docs: create organized documentation directory structure --- docs/README.md | 71 +++ docs/api/API_DOCUMENTATION.md | 712 +++++++++++++++++++++++ docs/gas/GAS_BENCHMARKING.md | 58 ++ docs/gas/GAS_CASE_STUDIES.md | 51 ++ docs/gas/GAS_COST_ANALYSIS.md | 131 +++++ docs/gas/GAS_MONITORING.md | 31 + docs/gas/GAS_OPTIMIZATION.md | 88 +++ docs/gas/GAS_TESTING_GUIDELINES.md | 32 + docs/gas/GAS_TROUBLESHOOTING.md | 27 + docs/operations/INCIDENT_RESPONSE.md | 50 ++ docs/security/ATTACK-VECTORS.md | 43 ++ docs/security/AUDIT_CHECKLIST.md | 21 + docs/security/SECURITY_BEST_PRACTICES.md | 24 + docs/security/SECURITY_CONSIDERATIONS.md | 52 ++ docs/security/SECURITY_TESTING_GUIDE.md | 18 + 15 files changed, 1409 insertions(+) create mode 100644 docs/README.md create mode 100644 docs/api/API_DOCUMENTATION.md create mode 100644 docs/gas/GAS_BENCHMARKING.md create mode 100644 docs/gas/GAS_CASE_STUDIES.md create mode 100644 docs/gas/GAS_COST_ANALYSIS.md create mode 100644 docs/gas/GAS_MONITORING.md create mode 100644 docs/gas/GAS_OPTIMIZATION.md create mode 100644 docs/gas/GAS_TESTING_GUIDELINES.md create mode 100644 docs/gas/GAS_TROUBLESHOOTING.md create mode 100644 docs/operations/INCIDENT_RESPONSE.md create mode 100644 docs/security/ATTACK-VECTORS.md create mode 100644 docs/security/AUDIT_CHECKLIST.md create mode 100644 docs/security/SECURITY_BEST_PRACTICES.md create mode 100644 docs/security/SECURITY_CONSIDERATIONS.md create mode 100644 docs/security/SECURITY_TESTING_GUIDE.md diff --git a/docs/README.md b/docs/README.md new file mode 100644 index 00000000..d9110eb9 --- /dev/null +++ b/docs/README.md @@ -0,0 +1,71 @@ +# ๐Ÿ“š 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 + +## ๐ŸŽฏ Quick Start + +1. **For Developers**: Start with [API Documentation](./api/API_DOCUMENTATION.md) +2. **For Security Auditors**: Review [Security Documentation](./security/) +3. **For Gas Optimization**: Check [Gas Optimization](./gas/GAS_OPTIMIZATION.md) +4. **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 +- **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/docs/api/API_DOCUMENTATION.md b/docs/api/API_DOCUMENTATION.md new file mode 100644 index 00000000..b2df7135 --- /dev/null +++ b/docs/api/API_DOCUMENTATION.md @@ -0,0 +1,712 @@ +# Predictify Hybrid API Documentation + +> **Version:** v1.0.0 +> **Platform:** Stellar Soroban +> **Audience:** Developers integrating with Predictify Hybrid smart contracts + +--- + +## ๐Ÿ“‹ Table of Contents + +1. [API Overview](#api-overview) +2. [API Versioning](#api-versioning) +3. [Core API Reference](#core-api-reference) +4. [Data Structures](#data-structures) +5. [Error Codes](#error-codes) +6. [Integration Examples](#integration-examples) +7. [Troubleshooting Guide](#troubleshooting-guide) +8. [Support and Resources](#support-and-resources) + +--- + +## ๐Ÿš€ API Overview + +The Predictify Hybrid smart contract provides a comprehensive API for building prediction market applications on the Stellar network. The API supports market creation, voting, dispute resolution, oracle integration, and administrative functions. + +### Key Features + +- **Market Management**: Create, extend, and resolve prediction markets +- **Voting System**: Stake-based voting with proportional payouts +- **Dispute Resolution**: Community-driven dispute and resolution system +- **Oracle Integration**: Support for Reflector, Pyth, and custom oracles +- **Fee Management**: Automated fee collection and distribution +- **Admin Governance**: Administrative functions for contract management + +--- + +## ๐Ÿ“š API Versioning + +### Current Version: v1.0.0 + +The Predictify Hybrid smart contract follows semantic versioning (SemVer) for API compatibility and contract upgrades. This section provides comprehensive information about API versions, compatibility, and migration strategies. + +### ๐Ÿท๏ธ Version Schema + +We use **Semantic Versioning (SemVer)** with the format `MAJOR.MINOR.PATCH`: + +- **MAJOR** (1.x.x): Breaking changes that require client updates +- **MINOR** (x.1.x): New features that are backward compatible +- **PATCH** (x.x.1): Bug fixes and optimizations + +### ๐Ÿ“‹ Version History + +#### v1.0.0 (Current) - Production Release +**Release Date:** 2025-01-15 +**Status:** โœ… Active + +**Core Features:** +- Complete prediction market functionality +- Oracle integration (Reflector, Pyth) +- Voting and dispute resolution system +- Fee collection and distribution +- Admin governance functions +- Comprehensive validation system + +**API Endpoints:** +- `initialize(admin: Address)` - Contract initialization +- `create_market(...)` - Market creation +- `vote(...)` - User voting +- `dispute_market(...)` - Dispute submission +- `claim_winnings(...)` - Claim payouts +- `collect_fees(...)` - Admin fee collection +- `resolve_market(...)` - Market resolution + +**Breaking Changes from v0.x.x:** +- Renamed `submit_vote()` to `vote()` +- Updated oracle configuration structure +- Modified dispute threshold calculation +- Enhanced validation error codes + +### ๐Ÿ”„ Compatibility Matrix + +| Client Version | Contract v1.0.x | Contract v0.9.x | Contract v0.8.x | +|----------------|-----------------|-----------------|------------------| +| Client v1.0.x | โœ… Full | โš ๏ธ Limited | โŒ Incompatible | +| Client v0.9.x | โš ๏ธ Limited | โœ… Full | โœ… Full | +| Client v0.8.x | โŒ Incompatible | โš ๏ธ Limited | โœ… Full | + +**Legend:** +- โœ… **Full**: Complete compatibility, all features supported +- โš ๏ธ **Limited**: Basic functionality works, some features unavailable +- โŒ **Incompatible**: Not supported, upgrade required + +### ๐Ÿš€ Upgrade Strategies + +#### For Contract Upgrades + +**1. Backward Compatible Updates (MINOR/PATCH)** +```bash +# Deploy new version alongside existing +soroban contract deploy \ + --wasm target/wasm32-unknown-unknown/release/predictify_hybrid_v1_1_0.wasm \ + --network mainnet + +# Update contract references gradually +# Old version continues to work +``` + +**2. Breaking Changes (MAJOR)** +```bash +# 1. Deploy new contract version +# 2. Migrate critical state (if supported) +# 3. Update all client applications +# 4. Deprecate old contract + +# Migration example +soroban contract invoke \ + --id $NEW_CONTRACT_ID \ + --fn migrate_from_v0 \ + --arg old_contract=$OLD_CONTRACT_ID +``` + +#### For Client Applications + +**JavaScript/TypeScript Example:** +```typescript +// Version-aware client initialization +const contractVersion = await getContractVersion(contractId); + +if (contractVersion.startsWith('1.0')) { + // Use v1.0 API + await contract.vote(marketId, outcome, stake); +} else if (contractVersion.startsWith('0.9')) { + // Use legacy API + await contract.submit_vote(marketId, outcome, stake); +} else { + throw new Error(`Unsupported contract version: ${contractVersion}`); +} +``` + +### ๐Ÿ“– API Documentation by Version + +#### Current API (v1.0.x) + +**Core Functions:** +- **Market Management**: `create_market()`, `extend_market()`, `resolve_market()` +- **Voting Operations**: `vote()`, `claim_winnings()` +- **Dispute System**: `dispute_market()`, `vote_on_dispute()` +- **Oracle Integration**: `submit_oracle_result()`, `update_oracle_config()` +- **Admin Functions**: `collect_fees()`, `update_config()`, `pause_contract()` + +**Data Structures:** +- `Market`: Core market data structure +- `Vote`: User vote representation +- `OracleConfig`: Oracle configuration +- `DisputeThreshold`: Dynamic dispute thresholds + +**Error Codes:** +- 100-199: User operation errors +- 200-299: Oracle errors +- 300-399: Validation errors +- 400-499: System errors + +#### Legacy API (v0.9.x) + +**Deprecated Functions:** +- `submit_vote()` โ†’ Use `vote()` in v1.0+ +- `create_prediction_market()` โ†’ Use `create_market()` in v1.0+ +- `get_market_stats()` โ†’ Use `get_market_analytics()` in v1.0+ + +### ๐Ÿ” Version Detection + +**Check Contract Version:** +```bash +# Using Soroban CLI +soroban contract invoke \ + --id $CONTRACT_ID \ + --fn get_version \ + --network mainnet +``` + +**JavaScript/TypeScript:** +```typescript +import { Contract } from '@stellar/stellar-sdk'; + +const getContractVersion = async (contractId: string): Promise => { + try { + const result = await contract.call('get_version'); + return result.toString(); + } catch (error) { + // Fallback for older contracts without version endpoint + return '0.9.0'; + } +}; +``` + +### ๐Ÿ›ก๏ธ Deprecation Policy + +**Timeline:** +- **Announcement**: 90 days before deprecation +- **Warning Period**: 60 days with deprecation warnings +- **End of Support**: 30 days notice before complete removal + +**Current Deprecations:** +- `submit_vote()`: Deprecated in v1.0.0, removal planned for v2.0.0 +- `create_prediction_market()`: Deprecated in v1.0.0, removal planned for v2.0.0 + +### ๐Ÿ“… Release Schedule + +**Planned Releases:** +- **v1.1.0** (Q2 2025): Enhanced analytics, batch operations +- **v1.2.0** (Q3 2025): Multi-token support, advanced oracles +- **v2.0.0** (Q4 2025): Complete API redesign, performance improvements + +### ๐Ÿ”— Version-Specific Resources + +**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](./migration/v0.9-to-v1.0.md) + +**Contract Addresses:** +- **v1.0.x Mainnet**: `CDLZFC3SYJYDZT7K67VZ75HPJVIEUVNIXF47ZG2FB2RMQQAHHAGK3HGU` +- **v0.9.x Mainnet**: `CBLZFC3SYJYDZT7K67VZ75HPJVIEUVNIXF47ZG2FB2RMQQAHHAGK3ABC` + +**Support Channels:** +- [GitHub Issues](https://github.com/predictify/contracts/issues) - Bug reports and feature requests +- [Discord #api-support](https://discord.gg/predictify) - Community support +- [Developer Forum](https://forum.predictify.io) - Technical discussions + +--- + +## ๐Ÿ”ง Core API Reference + +### Market Management Functions + +#### `create_market()` +Creates a new prediction market with specified parameters. + +**Signature:** +```rust +pub fn create_market( + env: Env, + admin: Address, + question: String, + outcomes: Vec, + duration_days: u32, + oracle_config: OracleConfig, +) -> Result +``` + +**Parameters:** +- `admin`: Market administrator address +- `question`: Market question (max 200 characters) +- `outcomes`: Possible outcomes (2-10 options) +- `duration_days`: Market duration (1-365 days) +- `oracle_config`: Oracle configuration for resolution + +**Returns:** Market ID (Symbol) + +**Example:** +```typescript +const marketId = await contract.create_market( + adminAddress, + "Will Bitcoin reach $100,000 by end of 2025?", + ["Yes", "No"], + 90, // 90 days + oracleConfig +); +``` + +#### `vote()` +Submit a vote on a market outcome with stake. + +**Signature:** +```rust +pub fn vote( + env: Env, + voter: Address, + market_id: Symbol, + outcome: String, + stake: i128, +) -> Result<(), Error> +``` + +**Parameters:** +- `voter`: Voter's address +- `market_id`: Target market ID +- `outcome`: Chosen outcome +- `stake`: Stake amount (minimum 0.1 XLM) + +**Example:** +```typescript +await contract.vote( + voterAddress, + "BTC_100K", + "Yes", + 5000000 // 0.5 XLM in stroops +); +``` + +#### `claim_winnings()` +Claim winnings from resolved markets. + +**Signature:** +```rust +pub fn claim_winnings( + env: Env, + user: Address, + market_id: Symbol, +) -> Result +``` + +**Returns:** Amount claimed in stroops + +--- + +## ๐Ÿ“Š Data Structures + +### Market +Core market data structure containing all market information. + +```rust +pub struct Market { + pub id: Symbol, + pub question: String, + pub outcomes: Vec, + pub creator: Address, + pub created_at: u64, + pub deadline: u64, + pub resolved: bool, + pub winning_outcome: Option, + pub total_stake: i128, + pub oracle_config: OracleConfig, +} +``` + +### Vote +Represents a user's vote on a market. + +```rust +pub struct Vote { + pub voter: Address, + pub market_id: Symbol, + pub outcome: String, + pub stake: i128, + pub timestamp: u64, + pub claimed: bool, +} +``` + +### OracleConfig +Configuration for oracle integration. + +```rust +pub struct OracleConfig { + pub provider: OracleProvider, + pub feed_id: String, + pub threshold: i128, + pub timeout_seconds: u64, +} +``` + +--- + +## โš ๏ธ Error Codes + +### User Operation Errors (100-199) +- **100**: `UserNotAuthorized` - User lacks required permissions +- **101**: `MarketNotFound` - Specified market doesn't exist +- **102**: `MarketClosed` - Market is closed for voting +- **103**: `InvalidOutcome` - Outcome not available for market +- **104**: `AlreadyVoted` - User has already voted on this market +- **105**: `NothingToClaim` - No winnings available to claim +- **106**: `MarketNotResolved` - Market resolution pending +- **107**: `InsufficientStake` - Stake below minimum requirement + +### Oracle Errors (200-299) +- **200**: `OracleUnavailable` - Oracle service unavailable +- **201**: `InvalidOracleConfig` - Oracle configuration invalid +- **202**: `OracleTimeout` - Oracle response timeout +- **203**: `OracleDataInvalid` - Oracle data format invalid + +### Validation Errors (300-399) +- **300**: `InvalidInput` - General input validation failure +- **301**: `InvalidMarket` - Market parameters invalid +- **302**: `InvalidVote` - Vote parameters invalid +- **303**: `InvalidDispute` - Dispute parameters invalid + +### System Errors (400-499) +- **400**: `ContractNotInitialized` - Contract requires initialization +- **401**: `AdminRequired` - Admin privileges required +- **402**: `ContractPaused` - Contract is paused +- **403**: `InsufficientBalance` - Account balance too low + +--- + +## ๐Ÿ’ก Integration Examples + +### Basic Market Creation and Voting + +```typescript +import { Contract, Keypair, Networks } from '@stellar/stellar-sdk'; + +// Initialize contract +const contract = new Contract(contractId); + +// Create market +const marketId = await contract.create_market( + adminKeypair.publicKey(), + "Will Ethereum reach $5,000 by Q2 2025?", + ["Yes", "No"], + 120, // 120 days + { + provider: "Reflector", + feed_id: "ETH/USD", + threshold: 5000000000, // $5,000 in stroops + timeout_seconds: 3600 + } +); + +// Vote on market +await contract.vote( + userKeypair.publicKey(), + marketId, + "Yes", + 10000000 // 1 XLM stake +); + +// Check market status +const market = await contract.get_market(marketId); +console.log(`Market: ${market.question}`); +console.log(`Total stake: ${market.total_stake} stroops`); + +// Claim winnings (after resolution) +const winnings = await contract.claim_winnings( + userKeypair.publicKey(), + marketId +); +console.log(`Claimed: ${winnings} stroops`); +``` + +### Batch Operations + +```typescript +// Create multiple markets +const markets = await Promise.all([ + contract.create_market(admin, "BTC > $100K?", ["Yes", "No"], 90, btcConfig), + contract.create_market(admin, "ETH > $5K?", ["Yes", "No"], 90, ethConfig), + contract.create_market(admin, "SOL > $200?", ["Yes", "No"], 90, solConfig) +]); + +// Vote on multiple markets +await Promise.all( + markets.map(marketId => + contract.vote(user, marketId, "Yes", 5000000) + ) +); +``` + +--- + +## ๐Ÿ†˜ Troubleshooting Guide + +### Common Issues and Solutions + +#### ๐Ÿ”ง Deployment Issues + +**Problem: Contract deployment fails with "Insufficient Balance"** +```bash +Error: Account has insufficient balance for transaction +``` +**Solution:** +```bash +# Check account balance +soroban config identity address +soroban balance --id --network mainnet + +# Fund account if needed (minimum 100 XLM recommended) +# Use Stellar Laboratory or send from funded account +``` + +**Problem: WASM file not found during deployment** +```bash +Error: No such file or directory: target/wasm32-unknown-unknown/release/predictify_hybrid.wasm +``` +**Solution:** +```bash +# Ensure contract is built first +cd contracts/predictify-hybrid +make build + +# Verify WASM file exists +ls -la target/wasm32-unknown-unknown/release/ +``` + +#### ๐Ÿ”ฎ Oracle Integration Issues + +**Problem: Oracle results not being accepted** +```rust +Error: InvalidOracleConfig (201) +``` +**Solution:** +```bash +# Verify oracle configuration +soroban contract invoke \ + --id $CONTRACT_ID \ + --fn get_oracle_config \ + --network mainnet + +# Update oracle configuration if needed +soroban contract invoke \ + --id $CONTRACT_ID \ + --fn update_oracle_config \ + --arg provider=Reflector \ + --arg feed_id="BTC/USD" \ + --network mainnet +``` + +**Problem: Oracle price feeds timing out** +```rust +Error: OracleUnavailable (200) +``` +**Solution:** +1. Check oracle service status +2. Verify network connectivity +3. Implement fallback oracle providers +4. Add retry logic with exponential backoff + +#### ๐Ÿ—ณ๏ธ Voting and Market Issues + +**Problem: User unable to vote** +```rust +Error: MarketClosed (102) +``` +**Solution:** +```bash +# Check market status and deadline +soroban contract invoke \ + --id $CONTRACT_ID \ + --fn get_market \ + --arg market_id="BTC_100K" \ + --network mainnet + +# Extend market if authorized and appropriate +soroban contract invoke \ + --id $CONTRACT_ID \ + --fn extend_market \ + --arg market_id="BTC_100K" \ + --arg additional_days=7 \ + --network mainnet +``` + +**Problem: Insufficient stake error** +```rust +Error: InsufficientStake (107) +``` +**Solution:** +```bash +# Check minimum stake requirements +echo "Minimum vote stake: 1,000,000 stroops (0.1 XLM)" +echo "Minimum dispute stake: 100,000,000 stroops (10 XLM)" + +# Verify user balance +soroban balance --id --network mainnet +``` + +#### ๐Ÿ›๏ธ Dispute Resolution Issues + +**Problem: Dispute submission rejected** +```rust +Error: DisputeVotingNotAllowed (406) +``` +**Solution:** +1. Verify market is in resolved state +2. Check dispute window timing (24-48 hours after resolution) +3. Ensure sufficient dispute stake +4. Verify user hasn't already disputed + +**Problem: Dispute threshold too high** +```rust +Error: ThresholdExceedsMaximum (412) +``` +**Solution:** +```bash +# Check current dispute threshold +soroban contract invoke \ + --id $CONTRACT_ID \ + --fn get_dispute_threshold \ + --arg market_id="BTC_100K" \ + --network mainnet + +# Admin can adjust if necessary +soroban contract invoke \ + --id $CONTRACT_ID \ + --fn update_dispute_threshold \ + --arg market_id="BTC_100K" \ + --arg new_threshold=50000000 \ + --network mainnet +``` + +#### ๐Ÿ’ฐ Fee and Payout Issues + +**Problem: Fee collection fails** +```rust +Error: NoFeesToCollect (415) +``` +**Solution:** +```bash +# Check if fees are available +soroban contract invoke \ + --id $CONTRACT_ID \ + --fn get_collectable_fees \ + --arg market_id="BTC_100K" \ + --network mainnet + +# Ensure market is resolved and fees haven't been collected +``` + +**Problem: User cannot claim winnings** +```rust +Error: NothingToClaim (105) +``` +**Solution:** +1. Verify user voted on winning outcome +2. Check market resolution status +3. Ensure user hasn't already claimed +4. Verify market dispute period has ended + +### ๐Ÿ” Debugging Tools + +#### Contract State Inspection +```bash +# Get complete market information +soroban contract invoke \ + --id $CONTRACT_ID \ + --fn get_market_analytics \ + --arg market_id="BTC_100K" \ + --network mainnet + +# Check user voting history +soroban contract invoke \ + --id $CONTRACT_ID \ + --fn get_user_votes \ + --arg user=
\ + --network mainnet + +# Inspect contract configuration +soroban contract invoke \ + --id $CONTRACT_ID \ + --fn get_config \ + --network mainnet +``` + +#### Transaction Analysis +```bash +# View transaction details +soroban events --id $CONTRACT_ID --network mainnet + +# Check specific transaction +soroban transaction --hash --network mainnet +``` + +#### Log Analysis +```bash +# Enable verbose logging +export RUST_LOG=debug + +# Run with detailed output +soroban contract invoke \ + --id $CONTRACT_ID \ + --fn vote \ + --arg market_id="BTC_100K" \ + --arg outcome="yes" \ + --arg stake=5000000 \ + --network mainnet \ + --verbose +``` + +--- + +## ๐Ÿ“ž Support and Resources + +### Error Code Reference +- **100-199**: User operation errors - Check user permissions and market state +- **200-299**: Oracle errors - Verify oracle configuration and connectivity +- **300-399**: Validation errors - Check input parameters and formats +- **400-499**: System errors - Contact support for system-level issues + +### Support Channels +1. **GitHub Issues**: [Report bugs and request features](https://github.com/predictify/contracts/issues) +2. **Discord Support**: [#technical-support channel](https://discord.gg/predictify) +3. **Developer Forum**: [Technical discussions](https://forum.predictify.io) +4. **Email Support**: technical-support@predictify.io + +### Before Contacting Support +1. Check this troubleshooting guide +2. Search existing GitHub issues +3. Verify your environment and configuration +4. Collect relevant error messages and transaction hashes +5. Note your contract version and network + +### Additional Resources +- [Stellar Soroban Documentation](https://soroban.stellar.org/) +- [Stellar SDK Documentation](https://stellar.github.io/js-stellar-sdk/) +- [Predictify GitHub Repository](https://github.com/predictify/contracts) +- [Community Examples](https://github.com/predictify/examples) + +--- + +**Last Updated:** 2025-01-15 +**API Version:** v1.0.0 +**Documentation Version:** 1.0 diff --git a/docs/gas/GAS_BENCHMARKING.md b/docs/gas/GAS_BENCHMARKING.md new file mode 100644 index 00000000..297d8c45 --- /dev/null +++ b/docs/gas/GAS_BENCHMARKING.md @@ -0,0 +1,58 @@ +## Gas Cost Benchmarking Procedures + +Goal: produce reproducible cost metrics per entrypoint across typical scenarios and catch regressions. + +### Tools + +- Stellar CLI (`stellar`) with `--cost` +- RPC simulateTransaction (client SDKs) + +### Build + +```bash +stellar contract build +``` + +### Local Simulation (recommended) + +- Use `stellar contract invoke --cost` (or `tx simulate`) to print execution cost breakdown before submit. +- For each function, craft inputs for small/medium/large cases. + +Example (pseudocode; replace ids/args): + +```bash +# Simulate vote cost +stellar contract invoke --id $CONTRACT_ID \ + --network futurenet --cost -- \ + vote --user $USER --market-id market_1 --outcome Yes --stake 1000 +``` + +Capture output (instructions, ledger read/write counts, bytes) into `benchmarks/results/*.csv`. + +### RPC Simulation (programmatic) + +- Use SDKs to build a tx that invokes the function and call `simulateTransaction`. +- Record `resourceFee`, `cpuInsns`, `readBytes`, `writeBytes`, `readEntries`, `writeEntries`, and events/return sizes. + +### Scenarios to Benchmark + +- create_market: short vs long question/outcomes +- vote: single voter; 100 voters; 1,000 voters +- claim_winnings: winner vs loser; large market iteration +- resolve_market: with/without oracle result, with disputes +- fetch_oracle_result: Reflector vs Pyth paths +- collect_fees: resolved vs unresolved + +### WASM Size Optimization + +```bash +stellar contract optimize --wasm target/wasm32v1-none/release/predictify_hybrid.wasm +``` + +Track optimized size and ensure below network limits. + +### Reporting + +- Commit CSVs and a short summary per release under `benchmarks/`. +- Update `../gas/GAS_COST_ANALYSIS.md` with highlights (e.g., hot paths, bytes drivers). + diff --git a/docs/gas/GAS_CASE_STUDIES.md b/docs/gas/GAS_CASE_STUDIES.md new file mode 100644 index 00000000..2052f7fc --- /dev/null +++ b/docs/gas/GAS_CASE_STUDIES.md @@ -0,0 +1,51 @@ +## Gas Optimization Case Studies (Predictify Hybrid) + +### 1) Voting: Avoid per-iteration storage access + +Issue: Repeated `.get()`/`.set()` inside loops increases read/write entries. + +Fix: Read market once, update in-memory, write once. + +See the `vote` implementation which already batches to a single final write: + +```302:308:contracts/predictify-hybrid/src/lib.rs +market.votes.set(user.clone(), outcome); +market.stakes.set(user.clone(), stake); +market.total_staked += stake; +env.storage().persistent().set(&market_id, &market); +``` + +Further improvement: Pre-validate `outcome` using an in-memory set if outcomes are large to avoid repeated scans. + +### 2) Claiming: Scale with participants carefully + +Current approach iterates all votes to compute `winning_total`: + +```395:404:contracts/predictify-hybrid/src/lib.rs +let mut winning_total = 0; +for (voter, outcome) in market.votes.iter() { + if &outcome == winning_outcome { + winning_total += market.stakes.get(voter.clone()).unwrap_or(0); + } +} +``` + +Optimizations: + +- Maintain `stakes_per_outcome` totals during `vote` to avoid O(n) scan at claim time. +- Consider a compact bitmap/flag for `claimed` to reduce map overhead. + +### 3) Market Creation: Bound string sizes + +Cost driver: `question` and `outcomes` lengths inflate write-bytes. + +Guideline: Enforce caps (e.g., 140/32 chars). Reject overlong inputs to protect fees. + +### 4) Oracle Resolution: Validate before calling + +Call the cheapest checks first (staleness, feed format) before cross-contract calls. Skip persistence until a valid result is known. + +### 5) Events over Storage + +Emit events for analytics (e.g., vote tally changes) and only persist aggregates needed for on-chain reads. + diff --git a/docs/gas/GAS_COST_ANALYSIS.md b/docs/gas/GAS_COST_ANALYSIS.md new file mode 100644 index 00000000..c289022e --- /dev/null +++ b/docs/gas/GAS_COST_ANALYSIS.md @@ -0,0 +1,131 @@ +## Gas Usage Analysis (Function Catalog) + +This document catalogs public entrypoints in `predictify-hybrid` and provides a structure to record gas usage characteristics and measured costs. Use the benchmarking guide to populate the "Measured Cost" columns. + +### Method Inventory + +- initialize(env, admin) +- create_market(env, admin, question, outcomes, duration_days, oracle_config) -> Symbol +- vote(env, user, market_id, outcome, stake) +- claim_winnings(env, user, market_id) +- get_market(env, market_id) -> Option +- fetch_oracle_result(env, market_id, oracle_contract) -> Result +- resolve_market(env, market_id) -> Result<(), Error> +- get_resolution_analytics(env) -> Result +- get_market_analytics(env, market_id) -> Result +- dispute_market(env, user, market_id, stake, reason) -> Result<(), Error> +- vote_on_dispute(env, user, market_id, dispute_id, vote, stake, reason) -> Result<(), Error> +- resolve_dispute(env, admin, market_id) -> Result +- collect_fees(env, admin, market_id) -> Result +- extend_market(env, admin, market_id, additional_days, reason, fee_amount) -> Result<(), Error> +- Storage optimization helpers (compress/cleanup/migrate/monitor/optimize/...) + +### Storage Touch Patterns (selected excerpts) + +Vote path writes a vote and stake, updates totals, and persists market: + +```275:308:contracts/predictify-hybrid/src/lib.rs +// vote(...) +// ... +// Store the vote and stake +market.votes.set(user.clone(), outcome); +market.stakes.set(user.clone(), stake); +market.total_staked += stake; + +env.storage().persistent().set(&market_id, &market); +``` + +Market creation allocates a new `Market` with several empty maps and persists once: + +```183:221:contracts/predictify-hybrid/src/lib.rs +// create_market(...) +// Generate ID, compute end_time, then +let market = Market { + // ... + oracle_result: None, + votes: Map::new(&env), + total_staked: 0, + dispute_stakes: Map::new(&env), + stakes: Map::new(&env), + claimed: Map::new(&env), + winning_outcome: None, + fee_collected: false, + state: MarketState::Active, + total_extension_days: 0, + max_extension_days: 30, + extension_history: Vec::new(&env), +}; +env.storage().persistent().set(&market_id, &market); +``` + +Claim path iterates to compute `winning_total` and marks `claimed`: + +```395:419:contracts/predictify-hybrid/src/lib.rs +// claim_winnings(...) +// Calculate total winning stakes +let mut winning_total = 0; +for (voter, outcome) in market.votes.iter() { + if &outcome == winning_outcome { + winning_total += market.stakes.get(voter.clone()).unwrap_or(0); + } +} +// Mark as claimed +market.claimed.set(user.clone(), true); +env.storage().persistent().set(&market_id, &market); +``` + +### Analysis Template + +Fill per method after running benchmarks (see ../gas/GAS_BENCHMARKING.md): + +- initialize + - Reads: 0-1 (admin guard if re-init) + - Writes: 1 (Admin key) + - Bytes written (est.): small + - Measured: instructions=โ€ฆ, r-entries=โ€ฆ, w-entries=โ€ฆ, rKB=โ€ฆ, wKB=โ€ฆ + +- create_market + - Reads: 1 (admin) + - Writes: 2 (counter, market) + - Bytes drivers: `question`, `outcomes` length + - Risks: long strings blow write-bytes; validate lengths + - Measured: โ€ฆ + +- vote + - Reads: 1 (market) + - Writes: 1 (market) + - Map ops: votes.set, stakes.set + - Loop: none + - Measured: โ€ฆ + +- claim_winnings + - Reads: 1 (market) + - Writes: 1 (market) + - Loop: iterates `votes` (cost scales with voters) + - Optimization: accumulate and cache totals off-chain; filter losers early + - Measured: โ€ฆ + +- fetch_oracle_result + - Reads: 1 (market) + - Cross-contract: yes (oracle) + - Writes: 0 (this method returns result only) + - Measured: โ€ฆ + +- resolve_market + - Likely reads+writes market; hybrid algorithm cost scales with votes + - Measured: โ€ฆ + +- collect_fees / extend_market / dispute* + - Admin read, market write patterns + - Measured: โ€ฆ + +### Length Limits to Enforce (to control write-bytes) + +- `question`: recommend <= 140 chars +- `outcomes[i]`: recommend <= 32 chars +- `reason` fields: recommend <= 160 chars + +### Recording Results + +Record CLI `--cost` outputs and RPC simulation breakdowns in a CSV under `benchmarks/results/` for each function and typical scenarios (small/medium/large markets). + diff --git a/docs/gas/GAS_MONITORING.md b/docs/gas/GAS_MONITORING.md new file mode 100644 index 00000000..cf746dcd --- /dev/null +++ b/docs/gas/GAS_MONITORING.md @@ -0,0 +1,31 @@ +## Gas Usage Monitoring and Operations + +### Pre-Submit Simulation + +- Always simulate and log `--cost` before sending transactions. +- Use RPC `getFeeStats()` to set inclusion fee (p90 recommended under load). + +### Metrics to Track + +- Distribution of resource fees per function +- Average read/write entries and bytes per function +- Event+return sizes (aim << 8 KB cap) +- Oracle call failure rates and retries + +### Alerting + +- Spike in write-bytes or write-entries +- Repeated tx failures due to under-estimated event/return size +- Inclusion fee surge vs baseline + +### Dashboards + +- Per-endpoint cost over time +- Top costly calls and scenarios +- WASM size trend per release + +### Operational Playbooks + +- If costs climb due to strings: enforce length caps at API layer and/or contract validation. +- If claim/resolve costs spike: batch payouts off-chain via token escrows or staged claims. + diff --git a/docs/gas/GAS_OPTIMIZATION.md b/docs/gas/GAS_OPTIMIZATION.md new file mode 100644 index 00000000..e3517b48 --- /dev/null +++ b/docs/gas/GAS_OPTIMIZATION.md @@ -0,0 +1,88 @@ +## Gas Optimization Guide (Soroban on Stellar) + +This guide explains how to write and maintain gas-efficient Soroban contracts in this repository, with concrete recommendations mapped to `predictify-hybrid` and `hello-world`. + +- Audience: Contract developers and reviewers +- Targets: Soroban SDK 22.x; built with wasm32v1-none + +### Key Facts (Resource Limits & Fees) + +- Max per-tx: 100M CPU instructions, 40 MB memory +- Ledger access limits: 40 reads, 25 writes; 200 KB read bytes; ~129 KB write bytes +- Fee highlights (stroops): + - 10,000 instructions: 25 + - Read 1 ledger entry: 6,250; Write 1 ledger entry: 10,000 + - Read 1 KB: 1,786; Write 1 KB: ~11,800 + - Events+return value: 10,000 per KB (up to 8 KB total) + - Bandwidth: 1,624/KB, History archival: 16,235/KB + +Reference: "Resource Limits & Fees" in Stellar docs. + +### Golden Rules + +- Prefer computation over storage. Reads/writes dominate costs; batch and cache in-memory. +- Read once, write once. Accumulate updates in memory, then persist once at end. +- Avoid per-iteration storage access inside loops. Pull state once, work in `Vec`/`Map`, write once. +- Keep data narrow. Use `Symbol`, `BytesN`, and compact enums/keys; avoid long `String` values. +- Emit events for audit-only data; store only what must be read on-chain later. +- Minimize cross-contract calls. They expand footprint, auth, and costs; batch where feasible. +- Validate inputs early and fail fast. Guard clauses save CPU and storage. +- Use fixed-size math and checked ops where possible; avoid unnecessary big-int math. +- Favor `Vec`/`Map` keyed by compact enums over wide maps with long keys. +- Keep return values small; event+return budget is capped at 8 KB. + +### Patterns for Soroban + +- Use `env.storage().persistent()` for durable state; consider `temporary()` for short-lived, re-creatable data. +- For lists, keep per-address collections keyed by an enum data key, not one giant vector of structs. +- Bundle external token/oracle transfers: one total transfer into the contract, then internal distributions. +- Avoid growing WASM linear memory repeatedly (e.g., large heap vec); pre-size or use small batches. + +### Contract-Specific Hotspots + +- `vote` and staking accrual: Favor in-memory aggregation; avoid repeated map lookups/sets. +- `claim_winnings`: Compute totals in-stream and avoid re-reading maps repeatedly; short-circuit losers early. +- `create_market`: Validate and compute once; store a compact `Market` struct; avoid overlong strings. +- Oracle resolution: Keep payloads compact, validate staleness and confidence before persisting. + +### Data Layout Recommendations + +- Keys: Use `Symbol`-based keys or small enums for storage keys. +- Strings: Restrict question/outcome lengths; validate length to prevent excess write bytes. +- Maps: Avoid nested maps when a single flat map of compact keys suffices. + +### Events vs Storage + +- Emit events for analytics/telemetry and off-chain consumption. +- Store only state needed for on-chain reads (e.g., current totals, winner, claims bitmap/flags). + +### Build & Profile Tips + +- Use `profile.release` with `opt-level = "z"`, `lto = true`, `panic = "abort"` (already configured). +- Run cost simulations with CLI `--cost` and RPC `simulateTransaction` before submitting. +- Keep function return values and emitted events small. + +### Safe Math + +- Keep `overflow-checks = true` (already set). Prefer `checked_*` for user-driven arithmetic. +- Normalize precision early (e.g., cents) and avoid repeated scaling. + +### Storage TTL and Rent + +- Prefer temporary storage for short-lived data; extend TTL intentionally for persistent data. +- Avoid frequent size growth of entries; growing entries triggers higher rent top-ups. + +### Code Review Checklist (Gas) + +- Are storage reads/writes minimized and batched? +- Any loops calling storage or cross-contract functions per iteration? +- Are keys and values compact? Any unbounded strings or vectors? +- Are external calls minimized, batched, and gated by pre-checks? +- Do functions fail early on invalid inputs to save CPU/storage? +- Are events used instead of storage where on-chain reads arenโ€™t required? + +### References + +- Stellar Docs: Analyzing smart contract cost and efficiency +- Stellar Docs: Resource Limits & Fees + diff --git a/docs/gas/GAS_TESTING_GUIDELINES.md b/docs/gas/GAS_TESTING_GUIDELINES.md new file mode 100644 index 00000000..2a346d21 --- /dev/null +++ b/docs/gas/GAS_TESTING_GUIDELINES.md @@ -0,0 +1,32 @@ +## Gas Optimization Testing Guidelines + +Objective: ensure PRs do not introduce significant cost regressions and follow best practices. + +### Unit Tests + +- Cover all public entrypoints with valid and invalid inputs (fail fast saves gas). +- Include large-market tests (e.g., many voters) to catch algorithmic costs. + +### Snapshot-Based Validation + +- For stable scenarios, snapshot CLI `--cost` outputs and diff on PRs. +- Store under `test_snapshots/cost/` with scenario descriptions. + +### Lints and Review + +- Review loops for storage/cross-contract calls per iteration. +- Check for repeated `.get()`/`.set()` rather than single read/single write patterns. +- Ensure strings/bytes sizes are validated. + +### PR Checklist (Gas) + +- [ ] Storage ops minimized and batched +- [ ] No per-iteration storage writes in loops +- [ ] External calls minimized/batched +- [ ] Return/events payloads small +- [ ] Enforced input length caps + +### Optional Static Analysis + +- Consider running a Soroban-focused analyzer to detect storage-in-loop and repeated indirect storage access patterns. + diff --git a/docs/gas/GAS_TROUBLESHOOTING.md b/docs/gas/GAS_TROUBLESHOOTING.md new file mode 100644 index 00000000..4befe792 --- /dev/null +++ b/docs/gas/GAS_TROUBLESHOOTING.md @@ -0,0 +1,27 @@ +## Gas Optimization Troubleshooting + +### Symptom: Transactions fail with insufficient fee or cost + +- Cause: Under-estimated events/return size or large write bytes. +- Fix: Increase refundable events/return budget on client; enforce input size caps. + +### Symptom: Cost spikes on claims/resolution + +- Cause: O(n) scans over voters; growing maps. +- Fix: Maintain per-outcome aggregates; paginate or stage claims. + +### Symptom: Reaching read/write entry limits + +- Cause: Too many storage keys touched per call. +- Fix: Normalize layout; merge maps; reduce per-user keys. + +### Symptom: Large WASM or linear memory grows + +- Cause: Big heap vecs; heavy deps. +- Fix: Pre-size small arrays; remove unused deps; run `stellar contract optimize`. + +### Symptom: Cross-contract call errors inflate retries + +- Cause: Oracle/Token contract misconfig or network flakiness. +- Fix: Validate addresses and pre-checks; implement fallback path; cache results if acceptable. + diff --git a/docs/operations/INCIDENT_RESPONSE.md b/docs/operations/INCIDENT_RESPONSE.md new file mode 100644 index 00000000..590accb2 --- /dev/null +++ b/docs/operations/INCIDENT_RESPONSE.md @@ -0,0 +1,50 @@ +This documentation helps in detecting incident response procedures, provides insights for security monitoring and security updates process + +## 1. Detection +- Alerts for traffic patterns +- Look for inappropriate user behavior or requests + +## 2. Containment +- Isolation od affected systems and revoke access tokens and secrets +- Disable accounts affected + +## 3. Eradication +- Detect for malicious code and patch the exploited vulnerability with clearing of logs + +## 4. Recovery +- Keep backup for recovery + +## 5. Post-Incident Review +- Documentation of incident and prevention +- Notfication to regulatory bodies during a security breach + +# Guidelines for Security Monitoring + +## Metrices to watch +- Look for unauthorised access endpoints +- Increase in user requests +- Failure in Login continuously + +## Log Retention Policies +- Regularly check for logs and monitor them + +## Tools and Frameworks +- Use tools like Datadog, Splunk, and ELK stack + +## Montoring Targets +- Look for admin activities +- Health of system and access to database and authentications details + +# Procedures for Security Updates + +## Regular Updates +- Patching of OS and Apps regularly +- Merge dependencies with low risks + +## Post-Update Verification +- Monitor for anamolies everyday +- Validation of Configuration + +## Communication +- Notification of critical updates to security teams + diff --git a/docs/security/ATTACK-VECTORS.md b/docs/security/ATTACK-VECTORS.md new file mode 100644 index 00000000..9ca0abb0 --- /dev/null +++ b/docs/security/ATTACK-VECTORS.md @@ -0,0 +1,43 @@ +# Analysis of Vector Analysis and Mitigation +This document highlights attack vectors with mitigations. + +## 1. SQL Injection +- A web security vulnerability that lets an attacker to change database of an organisation with malicious SQL queries injection. +- Using prepared statements and parameterized queries, can help in preventing SQL injection attacks. +- Using ORM(Object-Relational Mapping) Frameworks like Hibernate or Entity Framework can help in reducing SQL inject by default. + +## 2. Cross-Site Request Forgery(CSRF) +- The attacker exploits the trust of a web application with a authenticated user. +- The identity of the victim is used to perform some actions. +**Prevention**: +- Use an anti-CSRF token or synchronizer token. +- Add a CAPTCHA to validate that the use is human. + +## 3. Insecure API Access +- The application can run into broken authentication when APIs are not validated. +- When APIs get too nmany requests from user, resource limit problems can occur. Fake requests can be sent by attackers to the servers. + +**Prevention** +- Strong passwords implementation policy with two-step login can be implemented. +- Security standards can be applied to endpoints, like input validation, authentication, and authorization. + +## 4. Insider Threat +- Threats originating within an organisation. +- These threats can increase property thefts, data breach and disturbing operations. +**Prevention** +- Training to detect and stop insider threats. +- Regularly implementating montitorization and access reviews. + +## 5. Cross-Site Scripting(XSS) +- Malicious scripts are injected into trusted websites. +- Browser side script can be corrupted and send to different user. +**Prevention** +- Use approppriate headers, use Content-Type and X-Content-Type-Options, headers for interpretation of responses by the browsers. +- Use Content Security Policy(CSP) to prevent servere XSS vulnerabilities. + +## 6. Misconfiguration +- When security settings are not defined in the configuration, security Misconfiguration occurs. +- Directory Listing should not be enabled with not showing error messages which is sensitive information. +**Prevention** +- Regularly perform scans and identify security misconfigurations. +- Encryption of data at rest to prevent exploittaion of data. \ No newline at end of file diff --git a/docs/security/AUDIT_CHECKLIST.md b/docs/security/AUDIT_CHECKLIST.md new file mode 100644 index 00000000..0939be16 --- /dev/null +++ b/docs/security/AUDIT_CHECKLIST.md @@ -0,0 +1,21 @@ +#Security Audit Checklist + +## Monthly Internal Review +- [] Implementation of strong passwords policies +- [] Rotation of Secrets +- [] Retaintion of logs and their collections +- [] Enabling of MFA of authorized users with privilege access +- [] Third party dependencies are scanned to check vulnerabilities +- [] Validation of acces controls and firewall + +## Quarterly External Audit +- [] Review user access +- [] Scann all endpoints to check vulnerabilites +- [] Review compilance with GDPR/HIPAA +- [] Conduct Penetration Tests + +## Audit Logs +- Access Control Audits +- Incident Response Capability Assesment +- Resource Access +- Admin Operations \ No newline at end of file diff --git a/docs/security/SECURITY_BEST_PRACTICES.md b/docs/security/SECURITY_BEST_PRACTICES.md new file mode 100644 index 00000000..cbf112be --- /dev/null +++ b/docs/security/SECURITY_BEST_PRACTICES.md @@ -0,0 +1,24 @@ +# Recommendations of Security and Best Practices + +## Code Practices +- Use OWASP Application Security Verification Standard(ASVS) for the verification of security controls +- Implement servers and frameworks are running on latest versions. +- Encrypt highly sensitive information(authentication verification data) + +## Infrastucture +- Monitor networks and update software and hardware regularly +- Use Web Application Firewall(WAF) that monitors HTTP traffic across Internet and blocks vulnerabilities. + +## Updates +- Perform regular updates for libraries +- Use auto-scanning tools like Synk + +## Access Control +- Principle of Least Priviledge(PoLP) ensures authorized users can execute jobs within the system. +- Roles based access towards some operations. + +## Authentication +- Implementing strong password policies with rotation +- Implementing Multi-Factor Authentication(MFA) +- User tokens implemented during login form + diff --git a/docs/security/SECURITY_CONSIDERATIONS.md b/docs/security/SECURITY_CONSIDERATIONS.md new file mode 100644 index 00000000..1c1f39ad --- /dev/null +++ b/docs/security/SECURITY_CONSIDERATIONS.md @@ -0,0 +1,52 @@ +#Security Considerations + +This document highlights the important security concerns and protection strategies for the system. + +## 1. Data Classification and it's Sensitivity +Implementing a data classification property +There are different types of data categories: +- Financial Data +- Intellectual Data +- Confidential Business Data +- Personal Identifiable Information +- Proprietary Data +- Health Information + +Data classification based on sensitivity +- Public- Data can be accesed by public and free to access. +- Confidential - Data can accesed by authorized individuals, and highly protected data. +- Highly Confidential- Data is highly rescricted to acces and utmost confidentiality +- Internal: Data that can be shared only within an organization, which is private + +## 2. Implementation of Encrytion + +- Only authorized individuals can access data which is sensitive. +- Implementation of role-based access controls(RBAC) for permitting privileges based on roles and responsibilites. +- Implementating a multi-factor authentication(MFA) for adding extra layer of security for access control. +- For encrypting data during transmission, encryption mechanisms such as Secure Socket Layer(SSL) or Transport Layer Security(TLS) protocols can be added. + +## 3. Data Encryption +- Transit Data Encrytion: Data moving from one point to another, with internet or VPN. + +- Data Encryption at Rest: More secure and less data breach, less randsomeware attacks. + +- Key Management Policy protects the sensitive data with processing cryptographic keys, with key generation and storage of keys. + +## 4. Data Encrytion Algorithms +- The Advanced Encryption Standard(AES) is a symmetric-key algorithm. This employs block cipher methods. + +- The latest version of the TLS protocol is TLS 1.3. Modern version of SSL, utilized by HTTPS and other protocols for encryption. + +- Key rotation and retiring old keys with regularly updation of keys. + +## 5. Security practices for third party dependencies +- Implementating tools like Synk or OWASP Dependency-Check with regularly scanning dependencies. + +- Minimize risk posed by dependencies with isolation menthods: containerization, microservices architecture, and restricted permissions. + +- Keeping updated libraries for security. Manual reviews are important for compatibility. + +## 6. Regulatory Compilance +- HIPAA: Health Insurance Portability and Accountability Act maintains standards to protect sensitive health information from disclosure without patient's consent. + +- GDPR: General Data Protection Regulation permits individuals the right to ask organisations to delete their personal data. \ No newline at end of file diff --git a/docs/security/SECURITY_TESTING_GUIDE.md b/docs/security/SECURITY_TESTING_GUIDE.md new file mode 100644 index 00000000..ef45e3c2 --- /dev/null +++ b/docs/security/SECURITY_TESTING_GUIDE.md @@ -0,0 +1,18 @@ +# Security Test Guide + +## 1. Dependency Scanning +- Regularly check for source-code files with changes +- Check for compatibility and resolve performance issues + +## 2. Penetration Testing +- Use Kali Linux and Burp Suite to identify vulnerabilities +- Use Wireshark to check network traffic + +## 3. Dynamic Application Security Testing(DASP) +- DASP tools are used for identifying security misconfiguration, broken authentication and input/output validation +- ZED Attack Proxy is an open source tool for security testing provided by OWASP + +## 4. Static Application Security Testing(SAST) +- Tools help in detecting SQL injections,and other vulnerabilities +- SonarQube, Fortify are commonly used tools +- Integrate with IDEs and CI/CD pipelines From 46ac6898ff6bb2dbd4e3fb94fb119517a58e84f5 Mon Sep 17 00:00:00 2001 From: 1nonlypiece Date: Sun, 10 Aug 2025 16:08:34 +0530 Subject: [PATCH 02/20] docs: move API_DOCUMENTATION.md to docs/api/ --- API_DOCUMENTATION.md | 712 ------------------------------------------- 1 file changed, 712 deletions(-) delete mode 100644 API_DOCUMENTATION.md diff --git a/API_DOCUMENTATION.md b/API_DOCUMENTATION.md deleted file mode 100644 index ff8c30fa..00000000 --- a/API_DOCUMENTATION.md +++ /dev/null @@ -1,712 +0,0 @@ -# Predictify Hybrid API Documentation - -> **Version:** v1.0.0 -> **Platform:** Stellar Soroban -> **Audience:** Developers integrating with Predictify Hybrid smart contracts - ---- - -## ๐Ÿ“‹ Table of Contents - -1. [API Overview](#api-overview) -2. [API Versioning](#api-versioning) -3. [Core API Reference](#core-api-reference) -4. [Data Structures](#data-structures) -5. [Error Codes](#error-codes) -6. [Integration Examples](#integration-examples) -7. [Troubleshooting Guide](#troubleshooting-guide) -8. [Support and Resources](#support-and-resources) - ---- - -## ๐Ÿš€ API Overview - -The Predictify Hybrid smart contract provides a comprehensive API for building prediction market applications on the Stellar network. The API supports market creation, voting, dispute resolution, oracle integration, and administrative functions. - -### Key Features - -- **Market Management**: Create, extend, and resolve prediction markets -- **Voting System**: Stake-based voting with proportional payouts -- **Dispute Resolution**: Community-driven dispute and resolution system -- **Oracle Integration**: Support for Reflector, Pyth, and custom oracles -- **Fee Management**: Automated fee collection and distribution -- **Admin Governance**: Administrative functions for contract management - ---- - -## ๐Ÿ“š API Versioning - -### Current Version: v1.0.0 - -The Predictify Hybrid smart contract follows semantic versioning (SemVer) for API compatibility and contract upgrades. This section provides comprehensive information about API versions, compatibility, and migration strategies. - -### ๐Ÿท๏ธ Version Schema - -We use **Semantic Versioning (SemVer)** with the format `MAJOR.MINOR.PATCH`: - -- **MAJOR** (1.x.x): Breaking changes that require client updates -- **MINOR** (x.1.x): New features that are backward compatible -- **PATCH** (x.x.1): Bug fixes and optimizations - -### ๐Ÿ“‹ Version History - -#### v1.0.0 (Current) - Production Release -**Release Date:** 2025-01-15 -**Status:** โœ… Active - -**Core Features:** -- Complete prediction market functionality -- Oracle integration (Reflector, Pyth) -- Voting and dispute resolution system -- Fee collection and distribution -- Admin governance functions -- Comprehensive validation system - -**API Endpoints:** -- `initialize(admin: Address)` - Contract initialization -- `create_market(...)` - Market creation -- `vote(...)` - User voting -- `dispute_market(...)` - Dispute submission -- `claim_winnings(...)` - Claim payouts -- `collect_fees(...)` - Admin fee collection -- `resolve_market(...)` - Market resolution - -**Breaking Changes from v0.x.x:** -- Renamed `submit_vote()` to `vote()` -- Updated oracle configuration structure -- Modified dispute threshold calculation -- Enhanced validation error codes - -### ๐Ÿ”„ Compatibility Matrix - -| Client Version | Contract v1.0.x | Contract v0.9.x | Contract v0.8.x | -|----------------|-----------------|-----------------|------------------| -| Client v1.0.x | โœ… Full | โš ๏ธ Limited | โŒ Incompatible | -| Client v0.9.x | โš ๏ธ Limited | โœ… Full | โœ… Full | -| Client v0.8.x | โŒ Incompatible | โš ๏ธ Limited | โœ… Full | - -**Legend:** -- โœ… **Full**: Complete compatibility, all features supported -- โš ๏ธ **Limited**: Basic functionality works, some features unavailable -- โŒ **Incompatible**: Not supported, upgrade required - -### ๐Ÿš€ Upgrade Strategies - -#### For Contract Upgrades - -**1. Backward Compatible Updates (MINOR/PATCH)** -```bash -# Deploy new version alongside existing -soroban contract deploy \ - --wasm target/wasm32-unknown-unknown/release/predictify_hybrid_v1_1_0.wasm \ - --network mainnet - -# Update contract references gradually -# Old version continues to work -``` - -**2. Breaking Changes (MAJOR)** -```bash -# 1. Deploy new contract version -# 2. Migrate critical state (if supported) -# 3. Update all client applications -# 4. Deprecate old contract - -# Migration example -soroban contract invoke \ - --id $NEW_CONTRACT_ID \ - --fn migrate_from_v0 \ - --arg old_contract=$OLD_CONTRACT_ID -``` - -#### For Client Applications - -**JavaScript/TypeScript Example:** -```typescript -// Version-aware client initialization -const contractVersion = await getContractVersion(contractId); - -if (contractVersion.startsWith('1.0')) { - // Use v1.0 API - await contract.vote(marketId, outcome, stake); -} else if (contractVersion.startsWith('0.9')) { - // Use legacy API - await contract.submit_vote(marketId, outcome, stake); -} else { - throw new Error(`Unsupported contract version: ${contractVersion}`); -} -``` - -### ๐Ÿ“– API Documentation by Version - -#### Current API (v1.0.x) - -**Core Functions:** -- **Market Management**: `create_market()`, `extend_market()`, `resolve_market()` -- **Voting Operations**: `vote()`, `claim_winnings()` -- **Dispute System**: `dispute_market()`, `vote_on_dispute()` -- **Oracle Integration**: `submit_oracle_result()`, `update_oracle_config()` -- **Admin Functions**: `collect_fees()`, `update_config()`, `pause_contract()` - -**Data Structures:** -- `Market`: Core market data structure -- `Vote`: User vote representation -- `OracleConfig`: Oracle configuration -- `DisputeThreshold`: Dynamic dispute thresholds - -**Error Codes:** -- 100-199: User operation errors -- 200-299: Oracle errors -- 300-399: Validation errors -- 400-499: System errors - -#### Legacy API (v0.9.x) - -**Deprecated Functions:** -- `submit_vote()` โ†’ Use `vote()` in v1.0+ -- `create_prediction_market()` โ†’ Use `create_market()` in v1.0+ -- `get_market_stats()` โ†’ Use `get_market_analytics()` in v1.0+ - -### ๐Ÿ” Version Detection - -**Check Contract Version:** -```bash -# Using Soroban CLI -soroban contract invoke \ - --id $CONTRACT_ID \ - --fn get_version \ - --network mainnet -``` - -**JavaScript/TypeScript:** -```typescript -import { Contract } from '@stellar/stellar-sdk'; - -const getContractVersion = async (contractId: string): Promise => { - try { - const result = await contract.call('get_version'); - return result.toString(); - } catch (error) { - // Fallback for older contracts without version endpoint - return '0.9.0'; - } -}; -``` - -### ๐Ÿ›ก๏ธ Deprecation Policy - -**Timeline:** -- **Announcement**: 90 days before deprecation -- **Warning Period**: 60 days with deprecation warnings -- **End of Support**: 30 days notice before complete removal - -**Current Deprecations:** -- `submit_vote()`: Deprecated in v1.0.0, removal planned for v2.0.0 -- `create_prediction_market()`: Deprecated in v1.0.0, removal planned for v2.0.0 - -### ๐Ÿ“… Release Schedule - -**Planned Releases:** -- **v1.1.0** (Q2 2025): Enhanced analytics, batch operations -- **v1.2.0** (Q3 2025): Multi-token support, advanced oracles -- **v2.0.0** (Q4 2025): Complete API redesign, performance improvements - -### ๐Ÿ”— Version-Specific Resources - -**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) - -**Contract Addresses:** -- **v1.0.x Mainnet**: `CDLZFC3SYJYDZT7K67VZ75HPJVIEUVNIXF47ZG2FB2RMQQAHHAGK3HGU` -- **v0.9.x Mainnet**: `CBLZFC3SYJYDZT7K67VZ75HPJVIEUVNIXF47ZG2FB2RMQQAHHAGK3ABC` - -**Support Channels:** -- [GitHub Issues](https://github.com/predictify/contracts/issues) - Bug reports and feature requests -- [Discord #api-support](https://discord.gg/predictify) - Community support -- [Developer Forum](https://forum.predictify.io) - Technical discussions - ---- - -## ๐Ÿ”ง Core API Reference - -### Market Management Functions - -#### `create_market()` -Creates a new prediction market with specified parameters. - -**Signature:** -```rust -pub fn create_market( - env: Env, - admin: Address, - question: String, - outcomes: Vec, - duration_days: u32, - oracle_config: OracleConfig, -) -> Result -``` - -**Parameters:** -- `admin`: Market administrator address -- `question`: Market question (max 200 characters) -- `outcomes`: Possible outcomes (2-10 options) -- `duration_days`: Market duration (1-365 days) -- `oracle_config`: Oracle configuration for resolution - -**Returns:** Market ID (Symbol) - -**Example:** -```typescript -const marketId = await contract.create_market( - adminAddress, - "Will Bitcoin reach $100,000 by end of 2025?", - ["Yes", "No"], - 90, // 90 days - oracleConfig -); -``` - -#### `vote()` -Submit a vote on a market outcome with stake. - -**Signature:** -```rust -pub fn vote( - env: Env, - voter: Address, - market_id: Symbol, - outcome: String, - stake: i128, -) -> Result<(), Error> -``` - -**Parameters:** -- `voter`: Voter's address -- `market_id`: Target market ID -- `outcome`: Chosen outcome -- `stake`: Stake amount (minimum 0.1 XLM) - -**Example:** -```typescript -await contract.vote( - voterAddress, - "BTC_100K", - "Yes", - 5000000 // 0.5 XLM in stroops -); -``` - -#### `claim_winnings()` -Claim winnings from resolved markets. - -**Signature:** -```rust -pub fn claim_winnings( - env: Env, - user: Address, - market_id: Symbol, -) -> Result -``` - -**Returns:** Amount claimed in stroops - ---- - -## ๐Ÿ“Š Data Structures - -### Market -Core market data structure containing all market information. - -```rust -pub struct Market { - pub id: Symbol, - pub question: String, - pub outcomes: Vec, - pub creator: Address, - pub created_at: u64, - pub deadline: u64, - pub resolved: bool, - pub winning_outcome: Option, - pub total_stake: i128, - pub oracle_config: OracleConfig, -} -``` - -### Vote -Represents a user's vote on a market. - -```rust -pub struct Vote { - pub voter: Address, - pub market_id: Symbol, - pub outcome: String, - pub stake: i128, - pub timestamp: u64, - pub claimed: bool, -} -``` - -### OracleConfig -Configuration for oracle integration. - -```rust -pub struct OracleConfig { - pub provider: OracleProvider, - pub feed_id: String, - pub threshold: i128, - pub timeout_seconds: u64, -} -``` - ---- - -## โš ๏ธ Error Codes - -### User Operation Errors (100-199) -- **100**: `UserNotAuthorized` - User lacks required permissions -- **101**: `MarketNotFound` - Specified market doesn't exist -- **102**: `MarketClosed` - Market is closed for voting -- **103**: `InvalidOutcome` - Outcome not available for market -- **104**: `AlreadyVoted` - User has already voted on this market -- **105**: `NothingToClaim` - No winnings available to claim -- **106**: `MarketNotResolved` - Market resolution pending -- **107**: `InsufficientStake` - Stake below minimum requirement - -### Oracle Errors (200-299) -- **200**: `OracleUnavailable` - Oracle service unavailable -- **201**: `InvalidOracleConfig` - Oracle configuration invalid -- **202**: `OracleTimeout` - Oracle response timeout -- **203**: `OracleDataInvalid` - Oracle data format invalid - -### Validation Errors (300-399) -- **300**: `InvalidInput` - General input validation failure -- **301**: `InvalidMarket` - Market parameters invalid -- **302**: `InvalidVote` - Vote parameters invalid -- **303**: `InvalidDispute` - Dispute parameters invalid - -### System Errors (400-499) -- **400**: `ContractNotInitialized` - Contract requires initialization -- **401**: `AdminRequired` - Admin privileges required -- **402**: `ContractPaused` - Contract is paused -- **403**: `InsufficientBalance` - Account balance too low - ---- - -## ๐Ÿ’ก Integration Examples - -### Basic Market Creation and Voting - -```typescript -import { Contract, Keypair, Networks } from '@stellar/stellar-sdk'; - -// Initialize contract -const contract = new Contract(contractId); - -// Create market -const marketId = await contract.create_market( - adminKeypair.publicKey(), - "Will Ethereum reach $5,000 by Q2 2025?", - ["Yes", "No"], - 120, // 120 days - { - provider: "Reflector", - feed_id: "ETH/USD", - threshold: 5000000000, // $5,000 in stroops - timeout_seconds: 3600 - } -); - -// Vote on market -await contract.vote( - userKeypair.publicKey(), - marketId, - "Yes", - 10000000 // 1 XLM stake -); - -// Check market status -const market = await contract.get_market(marketId); -console.log(`Market: ${market.question}`); -console.log(`Total stake: ${market.total_stake} stroops`); - -// Claim winnings (after resolution) -const winnings = await contract.claim_winnings( - userKeypair.publicKey(), - marketId -); -console.log(`Claimed: ${winnings} stroops`); -``` - -### Batch Operations - -```typescript -// Create multiple markets -const markets = await Promise.all([ - contract.create_market(admin, "BTC > $100K?", ["Yes", "No"], 90, btcConfig), - contract.create_market(admin, "ETH > $5K?", ["Yes", "No"], 90, ethConfig), - contract.create_market(admin, "SOL > $200?", ["Yes", "No"], 90, solConfig) -]); - -// Vote on multiple markets -await Promise.all( - markets.map(marketId => - contract.vote(user, marketId, "Yes", 5000000) - ) -); -``` - ---- - -## ๐Ÿ†˜ Troubleshooting Guide - -### Common Issues and Solutions - -#### ๐Ÿ”ง Deployment Issues - -**Problem: Contract deployment fails with "Insufficient Balance"** -```bash -Error: Account has insufficient balance for transaction -``` -**Solution:** -```bash -# Check account balance -soroban config identity address -soroban balance --id --network mainnet - -# Fund account if needed (minimum 100 XLM recommended) -# Use Stellar Laboratory or send from funded account -``` - -**Problem: WASM file not found during deployment** -```bash -Error: No such file or directory: target/wasm32-unknown-unknown/release/predictify_hybrid.wasm -``` -**Solution:** -```bash -# Ensure contract is built first -cd contracts/predictify-hybrid -make build - -# Verify WASM file exists -ls -la target/wasm32-unknown-unknown/release/ -``` - -#### ๐Ÿ”ฎ Oracle Integration Issues - -**Problem: Oracle results not being accepted** -```rust -Error: InvalidOracleConfig (201) -``` -**Solution:** -```bash -# Verify oracle configuration -soroban contract invoke \ - --id $CONTRACT_ID \ - --fn get_oracle_config \ - --network mainnet - -# Update oracle configuration if needed -soroban contract invoke \ - --id $CONTRACT_ID \ - --fn update_oracle_config \ - --arg provider=Reflector \ - --arg feed_id="BTC/USD" \ - --network mainnet -``` - -**Problem: Oracle price feeds timing out** -```rust -Error: OracleUnavailable (200) -``` -**Solution:** -1. Check oracle service status -2. Verify network connectivity -3. Implement fallback oracle providers -4. Add retry logic with exponential backoff - -#### ๐Ÿ—ณ๏ธ Voting and Market Issues - -**Problem: User unable to vote** -```rust -Error: MarketClosed (102) -``` -**Solution:** -```bash -# Check market status and deadline -soroban contract invoke \ - --id $CONTRACT_ID \ - --fn get_market \ - --arg market_id="BTC_100K" \ - --network mainnet - -# Extend market if authorized and appropriate -soroban contract invoke \ - --id $CONTRACT_ID \ - --fn extend_market \ - --arg market_id="BTC_100K" \ - --arg additional_days=7 \ - --network mainnet -``` - -**Problem: Insufficient stake error** -```rust -Error: InsufficientStake (107) -``` -**Solution:** -```bash -# Check minimum stake requirements -echo "Minimum vote stake: 1,000,000 stroops (0.1 XLM)" -echo "Minimum dispute stake: 100,000,000 stroops (10 XLM)" - -# Verify user balance -soroban balance --id --network mainnet -``` - -#### ๐Ÿ›๏ธ Dispute Resolution Issues - -**Problem: Dispute submission rejected** -```rust -Error: DisputeVotingNotAllowed (406) -``` -**Solution:** -1. Verify market is in resolved state -2. Check dispute window timing (24-48 hours after resolution) -3. Ensure sufficient dispute stake -4. Verify user hasn't already disputed - -**Problem: Dispute threshold too high** -```rust -Error: ThresholdExceedsMaximum (412) -``` -**Solution:** -```bash -# Check current dispute threshold -soroban contract invoke \ - --id $CONTRACT_ID \ - --fn get_dispute_threshold \ - --arg market_id="BTC_100K" \ - --network mainnet - -# Admin can adjust if necessary -soroban contract invoke \ - --id $CONTRACT_ID \ - --fn update_dispute_threshold \ - --arg market_id="BTC_100K" \ - --arg new_threshold=50000000 \ - --network mainnet -``` - -#### ๐Ÿ’ฐ Fee and Payout Issues - -**Problem: Fee collection fails** -```rust -Error: NoFeesToCollect (415) -``` -**Solution:** -```bash -# Check if fees are available -soroban contract invoke \ - --id $CONTRACT_ID \ - --fn get_collectable_fees \ - --arg market_id="BTC_100K" \ - --network mainnet - -# Ensure market is resolved and fees haven't been collected -``` - -**Problem: User cannot claim winnings** -```rust -Error: NothingToClaim (105) -``` -**Solution:** -1. Verify user voted on winning outcome -2. Check market resolution status -3. Ensure user hasn't already claimed -4. Verify market dispute period has ended - -### ๐Ÿ” Debugging Tools - -#### Contract State Inspection -```bash -# Get complete market information -soroban contract invoke \ - --id $CONTRACT_ID \ - --fn get_market_analytics \ - --arg market_id="BTC_100K" \ - --network mainnet - -# Check user voting history -soroban contract invoke \ - --id $CONTRACT_ID \ - --fn get_user_votes \ - --arg user=
\ - --network mainnet - -# Inspect contract configuration -soroban contract invoke \ - --id $CONTRACT_ID \ - --fn get_config \ - --network mainnet -``` - -#### Transaction Analysis -```bash -# View transaction details -soroban events --id $CONTRACT_ID --network mainnet - -# Check specific transaction -soroban transaction --hash --network mainnet -``` - -#### Log Analysis -```bash -# Enable verbose logging -export RUST_LOG=debug - -# Run with detailed output -soroban contract invoke \ - --id $CONTRACT_ID \ - --fn vote \ - --arg market_id="BTC_100K" \ - --arg outcome="yes" \ - --arg stake=5000000 \ - --network mainnet \ - --verbose -``` - ---- - -## ๐Ÿ“ž Support and Resources - -### Error Code Reference -- **100-199**: User operation errors - Check user permissions and market state -- **200-299**: Oracle errors - Verify oracle configuration and connectivity -- **300-399**: Validation errors - Check input parameters and formats -- **400-499**: System errors - Contact support for system-level issues - -### Support Channels -1. **GitHub Issues**: [Report bugs and request features](https://github.com/predictify/contracts/issues) -2. **Discord Support**: [#technical-support channel](https://discord.gg/predictify) -3. **Developer Forum**: [Technical discussions](https://forum.predictify.io) -4. **Email Support**: technical-support@predictify.io - -### Before Contacting Support -1. Check this troubleshooting guide -2. Search existing GitHub issues -3. Verify your environment and configuration -4. Collect relevant error messages and transaction hashes -5. Note your contract version and network - -### Additional Resources -- [Stellar Soroban Documentation](https://soroban.stellar.org/) -- [Stellar SDK Documentation](https://stellar.github.io/js-stellar-sdk/) -- [Predictify GitHub Repository](https://github.com/predictify/contracts) -- [Community Examples](https://github.com/predictify/examples) - ---- - -**Last Updated:** 2025-01-15 -**API Version:** v1.0.0 -**Documentation Version:** 1.0 From 75fda9b35dd02fad6aa10467f1e2332fbe72b2dc Mon Sep 17 00:00:00 2001 From: 1nonlypiece Date: Sun, 10 Aug 2025 16:08:39 +0530 Subject: [PATCH 03/20] docs: move ATTACK-VECTORS.md to docs/security/ --- ATTACK-VECTORS.md | 43 ------------------------------------------- 1 file changed, 43 deletions(-) delete mode 100644 ATTACK-VECTORS.md diff --git a/ATTACK-VECTORS.md b/ATTACK-VECTORS.md deleted file mode 100644 index 9ca0abb0..00000000 --- a/ATTACK-VECTORS.md +++ /dev/null @@ -1,43 +0,0 @@ -# Analysis of Vector Analysis and Mitigation -This document highlights attack vectors with mitigations. - -## 1. SQL Injection -- A web security vulnerability that lets an attacker to change database of an organisation with malicious SQL queries injection. -- Using prepared statements and parameterized queries, can help in preventing SQL injection attacks. -- Using ORM(Object-Relational Mapping) Frameworks like Hibernate or Entity Framework can help in reducing SQL inject by default. - -## 2. Cross-Site Request Forgery(CSRF) -- The attacker exploits the trust of a web application with a authenticated user. -- The identity of the victim is used to perform some actions. -**Prevention**: -- Use an anti-CSRF token or synchronizer token. -- Add a CAPTCHA to validate that the use is human. - -## 3. Insecure API Access -- The application can run into broken authentication when APIs are not validated. -- When APIs get too nmany requests from user, resource limit problems can occur. Fake requests can be sent by attackers to the servers. - -**Prevention** -- Strong passwords implementation policy with two-step login can be implemented. -- Security standards can be applied to endpoints, like input validation, authentication, and authorization. - -## 4. Insider Threat -- Threats originating within an organisation. -- These threats can increase property thefts, data breach and disturbing operations. -**Prevention** -- Training to detect and stop insider threats. -- Regularly implementating montitorization and access reviews. - -## 5. Cross-Site Scripting(XSS) -- Malicious scripts are injected into trusted websites. -- Browser side script can be corrupted and send to different user. -**Prevention** -- Use approppriate headers, use Content-Type and X-Content-Type-Options, headers for interpretation of responses by the browsers. -- Use Content Security Policy(CSP) to prevent servere XSS vulnerabilities. - -## 6. Misconfiguration -- When security settings are not defined in the configuration, security Misconfiguration occurs. -- Directory Listing should not be enabled with not showing error messages which is sensitive information. -**Prevention** -- Regularly perform scans and identify security misconfigurations. -- Encryption of data at rest to prevent exploittaion of data. \ No newline at end of file From 85e0c0a6b268370ab7dd2b0abea14057084c5e42 Mon Sep 17 00:00:00 2001 From: 1nonlypiece Date: Sun, 10 Aug 2025 16:08:43 +0530 Subject: [PATCH 04/20] docs: move AUDIT_CHECKLIST.md to docs/security/ --- AUDIT_CHECKLIST.md | 21 --------------------- 1 file changed, 21 deletions(-) delete mode 100644 AUDIT_CHECKLIST.md diff --git a/AUDIT_CHECKLIST.md b/AUDIT_CHECKLIST.md deleted file mode 100644 index 0939be16..00000000 --- a/AUDIT_CHECKLIST.md +++ /dev/null @@ -1,21 +0,0 @@ -#Security Audit Checklist - -## Monthly Internal Review -- [] Implementation of strong passwords policies -- [] Rotation of Secrets -- [] Retaintion of logs and their collections -- [] Enabling of MFA of authorized users with privilege access -- [] Third party dependencies are scanned to check vulnerabilities -- [] Validation of acces controls and firewall - -## Quarterly External Audit -- [] Review user access -- [] Scann all endpoints to check vulnerabilites -- [] Review compilance with GDPR/HIPAA -- [] Conduct Penetration Tests - -## Audit Logs -- Access Control Audits -- Incident Response Capability Assesment -- Resource Access -- Admin Operations \ No newline at end of file From 921abecea0fe441b51154b5a4e0b5decc632c830 Mon Sep 17 00:00:00 2001 From: 1nonlypiece Date: Sun, 10 Aug 2025 16:08:49 +0530 Subject: [PATCH 05/20] docs: move SECURITY_BEST_PRACTICES.md to docs/security/ --- SECURITY_BEST_PRACTICES.md | 24 ------------------------ 1 file changed, 24 deletions(-) delete mode 100644 SECURITY_BEST_PRACTICES.md diff --git a/SECURITY_BEST_PRACTICES.md b/SECURITY_BEST_PRACTICES.md deleted file mode 100644 index cbf112be..00000000 --- a/SECURITY_BEST_PRACTICES.md +++ /dev/null @@ -1,24 +0,0 @@ -# Recommendations of Security and Best Practices - -## Code Practices -- Use OWASP Application Security Verification Standard(ASVS) for the verification of security controls -- Implement servers and frameworks are running on latest versions. -- Encrypt highly sensitive information(authentication verification data) - -## Infrastucture -- Monitor networks and update software and hardware regularly -- Use Web Application Firewall(WAF) that monitors HTTP traffic across Internet and blocks vulnerabilities. - -## Updates -- Perform regular updates for libraries -- Use auto-scanning tools like Synk - -## Access Control -- Principle of Least Priviledge(PoLP) ensures authorized users can execute jobs within the system. -- Roles based access towards some operations. - -## Authentication -- Implementing strong password policies with rotation -- Implementing Multi-Factor Authentication(MFA) -- User tokens implemented during login form - From 0687e443531f4055e4dc4e0ea87a434a2bde6041 Mon Sep 17 00:00:00 2001 From: 1nonlypiece Date: Sun, 10 Aug 2025 16:08:53 +0530 Subject: [PATCH 06/20] docs: move SECURITY_CONSIDERATIONS.md to docs/security/ --- SECURITY_CONSIDERATIONS.md | 52 -------------------------------------- 1 file changed, 52 deletions(-) delete mode 100644 SECURITY_CONSIDERATIONS.md diff --git a/SECURITY_CONSIDERATIONS.md b/SECURITY_CONSIDERATIONS.md deleted file mode 100644 index 1c1f39ad..00000000 --- a/SECURITY_CONSIDERATIONS.md +++ /dev/null @@ -1,52 +0,0 @@ -#Security Considerations - -This document highlights the important security concerns and protection strategies for the system. - -## 1. Data Classification and it's Sensitivity -Implementing a data classification property -There are different types of data categories: -- Financial Data -- Intellectual Data -- Confidential Business Data -- Personal Identifiable Information -- Proprietary Data -- Health Information - -Data classification based on sensitivity -- Public- Data can be accesed by public and free to access. -- Confidential - Data can accesed by authorized individuals, and highly protected data. -- Highly Confidential- Data is highly rescricted to acces and utmost confidentiality -- Internal: Data that can be shared only within an organization, which is private - -## 2. Implementation of Encrytion - -- Only authorized individuals can access data which is sensitive. -- Implementation of role-based access controls(RBAC) for permitting privileges based on roles and responsibilites. -- Implementating a multi-factor authentication(MFA) for adding extra layer of security for access control. -- For encrypting data during transmission, encryption mechanisms such as Secure Socket Layer(SSL) or Transport Layer Security(TLS) protocols can be added. - -## 3. Data Encryption -- Transit Data Encrytion: Data moving from one point to another, with internet or VPN. - -- Data Encryption at Rest: More secure and less data breach, less randsomeware attacks. - -- Key Management Policy protects the sensitive data with processing cryptographic keys, with key generation and storage of keys. - -## 4. Data Encrytion Algorithms -- The Advanced Encryption Standard(AES) is a symmetric-key algorithm. This employs block cipher methods. - -- The latest version of the TLS protocol is TLS 1.3. Modern version of SSL, utilized by HTTPS and other protocols for encryption. - -- Key rotation and retiring old keys with regularly updation of keys. - -## 5. Security practices for third party dependencies -- Implementating tools like Synk or OWASP Dependency-Check with regularly scanning dependencies. - -- Minimize risk posed by dependencies with isolation menthods: containerization, microservices architecture, and restricted permissions. - -- Keeping updated libraries for security. Manual reviews are important for compatibility. - -## 6. Regulatory Compilance -- HIPAA: Health Insurance Portability and Accountability Act maintains standards to protect sensitive health information from disclosure without patient's consent. - -- GDPR: General Data Protection Regulation permits individuals the right to ask organisations to delete their personal data. \ No newline at end of file From e976e46d84567ecdfc710d9ea5ff5a99ea5f67a8 Mon Sep 17 00:00:00 2001 From: 1nonlypiece Date: Sun, 10 Aug 2025 16:08:57 +0530 Subject: [PATCH 07/20] docs: move SECURITY_TESTING_GUIDE.md to docs/security/ --- SECURITY_TESTING_GUIDE.md | 18 ------------------ 1 file changed, 18 deletions(-) delete mode 100644 SECURITY_TESTING_GUIDE.md diff --git a/SECURITY_TESTING_GUIDE.md b/SECURITY_TESTING_GUIDE.md deleted file mode 100644 index ef45e3c2..00000000 --- a/SECURITY_TESTING_GUIDE.md +++ /dev/null @@ -1,18 +0,0 @@ -# Security Test Guide - -## 1. Dependency Scanning -- Regularly check for source-code files with changes -- Check for compatibility and resolve performance issues - -## 2. Penetration Testing -- Use Kali Linux and Burp Suite to identify vulnerabilities -- Use Wireshark to check network traffic - -## 3. Dynamic Application Security Testing(DASP) -- DASP tools are used for identifying security misconfiguration, broken authentication and input/output validation -- ZED Attack Proxy is an open source tool for security testing provided by OWASP - -## 4. Static Application Security Testing(SAST) -- Tools help in detecting SQL injections,and other vulnerabilities -- SonarQube, Fortify are commonly used tools -- Integrate with IDEs and CI/CD pipelines From c22d8ab69b8b85b677406d22401158dff15e74af Mon Sep 17 00:00:00 2001 From: 1nonlypiece Date: Sun, 10 Aug 2025 16:09:01 +0530 Subject: [PATCH 08/20] docs: move GAS_BENCHMARKING.md to docs/gas/ --- GAS_BENCHMARKING.md | 58 --------------------------------------------- 1 file changed, 58 deletions(-) delete mode 100644 GAS_BENCHMARKING.md diff --git a/GAS_BENCHMARKING.md b/GAS_BENCHMARKING.md deleted file mode 100644 index a2eeec28..00000000 --- a/GAS_BENCHMARKING.md +++ /dev/null @@ -1,58 +0,0 @@ -## Gas Cost Benchmarking Procedures - -Goal: produce reproducible cost metrics per entrypoint across typical scenarios and catch regressions. - -### Tools - -- Stellar CLI (`stellar`) with `--cost` -- RPC simulateTransaction (client SDKs) - -### Build - -```bash -stellar contract build -``` - -### Local Simulation (recommended) - -- Use `stellar contract invoke --cost` (or `tx simulate`) to print execution cost breakdown before submit. -- For each function, craft inputs for small/medium/large cases. - -Example (pseudocode; replace ids/args): - -```bash -# Simulate vote cost -stellar contract invoke --id $CONTRACT_ID \ - --network futurenet --cost -- \ - vote --user $USER --market-id market_1 --outcome Yes --stake 1000 -``` - -Capture output (instructions, ledger read/write counts, bytes) into `benchmarks/results/*.csv`. - -### RPC Simulation (programmatic) - -- Use SDKs to build a tx that invokes the function and call `simulateTransaction`. -- Record `resourceFee`, `cpuInsns`, `readBytes`, `writeBytes`, `readEntries`, `writeEntries`, and events/return sizes. - -### Scenarios to Benchmark - -- create_market: short vs long question/outcomes -- vote: single voter; 100 voters; 1,000 voters -- claim_winnings: winner vs loser; large market iteration -- resolve_market: with/without oracle result, with disputes -- fetch_oracle_result: Reflector vs Pyth paths -- collect_fees: resolved vs unresolved - -### WASM Size Optimization - -```bash -stellar contract optimize --wasm target/wasm32v1-none/release/predictify_hybrid.wasm -``` - -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). - From a60c0d3205a6ee97497a2e6d6b0cf2a7c76db156 Mon Sep 17 00:00:00 2001 From: 1nonlypiece Date: Sun, 10 Aug 2025 16:09:06 +0530 Subject: [PATCH 09/20] docs: move GAS_CASE_STUDIES.md to docs/gas/ --- GAS_CASE_STUDIES.md | 51 --------------------------------------------- 1 file changed, 51 deletions(-) delete mode 100644 GAS_CASE_STUDIES.md diff --git a/GAS_CASE_STUDIES.md b/GAS_CASE_STUDIES.md deleted file mode 100644 index 2052f7fc..00000000 --- a/GAS_CASE_STUDIES.md +++ /dev/null @@ -1,51 +0,0 @@ -## Gas Optimization Case Studies (Predictify Hybrid) - -### 1) Voting: Avoid per-iteration storage access - -Issue: Repeated `.get()`/`.set()` inside loops increases read/write entries. - -Fix: Read market once, update in-memory, write once. - -See the `vote` implementation which already batches to a single final write: - -```302:308:contracts/predictify-hybrid/src/lib.rs -market.votes.set(user.clone(), outcome); -market.stakes.set(user.clone(), stake); -market.total_staked += stake; -env.storage().persistent().set(&market_id, &market); -``` - -Further improvement: Pre-validate `outcome` using an in-memory set if outcomes are large to avoid repeated scans. - -### 2) Claiming: Scale with participants carefully - -Current approach iterates all votes to compute `winning_total`: - -```395:404:contracts/predictify-hybrid/src/lib.rs -let mut winning_total = 0; -for (voter, outcome) in market.votes.iter() { - if &outcome == winning_outcome { - winning_total += market.stakes.get(voter.clone()).unwrap_or(0); - } -} -``` - -Optimizations: - -- Maintain `stakes_per_outcome` totals during `vote` to avoid O(n) scan at claim time. -- Consider a compact bitmap/flag for `claimed` to reduce map overhead. - -### 3) Market Creation: Bound string sizes - -Cost driver: `question` and `outcomes` lengths inflate write-bytes. - -Guideline: Enforce caps (e.g., 140/32 chars). Reject overlong inputs to protect fees. - -### 4) Oracle Resolution: Validate before calling - -Call the cheapest checks first (staleness, feed format) before cross-contract calls. Skip persistence until a valid result is known. - -### 5) Events over Storage - -Emit events for analytics (e.g., vote tally changes) and only persist aggregates needed for on-chain reads. - From 252a5735e177d6ac41e868c095882f5c989e5123 Mon Sep 17 00:00:00 2001 From: 1nonlypiece Date: Sun, 10 Aug 2025 16:09:10 +0530 Subject: [PATCH 10/20] docs: move GAS_COST_ANALYSIS.md to docs/gas/ --- GAS_COST_ANALYSIS.md | 131 ------------------------------------------- 1 file changed, 131 deletions(-) delete mode 100644 GAS_COST_ANALYSIS.md diff --git a/GAS_COST_ANALYSIS.md b/GAS_COST_ANALYSIS.md deleted file mode 100644 index fc77611b..00000000 --- a/GAS_COST_ANALYSIS.md +++ /dev/null @@ -1,131 +0,0 @@ -## Gas Usage Analysis (Function Catalog) - -This document catalogs public entrypoints in `predictify-hybrid` and provides a structure to record gas usage characteristics and measured costs. Use the benchmarking guide to populate the "Measured Cost" columns. - -### Method Inventory - -- initialize(env, admin) -- create_market(env, admin, question, outcomes, duration_days, oracle_config) -> Symbol -- vote(env, user, market_id, outcome, stake) -- claim_winnings(env, user, market_id) -- get_market(env, market_id) -> Option -- fetch_oracle_result(env, market_id, oracle_contract) -> Result -- resolve_market(env, market_id) -> Result<(), Error> -- get_resolution_analytics(env) -> Result -- get_market_analytics(env, market_id) -> Result -- dispute_market(env, user, market_id, stake, reason) -> Result<(), Error> -- vote_on_dispute(env, user, market_id, dispute_id, vote, stake, reason) -> Result<(), Error> -- resolve_dispute(env, admin, market_id) -> Result -- collect_fees(env, admin, market_id) -> Result -- extend_market(env, admin, market_id, additional_days, reason, fee_amount) -> Result<(), Error> -- Storage optimization helpers (compress/cleanup/migrate/monitor/optimize/...) - -### Storage Touch Patterns (selected excerpts) - -Vote path writes a vote and stake, updates totals, and persists market: - -```275:308:contracts/predictify-hybrid/src/lib.rs -// vote(...) -// ... -// Store the vote and stake -market.votes.set(user.clone(), outcome); -market.stakes.set(user.clone(), stake); -market.total_staked += stake; - -env.storage().persistent().set(&market_id, &market); -``` - -Market creation allocates a new `Market` with several empty maps and persists once: - -```183:221:contracts/predictify-hybrid/src/lib.rs -// create_market(...) -// Generate ID, compute end_time, then -let market = Market { - // ... - oracle_result: None, - votes: Map::new(&env), - total_staked: 0, - dispute_stakes: Map::new(&env), - stakes: Map::new(&env), - claimed: Map::new(&env), - winning_outcome: None, - fee_collected: false, - state: MarketState::Active, - total_extension_days: 0, - max_extension_days: 30, - extension_history: Vec::new(&env), -}; -env.storage().persistent().set(&market_id, &market); -``` - -Claim path iterates to compute `winning_total` and marks `claimed`: - -```395:419:contracts/predictify-hybrid/src/lib.rs -// claim_winnings(...) -// Calculate total winning stakes -let mut winning_total = 0; -for (voter, outcome) in market.votes.iter() { - if &outcome == winning_outcome { - winning_total += market.stakes.get(voter.clone()).unwrap_or(0); - } -} -// Mark as claimed -market.claimed.set(user.clone(), true); -env.storage().persistent().set(&market_id, &market); -``` - -### Analysis Template - -Fill per method after running benchmarks (see GAS_BENCHMARKING.md): - -- initialize - - Reads: 0-1 (admin guard if re-init) - - Writes: 1 (Admin key) - - Bytes written (est.): small - - Measured: instructions=โ€ฆ, r-entries=โ€ฆ, w-entries=โ€ฆ, rKB=โ€ฆ, wKB=โ€ฆ - -- create_market - - Reads: 1 (admin) - - Writes: 2 (counter, market) - - Bytes drivers: `question`, `outcomes` length - - Risks: long strings blow write-bytes; validate lengths - - Measured: โ€ฆ - -- vote - - Reads: 1 (market) - - Writes: 1 (market) - - Map ops: votes.set, stakes.set - - Loop: none - - Measured: โ€ฆ - -- claim_winnings - - Reads: 1 (market) - - Writes: 1 (market) - - Loop: iterates `votes` (cost scales with voters) - - Optimization: accumulate and cache totals off-chain; filter losers early - - Measured: โ€ฆ - -- fetch_oracle_result - - Reads: 1 (market) - - Cross-contract: yes (oracle) - - Writes: 0 (this method returns result only) - - Measured: โ€ฆ - -- resolve_market - - Likely reads+writes market; hybrid algorithm cost scales with votes - - Measured: โ€ฆ - -- collect_fees / extend_market / dispute* - - Admin read, market write patterns - - Measured: โ€ฆ - -### Length Limits to Enforce (to control write-bytes) - -- `question`: recommend <= 140 chars -- `outcomes[i]`: recommend <= 32 chars -- `reason` fields: recommend <= 160 chars - -### Recording Results - -Record CLI `--cost` outputs and RPC simulation breakdowns in a CSV under `benchmarks/results/` for each function and typical scenarios (small/medium/large markets). - From e0995971fe80f32fb2c9c06d01d20516dbe2c035 Mon Sep 17 00:00:00 2001 From: 1nonlypiece Date: Sun, 10 Aug 2025 16:09:15 +0530 Subject: [PATCH 11/20] docs: move GAS_MONITORING.md to docs/gas/ --- GAS_MONITORING.md | 31 ------------------------------- 1 file changed, 31 deletions(-) delete mode 100644 GAS_MONITORING.md diff --git a/GAS_MONITORING.md b/GAS_MONITORING.md deleted file mode 100644 index cf746dcd..00000000 --- a/GAS_MONITORING.md +++ /dev/null @@ -1,31 +0,0 @@ -## Gas Usage Monitoring and Operations - -### Pre-Submit Simulation - -- Always simulate and log `--cost` before sending transactions. -- Use RPC `getFeeStats()` to set inclusion fee (p90 recommended under load). - -### Metrics to Track - -- Distribution of resource fees per function -- Average read/write entries and bytes per function -- Event+return sizes (aim << 8 KB cap) -- Oracle call failure rates and retries - -### Alerting - -- Spike in write-bytes or write-entries -- Repeated tx failures due to under-estimated event/return size -- Inclusion fee surge vs baseline - -### Dashboards - -- Per-endpoint cost over time -- Top costly calls and scenarios -- WASM size trend per release - -### Operational Playbooks - -- If costs climb due to strings: enforce length caps at API layer and/or contract validation. -- If claim/resolve costs spike: batch payouts off-chain via token escrows or staged claims. - From d575d651bfd4e2ab38d21b22f80b5e6a87c1894e Mon Sep 17 00:00:00 2001 From: 1nonlypiece Date: Sun, 10 Aug 2025 16:09:19 +0530 Subject: [PATCH 12/20] docs: move GAS_OPTIMIZATION.md to docs/gas/ --- GAS_OPTIMIZATION.md | 88 --------------------------------------------- 1 file changed, 88 deletions(-) delete mode 100644 GAS_OPTIMIZATION.md diff --git a/GAS_OPTIMIZATION.md b/GAS_OPTIMIZATION.md deleted file mode 100644 index e3517b48..00000000 --- a/GAS_OPTIMIZATION.md +++ /dev/null @@ -1,88 +0,0 @@ -## Gas Optimization Guide (Soroban on Stellar) - -This guide explains how to write and maintain gas-efficient Soroban contracts in this repository, with concrete recommendations mapped to `predictify-hybrid` and `hello-world`. - -- Audience: Contract developers and reviewers -- Targets: Soroban SDK 22.x; built with wasm32v1-none - -### Key Facts (Resource Limits & Fees) - -- Max per-tx: 100M CPU instructions, 40 MB memory -- Ledger access limits: 40 reads, 25 writes; 200 KB read bytes; ~129 KB write bytes -- Fee highlights (stroops): - - 10,000 instructions: 25 - - Read 1 ledger entry: 6,250; Write 1 ledger entry: 10,000 - - Read 1 KB: 1,786; Write 1 KB: ~11,800 - - Events+return value: 10,000 per KB (up to 8 KB total) - - Bandwidth: 1,624/KB, History archival: 16,235/KB - -Reference: "Resource Limits & Fees" in Stellar docs. - -### Golden Rules - -- Prefer computation over storage. Reads/writes dominate costs; batch and cache in-memory. -- Read once, write once. Accumulate updates in memory, then persist once at end. -- Avoid per-iteration storage access inside loops. Pull state once, work in `Vec`/`Map`, write once. -- Keep data narrow. Use `Symbol`, `BytesN`, and compact enums/keys; avoid long `String` values. -- Emit events for audit-only data; store only what must be read on-chain later. -- Minimize cross-contract calls. They expand footprint, auth, and costs; batch where feasible. -- Validate inputs early and fail fast. Guard clauses save CPU and storage. -- Use fixed-size math and checked ops where possible; avoid unnecessary big-int math. -- Favor `Vec`/`Map` keyed by compact enums over wide maps with long keys. -- Keep return values small; event+return budget is capped at 8 KB. - -### Patterns for Soroban - -- Use `env.storage().persistent()` for durable state; consider `temporary()` for short-lived, re-creatable data. -- For lists, keep per-address collections keyed by an enum data key, not one giant vector of structs. -- Bundle external token/oracle transfers: one total transfer into the contract, then internal distributions. -- Avoid growing WASM linear memory repeatedly (e.g., large heap vec); pre-size or use small batches. - -### Contract-Specific Hotspots - -- `vote` and staking accrual: Favor in-memory aggregation; avoid repeated map lookups/sets. -- `claim_winnings`: Compute totals in-stream and avoid re-reading maps repeatedly; short-circuit losers early. -- `create_market`: Validate and compute once; store a compact `Market` struct; avoid overlong strings. -- Oracle resolution: Keep payloads compact, validate staleness and confidence before persisting. - -### Data Layout Recommendations - -- Keys: Use `Symbol`-based keys or small enums for storage keys. -- Strings: Restrict question/outcome lengths; validate length to prevent excess write bytes. -- Maps: Avoid nested maps when a single flat map of compact keys suffices. - -### Events vs Storage - -- Emit events for analytics/telemetry and off-chain consumption. -- Store only state needed for on-chain reads (e.g., current totals, winner, claims bitmap/flags). - -### Build & Profile Tips - -- Use `profile.release` with `opt-level = "z"`, `lto = true`, `panic = "abort"` (already configured). -- Run cost simulations with CLI `--cost` and RPC `simulateTransaction` before submitting. -- Keep function return values and emitted events small. - -### Safe Math - -- Keep `overflow-checks = true` (already set). Prefer `checked_*` for user-driven arithmetic. -- Normalize precision early (e.g., cents) and avoid repeated scaling. - -### Storage TTL and Rent - -- Prefer temporary storage for short-lived data; extend TTL intentionally for persistent data. -- Avoid frequent size growth of entries; growing entries triggers higher rent top-ups. - -### Code Review Checklist (Gas) - -- Are storage reads/writes minimized and batched? -- Any loops calling storage or cross-contract functions per iteration? -- Are keys and values compact? Any unbounded strings or vectors? -- Are external calls minimized, batched, and gated by pre-checks? -- Do functions fail early on invalid inputs to save CPU/storage? -- Are events used instead of storage where on-chain reads arenโ€™t required? - -### References - -- Stellar Docs: Analyzing smart contract cost and efficiency -- Stellar Docs: Resource Limits & Fees - From f2ca0621a2a6c6a7deb5c030aa60e185d4c34d13 Mon Sep 17 00:00:00 2001 From: 1nonlypiece Date: Sun, 10 Aug 2025 16:09:24 +0530 Subject: [PATCH 13/20] docs: move GAS_TESTING_GUIDELINES.md to docs/gas/ --- GAS_TESTING_GUIDELINES.md | 32 -------------------------------- 1 file changed, 32 deletions(-) delete mode 100644 GAS_TESTING_GUIDELINES.md diff --git a/GAS_TESTING_GUIDELINES.md b/GAS_TESTING_GUIDELINES.md deleted file mode 100644 index 2a346d21..00000000 --- a/GAS_TESTING_GUIDELINES.md +++ /dev/null @@ -1,32 +0,0 @@ -## Gas Optimization Testing Guidelines - -Objective: ensure PRs do not introduce significant cost regressions and follow best practices. - -### Unit Tests - -- Cover all public entrypoints with valid and invalid inputs (fail fast saves gas). -- Include large-market tests (e.g., many voters) to catch algorithmic costs. - -### Snapshot-Based Validation - -- For stable scenarios, snapshot CLI `--cost` outputs and diff on PRs. -- Store under `test_snapshots/cost/` with scenario descriptions. - -### Lints and Review - -- Review loops for storage/cross-contract calls per iteration. -- Check for repeated `.get()`/`.set()` rather than single read/single write patterns. -- Ensure strings/bytes sizes are validated. - -### PR Checklist (Gas) - -- [ ] Storage ops minimized and batched -- [ ] No per-iteration storage writes in loops -- [ ] External calls minimized/batched -- [ ] Return/events payloads small -- [ ] Enforced input length caps - -### Optional Static Analysis - -- Consider running a Soroban-focused analyzer to detect storage-in-loop and repeated indirect storage access patterns. - From 82d8a06cfb4df9f0f89d2ae6377cac33d5cc9f99 Mon Sep 17 00:00:00 2001 From: 1nonlypiece Date: Sun, 10 Aug 2025 16:09:29 +0530 Subject: [PATCH 14/20] docs: move GAS_TROUBLESHOOTING.md to docs/gas/ --- GAS_TROUBLESHOOTING.md | 27 --------------------------- 1 file changed, 27 deletions(-) delete mode 100644 GAS_TROUBLESHOOTING.md diff --git a/GAS_TROUBLESHOOTING.md b/GAS_TROUBLESHOOTING.md deleted file mode 100644 index 4befe792..00000000 --- a/GAS_TROUBLESHOOTING.md +++ /dev/null @@ -1,27 +0,0 @@ -## Gas Optimization Troubleshooting - -### Symptom: Transactions fail with insufficient fee or cost - -- Cause: Under-estimated events/return size or large write bytes. -- Fix: Increase refundable events/return budget on client; enforce input size caps. - -### Symptom: Cost spikes on claims/resolution - -- Cause: O(n) scans over voters; growing maps. -- Fix: Maintain per-outcome aggregates; paginate or stage claims. - -### Symptom: Reaching read/write entry limits - -- Cause: Too many storage keys touched per call. -- Fix: Normalize layout; merge maps; reduce per-user keys. - -### Symptom: Large WASM or linear memory grows - -- Cause: Big heap vecs; heavy deps. -- Fix: Pre-size small arrays; remove unused deps; run `stellar contract optimize`. - -### Symptom: Cross-contract call errors inflate retries - -- Cause: Oracle/Token contract misconfig or network flakiness. -- Fix: Validate addresses and pre-checks; implement fallback path; cache results if acceptable. - From 1b0afff77630339a2a8c92009cda37758116fed8 Mon Sep 17 00:00:00 2001 From: 1nonlypiece Date: Sun, 10 Aug 2025 16:09:34 +0530 Subject: [PATCH 15/20] docs: move INCIDENT_RESPONSE.md to docs/operations/ --- INCIDENT_RESPONSE.md | 50 -------------------------------------------- 1 file changed, 50 deletions(-) delete mode 100644 INCIDENT_RESPONSE.md diff --git a/INCIDENT_RESPONSE.md b/INCIDENT_RESPONSE.md deleted file mode 100644 index 590accb2..00000000 --- a/INCIDENT_RESPONSE.md +++ /dev/null @@ -1,50 +0,0 @@ -This documentation helps in detecting incident response procedures, provides insights for security monitoring and security updates process - -## 1. Detection -- Alerts for traffic patterns -- Look for inappropriate user behavior or requests - -## 2. Containment -- Isolation od affected systems and revoke access tokens and secrets -- Disable accounts affected - -## 3. Eradication -- Detect for malicious code and patch the exploited vulnerability with clearing of logs - -## 4. Recovery -- Keep backup for recovery - -## 5. Post-Incident Review -- Documentation of incident and prevention -- Notfication to regulatory bodies during a security breach - -# Guidelines for Security Monitoring - -## Metrices to watch -- Look for unauthorised access endpoints -- Increase in user requests -- Failure in Login continuously - -## Log Retention Policies -- Regularly check for logs and monitor them - -## Tools and Frameworks -- Use tools like Datadog, Splunk, and ELK stack - -## Montoring Targets -- Look for admin activities -- Health of system and access to database and authentications details - -# Procedures for Security Updates - -## Regular Updates -- Patching of OS and Apps regularly -- Merge dependencies with low risks - -## Post-Update Verification -- Monitor for anamolies everyday -- Validation of Configuration - -## Communication -- Notification of critical updates to security teams - From 2591dda57a72a6013fb6334285e1c01651960b8a Mon Sep 17 00:00:00 2001 From: 1nonlypiece Date: Sun, 10 Aug 2025 16:09:43 +0530 Subject: [PATCH 16/20] docs: update README.md to reference new organized documentation structure --- README.md | 35 ++++++++++++++--------------------- 1 file changed, 14 insertions(+), 21 deletions(-) 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. --- From 6082c0471edeab5ac6a8ac9ccae51fc2e657434c Mon Sep 17 00:00:00 2001 From: 1nonlypiece Date: Sun, 10 Aug 2025 16:13:48 +0530 Subject: [PATCH 17/20] docs: add contracts documentation directory with TYPES_SYSTEM.md and VOTING_SYSTEM.md --- docs/contracts/TYPES_SYSTEM.md | 541 ++++++++++++++++++++++++++++++++ docs/contracts/VOTING_SYSTEM.md | 412 ++++++++++++++++++++++++ 2 files changed, 953 insertions(+) create mode 100644 docs/contracts/TYPES_SYSTEM.md create mode 100644 docs/contracts/VOTING_SYSTEM.md diff --git a/docs/contracts/TYPES_SYSTEM.md b/docs/contracts/TYPES_SYSTEM.md new file mode 100644 index 00000000..2b54f3cd --- /dev/null +++ b/docs/contracts/TYPES_SYSTEM.md @@ -0,0 +1,541 @@ +# Predictify Hybrid Types System + +## Overview + +The Predictify Hybrid contract now features a comprehensive, organized type system that centralizes all data structures and provides better organization, validation, and maintainability. This document outlines the architecture, usage patterns, and best practices for working with the types system. + +## Architecture + +### Type Categories + +Types are organized into logical categories for better understanding and maintenance: + +1. **Oracle Types** - Oracle providers, configurations, and data structures +2. **Market Types** - Market data structures and state management +3. **Price Types** - Price data and validation structures +4. **Validation Types** - Input validation and business logic types +5. **Utility Types** - Helper types and conversion utilities + +### Core Components + +#### 1. Oracle Types + +**OracleProvider Enum** +```rust +pub enum OracleProvider { + BandProtocol, + DIA, + Reflector, + Pyth, +} +``` + +**OracleConfig Struct** +```rust +pub struct OracleConfig { + pub provider: OracleProvider, + pub feed_id: String, + pub threshold: i128, + pub comparison: String, +} +``` + +#### 2. Market Types + +**Market Struct** +```rust +pub struct Market { + pub admin: Address, + pub question: String, + pub outcomes: Vec, + pub end_time: u64, + pub oracle_config: OracleConfig, + // ... other fields +} +``` + +#### 3. Price Types + +**PythPrice Struct** +```rust +pub struct PythPrice { + pub price: i128, + pub conf: u64, + pub expo: i32, + pub publish_time: u64, +} +``` + +**ReflectorPriceData Struct** +```rust +pub struct ReflectorPriceData { + pub price: i128, + pub timestamp: u64, +} +``` + +## Usage Patterns + +### 1. Creating Oracle Configurations + +```rust +use types::{OracleProvider, OracleConfig}; + +let oracle_config = OracleConfig::new( + OracleProvider::Pyth, + String::from_str(&env, "BTC/USD"), + 2500000, // $25,000 threshold + String::from_str(&env, "gt"), // greater than +); + +// Validate the configuration +oracle_config.validate(&env)?; +``` + +### 2. Creating Markets + +```rust +use types::{Market, OracleConfig, OracleProvider}; + +let market = Market::new( + &env, + admin, + question, + outcomes, + end_time, + oracle_config, +); + +// Validate market parameters +market.validate(&env)?; +``` + +### 3. Market State Management + +```rust +use types::MarketState; + +let state = MarketState::from_market(&market, current_time); + +if state.is_active() { + // Market is accepting votes +} else if state.has_ended() { + // Market has ended +} else if state.is_resolved() { + // Market is resolved +} +``` + +### 4. Oracle Result Handling + +```rust +use types::OracleResult; + +let result = OracleResult::price(2500000); + +if result.is_available() { + if let Some(price) = result.get_price() { + // Use the price + } +} +``` + +## Type Validation + +### Built-in Validation + +All types include built-in validation methods: + +```rust +// Oracle configuration validation +oracle_config.validate(&env)?; + +// Market validation +market.validate(&env)?; + +// Price validation +pyth_price.validate()?; +``` + +### Validation Helpers + +The types module provides validation helper functions: + +```rust +use types::validation; + +// Validate oracle provider +validation::validate_oracle_provider(&OracleProvider::Pyth)?; + +// Validate price +validation::validate_price(2500000)?; + +// Validate stake +validation::validate_stake(stake, min_stake)?; + +// Validate duration +validation::validate_duration(30)?; +``` + +## Type Conversion + +### Conversion Helpers + +```rust +use types::conversion; + +// Convert string to oracle provider +let provider = conversion::string_to_oracle_provider("pyth") + .ok_or(Error::InvalidOracleConfig)?; + +// Convert oracle provider to string +let provider_name = conversion::oracle_provider_to_string(&provider); + +// Validate comparison operator +conversion::validate_comparison(&comparison, &env)?; +``` + +## Market Operations + +### Market State Queries + +```rust +// Check if market is active +if market.is_active(current_time) { + // Accept votes +} + +// Check if market has ended +if market.has_ended(current_time) { + // Resolve market +} + +// Check if market is resolved +if market.is_resolved() { + // Allow claims +} +``` + +### User Operations + +```rust +// Get user's vote +let user_vote = market.get_user_vote(&user); + +// Get user's stake +let user_stake = market.get_user_stake(&user); + +// Check if user has claimed +let has_claimed = market.has_user_claimed(&user); + +// Get user's dispute stake +let dispute_stake = market.get_user_dispute_stake(&user); +``` + +### Market Modifications + +```rust +// Add vote and stake +market.add_vote(user, outcome, stake); + +// Add dispute stake +market.add_dispute_stake(user, stake); + +// Mark user as claimed +market.mark_claimed(user); + +// Set oracle result +market.set_oracle_result(result); + +// Set winning outcome +market.set_winning_outcome(outcome); + +// Mark fees as collected +market.mark_fees_collected(); +``` + +### Market Calculations + +```rust +// Get total dispute stakes +let total_disputes = market.total_dispute_stakes(); + +// Get winning stake total +let winning_total = market.winning_stake_total(); +``` + +## Oracle Integration + +### Oracle Provider Support + +```rust +// Check if provider is supported +if oracle_provider.is_supported() { + // Use the provider +} + +// Get provider name +let name = oracle_provider.name(); + +// Get default feed format +let format = oracle_provider.default_feed_format(); +``` + +### Oracle Configuration + +```rust +// Check comparison operators +if oracle_config.is_greater_than(&env) { + // Handle greater than comparison +} else if oracle_config.is_less_than(&env) { + // Handle less than comparison +} else if oracle_config.is_equal_to(&env) { + // Handle equal to comparison +} +``` + +## Price Data Handling + +### Pyth Price Data + +```rust +let pyth_price = PythPrice::new(2500000, 1000, -2, timestamp); + +// Get price in cents +let price_cents = pyth_price.price_in_cents(); + +// Check if price is stale +if pyth_price.is_stale(current_time, max_age) { + // Handle stale price +} + +// Validate price data +pyth_price.validate()?; +``` + +### Reflector Price Data + +```rust +let reflector_price = ReflectorPriceData::new(2500000, timestamp); + +// Get price in cents +let price_cents = reflector_price.price_in_cents(); + +// Check if price is stale +if reflector_price.is_stale(current_time, max_age) { + // Handle stale price +} + +// Validate price data +reflector_price.validate()?; +``` + +## Validation Types + +### Market Creation Parameters + +```rust +let params = MarketCreationParams::new( + admin, + question, + outcomes, + duration_days, + oracle_config, +); + +// Validate all parameters +params.validate(&env)?; + +// Calculate end time +let end_time = params.calculate_end_time(&env); +``` + +### Vote Parameters + +```rust +let vote_params = VoteParams::new(user, outcome, stake); + +// Validate vote parameters +vote_params.validate(&env, &market)?; +``` + +## Best Practices + +### 1. Always Validate Types + +```rust +// โŒ Don't skip validation +let market = Market::new(&env, admin, question, outcomes, end_time, oracle_config); + +// โœ… Always validate +let market = Market::new(&env, admin, question, outcomes, end_time, oracle_config); +market.validate(&env)?; +``` + +### 2. Use Type-Safe Operations + +```rust +// โŒ Manual state checking +if current_time < market.end_time && market.winning_outcome.is_none() { + // Market is active +} + +// โœ… Use type-safe methods +if market.is_active(current_time) { + // Market is active +} +``` + +### 3. Leverage Built-in Methods + +```rust +// โŒ Manual calculations +let mut total = 0; +for (user, outcome) in market.votes.iter() { + if &outcome == winning_outcome { + total += market.stakes.get(user.clone()).unwrap_or(0); + } +} + +// โœ… Use built-in methods +let total = market.winning_stake_total(); +``` + +### 4. Use Validation Helpers + +```rust +// โŒ Manual validation +if stake < min_stake { + return Err(Error::InsufficientStake); +} + +// โœ… Use validation helpers +validation::validate_stake(stake, min_stake)?; +``` + +### 5. Handle Oracle Results Safely + +```rust +// โŒ Direct access +let price = oracle_result.price; + +// โœ… Safe access +if let Some(price) = oracle_result.get_price() { + // Use the price +} +``` + +## Testing + +### Type Testing + +The types module includes comprehensive tests: + +```rust +#[test] +fn test_oracle_provider() { + let provider = OracleProvider::Pyth; + assert_eq!(provider.name(), "Pyth Network"); + assert!(provider.is_supported()); +} + +#[test] +fn test_market_creation() { + let market = Market::new(&env, admin, question, outcomes, end_time, oracle_config); + assert!(market.is_active(current_time)); + assert!(!market.is_resolved()); +} + +#[test] +fn test_validation_helpers() { + assert!(validation::validate_oracle_provider(&OracleProvider::Pyth).is_ok()); + assert!(validation::validate_price(2500000).is_ok()); +} +``` + +## Migration Guide + +### From Direct Type Usage + +1. **Replace direct struct creation**: + ```rust + // Old + let market = Market { /* fields */ }; + + // New + let market = Market::new(&env, admin, question, outcomes, end_time, oracle_config); + ``` + +2. **Use validation methods**: + ```rust + // Old + if threshold <= 0 { return Err(Error::InvalidThreshold); } + + // New + oracle_config.validate(&env)?; + ``` + +3. **Use type-safe operations**: + ```rust + // Old + if current_time < market.end_time { /* active */ } + + // New + if market.is_active(current_time) { /* active */ } + ``` + +## Type Reference + +### Oracle Types + +| Type | Purpose | Key Methods | +|------|---------|-------------| +| `OracleProvider` | Oracle service enumeration | `name()`, `is_supported()`, `default_feed_format()` | +| `OracleConfig` | Oracle configuration | `new()`, `validate()`, `is_supported()`, `is_greater_than()` | +| `PythPrice` | Pyth price data | `new()`, `price_in_cents()`, `is_stale()`, `validate()` | +| `ReflectorPriceData` | Reflector price data | `new()`, `price_in_cents()`, `is_stale()`, `validate()` | + +### Market Types + +| Type | Purpose | Key Methods | +|------|---------|-------------| +| `Market` | Market data structure | `new()`, `validate()`, `is_active()`, `add_vote()` | +| `MarketState` | Market state enumeration | `from_market()`, `is_active()`, `has_ended()` | +| `MarketCreationParams` | Market creation parameters | `new()`, `validate()`, `calculate_end_time()` | +| `VoteParams` | Vote parameters | `new()`, `validate()` | + +### Utility Types + +| Type | Purpose | Key Methods | +|------|---------|-------------| +| `OracleResult` | Oracle result wrapper | `price()`, `unavailable()`, `is_available()`, `get_price()` | +| `ReflectorAsset` | Reflector asset types | `stellar()`, `other()`, `is_stellar()`, `is_other()` | + +### Validation Functions + +| Function | Purpose | Parameters | +|----------|---------|------------| +| `validate_oracle_provider()` | Validate oracle provider | `provider: &OracleProvider` | +| `validate_price()` | Validate price value | `price: i128` | +| `validate_stake()` | Validate stake amount | `stake: i128, min_stake: i128` | +| `validate_duration()` | Validate duration | `duration_days: u32` | + +### Conversion Functions + +| Function | Purpose | Parameters | +|----------|---------|------------| +| `string_to_oracle_provider()` | Convert string to provider | `s: &str` | +| `oracle_provider_to_string()` | Convert provider to string | `provider: &OracleProvider` | +| `validate_comparison()` | Validate comparison operator | `comparison: &String, env: &Env` | + +## Future Enhancements + +1. **Type Serialization**: Proper serialization/deserialization support +2. **Type Metrics**: Collection and reporting of type usage statistics +3. **Type Validation**: Enhanced validation with custom rules +4. **Type Events**: Event emission for type state changes +5. **Type Localization**: Support for multiple languages in type messages + +## Conclusion + +The new types system provides a robust foundation for managing data structures in the Predictify Hybrid contract. By following the patterns and best practices outlined in this document, developers can create more maintainable, type-safe, and well-organized code. \ No newline at end of file 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 From 1ff4414bcd95878c7c0d2d7f9e1ae08f285af106 Mon Sep 17 00:00:00 2001 From: 1nonlypiece Date: Sun, 10 Aug 2025 16:13:54 +0530 Subject: [PATCH 18/20] docs: remove TYPES_SYSTEM.md from contract folder (moved to docs/contracts/) --- contracts/predictify-hybrid/TYPES_SYSTEM.md | 541 -------------------- 1 file changed, 541 deletions(-) delete mode 100644 contracts/predictify-hybrid/TYPES_SYSTEM.md diff --git a/contracts/predictify-hybrid/TYPES_SYSTEM.md b/contracts/predictify-hybrid/TYPES_SYSTEM.md deleted file mode 100644 index 2b54f3cd..00000000 --- a/contracts/predictify-hybrid/TYPES_SYSTEM.md +++ /dev/null @@ -1,541 +0,0 @@ -# Predictify Hybrid Types System - -## Overview - -The Predictify Hybrid contract now features a comprehensive, organized type system that centralizes all data structures and provides better organization, validation, and maintainability. This document outlines the architecture, usage patterns, and best practices for working with the types system. - -## Architecture - -### Type Categories - -Types are organized into logical categories for better understanding and maintenance: - -1. **Oracle Types** - Oracle providers, configurations, and data structures -2. **Market Types** - Market data structures and state management -3. **Price Types** - Price data and validation structures -4. **Validation Types** - Input validation and business logic types -5. **Utility Types** - Helper types and conversion utilities - -### Core Components - -#### 1. Oracle Types - -**OracleProvider Enum** -```rust -pub enum OracleProvider { - BandProtocol, - DIA, - Reflector, - Pyth, -} -``` - -**OracleConfig Struct** -```rust -pub struct OracleConfig { - pub provider: OracleProvider, - pub feed_id: String, - pub threshold: i128, - pub comparison: String, -} -``` - -#### 2. Market Types - -**Market Struct** -```rust -pub struct Market { - pub admin: Address, - pub question: String, - pub outcomes: Vec, - pub end_time: u64, - pub oracle_config: OracleConfig, - // ... other fields -} -``` - -#### 3. Price Types - -**PythPrice Struct** -```rust -pub struct PythPrice { - pub price: i128, - pub conf: u64, - pub expo: i32, - pub publish_time: u64, -} -``` - -**ReflectorPriceData Struct** -```rust -pub struct ReflectorPriceData { - pub price: i128, - pub timestamp: u64, -} -``` - -## Usage Patterns - -### 1. Creating Oracle Configurations - -```rust -use types::{OracleProvider, OracleConfig}; - -let oracle_config = OracleConfig::new( - OracleProvider::Pyth, - String::from_str(&env, "BTC/USD"), - 2500000, // $25,000 threshold - String::from_str(&env, "gt"), // greater than -); - -// Validate the configuration -oracle_config.validate(&env)?; -``` - -### 2. Creating Markets - -```rust -use types::{Market, OracleConfig, OracleProvider}; - -let market = Market::new( - &env, - admin, - question, - outcomes, - end_time, - oracle_config, -); - -// Validate market parameters -market.validate(&env)?; -``` - -### 3. Market State Management - -```rust -use types::MarketState; - -let state = MarketState::from_market(&market, current_time); - -if state.is_active() { - // Market is accepting votes -} else if state.has_ended() { - // Market has ended -} else if state.is_resolved() { - // Market is resolved -} -``` - -### 4. Oracle Result Handling - -```rust -use types::OracleResult; - -let result = OracleResult::price(2500000); - -if result.is_available() { - if let Some(price) = result.get_price() { - // Use the price - } -} -``` - -## Type Validation - -### Built-in Validation - -All types include built-in validation methods: - -```rust -// Oracle configuration validation -oracle_config.validate(&env)?; - -// Market validation -market.validate(&env)?; - -// Price validation -pyth_price.validate()?; -``` - -### Validation Helpers - -The types module provides validation helper functions: - -```rust -use types::validation; - -// Validate oracle provider -validation::validate_oracle_provider(&OracleProvider::Pyth)?; - -// Validate price -validation::validate_price(2500000)?; - -// Validate stake -validation::validate_stake(stake, min_stake)?; - -// Validate duration -validation::validate_duration(30)?; -``` - -## Type Conversion - -### Conversion Helpers - -```rust -use types::conversion; - -// Convert string to oracle provider -let provider = conversion::string_to_oracle_provider("pyth") - .ok_or(Error::InvalidOracleConfig)?; - -// Convert oracle provider to string -let provider_name = conversion::oracle_provider_to_string(&provider); - -// Validate comparison operator -conversion::validate_comparison(&comparison, &env)?; -``` - -## Market Operations - -### Market State Queries - -```rust -// Check if market is active -if market.is_active(current_time) { - // Accept votes -} - -// Check if market has ended -if market.has_ended(current_time) { - // Resolve market -} - -// Check if market is resolved -if market.is_resolved() { - // Allow claims -} -``` - -### User Operations - -```rust -// Get user's vote -let user_vote = market.get_user_vote(&user); - -// Get user's stake -let user_stake = market.get_user_stake(&user); - -// Check if user has claimed -let has_claimed = market.has_user_claimed(&user); - -// Get user's dispute stake -let dispute_stake = market.get_user_dispute_stake(&user); -``` - -### Market Modifications - -```rust -// Add vote and stake -market.add_vote(user, outcome, stake); - -// Add dispute stake -market.add_dispute_stake(user, stake); - -// Mark user as claimed -market.mark_claimed(user); - -// Set oracle result -market.set_oracle_result(result); - -// Set winning outcome -market.set_winning_outcome(outcome); - -// Mark fees as collected -market.mark_fees_collected(); -``` - -### Market Calculations - -```rust -// Get total dispute stakes -let total_disputes = market.total_dispute_stakes(); - -// Get winning stake total -let winning_total = market.winning_stake_total(); -``` - -## Oracle Integration - -### Oracle Provider Support - -```rust -// Check if provider is supported -if oracle_provider.is_supported() { - // Use the provider -} - -// Get provider name -let name = oracle_provider.name(); - -// Get default feed format -let format = oracle_provider.default_feed_format(); -``` - -### Oracle Configuration - -```rust -// Check comparison operators -if oracle_config.is_greater_than(&env) { - // Handle greater than comparison -} else if oracle_config.is_less_than(&env) { - // Handle less than comparison -} else if oracle_config.is_equal_to(&env) { - // Handle equal to comparison -} -``` - -## Price Data Handling - -### Pyth Price Data - -```rust -let pyth_price = PythPrice::new(2500000, 1000, -2, timestamp); - -// Get price in cents -let price_cents = pyth_price.price_in_cents(); - -// Check if price is stale -if pyth_price.is_stale(current_time, max_age) { - // Handle stale price -} - -// Validate price data -pyth_price.validate()?; -``` - -### Reflector Price Data - -```rust -let reflector_price = ReflectorPriceData::new(2500000, timestamp); - -// Get price in cents -let price_cents = reflector_price.price_in_cents(); - -// Check if price is stale -if reflector_price.is_stale(current_time, max_age) { - // Handle stale price -} - -// Validate price data -reflector_price.validate()?; -``` - -## Validation Types - -### Market Creation Parameters - -```rust -let params = MarketCreationParams::new( - admin, - question, - outcomes, - duration_days, - oracle_config, -); - -// Validate all parameters -params.validate(&env)?; - -// Calculate end time -let end_time = params.calculate_end_time(&env); -``` - -### Vote Parameters - -```rust -let vote_params = VoteParams::new(user, outcome, stake); - -// Validate vote parameters -vote_params.validate(&env, &market)?; -``` - -## Best Practices - -### 1. Always Validate Types - -```rust -// โŒ Don't skip validation -let market = Market::new(&env, admin, question, outcomes, end_time, oracle_config); - -// โœ… Always validate -let market = Market::new(&env, admin, question, outcomes, end_time, oracle_config); -market.validate(&env)?; -``` - -### 2. Use Type-Safe Operations - -```rust -// โŒ Manual state checking -if current_time < market.end_time && market.winning_outcome.is_none() { - // Market is active -} - -// โœ… Use type-safe methods -if market.is_active(current_time) { - // Market is active -} -``` - -### 3. Leverage Built-in Methods - -```rust -// โŒ Manual calculations -let mut total = 0; -for (user, outcome) in market.votes.iter() { - if &outcome == winning_outcome { - total += market.stakes.get(user.clone()).unwrap_or(0); - } -} - -// โœ… Use built-in methods -let total = market.winning_stake_total(); -``` - -### 4. Use Validation Helpers - -```rust -// โŒ Manual validation -if stake < min_stake { - return Err(Error::InsufficientStake); -} - -// โœ… Use validation helpers -validation::validate_stake(stake, min_stake)?; -``` - -### 5. Handle Oracle Results Safely - -```rust -// โŒ Direct access -let price = oracle_result.price; - -// โœ… Safe access -if let Some(price) = oracle_result.get_price() { - // Use the price -} -``` - -## Testing - -### Type Testing - -The types module includes comprehensive tests: - -```rust -#[test] -fn test_oracle_provider() { - let provider = OracleProvider::Pyth; - assert_eq!(provider.name(), "Pyth Network"); - assert!(provider.is_supported()); -} - -#[test] -fn test_market_creation() { - let market = Market::new(&env, admin, question, outcomes, end_time, oracle_config); - assert!(market.is_active(current_time)); - assert!(!market.is_resolved()); -} - -#[test] -fn test_validation_helpers() { - assert!(validation::validate_oracle_provider(&OracleProvider::Pyth).is_ok()); - assert!(validation::validate_price(2500000).is_ok()); -} -``` - -## Migration Guide - -### From Direct Type Usage - -1. **Replace direct struct creation**: - ```rust - // Old - let market = Market { /* fields */ }; - - // New - let market = Market::new(&env, admin, question, outcomes, end_time, oracle_config); - ``` - -2. **Use validation methods**: - ```rust - // Old - if threshold <= 0 { return Err(Error::InvalidThreshold); } - - // New - oracle_config.validate(&env)?; - ``` - -3. **Use type-safe operations**: - ```rust - // Old - if current_time < market.end_time { /* active */ } - - // New - if market.is_active(current_time) { /* active */ } - ``` - -## Type Reference - -### Oracle Types - -| Type | Purpose | Key Methods | -|------|---------|-------------| -| `OracleProvider` | Oracle service enumeration | `name()`, `is_supported()`, `default_feed_format()` | -| `OracleConfig` | Oracle configuration | `new()`, `validate()`, `is_supported()`, `is_greater_than()` | -| `PythPrice` | Pyth price data | `new()`, `price_in_cents()`, `is_stale()`, `validate()` | -| `ReflectorPriceData` | Reflector price data | `new()`, `price_in_cents()`, `is_stale()`, `validate()` | - -### Market Types - -| Type | Purpose | Key Methods | -|------|---------|-------------| -| `Market` | Market data structure | `new()`, `validate()`, `is_active()`, `add_vote()` | -| `MarketState` | Market state enumeration | `from_market()`, `is_active()`, `has_ended()` | -| `MarketCreationParams` | Market creation parameters | `new()`, `validate()`, `calculate_end_time()` | -| `VoteParams` | Vote parameters | `new()`, `validate()` | - -### Utility Types - -| Type | Purpose | Key Methods | -|------|---------|-------------| -| `OracleResult` | Oracle result wrapper | `price()`, `unavailable()`, `is_available()`, `get_price()` | -| `ReflectorAsset` | Reflector asset types | `stellar()`, `other()`, `is_stellar()`, `is_other()` | - -### Validation Functions - -| Function | Purpose | Parameters | -|----------|---------|------------| -| `validate_oracle_provider()` | Validate oracle provider | `provider: &OracleProvider` | -| `validate_price()` | Validate price value | `price: i128` | -| `validate_stake()` | Validate stake amount | `stake: i128, min_stake: i128` | -| `validate_duration()` | Validate duration | `duration_days: u32` | - -### Conversion Functions - -| Function | Purpose | Parameters | -|----------|---------|------------| -| `string_to_oracle_provider()` | Convert string to provider | `s: &str` | -| `oracle_provider_to_string()` | Convert provider to string | `provider: &OracleProvider` | -| `validate_comparison()` | Validate comparison operator | `comparison: &String, env: &Env` | - -## Future Enhancements - -1. **Type Serialization**: Proper serialization/deserialization support -2. **Type Metrics**: Collection and reporting of type usage statistics -3. **Type Validation**: Enhanced validation with custom rules -4. **Type Events**: Event emission for type state changes -5. **Type Localization**: Support for multiple languages in type messages - -## Conclusion - -The new types system provides a robust foundation for managing data structures in the Predictify Hybrid contract. By following the patterns and best practices outlined in this document, developers can create more maintainable, type-safe, and well-organized code. \ No newline at end of file From 4876514f77c3c61452e467a7b7256e079cf4b9f9 Mon Sep 17 00:00:00 2001 From: 1nonlypiece Date: Sun, 10 Aug 2025 16:13:59 +0530 Subject: [PATCH 19/20] docs: remove VOTING_SYSTEM.md from contract folder (moved to docs/contracts/) --- contracts/predictify-hybrid/VOTING_SYSTEM.md | 1 - 1 file changed, 1 deletion(-) delete mode 100644 contracts/predictify-hybrid/VOTING_SYSTEM.md 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 From e9a7ac5e2a54d132f956b2c2f7785dd582a929b9 Mon Sep 17 00:00:00 2001 From: 1nonlypiece Date: Sun, 10 Aug 2025 16:14:21 +0530 Subject: [PATCH 20/20] docs: update docs README.md to include contracts documentation section --- docs/README.md | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/docs/README.md b/docs/README.md index d9110eb9..7b6a352d 100644 --- a/docs/README.md +++ b/docs/README.md @@ -36,12 +36,19 @@ 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 Security Auditors**: Review [Security Documentation](./security/) -3. **For Gas Optimization**: Check [Gas Optimization](./gas/GAS_OPTIMIZATION.md) -4. **For Operations**: Read [Incident Response](./operations/INCIDENT_RESPONSE.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 @@ -61,6 +68,7 @@ When adding new documentation: ## ๐Ÿท๏ธ 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