Overview
The MetaVault smart contract system is built on Solidity ^0.8.28 using the Hardhat development framework. It implements a modular vault architecture with pluggable strategies, enabling flexible asset allocation and risk management.Contract Architecture Diagram
Core Contracts
1. Vault.sol
Location:packages/contracts/contracts/Vault.sol
Purpose: The main vault contract that manages user deposits, withdrawals, and share accounting.
Key Features
- ERC20 Shares: Users receive “Vault Share Tokens” (VST) representing their portion of the vault
- Share-Based Accounting: Automatically handles profit distribution through share value appreciation
- Fee Management: Performance fees and withdrawal fees
- User Tracking: Tracks deposits and withdrawals for PnL calculation
State Variables
Core Functions
Deposit- Converts assets to shares using
convertToShares() - Transfers assets from user to vault
- Mints shares to user
- Tracks deposit history
- Burns user’s shares
- Pulls assets from strategies if needed (via router)
- Applies withdrawal fee
- Transfers assets to user
- Tracks withdrawal history
- Implements ERC4626-style share calculation
- Adjusts for total managed assets across all strategies
- Calculates profit/loss for individual users
- Returns absolute PnL and percentage growth
- Router-only functions for fund movement
moveToStrategy: Transfers funds to strategy for investmentreceiveFromStrategy: Accounting hook when funds returnhandleHarvestProfit: Applies performance fee to profits
- Sums vault balance + all strategy balances
- Used for share price calculation
2. StrategyRouter.sol
Location:packages/contracts/contracts/strategy/StrategyRouter.sol
Purpose: Orchestrates capital allocation across multiple strategies.
Key Features
- Multi-Strategy Management: Tracks and allocates to multiple strategies
- Target-Based Allocation: Each strategy has a target weight in basis points (0-10000)
- Automated Rebalancing: Pulls from overweight strategies, pushes to underweight
- Harvest Coordination: Collects profits from all strategies
- Risk Management: Can trigger deleveraging on risky strategies
State Variables
Core Functions
Strategy Configuration- Sets active strategies and their target allocations
- Validates that targets sum to 10000 (100%)
- Clears old strategies before setting new ones
- Calculate total managed assets (vault + strategies)
- For each strategy:
- If overweight: Withdraw excess to vault
- If underweight: Move funds from vault to strategy
- Recalculate after each step to handle dynamic balances
- Uses try/catch to handle failing strategies gracefully
- Iterates through all strategies
- Calls
harvest()on each - Measures vault balance before/after
- Applies performance fee via
vault.handleHarvestProfit()
- Owner functions for manual capital allocation
- Used by AI agents to deploy funds
- Called by vault when user withdraws but vault lacks liquidity
- Iterates strategies, pulling funds until amount satisfied
- Handles failures gracefully with try/catch
- Triggers deleveraging on a specific strategy
- Used by agents during high-risk periods
- Returns current state of all strategies
- Used by frontend and agents for monitoring
Strategy Interface
Location:packages/contracts/contracts/interfaces/IStrategy.sol
Strategy Implementations
1. StrategyAaveV3
Location:packages/contracts/contracts/strategy/StrategyAave.sol
Type: Safe, passive yield strategy
Mechanism:
- Supplies LINK to Aave V3 lending pool
- Earns supply APY from borrowers
- Tracks principal vs aToken balance to measure profit
2. StrategyAaveLeverage
Location:packages/contracts/contracts/strategy/StrategyAaveLeverage.sol
Type: Aggressive, leveraged yield strategy
Mechanism (Looping):
Key State Variables:
- Liquidation risk if LINK price drops
- LTV must stay below Aave’s liquidation threshold
- AI agents monitor and auto-deleverage when needed
Mock Contracts (Testing)
For development, the system uses mock contracts:- MockAavePoolB: Simulates Aave supply/borrow/repay
- MockSwapRouterV2: Simulates Uniswap V2 swaps
- MockPriceOracle: Returns mock prices for LINK/WETH
- MockProtocolDataProvider: Returns aToken addresses
- MockERC20: Standard ERC20 with mint function
- MockAToken: Simulates interest-bearing aTokens
Access Control
Access Control Summary
| Function | Caller | Contract | Purpose |
|---|---|---|---|
deposit/withdraw | Users | Vault | User operations |
setRouter | Owner | Vault | One-time setup |
setStrategies | Owner | Router | Configure allocations |
rebalance | Owner | Router | Reallocate funds |
harvestAll | Owner | Router | Collect profits |
moveFundsToStrategy | Owner | Router | Manual allocation |
triggerDeleverage | Owner | Router | Risk management |
moveToStrategy | Router | Vault | Fund movement |
invest | Router | Strategy | Deploy capital |
harvest | Router | Strategy | Collect yield |
Events
Vault Events
Router Events
Strategy Events
Gas Optimization
- Immutable Variables: Contract addresses stored as
immutable - Batch Operations:
harvestAll()instead of individual harvests - View Functions: Extensive use for gas-free reads
- SafeERC20: Only where necessary (external calls)
- Mapping vs Array: Mappings for O(1) lookups
Security Considerations
- Reentrancy: Checks-effects-interactions pattern
- Integer Overflow: Solidity ^0.8.0 has built-in checks
- Access Control:
onlyOwnerandonlyRoutermodifiers - Failed Strategy Handling: Try/catch blocks in router
- Price Manipulation: Uses Chainlink oracles in production
- Slippage Protection: Min output amounts in swaps (not in mocks)
Deployment
Script:packages/contracts/scripts/deploy_mocks.ts
Deployment Order:
- Deploy mock ERC20 tokens (LINK, WETH)
- Deploy mock Aave pool and data provider
- Deploy mock swap router and oracle
- Deploy Vault
- Deploy StrategyRouter
- Deploy strategies (Aave, Leverage)
- Configure router with strategies and target weights
- Transfer ownership to agent EOA
Testing
Framework: Hardhat + Chai Test Coverage:- Deposit/withdraw flows
- Share price calculation
- Rebalancing logic
- Strategy investment/withdrawal
- Leverage looping
- Deleveraging
- Fee distribution
- Access control
Future Enhancements
- Governance: Transition to multi-sig or DAO
- More Strategies: Curve, Convex, Yearn integrations
- Flash Loan Rebalancing: Use Aave flash loans for efficient rebalancing
- Circuit Breakers: Auto-pause on extreme market conditions
- Upgradability: UUPS proxy pattern for upgradable strategies