Skip to content

nIMblEt06/starx

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

3 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

STARx Protocol

Project Overview

STARx Protocol is a sophisticated DeFi protocol built on StarkNet that provides leveraged exposure to liquid staking tokens (LSTs) through two primary tokens:

  • sUSD: A stablecoin backed by liquid staking tokens (LSTs) like staked ETH, staked STRK
  • STARx: A leveraged token that provides amplified exposure to the underlying LST yield and price appreciation

The protocol implements an innovative leverage mechanism where STARx tokens maintain a target 3x leverage ratio to the underlying LST collateral, automatically rebalancing to maintain optimal leverage while maximizing yield generation through DeFi integrations.

Core Value Proposition

  1. Leveraged LST Exposure: STARx provides 3x leveraged exposure to staking yields and price appreciation
  2. Automated Rebalancing: Protocol automatically maintains target leverage through mint/redeem incentives
  3. Multi-Protocol Yield: Integrates with zkLend for lending yield and JediSwap for DEX operations
  4. Stability Mechanisms: Circuit breakers, price oracles, and emergency controls ensure protocol safety

Contract Capabilities

Core Contracts

1. STARx Token Contract (/src/core/starx.cairo)

Main Interface: ISTARx

ERC20 Functions:

  • name(), symbol(), decimals(): Standard token metadata
  • total_supply(), balance_of(), allowance(): Standard ERC20 view functions
  • transfer(), transfer_from(), approve(): Standard ERC20 transfer functions

STARx-Specific Functions:

  • mint(susd_amount: u256) -> u256: Mint STARx tokens using sUSD, applies dynamic bonuses during rebalancing
  • redeem(starx_amount: u256) -> u256: Redeem STARx for sUSD with fees
  • calculate_price() -> u256: Calculate current STARx price based on TVL and supply
  • get_effective_leverage() -> u256: Get current leverage ratio
  • get_total_tvl() -> u256: Get total value locked in the treasury
  • get_susd_supply() -> u256: Get total sUSD token supply

Admin Functions:

  • set_treasury(): Update treasury contract address
  • set_susd_token(): Update sUSD contract address
  • trigger_rebalance(): Manually trigger leverage rebalancing (owner only)

Key Features:

  • Dynamic pricing based on TVL and token supplies
  • Leverage-based mint bonuses to incentivize rebalancing
  • Fee system with configurable mint/redeem fees
  • Critical leverage protection to prevent liquidation risks

2. sUSD Stablecoin Contract (/src/core/susd.cairo)

Main Interface: ISUSD

ERC20 Functions: Standard ERC20 implementation

Minting/Redeeming:

  • mint(lst_address: ContractAddress, lst_amount: u256): Mint sUSD by depositing supported LSTs
  • redeem(susd_amount: u256, lst_address: ContractAddress): Redeem sUSD for LSTs

View Functions:

  • get_collateral_amount(lst_address: ContractAddress) -> u256: Get collateral amount for specific LST
  • get_total_collateral_value() -> u256: Get total USD value of all collateral
  • is_supported_lst(lst_address: ContractAddress) -> bool: Check if LST is supported

Admin Functions:

  • add_supported_lst(): Add new LST with oracle configuration
  • remove_supported_lst(): Remove LST from supported list
  • set_minting_paused(): Emergency pause/unpause minting
  • set_oracle(), set_treasury(): Update protocol addresses

Key Features:

  • Multi-LST collateral support
  • Price validation through Pragma Oracle integration
  • Fee collection mechanism
  • Collateral tracking and liquidity management
  • Emergency pause capabilities

3. Treasury Contract (/src/core/treasury.cairo)

Main Interface: ITreasury

Core Functions:

  • get_total_tvl() -> u256: Calculate total value locked across all assets
  • get_collateral_balance(token: ContractAddress) -> u256: Get balance for specific token
  • deposit_collateral(): Accept collateral deposits from core contracts
  • withdraw_collateral(): Allow authorized withdrawals
  • harvest_yield() -> u256: Harvest yield from integrated protocols
  • set_oracle(): Update price oracle

Key Features:

  • Multi-token collateral management
  • Real-time TVL calculation with oracle pricing
  • Integration with lending protocols for yield generation
  • Access control for authorized contracts only
  • Comprehensive event logging for all operations

Integration Contracts

1. zkLend Integration (/src/integrations/zklend.cairo)

Main Interface: IZkLendIntegration

Core Functions:

  • deposit_to_lending(): Deposit assets to zkLend for yield
  • withdraw_from_lending(): Withdraw assets and earned interest
  • get_deposited_amount(): View deposited amounts per asset
  • get_total_deposited_value(): Get total USD value of deposits
  • harvest_rewards(): Claim accumulated rewards
  • get_health_factor(): Monitor lending position health

Key Features:

  • Reentrancy protection for all operations
  • Interest tracking and reward harvesting
  • Health factor monitoring for risk management
  • Multi-asset support with oracle pricing
  • Access control (treasury-only operations)

2. JediSwap Integration (/src/integrations/jediswap.cairo)

Main Interface: IJediSwapIntegration

Core Functions:

  • swap_tokens(): Execute token swaps with slippage protection
  • add_liquidity(): Add liquidity to DEX pairs
  • remove_liquidity(): Remove liquidity from DEX pairs
  • get_quote(): Get swap quotes without execution
  • set_slippage_tolerance(): Configure acceptable slippage

Key Features:

  • Automated slippage protection (default 1%, max 10%)
  • Circuit breaker integration for daily limits
  • Liquidity position tracking
  • Deadline enforcement for time-sensitive operations
  • Multi-hop swap path support

3. Pragma Oracle Integration (/src/integrations/pragma_oracle.cairo)

Main Interface: IOracle (implements standard oracle interface)

Core Functions:

  • get_price(asset_id: felt252) -> PriceData: Get current price data
  • get_price_no_older_than(): Get price with freshness validation
  • get_latest_round_data(): Get latest oracle round data
  • set_price_source(): Configure price sources per asset

Key Features:

  • Price staleness validation (5-minute default max age)
  • Circuit breaker protection against price manipulation
  • Support for multiple price pairs (ETH/USD, STRK/USD, etc.)
  • Fallback mechanisms for oracle failures

Library Modules

1. Math Library (/src/libraries/math.cairo)

Key Functions:

  • mul_div(): Overflow-safe multiplication and division
  • safe_mul(), safe_add(), safe_sub(): Overflow protection
  • scale_to_decimals(): Convert between different decimal representations
  • calculate_percentage(): Basis point calculations
  • pow_10(): Power of 10 calculations

2. Leverage Library (/src/libraries/leverage.cairo)

Key Functions:

  • calculate_effective_leverage(): Compute current leverage ratio
  • calculate_starx_price(): Price calculation based on TVL and supplies
  • check_leverage_bounds(): Validate leverage is within acceptable range
  • calculate_rebalance_amount(): Determine rebalancing requirements
  • calculate_mint_bonus(): Dynamic bonuses for rebalancing incentives

Constants:

  • Target Leverage: 3.0x
  • Min/Max Leverage: 2.0x - 5.0x
  • Critical Leverage: 1.5x - 5.5x

3. Security Library (/src/libraries/security.cairo)

Components:

  • ReentrancyGuard: Protection against reentrancy attacks
  • SecurityUtils: Address validation, percentage checks, deadline validation

4. Circuit Breaker Library (/src/libraries/circuit_breaker.cairo)

Key Functions:

  • Daily mint/redeem limits with automatic reset
  • Leverage bound enforcement
  • Price impact protection
  • Emergency condition detection

5. Access Control Library (/src/libraries/access_control.cairo)

Features:

  • Role-based access control (Admin, Operator, Guardian, Treasury)
  • Time-locked administrative actions (48-hour delay)
  • Multi-signature support for critical operations

6. Pausable Library (/src/libraries/pausable.cairo)

Features:

  • Emergency pause/unpause mechanisms
  • Guardian role for rapid response
  • Pause duration tracking

7. Price Library (/src/libraries/price.cairo)

Key Functions:

  • Price validation and freshness checks
  • Price deviation monitoring (2% threshold)
  • Multi-source price aggregation
  • Price impact calculation

System Architecture

High-Level Architecture

┌─────────────────┐    ┌─────────────────┐    ┌─────────────────┐
│     Users       │────│   sUSD Token    │────│  STARx Token    │
│                 │    │                 │    │                 │
└─────────────────┘    └─────────────────┘    └─────────────────┘
         │                       │                       │
         │                       │                       │
         ▼                       ▼                       ▼
┌─────────────────┐    ┌─────────────────┐    ┌─────────────────┐
│   LST Assets    │────│    Treasury     │────│  Rebalancing    │
│  (ETH, STRK)    │    │   Management    │    │   Mechanism     │
└─────────────────┘    └─────────────────┘    └─────────────────┘
         │                       │                       │
         │                       ▼                       │
         │              ┌─────────────────┐               │
         │              │  Price Oracle   │               │
         │              │   (Pragma)      │               │
         │              └─────────────────┘               │
         │                                                │
         ▼                                                ▼
┌─────────────────┐                            ┌─────────────────┐
│ Yield Sources   │                            │ Risk Management │
│                 │                            │                 │
│ • zkLend        │                            │ • Circuit       │
│ • JediSwap      │                            │   Breakers      │
│ • Staking       │                            │ • Pause         │
│                 │                            │   Mechanisms    │
└─────────────────┘                            └─────────────────┘

Component Interactions

  1. User Operations Flow:

    • Users deposit LSTs → sUSD minted → Treasury receives collateral
    • Users mint STARx with sUSD → Leverage calculated → Dynamic pricing applied
    • Rebalancing incentives adjust based on current leverage ratio
  2. Yield Generation:

    • Treasury deposits collateral to zkLend for lending yield
    • LSTs continue earning staking rewards
    • Yield harvested periodically and reinvested
  3. Price Management:

    • Pragma Oracle provides real-time LST prices
    • STARx price calculated: (TVL - sUSD_supply) / STARx_supply
    • Circuit breakers prevent manipulation
  4. Risk Management:

    • Leverage bounds enforced (2x-5x range)
    • Daily mint/redeem limits prevent large disruptions
    • Emergency pause mechanisms for crisis situations

Current Implementation Status

Fully Implemented ✅

  1. Core Token Logic:

    • Complete ERC20 implementations for both sUSD and STARx
    • Mint/redeem functionality with fee calculations
    • Dynamic pricing mechanisms
  2. Security Framework:

    • Reentrancy guards on all external calls
    • Access control with role-based permissions
    • Pausable mechanisms for emergency stops
    • Circuit breakers with daily limits
  3. Mathematical Libraries:

    • Safe arithmetic operations with overflow protection
    • Leverage calculation algorithms
    • Price manipulation protections
  4. Event System:

    • Comprehensive event logging for all operations
    • Structured event data for off-chain monitoring

Partially Implemented ⚠️

  1. Oracle Integration:

    • Interface definitions complete
    • Pragma Oracle adapter implemented but uses placeholder prices
    • Price validation logic in place
  2. External Protocol Integrations:

    • zkLend integration framework complete but needs actual protocol calls
    • JediSwap integration has router interface but simplified execution
    • Asset tracking and management implemented
  3. Treasury Management:

    • Basic collateral tracking implemented
    • TVL calculation framework exists but needs completion
    • Yield harvesting structure defined

Placeholder Implementations 🚧

  1. TVL Calculation (treasury.cairo:289):

    // Placeholder implementation
    1000000 * SCALE // $1M TVL placeholder
  2. Oracle Price Data (pragma_oracle.cairo:62-70):

    // Simulate realistic price data with validation
    let base_price: u256 = if asset_id == 'ETH/USD' {
        2000000000000 // $2000 in 8 decimals
    } // ... other hardcoded prices
  3. Storage Vector Operations (treasury.cairo:156-157):

    let tokens_count: u64 = 0; // Would get actual count from Vec
    // Would read token from Vec storage
  4. DEX Quote Calculation (jediswap.cairo:432):

    // This is a simplified quote - in production would call router.getAmountOut
    amount_in * 995 / 1000 // 0.5% fee approximation

TODO List - Complete Implementation Plan

CRITICAL PRIORITY 🚨

1. Oracle Integration

  • Replace placeholder prices in Pragma Oracle adapter
    • Remove hardcoded price simulations
    • Implement actual Pragma Oracle calls
    • Add price staleness and deviation validation
    • Test with real Pragma testnet data

2. Treasury TVL Calculation

  • Implement real TVL calculation logic
    • Complete _update_tvl() function in treasury.cairo
    • Iterate through supported tokens properly using Vec storage
    • Integrate with oracle for real-time pricing
    • Add lending protocol value calculation

3. zkLend Integration Completion

  • Complete actual zkLend protocol calls
    • Replace placeholder logic with real zkLend Pool interactions
    • Implement proper error handling for external protocol failures
    • Add health factor monitoring and alerting
    • Test with zkLend testnet environment

4. JediSwap Integration Finalization

  • Complete DEX integration
    • Implement actual router calls for swaps and liquidity operations
    • Add proper reserve calculation and slippage protection
    • Implement LP token management for liquidity positions
    • Test with JediSwap testnet

HIGH PRIORITY ⚠️

5. Storage Management

  • Fix Vec storage operations
    • Implement proper Vec append/read operations for supported tokens
    • Add iteration support for token lists
    • Optimize gas costs for storage operations

6. Access Control Implementation

  • Complete role-based permissions
    • Implement time-locked admin functions
    • Add multi-signature support for critical operations
    • Set up proper role assignment and verification

7. Error Handling & Validation

  • Comprehensive input validation
    • Add bounds checking for all user inputs
    • Implement proper error messages and recovery mechanisms
    • Add deadline validation for time-sensitive operations

8. Testing Framework

  • Complete test suite
    • Unit tests for all contract functions
    • Integration tests for multi-contract operations
    • End-to-end user journey tests
    • Stress testing for edge cases

MEDIUM PRIORITY 💡

9. Gas Optimization

  • Optimize contract efficiency
    • Review storage patterns for gas efficiency
    • Minimize external calls in critical paths
    • Implement batch operations where possible

10. Advanced Features

  • Enhanced functionality
    • Implement automated rebalancing mechanisms
    • Add yield compounding strategies
    • Create analytics and reporting functions

11. Monitoring & Alerting

  • Operational tools
    • Health monitoring dashboards
    • Automated alerting for critical thresholds
    • Performance metrics tracking

LOW PRIORITY 📋

12. Documentation & Tooling

  • Developer experience
    • Complete inline code documentation
    • Create developer integration guides
    • Build deployment and maintenance scripts

13. Advanced Security

  • Additional protections
    • Implement MEV protection mechanisms
    • Add advanced circuit breakers
    • Create emergency response procedures

Security Features

Current Security Measures

1. Reentrancy Protection

  • ReentrancyGuard implemented across all external calls
  • State changes before external interactions
  • Comprehensive protection against reentrancy attacks

2. Access Control

  • Role-based permissions (Admin, Treasury, Guardian, Operator)
  • Owner-only functions for critical operations
  • Time-locked administrative changes

3. Circuit Breakers

  • Daily mint/redeem limits to prevent bank runs
  • Leverage bounds enforcement (2x-5x)
  • Price impact protection (max 20% deviation)
  • Emergency conditions detection

4. Input Validation

  • Non-zero address checks
  • Amount bounds validation (min/max limits)
  • Deadline enforcement for time-sensitive operations
  • Percentage validation for fee parameters

5. Mathematical Safety

  • Overflow protection in all arithmetic operations
  • Safe division with zero-check assertions
  • Precision handling for decimal conversions

6. Oracle Protection

  • Price staleness validation (5-minute maximum age)
  • Multi-source price verification
  • Price deviation monitoring and alerts

Additional Security Considerations

1. External Protocol Risk

  • zkLend Integration: Monitor health factors, implement position limits
  • JediSwap Operations: Slippage protection, MEV considerations
  • Oracle Dependencies: Multiple oracle sources, fallback mechanisms

2. Economic Attacks

  • Flash Loan Protection: Transaction-level state validation
  • Price Manipulation: Circuit breakers, oracle aggregation
  • Governance Attacks: Time-locked changes, multi-signature requirements

3. Smart Contract Risk

  • Upgrade Safety: Immutable core logic, proxy patterns for upgrades
  • Code Audits: Professional security audits before mainnet deployment
  • Bug Bounty Programs: Incentivized security research

Testing Requirements

Unit Testing

  1. Core Contracts:

    • Test all ERC20 functions with edge cases
    • Validate mint/redeem calculations under various conditions
    • Test access control and permission boundaries
    • Verify fee calculations and distributions
  2. Library Functions:

    • Mathematical operations with overflow conditions
    • Leverage calculations across all leverage ranges
    • Circuit breaker triggers and resets
    • Price validation and staleness checks
  3. Integration Contracts:

    • Mock external protocol interactions
    • Test error handling for external failures
    • Validate state changes after external calls

Integration Testing

  1. Multi-Contract Workflows:

    • Complete user journeys (mint sUSD → mint STARx → redeem)
    • Treasury operations with yield harvesting
    • Rebalancing scenarios under different market conditions
  2. Oracle Integration:

    • Price update workflows
    • Staleness and deviation scenarios
    • Fallback mechanism testing
  3. External Protocol Integration:

    • zkLend deposit/withdraw operations
    • JediSwap swap and liquidity operations
    • Error handling when external protocols fail

Stress Testing

  1. Economic Scenarios:

    • Market crash simulations (50%+ price drops)
    • High volatility periods with frequent rebalancing
    • Large redemption scenarios (bank run simulations)
  2. Technical Limits:

    • Gas limit testing for complex operations
    • Storage limit testing with large user bases
    • Circuit breaker activation under extreme conditions

Security Testing

  1. Attack Scenarios:

    • Reentrancy attack attempts
    • Flash loan arbitrage attempts
    • Price manipulation scenarios
  2. Access Control Testing:

    • Unauthorized access attempts
    • Role escalation testing
    • Time-lock bypass attempts

Deployment Considerations

Pre-Deployment Checklist

1. Contract Configuration

  • Set correct oracle addresses (Pragma mainnet)
  • Configure supported LST tokens with correct oracle pair IDs
  • Set appropriate fee parameters (mint: 0.3%, redeem: 0.5%)
  • Initialize circuit breaker limits (daily: 10M tokens)
  • Configure access control roles and addresses

2. External Integration Setup

  • Verify zkLend pool addresses and supported assets
  • Confirm JediSwap router and factory addresses
  • Test oracle connectivity and price feeds
  • Validate all external contract interfaces

3. Security Validation

  • Complete professional security audit
  • Implement and test all emergency procedures
  • Set up monitoring and alerting systems
  • Create incident response playbook

4. Operational Setup

  • Deploy all contracts in correct dependency order
  • Initialize inter-contract connections
  • Fund initial liquidity if required
  • Test all critical user journeys

Deployment Sequence

  1. Phase 1: Core Infrastructure

    • Deploy utility libraries and interfaces
    • Deploy Oracle adapter with testnet configuration
    • Deploy Treasury contract
  2. Phase 2: Token Contracts

    • Deploy sUSD contract with Treasury integration
    • Deploy STARx contract with sUSD and Treasury integration
    • Configure initial parameters and limits
  3. Phase 3: Integration Contracts

    • Deploy zkLend integration with proper permissions
    • Deploy JediSwap integration with slippage protection
    • Connect all contracts and test integration
  4. Phase 4: Validation & Go-Live

    • Comprehensive end-to-end testing
    • Performance validation under load
    • Security audit final review
    • Gradual rollout with monitoring

Post-Deployment Monitoring

1. Key Metrics

  • Total Value Locked (TVL) growth and composition
  • STARx leverage ratio stability and rebalancing frequency
  • User adoption metrics (unique users, transaction volume)
  • Yield generation efficiency across integrated protocols

2. Risk Monitoring

  • Health factors for lending positions
  • Price deviation and oracle performance
  • Circuit breaker activations and reasons
  • Gas cost optimization opportunities

3. Performance Monitoring

  • Transaction success rates and failure analysis
  • Response times for oracle price updates
  • Integration protocol availability and performance
  • Smart contract gas usage and optimization opportunities

Getting Started

Development Environment Setup

  1. Install Scarb (Cairo package manager):

    curl --proto '=https' --tlsv1.2 -sSf https://docs.swmansion.com/scarb/install.sh | sh
  2. Clone and Build:

    git clone <repository-url>
    cd starx
    scarb build
  3. Run Tests:

    scarb test

Contract Interaction Examples

Minting sUSD with LSTs

// 1. Approve LST spending
lst_token.approve(susd_contract_address, amount);

// 2. Mint sUSD
susd_contract.mint(lst_token_address, amount);

Minting STARx for Leverage

// 1. Approve sUSD spending  
susd_token.approve(starx_contract_address, susd_amount);

// 2. Mint STARx (receives leverage exposure)
starx_contract.mint(susd_amount);

Note: This protocol is under active development. All contracts should be thoroughly tested and audited before any mainnet deployment. The current implementation contains placeholder values and incomplete integrations that must be resolved before production use.

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages