Skip to main content

Overview

MetaVault AI includes comprehensive testing for smart contracts and provides guidelines for testing AI agents and frontend functionality.
Testing ensures the vault operates correctly and safely manages user funds. Always run tests before deploying to production.

Test Structure

The project includes tests at different levels:

Contract Tests

Unit and integration tests for smart contracts using Hardhat and Chai

Agent Testing

Manual and automated testing of AI agent behaviors

Integration Tests

End-to-end tests covering the full stack

Smart Contract Testing

Running Contract Tests

Navigate to the contracts package and run the test suite:
pnpm contracts:test

Test Configuration

The Hardhat configuration includes:
hardhat.config.ts
const config: HardhatUserConfig = {
  solidity: {
    version: "0.8.28",
    settings: {
      optimizer: {
        enabled: true,
        runs: 200,
      },
      viaIR: true
    }
  },
  networks: {
    hardhat: {
      forking: {
        url: `https://sepolia.infura.io/v3/${process.env.INFURA_KEY}`,
      }
    }
  }
};
Tests run on a local Hardhat network that can fork Sepolia testnet for realistic testing conditions.

Writing Contract Tests

Contract tests are located in packages/contracts/test/ and use the following structure:
import { expect } from "chai";
import { ethers } from "hardhat";
import { loadFixture } from "@nomicfoundation/hardhat-network-helpers";

describe("MetaVault", function () {
  async function deployVaultFixture() {
    const [owner, user1] = await ethers.getSigners();
    
    // Deploy contracts
    const Vault = await ethers.getContractFactory("MetaVault");
    const vault = await Vault.deploy();
    
    return { vault, owner, user1 };
  }

  it("Should allow deposits", async function () {
    const { vault, user1 } = await loadFixture(deployVaultFixture);
    // Test logic
  });
});

Test Coverage

Generate a coverage report:
cd packages/contracts
pnpm hardhat coverage
This creates a detailed coverage report showing:
  • Line coverage
  • Branch coverage
  • Function coverage
  • Statement coverage
Aim for at least 80% coverage on critical contract functionality like deposits, withdrawals, and strategy management.

Testing with Mock Contracts

MetaVault AI uses mock contracts to simulate DeFi protocols:
1

Deploy Mock Contracts

Deploy the complete mock environment:
pnpm contracts:deploy:local
This deploys:
  • Mock LINK and WETH tokens
  • Mock Aave Pool (simulates lending)
  • Mock Swap Router (simulates Uniswap)
  • MetaVault and strategies
2

Run Testing Script

Use the testing script to simulate various scenarios:
cd packages/contracts
pnpm hardhat run scripts/testing.ts --network localhost
This script can:
  • Simulate deposits and withdrawals
  • Test strategy allocations
  • Trigger yield accrual
  • Test emergency scenarios
3

Verify Results

Check the console output for:
  • Transaction confirmations
  • Balance changes
  • Strategy performance
  • Gas usage estimates

AI Agent Testing

Test the AI agents to ensure they manage the vault correctly:

Manual Agent Testing

1

Start Test Environment

Ensure all services are running:
# Terminal 1: Blockchain
pnpm dev:contracts

# Terminal 2: Deploy contracts
pnpm contracts:deploy:local

# Terminal 3: Agents
pnpm dev:agents
2

Test Strategy Sentinel

The Strategy Sentinel Agent monitors vault health. Test by:
  1. Checking initial strategy state
  2. Simulating market volatility (adjust mock prices)
  3. Observing agent responses
  4. Verifying rebalancing actions
Monitor agent logs for decisions:
🛡️ Strategy Sentinel: Checking vault health...
📊 LTV Ratio: 65%
⚠️  High volatility detected
🔄 Rebalancing portfolio...
✅ Rebalance complete
3

Test Chat Agent

Test the user-facing chat agent:
# Send test request to chat endpoint
curl -X POST http://localhost:3002/chat \
  -H "Content-Type: application/json" \
  -d '{
    "message": "What is my vault balance?",
    "userAddress": "0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266"
  }'
Test various queries:
  • Balance inquiries
  • Deposit/withdrawal requests
  • Strategy information
  • Market conditions
4

Test Yield Simulator

Simulate yield generation:
# Call yield simulator endpoint
curl -X POST http://localhost:3001/simulate-yield \
  -H "Content-Type: application/json" \
  -d '{
    "amount": "1000",
    "duration": "30"
  }'

Automated Agent Testing

Test automation capabilities:
cd packages/agents/defi-portfolio
pnpm run automate:cron
The automation will:
  • Run every 5 minutes (configurable)
  • Monitor strategy health
  • Check liquidation risks
  • Perform rebalancing if needed
  • Harvest and compound yields
Automated testing should only run on test networks. Never run automation on mainnet without thorough testing.

Frontend Testing

Manual Frontend Testing

1

Start Development Server

cd packages/frontend
pnpm dev
Access at http://localhost:3000
2

Test Wallet Connection

  1. Connect MetaMask to localhost network
  2. Import test account from Hardhat
  3. Connect wallet through UI
  4. Verify account displays correctly
3

Test Core Functions

Test the main user flows:Deposit Flow:
  • Navigate to deposit interface
  • Enter amount to deposit
  • Approve token spending (if needed)
  • Confirm deposit transaction
  • Verify balance updates
Withdrawal Flow:
  • Navigate to withdrawal interface
  • Enter amount to withdraw
  • Confirm withdrawal transaction
  • Verify balance updates
Chat Interface:
  • Open chat widget
  • Send test messages
  • Verify AI responses
  • Test different query types
4

Test Strategy Display

Verify strategy information displays correctly:
  • Strategy names and descriptions
  • Current allocations
  • APY/returns
  • Risk levels
  • Historical performance

Linting and Type Checking

Run code quality checks:
cd packages/frontend

# Run ESLint
pnpm lint

# Type check with TypeScript
pnpm tsc --noEmit

Integration Testing

Test the complete system working together:

End-to-End Test Scenario

1

Setup

Start all services:
pnpm dev:all
Deploy contracts and update environment variables.
2

User Deposit

  1. Connect wallet to frontend
  2. Approve LINK token spending
  3. Deposit 1000 LINK tokens
  4. Verify:
    • Transaction confirms
    • Vault balance increases
    • User receives vault shares
    • Frontend updates balance
3

Strategy Allocation

  1. Check initial strategy allocations
  2. Verify funds distributed correctly
  3. Monitor agent logs for allocation decisions
  4. Confirm strategies receive funds
4

Yield Generation

  1. Wait for yield to accrue (or simulate)
  2. Check updated vault value
  3. Verify yield calculation
  4. Test harvest functionality
5

Agent Actions

  1. Trigger agent automation
  2. Monitor rebalancing decisions
  3. Verify risk management
  4. Check strategy adjustments
6

User Withdrawal

  1. Request withdrawal through frontend
  2. Verify:
    • Transaction confirms
    • Correct amount withdrawn
    • Vault shares burned
    • Strategies unwind if needed
    • User receives tokens

Performance Testing

Test system performance and gas usage:

Gas Usage Analysis

cd packages/contracts
pnpm hardhat test --gas-report
This generates a gas report showing:
  • Gas per function call
  • Average gas costs
  • Deployment costs
Optimize functions with high gas usage. The Solidity optimizer is enabled with 200 runs, balancing deployment and execution costs.

Load Testing Agents

Test agent performance under load:
# Send multiple concurrent requests
for i in {1..10}; do
  curl -X POST http://localhost:3002/chat \
    -H "Content-Type: application/json" \
    -d '{"message": "What is the vault TVL?"}' &
done
wait
Monitor:
  • Response times
  • Memory usage
  • CPU utilization
  • Error rates

Debugging Tests

Hardhat Console

Debug contracts interactively:
cd packages/contracts
pnpm hardhat console --network localhost
// Example: Check vault state
const Vault = await ethers.getContractFactory("MetaVault");
const vault = await Vault.attach("0x...");
const balance = await vault.totalAssets();
console.log("Total assets:", balance.toString());

Agent Debug Logs

Enable detailed logging:
# In packages/agents/defi-portfolio/.env
ADK_DEBUG="true"
Logs will show:
  • Tool invocations
  • Agent decisions
  • State changes
  • Error traces

Frontend DevTools

Use browser developer tools:
  • Console for errors and warnings
  • Network tab for API calls
  • React DevTools for component state
  • MetaMask for transaction details

Test Checklist

Before deploying or major changes:
  • All unit tests pass
  • Coverage above 80%
  • Gas usage optimized
  • Edge cases covered
  • Mock contracts work correctly
  • Strategy Sentinel monitors correctly
  • Chat Agent responds appropriately
  • Yield Simulator generates accurate projections
  • Automation runs without errors
  • Error handling works
  • Wallet connection works
  • Deposits process correctly
  • Withdrawals work as expected
  • UI updates reflect blockchain state
  • Chat interface functions
  • Mobile responsive
  • Full deposit-to-withdrawal flow works
  • Agents interact with contracts correctly
  • Frontend displays accurate data
  • Error states handled gracefully
  • Multi-user scenarios work

Continuous Integration

Set up CI/CD for automated testing:
.github/workflows/test.yml
name: Test Suite

on: [push, pull_request]

jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
      - uses: pnpm/action-setup@v2
      - uses: actions/setup-node@v3
        with:
          node-version: 18
          cache: 'pnpm'
      
      - run: pnpm install
      - run: pnpm contracts:test
      - run: pnpm build:frontend
      - run: pnpm build:agents

Common Issues

Recompile contracts and regenerate types:
cd packages/contracts
pnpm hardhat clean
pnpm hardhat compile
Ensure:
  • Contracts are deployed
  • RPC URL is correct
  • OpenRouter API key is valid
  • Increase timeout in test config
Common causes:
  • Missing environment variables
  • Node version mismatch
  • Cache issues
Use consistent Node.js version and clear cache:
pnpm store prune
Optimize contracts:
  • Use memory instead of storage where possible
  • Batch operations
  • Optimize loops
  • Use events instead of storage for historical data

Best Practices

Test Isolation

Each test should be independent and not rely on previous test state

Clear Assertions

Use descriptive test names and clear assertion messages

Test Edge Cases

Test boundary conditions, zero values, and error states

Mock External Calls

Use mocks for external protocols to ensure consistent test results

Next Steps

Architecture

Understand the system architecture

Smart Contracts

Learn about the smart contract design

Build docs developers (and LLMs) love