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.
- Leveraged LST Exposure: STARx provides 3x leveraged exposure to staking yields and price appreciation
- Automated Rebalancing: Protocol automatically maintains target leverage through mint/redeem incentives
- Multi-Protocol Yield: Integrates with zkLend for lending yield and JediSwap for DEX operations
- Stability Mechanisms: Circuit breakers, price oracles, and emergency controls ensure protocol safety
Main Interface: ISTARx
ERC20 Functions:
name(),symbol(),decimals(): Standard token metadatatotal_supply(),balance_of(),allowance(): Standard ERC20 view functionstransfer(),transfer_from(),approve(): Standard ERC20 transfer functions
STARx-Specific Functions:
mint(susd_amount: u256) -> u256: Mint STARx tokens using sUSD, applies dynamic bonuses during rebalancingredeem(starx_amount: u256) -> u256: Redeem STARx for sUSD with feescalculate_price() -> u256: Calculate current STARx price based on TVL and supplyget_effective_leverage() -> u256: Get current leverage ratioget_total_tvl() -> u256: Get total value locked in the treasuryget_susd_supply() -> u256: Get total sUSD token supply
Admin Functions:
set_treasury(): Update treasury contract addressset_susd_token(): Update sUSD contract addresstrigger_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
Main Interface: ISUSD
ERC20 Functions: Standard ERC20 implementation
Minting/Redeeming:
mint(lst_address: ContractAddress, lst_amount: u256): Mint sUSD by depositing supported LSTsredeem(susd_amount: u256, lst_address: ContractAddress): Redeem sUSD for LSTs
View Functions:
get_collateral_amount(lst_address: ContractAddress) -> u256: Get collateral amount for specific LSTget_total_collateral_value() -> u256: Get total USD value of all collateralis_supported_lst(lst_address: ContractAddress) -> bool: Check if LST is supported
Admin Functions:
add_supported_lst(): Add new LST with oracle configurationremove_supported_lst(): Remove LST from supported listset_minting_paused(): Emergency pause/unpause mintingset_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
Main Interface: ITreasury
Core Functions:
get_total_tvl() -> u256: Calculate total value locked across all assetsget_collateral_balance(token: ContractAddress) -> u256: Get balance for specific tokendeposit_collateral(): Accept collateral deposits from core contractswithdraw_collateral(): Allow authorized withdrawalsharvest_yield() -> u256: Harvest yield from integrated protocolsset_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
Main Interface: IZkLendIntegration
Core Functions:
deposit_to_lending(): Deposit assets to zkLend for yieldwithdraw_from_lending(): Withdraw assets and earned interestget_deposited_amount(): View deposited amounts per assetget_total_deposited_value(): Get total USD value of depositsharvest_rewards(): Claim accumulated rewardsget_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)
Main Interface: IJediSwapIntegration
Core Functions:
swap_tokens(): Execute token swaps with slippage protectionadd_liquidity(): Add liquidity to DEX pairsremove_liquidity(): Remove liquidity from DEX pairsget_quote(): Get swap quotes without executionset_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
Main Interface: IOracle (implements standard oracle interface)
Core Functions:
get_price(asset_id: felt252) -> PriceData: Get current price dataget_price_no_older_than(): Get price with freshness validationget_latest_round_data(): Get latest oracle round dataset_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
Key Functions:
mul_div(): Overflow-safe multiplication and divisionsafe_mul(),safe_add(),safe_sub(): Overflow protectionscale_to_decimals(): Convert between different decimal representationscalculate_percentage(): Basis point calculationspow_10(): Power of 10 calculations
Key Functions:
calculate_effective_leverage(): Compute current leverage ratiocalculate_starx_price(): Price calculation based on TVL and suppliescheck_leverage_bounds(): Validate leverage is within acceptable rangecalculate_rebalance_amount(): Determine rebalancing requirementscalculate_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
Components:
ReentrancyGuard: Protection against reentrancy attacksSecurityUtils: Address validation, percentage checks, deadline validation
Key Functions:
- Daily mint/redeem limits with automatic reset
- Leverage bound enforcement
- Price impact protection
- Emergency condition detection
Features:
- Role-based access control (Admin, Operator, Guardian, Treasury)
- Time-locked administrative actions (48-hour delay)
- Multi-signature support for critical operations
Features:
- Emergency pause/unpause mechanisms
- Guardian role for rapid response
- Pause duration tracking
Key Functions:
- Price validation and freshness checks
- Price deviation monitoring (2% threshold)
- Multi-source price aggregation
- Price impact calculation
┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐
│ 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 │
└─────────────────┘ └─────────────────┘
-
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
-
Yield Generation:
- Treasury deposits collateral to zkLend for lending yield
- LSTs continue earning staking rewards
- Yield harvested periodically and reinvested
-
Price Management:
- Pragma Oracle provides real-time LST prices
- STARx price calculated:
(TVL - sUSD_supply) / STARx_supply - Circuit breakers prevent manipulation
-
Risk Management:
- Leverage bounds enforced (2x-5x range)
- Daily mint/redeem limits prevent large disruptions
- Emergency pause mechanisms for crisis situations
-
Core Token Logic:
- Complete ERC20 implementations for both sUSD and STARx
- Mint/redeem functionality with fee calculations
- Dynamic pricing mechanisms
-
Security Framework:
- Reentrancy guards on all external calls
- Access control with role-based permissions
- Pausable mechanisms for emergency stops
- Circuit breakers with daily limits
-
Mathematical Libraries:
- Safe arithmetic operations with overflow protection
- Leverage calculation algorithms
- Price manipulation protections
-
Event System:
- Comprehensive event logging for all operations
- Structured event data for off-chain monitoring
-
Oracle Integration:
- Interface definitions complete
- Pragma Oracle adapter implemented but uses placeholder prices
- Price validation logic in place
-
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
-
Treasury Management:
- Basic collateral tracking implemented
- TVL calculation framework exists but needs completion
- Yield harvesting structure defined
-
TVL Calculation (
treasury.cairo:289):// Placeholder implementation 1000000 * SCALE // $1M TVL placeholder
-
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
-
Storage Vector Operations (
treasury.cairo:156-157):let tokens_count: u64 = 0; // Would get actual count from Vec // Would read token from Vec storage
-
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
- 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
- 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
- Complete
- 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
- 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
- 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
- Complete role-based permissions
- Implement time-locked admin functions
- Add multi-signature support for critical operations
- Set up proper role assignment and verification
- Comprehensive input validation
- Add bounds checking for all user inputs
- Implement proper error messages and recovery mechanisms
- Add deadline validation for time-sensitive operations
- 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
- Optimize contract efficiency
- Review storage patterns for gas efficiency
- Minimize external calls in critical paths
- Implement batch operations where possible
- Enhanced functionality
- Implement automated rebalancing mechanisms
- Add yield compounding strategies
- Create analytics and reporting functions
- Operational tools
- Health monitoring dashboards
- Automated alerting for critical thresholds
- Performance metrics tracking
- Developer experience
- Complete inline code documentation
- Create developer integration guides
- Build deployment and maintenance scripts
- Additional protections
- Implement MEV protection mechanisms
- Add advanced circuit breakers
- Create emergency response procedures
ReentrancyGuardimplemented across all external calls- State changes before external interactions
- Comprehensive protection against reentrancy attacks
- Role-based permissions (Admin, Treasury, Guardian, Operator)
- Owner-only functions for critical operations
- Time-locked administrative changes
- Daily mint/redeem limits to prevent bank runs
- Leverage bounds enforcement (2x-5x)
- Price impact protection (max 20% deviation)
- Emergency conditions detection
- Non-zero address checks
- Amount bounds validation (min/max limits)
- Deadline enforcement for time-sensitive operations
- Percentage validation for fee parameters
- Overflow protection in all arithmetic operations
- Safe division with zero-check assertions
- Precision handling for decimal conversions
- Price staleness validation (5-minute maximum age)
- Multi-source price verification
- Price deviation monitoring and alerts
- zkLend Integration: Monitor health factors, implement position limits
- JediSwap Operations: Slippage protection, MEV considerations
- Oracle Dependencies: Multiple oracle sources, fallback mechanisms
- Flash Loan Protection: Transaction-level state validation
- Price Manipulation: Circuit breakers, oracle aggregation
- Governance Attacks: Time-locked changes, multi-signature requirements
- Upgrade Safety: Immutable core logic, proxy patterns for upgrades
- Code Audits: Professional security audits before mainnet deployment
- Bug Bounty Programs: Incentivized security research
-
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
-
Library Functions:
- Mathematical operations with overflow conditions
- Leverage calculations across all leverage ranges
- Circuit breaker triggers and resets
- Price validation and staleness checks
-
Integration Contracts:
- Mock external protocol interactions
- Test error handling for external failures
- Validate state changes after external calls
-
Multi-Contract Workflows:
- Complete user journeys (mint sUSD → mint STARx → redeem)
- Treasury operations with yield harvesting
- Rebalancing scenarios under different market conditions
-
Oracle Integration:
- Price update workflows
- Staleness and deviation scenarios
- Fallback mechanism testing
-
External Protocol Integration:
- zkLend deposit/withdraw operations
- JediSwap swap and liquidity operations
- Error handling when external protocols fail
-
Economic Scenarios:
- Market crash simulations (50%+ price drops)
- High volatility periods with frequent rebalancing
- Large redemption scenarios (bank run simulations)
-
Technical Limits:
- Gas limit testing for complex operations
- Storage limit testing with large user bases
- Circuit breaker activation under extreme conditions
-
Attack Scenarios:
- Reentrancy attack attempts
- Flash loan arbitrage attempts
- Price manipulation scenarios
-
Access Control Testing:
- Unauthorized access attempts
- Role escalation testing
- Time-lock bypass attempts
- 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
- Verify zkLend pool addresses and supported assets
- Confirm JediSwap router and factory addresses
- Test oracle connectivity and price feeds
- Validate all external contract interfaces
- Complete professional security audit
- Implement and test all emergency procedures
- Set up monitoring and alerting systems
- Create incident response playbook
- Deploy all contracts in correct dependency order
- Initialize inter-contract connections
- Fund initial liquidity if required
- Test all critical user journeys
-
Phase 1: Core Infrastructure
- Deploy utility libraries and interfaces
- Deploy Oracle adapter with testnet configuration
- Deploy Treasury contract
-
Phase 2: Token Contracts
- Deploy sUSD contract with Treasury integration
- Deploy STARx contract with sUSD and Treasury integration
- Configure initial parameters and limits
-
Phase 3: Integration Contracts
- Deploy zkLend integration with proper permissions
- Deploy JediSwap integration with slippage protection
- Connect all contracts and test integration
-
Phase 4: Validation & Go-Live
- Comprehensive end-to-end testing
- Performance validation under load
- Security audit final review
- Gradual rollout with monitoring
- 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
- Health factors for lending positions
- Price deviation and oracle performance
- Circuit breaker activations and reasons
- Gas cost optimization opportunities
- Transaction success rates and failure analysis
- Response times for oracle price updates
- Integration protocol availability and performance
- Smart contract gas usage and optimization opportunities
-
Install Scarb (Cairo package manager):
curl --proto '=https' --tlsv1.2 -sSf https://docs.swmansion.com/scarb/install.sh | sh
-
Clone and Build:
git clone <repository-url> cd starx scarb build
-
Run Tests:
scarb test
// 1. Approve LST spending
lst_token.approve(susd_contract_address, amount);
// 2. Mint sUSD
susd_contract.mint(lst_token_address, amount);// 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.