precolator-program 1.0.0

Core Rust library for the Precolator perpetual futures trading protocol on Solana β€” oracle management, position handling, risk engine, and liquidation system.
Documentation

Precolator Program - Rust Core Library

A comprehensive Rust library for the Precolator perpetual futures trading protocol. This package provides core functionality for oracle management, position handling, risk assessment, and liquidation tracking on Solana.

πŸ“¦ Overview

Precolator Program is a modular, production-grade Rust library designed to support perpetual futures trading operations. It provides:

  • Oracle Management: Price feed validation, aggregation, and manipulation detection
  • Position Management: Opening, updating, closing, and tracking trading positions
  • Risk Engine: Dynamic leverage scaling, margin calculations, and stress testing
  • Liquidation System: Liquidation detection, execution, and insurance fund management
  • Utility Functions: Safe arithmetic, fee calculations, and helper functions

πŸ“š Module Documentation

Oracle Module (oracle.rs)

Manages oracle price feeds and aggregation.

Key Structures:

  • PriceData: Represents a single price feed with confidence and timestamp
  • OracleConfig: Configuration for oracle feeds including circuit breaker settings
  • OracleManager: Main interface for oracle operations

Key Functions:

  • validate_price() - Validate price data and staleness
  • aggregate_prices() - Aggregate prices from multiple sources
  • check_circuit_breaker() - Detect suspicious price movements
  • calculate_price_impact() - Calculate slippage for large orders
  • detect_manipulation() - Identify potential oracle manipulation

Position Module (position.rs)

Manages the complete position lifecycle.

Key Structures:

  • Position: Represents an open or closed trading position
  • PositionUpdate: Contains position update information
  • PositionStatus: Enum for position states (Open, Closed, Liquidated)
  • PositionSide: Enum for direction (Long, Short)

Key Functions:

  • open_position() - Create a new trading position
  • calculate_pnl() - Calculate unrealized P&L
  • calculate_pnl_percent() - Calculate P&L percentage
  • calculate_health_factor() - Calculate position health (0-10000)
  • close_position() - Close position and calculate settlement
  • update_position_price() - Update price and recalculate metrics
  • is_liquidatable() - Check if position meets liquidation criteria

Risk Engine (risk.rs)

Comprehensive risk assessment and management.

Key Enums:

  • RiskLevel: Low, Medium, High, Critical
  • RiskMetrics: Comprehensive risk assessment data

Key Functions:

  • assess_risk_level() - Determine risk level from utilization
  • get_leverage_multiplier() - Get dynamic leverage multiplier
  • calculate_max_leverage() - Calculate allowed leverage based on utilization
  • calculate_liquidation_price() - Calculate liquidation price with fees
  • calculate_var_95() - Calculate Value at Risk at 95% confidence
  • stress_test_position() - Test position under price shocks
  • calculate_funding_fee() - Calculate funding rate charges
  • validate_risk_parameters() - Validate risk constraints before trading

Liquidation Module (liquidation.rs)

Liquidation detection, execution, and insurance management.

Key Structures:

  • LiquidationEvent: Records a liquidation execution
  • LiquidationTrigger: Enum for liquidation causes

Key Functions:

  • should_liquidate() - Determine if position is liquidatable
  • calculate_liquidation_fee() - Calculate fee from liquidation
  • calculate_insurance_payout() - Calculate insurance fund usage
  • execute_liquidation() - Execute liquidation transaction
  • calculate_liquidator_reward() - Calculate liquidator incentive
  • batch_check_liquidations() - Check multiple positions

Utilities (utils.rs)

Helper functions and safe arithmetic.

Key Functions:

  • calculate_bps_amount() - Calculate basis point amount
  • safe_mul(), safe_add(), safe_sub() - Safe arithmetic with overflow checking
  • calculate_percentage_change() - Calculate percentage changes
  • next_power_of_2() - Round up to next power of 2
  • clamp() - Clamp value between bounds

πŸš€ Quick Start

Building

cd program
chmod +x scripts/build.sh
./scripts/build.sh

Running Tests

chmod +x scripts/test.sh
./scripts/test.sh

Running Individual Binaries

# Oracle Feeder
cargo run --bin oracle-feeder --release

# Liquidation Keeper
cargo run --bin liquidation-keeper --release

# Position Monitor
cargo run --bin position-monitor --release

πŸ“Š Key Features

1. Dynamic Leverage Scaling

Leverage automatically adjusts based on protocol utilization:

  • Low Utilization (< 40%): Full leverage allowed (100% multiplier)
  • Medium Utilization (40-75%): Reduced leverage (75% multiplier)
  • High Utilization (> 75%): Severely restricted (50% multiplier)
  • Critical (> 95%): Extreme restrictions (25% multiplier)

2. Risk Management

  • Health factor tracking (0-10000 = 0-100%)
  • Maintenance margin enforcement (5% minimum)
  • Initial margin requirements (10% minimum)
  • Insurance fund management

3. Liquidation System

  • Continuous liquidation monitoring
  • Multiple liquidation triggers:
    • Maintenance margin breached
    • Health factor critical
    • Oracle price reached liquidation level
    • Bad debt detection
  • Liquidation fee distribution (0.5% of position)

4. Oracle Management

  • Multi-source price aggregation
  • Staleness detection (300 slot max)
  • Circuit breaker for suspicious movements (Β±5% max)
  • Manipulation detection with volatility analysis

5. Fee Structure

  • Trading Fee: 0.5% on position opening
  • Maintenance Fee: 0.1% periodic
  • Liquidation Fee: 0.5% to protocol (50% to liquidator, 50% to insurance)
  • Funding Fees: Hourly charges based on open interest

πŸ”’ Mathematical Functions

P&L Calculation (Long Position)

If Current Price >= Entry Price:
    PnL = (Current Price - Entry Price) Γ— Position Size Γ· SCALE
Else:
    PnL = -((Entry Price - Current Price) Γ— Position Size Γ· SCALE)

Liquidation Price Calculation (Long)

Liquidation Price = (Entry Price Γ— (Leverage - 1)) Γ· Leverage

Liquidation Price Calculation (Short)

Liquidation Price = (Entry Price Γ— (Leverage + 1)) Γ· Leverage

Margin Requirement

Margin Required = Position Value Γ· Leverage

Health Factor

Health Factor = (Margin Γ· Collateral) Γ— 10,000
Liquidatable if: Health Factor < 500 (5%)

Value at Risk (95% confidence)

VaR₉₅ = Position Value Γ— Volatility Γ— Z-Score(1.645)

Funding Fee (hourly)

Funding Rate = (Open Interest Γ· Available Liquidity) Γ— 5%
Hourly Fee = Funding Rate Γ— Position Size

βš™οΈ Configuration

Key constants in src/constants.rs:

// Position limits
MAX_LEVERAGE: u8 = 50
MIN_LEVERAGE: u8 = 1
MIN_COLLATERAL: u64 = 1_000_000  // 0.01 SOL

// Risk thresholds
MAINTENANCE_MARGIN_BPS: u16 = 500    // 5%
INITIAL_MARGIN_BPS: u16 = 1000       // 10%

// Fee configuration (basis points)
TRADING_FEE_BPS: u16 = 50            // 0.5%
LIQUIDATION_FEE_BPS: u16 = 50        // 0.5%

// Oracle settings
MAX_ORACLE_STALENESS_SLOTS: i64 = 300  // ~5 minutes
PRICE_CONFIDENCE_BPS: u16 = 100       // 1% max band

πŸ§ͺ Testing

The project includes comprehensive test coverage:

Integration Tests (tests/integration_tests.rs)

  • Full position lifecycle workflows
  • Oracle aggregation and validation
  • Risk assessment workflows
  • Liquidation execution flows
  • Batch liquidation checks
  • Stress testing scenarios

Unit Tests (tests/unit_tests.rs)

  • Oracle price normalization
  • Position P&L calculations
  • Risk level assessment
  • Leverage multiplier calculations
  • Liquidation fee calculations
  • Safe arithmetic operations

Run all tests:

cargo test --release

Run specific test module:

cargo test oracle::tests --release
cargo test position::tests --release

πŸ“¦ Dependencies

  • solana-program: Solana program framework
  • solana-sdk: Solana SDK utilities
  • spl-token: SPL token interface
  • anchor-lang: Anchor framework for instruction handling
  • anchor-spl: Anchor SPL token wrapper
  • serde: Serialization framework
  • thiserror: Error handling

πŸ” Security Considerations

  1. Safe Arithmetic: All operations use checked arithmetic to prevent overflows
  2. Price Validation: Oracle prices are validated for staleness and confidence
  3. Circuit Breaker: Excessive price changes trigger circuit breaker
  4. Liquidation Safeguards: Multiple triggers and validation checks
  5. Insurance Fund: Protects against bad debt and protocol solvency

πŸ› οΈ Operational Scripts

Build

./scripts/build.sh

Builds the library and all binary targets in release mode.

Test

./scripts/test.sh

Runs all unit and integration tests.

Lint

./scripts/lint.sh

Formats code and runs clippy linter.

Documentation

./scripts/docs.sh

Generates and opens cargo documentation.

Benchmark

./scripts/benchmark.sh

Runs performance benchmarks and profiling.

πŸš€ Binary Programs

Oracle Feeder

Continuously updates oracle prices from multiple sources:

cargo run --bin oracle-feeder --release

Liquidation Keeper

Monitors and executes liquidations:

cargo run --bin liquidation-keeper --release

Position Monitor

Real-time position analytics and alerts:

cargo run --bin position-monitor --release

πŸ“ˆ Performance

Expected operation throughput (on modern hardware):

  • P&L Calculation: > 100,000 ops/sec
  • Position Updates: > 50,000 ops/sec
  • Risk Assessment: > 80,000 ops/sec
  • Liquidation Checks: > 30,000 ops/sec

🀝 Contributing

  1. Follow Rust naming conventions
  2. Add tests for new functionality
  3. Run ./scripts/lint.sh before committing
  4. Document public APIs with doc comments

πŸ“„ License

MIT License - See LICENSE file for details

πŸ”— Related Repositories

πŸ“ž Support

For issues or questions:

  1. Check existing documentation
  2. Review test cases for usage examples
  3. File an issue on GitHub

Version: 1.0.0
Last Updated: 2024
Status: Production Ready βœ…

precolator-prog