Smart Contracts Overview
Introduction
Wafra’s smart contract architecture implements a sophisticated yield optimization protocol built on Base network. The system employs upgradeable proxy patterns, modular inheritance structures, and a pluggable strategy system to provide secure, efficient, and extensible DeFi yield generation.
Contract Architecture
Core Contract Hierarchy
The Wafra platform uses a modular inheritance pattern with specialized contracts for different functionality areas:
FundContract: Main entry point inheriting from multiple specialized contracts
- FundFeeCollection: Management fee collection and referral systems
- FundDeposit: User deposit and withdrawal operations
- FundSecurity: Security controls and emergency procedures
- FundReferrals: Referral program management
- FundStrategy: Strategy deployment and management
- FundRedemption: Token redemption and burning logic
- FundERC20: Scaled balance token mechanics
- FundStorage: Core storage patterns and state management
Foundation Layer: OpenZeppelin security and upgradeability
- OwnableUpgradeable: Ownership management
- AccessControlUpgradeable: Role-based permissions
- ReentrancyGuardUpgradeable: Reentrancy protection
- UUPSUpgradeable: Upgradeable proxy implementation
Design Principles:
- Modular Inheritance: Separation of concerns across focused contracts
- Upgradeable Proxy Pattern: UUPS proxies for safe contract evolution
- Strategy Pattern: Pluggable yield generation strategies
- Security First: Multiple layers of access control and reentrancy protection
Current Deployments (Base Network)
Core Contracts:
- FundContract:
0x869BbaC3AB332EAb7Eeff07F7cD273f39C683E03 - WST Token:
0x7610cc3c7B67e2F74b1Db2D115102153175855a9
Active Strategies:
- AaveStrategy:
0x0ca7b718fb0e1abD832D006484E03bf0C22C7E28 - MorphoStrategy:
0xa15066299b59c073D4F02C9763a4759ABfE0115c - PendleStrategy:
0x55b07CEeE81e983b9De39620DD30083eA026873A
WST Token Mechanics
Scaled Balance System
Core Innovation: WST tokens implement a scaled balance system that enables automatic yield accrual without requiring user transactions.
The system uses a liquidity index that increases over time as yield is generated, causing all user balances to grow proportionally without individual token transfers.
Key Components:
- Scaled Balances: Internal representation of user holdings
- Liquidity Index: Global multiplier that increases with yield
- Precision: 27-decimal precision prevents rounding errors
- Exchange Rate: Publicly viewable conversion rate
Interest Accrual Mechanism
Compound-Style Interest:
The system accrues interest daily by updating the global liquidity index. When yield is generated from strategies, it’s distributed proportionally to all token holders by increasing the liquidity index.
Calculation Process:
- Daily yield harvesting from strategies
- Calculate proportional yield per token
- Update global liquidity index
- All user balances automatically increase
Key Features:
- Automatic Compounding: Token value increases automatically as yield accrues
- Gas Efficiency: No individual user transactions required for yield distribution
- Precision: 27-decimal precision prevents rounding errors
- Transparency: Exchange rate publicly viewable in real-time
Strategy System Architecture
Abstract Strategy Interface
Common Strategy Interface:
All strategies implement a standardized interface that enables consistent integration with the fund contract:
Core Functions:
- deposit: Allocate capital to the strategy
- withdraw: Remove capital from the strategy
- totalValue: Current value of strategy holdings
- expectedAPY: Projected annual percentage yield
- harvest: Realize profits and compound returns
- emergencyWithdraw: Emergency capital recovery
Access Control:
- CONTROLLER_ROLE: Operational control for fund management
- ADMIN_ROLE: Administrative control for strategy management
Current Strategy Portfolio
Aave Strategy (Lending)
Protocol Integration: Aave V3 Lending
The Aave strategy provides conservative yield through USDC lending on Aave’s money market protocol. This strategy serves as the foundation layer providing stable returns and high liquidity.
Implementation Details:
- Deposits USDC into Aave lending pools
- Receives aUSDC tokens representing accruing interest
- Automatically compounds interest through Aave’s native mechanism
- Provides instant liquidity for withdrawals
Key Features:
- Risk Level: Low
- Expected APY: 3-5%
- Mechanism: Supply USDC to earn interest
- Liquidity: High (instant withdrawals)
- Protocol: Aave V3 on Base
Morpho Strategy (P2P Lending)
Protocol Integration: Morpho Blue P2P Lending
Morpho strategy enhances lending yields through peer-to-peer optimization, matching lenders and borrowers directly to reduce intermediary costs and improve rates.
Key Features:
- Risk Level: Low-Medium
- Expected APY: 4-7%
- Mechanism: P2P lending optimization
- Liquidity: High
- Protocol: Morpho Blue
Pendle Strategy (Yield Trading)
Protocol Integration: Pendle Finance Yield Trading
The Pendle strategy implements advanced yield trading through Principal Tokens (PT) and Yield Tokens (YT), enabling speculation on future yield rates and enhanced returns.
Implementation Process:
- Convert USDC to underlying yield-bearing assets
- Analyze available Pendle markets for best yields
- Deploy capital to highest APY markets
- Trade Principal Tokens for enhanced returns
- Monitor and rebalance across market opportunities
Market Selection Logic:
- Evaluate all active markets for expiry dates
- Calculate implied APY for each market
- Select highest yielding opportunities
- Automatically rebalance as conditions change
Key Features:
- Risk Level: Medium
- Expected APY: 6-12%
- Mechanism: Fixed yield trading and tokenization
- Liquidity: Medium (market-dependent)
- Protocol: Pendle Finance
Strategy Allocation System
Weight-Based Distribution:
The fund contract manages multiple strategies through a dynamic allocation system that maintains target weights for each strategy based on risk-return profiles.
Allocation Process:
- Calculate total portfolio value across all strategies
- Determine target allocation for each strategy based on weights
- Compare current allocation to target allocation
- Rebalance by withdrawing from over-allocated strategies
- Deploy excess capital to under-allocated strategies
Current Allocation Model:
- Aave Strategy: 40% - Conservative base with high liquidity
- Morpho Strategy: 35% - Enhanced lending yields
- Pendle Strategy: 25% - Higher risk/reward opportunities
Rebalancing Triggers:
- Significant strategy performance changes
- Capital deployment from new deposits
- Regular scheduled rebalancing
- Emergency reallocation needs
Fund Contract Architecture
Core Fund Storage
State Management:
The fund contract maintains comprehensive state for token mechanics, strategy management, fee collection, and referral systems.
Key State Variables:
- Token Contracts: USDC reference for deposits/withdrawals
- Strategy Management: Array of active strategies with weights
- Fee Management: Weekly fee rates and collection timestamps
- Referral System: Referral rates and discount structures
- Interest Accrual: Liquidity index and precision constants
Storage Organization:
- Strategic variable packing for gas optimization
- Inheritance-safe storage gaps for upgradeability
- Clear separation between functional areas
- Event logging for all state changes
Deposit & Withdrawal Flow
Deposit Process:
- Interest Accrual: Update liquidity index with latest yield
- Amount Validation: Ensure deposit amount is greater than zero
- Scaled Calculation: Calculate scaled tokens to mint based on current index
- Token Transfer: Transfer USDC from user to contract
- Token Minting: Mint scaled WST tokens to user
- Event Emission: Log deposit for tracking and analytics
Withdrawal Process:
- Interest Accrual: Update liquidity index with latest yield
- Balance Validation: Ensure user has sufficient WST balance
- Scaled Calculation: Calculate scaled tokens to burn
- Liquidity Management: Withdraw from strategies if needed
- Token Burning: Burn user’s scaled WST tokens
- Token Transfer: Transfer USDC to user
- Event Emission: Log withdrawal for tracking and analytics
Liquidity Management:
When withdrawals exceed available USDC in the contract, the system automatically withdraws from strategies in order of liquidity preference, ensuring users can always access their funds.
Fee Collection System
Management Fee Structure:
The protocol charges a 2% annual management fee (0.0377% weekly) that is automatically collected and distributed between the treasury and referral rewards.
Fee Collection Process:
- Frequency: Weekly fee collection
- Calculation: Based on total fund value
- Distribution: 75% to treasury, 25% to referral pool
- Implementation: Mint new tokens rather than transfer existing ones
Referral System Integration:
- Referral Rate: 25% of fees go to referrers
- Referred Discount: 5% fee reduction for referred users
- Tracking: Complete referral chain tracking
- Rewards: Automatic distribution to referrers
Security Features
Access Control System
Role-Based Permissions:
The contract implements OpenZeppelin’s AccessControl with hierarchical role management:
ADMIN_ROLE: Full administrative control
- Contract upgrades
- Strategy management
- Parameter adjustments
- Emergency procedures
CONTROLLER_ROLE: Operational control
- Capital deployment
- Yield harvesting
- Fee collection
- Strategy rebalancing
Role Hierarchy:
- Admin role can grant and revoke controller roles
- Role changes are logged and monitored
- Time-locked changes for critical parameters
Safety Mechanisms
Multiple Protection Layers:
- Reentrancy Guards: All external functions protected against reentrancy attacks
- Pause Functionality: Emergency pause capability for the entire system
- Strategy Isolation: Failed strategies don’t affect others or core operations
- Upgrade Safety: Storage gap preservation and upgrade validation
Emergency Procedures:
The contract includes comprehensive emergency procedures for crisis management:
- Emergency Withdrawal: Remove all funds from strategies
- Strategy Pause: Disable individual strategies
- System Pause: Halt all operations
- Administrative Override: Manual intervention capabilities
Upgrade System
UUPS Proxy Pattern:
The contract uses Universal Upgradeable Proxy Standard for safe contract evolution:
Upgrade Authorization:
- Only admin role can authorize upgrades
- Additional validation through upgrade validator
- Storage layout compatibility verification
- Interface compatibility validation
Storage Safety:
- Storage gaps prevent slot collisions during upgrades
- Careful inheritance order maintains compatibility
- Upgrade validation prevents malicious implementations
- Rollback procedures for failed upgrades
Strategy Management
Dynamic Allocation Framework
Capital Deployment System:
The fund contract automatically manages capital allocation across strategies based on predefined weights and market conditions.
Deployment Logic:
- Calculate total available capital across fund and strategies
- Determine target allocation for each strategy
- Identify rebalancing needs (over/under allocated strategies)
- Execute withdrawals from over-allocated strategies
- Deploy available capital to under-allocated strategies
Strategy Integration Process
New Strategy Deployment:
Adding new strategies follows a structured validation and integration process:
Validation Requirements:
- Strategy must implement required interface
- Underlying token must match fund requirements
- Strategy cannot already exist in the system
- Security audit and testing completion
Integration Steps:
- Deploy strategy contract with proper initialization
- Validate strategy implementation and interface
- Add strategy to fund contract with initial weight
- Set strategy limits and risk parameters
- Perform initial capital deployment
- Monitor performance and adjust as needed
Risk Management Framework
Strategy-Level Risk Controls:
Individual Strategy Limits:
- Maximum Allocation: Percentage cap of total funds
- Maximum Single Deposit: Limit on individual deposit size
- Emergency Threshold: Trigger point for emergency procedures
- Pause State: Ability to disable strategy operations
Portfolio-Level Risk Management:
Diversification Monitoring:
- No single strategy exceeds 50% allocation
- Minimum of 3 active strategies at all times
- Regular risk assessment and rebalancing
- Concentration risk alerts and automatic rebalancing
Emergency Controls:
- Strategy Emergency Withdrawal: Remove all funds from specific strategy
- Strategy Pause: Temporarily disable strategy operations
- Portfolio Emergency Mode: Withdraw from all strategies
- Administrative Override: Manual intervention capabilities
Performance Analytics
Strategy Performance Tracking:
The system maintains comprehensive performance metrics for each strategy:
Performance Metrics:
- Total Deposited: Cumulative capital allocated
- Total Withdrawn: Cumulative capital removed
- Current Value: Real-time strategy value
- Realized Gains: Actual profits harvested
- Unrealized Gains: Current position gains/losses
- Fees: Strategy-specific fee tracking
Real-Time APY Calculation:
The portfolio APY is calculated as a weighted average of individual strategy APYs based on current allocations, providing users with accurate yield expectations.
Performance Optimizations
Gas Efficiency
Optimized Operations:
- Batch Strategy Operations: Multiple actions in single transaction
- Efficient Storage Layout: Strategic variable packing reduces storage costs
- View Function Optimization: Minimal external calls for read operations
- Cache Calculations: Reduced redundant computations
Scalability Features
Modular Design:
- Strategy Extensibility: Framework supports easy addition of new yield sources
- Weight Rebalancing: Dynamic allocation adjustments without contract changes
- Multi-Asset Support: Architecture ready for additional token types
- Cross-Chain Ready: Design supports multi-chain deployment
Future Development
Planned Enhancements
Strategy Expansion:
- Additional DeFi Protocols: Integration with emerging yield opportunities
- Real-World Assets: Tokenized asset integration for diversification
- Cross-Chain Strategies: Multi-chain yield optimization
- Custom Strategies: Wafra-specific yield opportunities
Governance Integration
Decentralization Roadmap:
- Strategy Weight Voting: Community-driven allocation decisions
- Parameter Governance: Decentralized fee rate and threshold management
- Strategy Approval: Community validation of new strategy additions
- Treasury Management: Decentralized protocol fund management
This smart contract architecture provides a robust, secure, and extensible foundation for automated yield optimization while maintaining the flexibility to evolve with the DeFi ecosystem.