Skip to main content

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
Withdraw
  • Burns user’s shares
  • Pulls assets from strategies if needed (via router)
  • Applies withdrawal fee
  • Transfers assets to user
  • Tracks withdrawal history
Share Conversion
  • Implements ERC4626-style share calculation
  • Adjusts for total managed assets across all strategies
User Growth Tracking
  • Calculates profit/loss for individual users
  • Returns absolute PnL and percentage growth
Strategy Integration
  • Router-only functions for fund movement
  • moveToStrategy: Transfers funds to strategy for investment
  • receiveFromStrategy: Accounting hook when funds return
  • handleHarvestProfit: Applies performance fee to profits
Total Managed Assets
  • 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
Rebalancing
  1. Calculate total managed assets (vault + strategies)
  2. For each strategy:
    • If overweight: Withdraw excess to vault
    • If underweight: Move funds from vault to strategy
  3. Recalculate after each step to handle dynamic balances
  4. Uses try/catch to handle failing strategies gracefully
Harvesting
  • Iterates through all strategies
  • Calls harvest() on each
  • Measures vault balance before/after
  • Applies performance fee via vault.handleHarvestProfit()
Manual Fund Movement
  • Owner functions for manual capital allocation
  • Used by AI agents to deploy funds
Withdrawal Support
  • Called by vault when user withdraws but vault lacks liquidity
  • Iterates strategies, pulling funds until amount satisfied
  • Handles failures gracefully with try/catch
Deleveraging
  • Triggers deleveraging on a specific strategy
  • Used by agents during high-risk periods
Portfolio Queries
  • 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:
  1. Supplies LINK to Aave V3 lending pool
  2. Earns supply APY from borrowers
  3. Tracks principal vs aToken balance to measure profit
Key Functions:
Risk Profile: Low (no borrowing, no liquidation risk)

2. StrategyAaveLeverage

Location: packages/contracts/contracts/strategy/StrategyAaveLeverage.sol Type: Aggressive, leveraged yield strategy Mechanism (Looping): Key State Variables:
Key Functions:
Risk Profile: High
  • 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

Note: The “Owner” is typically an EOA controlled by the AI agent system.

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

  1. Reentrancy: Checks-effects-interactions pattern
  2. Integer Overflow: Solidity ^0.8.0 has built-in checks
  3. Access Control: onlyOwner and onlyRouter modifiers
  4. Failed Strategy Handling: Try/catch blocks in router
  5. Price Manipulation: Uses Chainlink oracles in production
  6. Slippage Protection: Min output amounts in swaps (not in mocks)

Deployment

Script: packages/contracts/scripts/deploy_mocks.ts Deployment Order:
  1. Deploy mock ERC20 tokens (LINK, WETH)
  2. Deploy mock Aave pool and data provider
  3. Deploy mock swap router and oracle
  4. Deploy Vault
  5. Deploy StrategyRouter
  6. Deploy strategies (Aave, Leverage)
  7. Configure router with strategies and target weights
  8. 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