Skip to content

ReVaultron/contracts

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

21 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

ReVaultron Protocol

AI-Powered Multi-Chain Yield Optimization Vault with Autonomous Rebalancing

Built with Chainlink Runtime Environment (CRE) Γ— Gemini AI

License: MIT Solidity CRE

πŸ† Built for Chainlink Convergence Hackathon
🎯 Tracks: DeFi & Tokenization | CRE & AI | Top 10 Projects


Table of Contents


Problem Statement

The Current State of DeFi Yield Management

  1. Manual Monitoring is Exhausting

    • Users must constantly track APYs across 100+ protocols
    • Rates fluctuate hourly based on market conditions
    • Missing opportunities costs users significant yields
  2. Reactive Aggregators Fall Short

    • Existing vault aggregators (Yearn, Beefy) rebalance after rates drop
    • No predictive intelligence - always one step behind
    • Single-chain focus limits yield potential
  3. High Rebalancing Costs

    • Manual rebalancing wastes gas fees
    • Small accounts can't afford frequent rebalancing
    • Timing rebalances optimally requires constant attention
  4. Lack of Transparency

    • Black-box algorithms make opaque decisions
    • Users don't understand why funds move
    • No audit trail for strategy changes

Result: Users leave 1-3% APY on the table annually, costing billions in lost yields.


Solution

ReVaultron: Predictive, Multi-Chain, AI-Driven Yield Optimization

ReVaultron is an ERC-4626 compliant vault that uses Chainlink Runtime Environment (CRE) to orchestrate AI-powered yield optimization across multiple blockchains.

Core Capabilities

βœ… Predictive AI Allocation - Gemini AI forecasts which strategies will outperform before they do
βœ… Multi-Chain Execution - Aggregates best yields from Ethereum and Base simultaneously
βœ… Autonomous Rebalancing - CRE automatically moves funds when opportunities arise
βœ… Gas Optimized - Only rebalances when profit exceeds transaction costs
βœ… Full Transparency - All AI decisions logged on-chain and in Firestore
βœ… Standard Compliant - ERC-4626 vault compatible with all DeFi integrations

How It Works

User deposits USDC β†’ ReVaultron analyzes strategies via AI β†’ 
CRE allocates across chains β†’ AI monitors 24/7 β†’ 
Autonomous rebalancing β†’ User earns optimal yields

Architecture Overview

System Architecture

graph TB
    subgraph "User Interface"
        A[User] -->|Deposit USDC| B[ReVaultron Vault]
        B -->|Withdraw + Yields| A
        A -->|View Performance| UI[Next.js Dashboard]
    end
    
    subgraph "Chainlink Runtime Environment"
        CRE[CRE Workflow Orchestrator]
        CRE -->|Triggers AI Analysis| AI[Gemini AI Engine]
        CRE -->|Fetches Strategy Data| APIs[DeFi APIs]
        CRE -->|Stores Analytics| DB[(Firestore)]
        CRE -->|Executes Rebalancing| TXN[Transaction Executor]
    end
    
    subgraph "Ethereum Sepolia"
        B -->|Allocates| E1[Aave USDC Strategy]
        B -->|Allocates| E2[Yearn USDC Vault]
        TXN -->|Rebalance| E1
        TXN -->|Rebalance| E2
    end
    
    subgraph "Base Sepolia"
        B -->|Bridge & Allocate| B1[Uniswap V3 USDC/WETH LP]
        B -->|Bridge & Allocate| B2[Beefy Optimized Vault]
        TXN -->|Rebalance| B1
        TXN -->|Rebalance| B2
    end
    
    AI -->|Strategy Recommendations| CRE
    APIs -->|Current APYs & TVL| AI
    E1 -->|Performance Data| CRE
    E2 -->|Performance Data| CRE
    B1 -->|Performance Data| CRE
    B2 -->|Performance Data| CRE
    
    DB -->|Historical Data| UI
    
    style CRE fill:#00ff00,stroke:#006600,stroke-width:3px
    style AI fill:#ff9900,stroke:#cc6600,stroke-width:2px
    style B fill:#0066ff,stroke:#003399,stroke-width:2px
Loading

Component Flow

sequenceDiagram
    participant User
    participant ReVaultron
    participant CRE
    participant Gemini AI
    participant Ethereum
    participant Base
    participant Firestore
    
    User->>ReVaultron: Deposit 1000 USDC
    ReVaultron->>CRE: Emit DepositEvent
    
    Note over CRE: Triggered every 6 hours or on deposit
    
    CRE->>Ethereum: Fetch Aave APY (4.2%)
    CRE->>Ethereum: Fetch Yearn APY (5.1%)
    CRE->>Base: Fetch Uniswap LP APY (8.5%)
    CRE->>Base: Fetch Beefy APY (6.3%)
    
    CRE->>Gemini AI: Analyze strategies + market context
    
    Note over Gemini AI: Predicts optimal allocation<br/>based on trends, risk, gas
    
    Gemini AI-->>CRE: Recommended allocation:<br/>Aave 30%, Yearn 35%,<br/>Uniswap 25%, Beefy 10%
    
    CRE->>Ethereum: Allocate 650 USDC (65%)
    CRE->>Base: Bridge 350 USDC (35%)
    
    Ethereum-->>ReVaultron: Deposited to Aave + Yearn
    Base-->>ReVaultron: Deposited to Uniswap + Beefy
    
    CRE->>Firestore: Log AI decision + allocations
    
    Note over CRE: 6 hours later...
    
    CRE->>Gemini AI: Re-analyze (Yearn APY dropped to 3.8%)
    Gemini AI-->>CRE: Rebalance: Move 15% from Yearn to Uniswap
    
    CRE->>Ethereum: Withdraw from Yearn
    CRE->>Base: Deposit to Uniswap
    
    CRE->>Firestore: Log rebalancing event
    
    User->>ReVaultron: View Dashboard
    ReVaultron->>Firestore: Fetch analytics
    Firestore-->>User: Display AI insights + performance
Loading

Protocol Design

Smart Contract Architecture

classDiagram
    class ReVaultron {
        +ERC4626
        +IERC20 asset
        +Strategy[] strategies
        +mapping allocations
        +deposit(uint256 assets)
        +withdraw(uint256 shares)
        +rebalance(uint256[] newAllocations)
        +harvest()
        +totalAssets() uint256
    }
    
    class IStrategy {
        <<interface>>
        +deposit(uint256 amount)
        +withdraw(uint256 amount)
        +balanceOf() uint256
        +apy() uint256
    }
    
    class AaveStrategy {
        +IPool aavePool
        +deposit(uint256 amount)
        +withdraw(uint256 amount)
        +harvest()
        +balanceOf() uint256
    }
    
    class YearnStrategy {
        +IYearnVault yearnVault
        +deposit(uint256 amount)
        +withdraw(uint256 amount)
        +harvest()
        +balanceOf() uint256
    }
    
    class UniswapV3Strategy {
        +INonfungiblePositionManager positionManager
        +deposit(uint256 amount)
        +withdraw(uint256 amount)
        +collectFees()
        +balanceOf() uint256
    }
    
    class BeefyStrategy {
        +IBeefyVault beefyVault
        +deposit(uint256 amount)
        +withdraw(uint256 amount)
        +harvest()
        +balanceOf() uint256
    }
    
    class ReceiverTemplate {
        +onReport(bytes report, bytes32[] signatures)
        +validateSignatures()
    }
    
    ReVaultron --|> ReceiverTemplate
    ReVaultron --> IStrategy
    IStrategy <|.. AaveStrategy
    IStrategy <|.. YearnStrategy
    IStrategy <|.. UniswapV3Strategy
    IStrategy <|.. BeefyStrategy
Loading

Data Flow

flowchart TD
    Start([User Deposits USDC]) --> Vault[ReVaultron Vault Contract]
    
    Vault --> Event{Emit Deposit Event}
    Event --> CRE[CRE Workflow Listener]
    
    CRE --> Fetch[Fetch Strategy Data]
    Fetch --> |Ethereum| AaveData[Aave APY: 4.2%]
    Fetch --> |Ethereum| YearnData[Yearn APY: 5.1%]
    Fetch --> |Base| UniData[Uniswap LP APY: 8.5%]
    Fetch --> |Base| BeefyData[Beefy APY: 6.3%]
    
    AaveData --> AI{Gemini AI Analyzer}
    YearnData --> AI
    UniData --> AI
    BeefyData --> AI
    
    AI --> |Market Context| Context[Fed Rates, Volatility,<br/>TVL Trends, Gas Prices]
    Context --> AI
    
    AI --> Decision{AI Decision Engine}
    Decision --> Allocation[Optimal Allocation:<br/>Aave 30%, Yearn 35%,<br/>Uniswap 25%, Beefy 10%]
    
    Allocation --> GasCheck{Profitable after<br/>gas costs?}
    GasCheck -->|No| Wait[Wait for next cycle]
    GasCheck -->|Yes| Execute[Execute Rebalancing]
    
    Execute --> ETH[Ethereum Txns]
    Execute --> BASE[Base Txns]
    
    ETH --> AaveDep[Deposit to Aave]
    ETH --> YearnDep[Deposit to Yearn]
    BASE --> UniDep[Deposit to Uniswap]
    BASE --> BeefyDep[Deposit to Beefy]
    
    AaveDep --> Log[Log to Firestore]
    YearnDep --> Log
    UniDep --> Log
    BeefyDep --> Log
    
    Log --> Monitor[24/7 Monitoring]
    Monitor --> |Every 6 hours| CRE
    
    Wait --> Monitor
    
    style AI fill:#ff9900
    style CRE fill:#00ff00
    style Decision fill:#ff9900
    style Vault fill:#0066ff
Loading

Key Innovations

1. Predictive AI Allocation

Unlike reactive vault aggregators, ReVaultron uses AI to forecast which strategies will outperform:

// AI analyzes historical trends, not just current APYs
const prediction = await analyzeStrategy({
  currentAPY: 5.1,
  trend30d: [4.8, 4.9, 5.0, 5.1, 5.2],  // Upward trend
  volatility: 0.8,                        // Low volatility
  tvlGrowth: 1.15,                        // 15% TVL increase
  marketConditions: "bullish"
});

// Result: "Predicted APY in 7 days: 5.8% (confidence: 82%)"

Impact: Users capture yields 1-2 days before others notice the opportunity.

2. Multi-Chain Orchestration via CRE

First vault to use CRE for seamless cross-chain yield optimization:

// CRE executes complex multi-chain rebalancing atomically
function rebalanceMultiChain(
    RebalanceParams[] calldata ethereumOps,
    RebalanceParams[] calldata baseOps
) external onlyForwarder {
    // Execute all Ethereum operations
    for (uint i = 0; i < ethereumOps.length; i++) {
        _executeRebalance(ethereumOps[i]);
    }
    
    // Bridge funds to Base if needed
    if (baseOps.length > 0) {
        _bridgeToBase(calculateBaseNeeds(baseOps));
    }
    
    // Base operations executed via CRE on Base chain
}

Impact: Capture yields on any chain without manual intervention.

3. Gas-Optimized Execution

Only rebalances when profit exceeds costs:

const netProfit = calculateRebalanceProfit(currentAllocation, targetAllocation);
const gasCost = estimateGasCost(rebalancingTxns);

if (netProfit <= gasCost * 1.5) {  // 50% margin
  console.log("Skipping rebalance - not profitable");
  return;
}

Impact: Small accounts benefit without gas costs eating returns.

4. Full Transparency & Auditability

Every AI decision is logged with complete reasoning:

{
  "timestamp": "2026-02-15T10:30:00Z",
  "aiRecommendation": {
    "allocations": {"aave": 30, "yearn": 35, "uniswap": 25, "beefy": 10},
    "reasoning": "Yearn showing strong upward trend (4.8% β†’ 5.1% over 30d). Uniswap LP fees elevated due to high ETH volatility. Aave stable but lower ceiling.",
    "confidence": 0.82,
    "expectedAPY": "5.8%",
    "riskLevel": "medium"
  },
  "executed": true,
  "gasSpent": "0.0045 ETH",
  "netProfit": "12.5 USDC"
}

Impact: Users trust the system and can audit all decisions.

5. ERC-4626 Standard Compliance

Fully compatible with DeFi ecosystem:

  • βœ… Compatible with aggregator aggregators (1inch, Zapper)
  • βœ… Can be used as collateral in lending protocols
  • βœ… Composable with other DeFi primitives
  • βœ… Standard deposit/withdraw interfaces

Repository Structure

revaultron-protocol/
β”œβ”€β”€ contracts/                          # Foundry smart contracts
β”‚   β”œβ”€β”€ src/
β”‚   β”‚   β”œβ”€β”€ ReVaultron.sol             # Main ERC-4626 vault
β”‚   β”‚   β”œβ”€β”€ ReVaultronSatellite.sol    # Cross-chain satellite vaults
β”‚   β”‚   β”œβ”€β”€ strategies/
β”‚   β”‚   β”‚   β”œβ”€β”€ BaseStrategy.sol       # Abstract strategy template
β”‚   β”‚   β”‚   β”œβ”€β”€ AaveStrategy.sol       # Aave v3 integration
β”‚   β”‚   β”‚   β”œβ”€β”€ YearnStrategy.sol      # Yearn vault integration
β”‚   β”‚   β”‚   β”œβ”€β”€ UniswapV3Strategy.sol  # Uniswap V3 LP strategy
β”‚   β”‚   β”‚   └── BeefyStrategy.sol      # Beefy vault integration
β”‚   β”‚   β”œβ”€β”€ interfaces/
β”‚   β”‚   β”‚   β”œβ”€β”€ IStrategy.sol
β”‚   β”‚   β”‚   β”œβ”€β”€ IAave.sol
β”‚   β”‚   β”‚   β”œβ”€β”€ IYearn.sol
β”‚   β”‚   β”‚   β”œβ”€β”€ IUniswapV3.sol
β”‚   β”‚   β”‚   └── IBeefy.sol
β”‚   β”‚   β”œβ”€β”€ libraries/
β”‚   β”‚   β”‚   β”œβ”€β”€ RebalanceLib.sol       # Rebalancing calculations
β”‚   β”‚   β”‚   └── GasEstimator.sol       # Gas cost estimation
β”‚   β”‚   └── ReceiverTemplate.sol       # CRE receiver integration
β”‚   β”œβ”€β”€ script/
β”‚   β”‚   β”œβ”€β”€ Deploy.s.sol               # Deployment script
β”‚   β”‚   β”œβ”€β”€ DeployStrategies.s.sol     # Strategy deployment
β”‚   β”‚   β”œβ”€β”€ AddStrategy.s.sol          # Add new strategy
β”‚   β”‚   β”œβ”€β”€ Rebalance.s.sol            # Manual rebalance (testing)
β”‚   β”‚   └── Simulate.s.sol             # Local simulation
β”‚   β”œβ”€β”€ test/
β”‚   β”‚   β”œβ”€β”€ ReVaultron.t.sol           # Vault tests
β”‚   β”‚   β”œβ”€β”€ Strategies.t.sol           # Strategy tests
β”‚   β”‚   β”œβ”€β”€ Rebalancing.t.sol          # Rebalancing logic tests
β”‚   β”‚   β”œβ”€β”€ Integration.t.sol          # End-to-end tests
β”‚   β”‚   └── mocks/                     # Mock contracts for testing
β”‚   β”œβ”€β”€ foundry.toml
β”‚   └── README.md
β”‚
β”œβ”€β”€ cre-workflow/                       # Chainlink Runtime Environment
β”‚   β”œβ”€β”€ revaultron-orchestrator/
β”‚   β”‚   β”œβ”€β”€ src/
β”‚   β”‚   β”‚   β”œβ”€β”€ workflow.ts            # Main CRE workflow logic
β”‚   β”‚   β”‚   β”œβ”€β”€ aiAnalyzer.ts          # Gemini AI integration
β”‚   β”‚   β”‚   β”œβ”€β”€ strategyFetcher.ts     # Multi-chain data fetching
β”‚   β”‚   β”‚   β”œβ”€β”€ rebalancer.ts          # Rebalancing execution engine
β”‚   β”‚   β”‚   β”œβ”€β”€ gasEstimator.ts        # Gas cost calculations
β”‚   β”‚   β”‚   β”œβ”€β”€ firestoreLogger.ts     # Analytics storage
β”‚   β”‚   β”‚   └── types.ts               # TypeScript type definitions
β”‚   β”‚   β”œβ”€β”€ config.json                # Protocol addresses & config
β”‚   β”‚   β”œβ”€β”€ package.json
β”‚   β”‚   β”œβ”€β”€ tsconfig.json
β”‚   β”‚   └── README.md
β”‚   β”œβ”€β”€ project.yaml                   # CRE project configuration
β”‚   β”œβ”€β”€ .env.example                   # Environment variables template
β”‚   └── README.md
β”‚
β”œβ”€β”€ frontend/                           # Next.js user interface
β”‚   β”œβ”€β”€ app/
β”‚   β”‚   β”œβ”€β”€ page.tsx                   # Main dashboard
β”‚   β”‚   β”œβ”€β”€ vault/
β”‚   β”‚   β”‚   └── [id]/
β”‚   β”‚   β”‚       └── page.tsx           # Individual vault details
β”‚   β”‚   β”œβ”€β”€ analytics/
β”‚   β”‚   β”‚   └── page.tsx               # Historical analytics
β”‚   β”‚   β”œβ”€β”€ layout.tsx
β”‚   β”‚   └── globals.css
β”‚   β”œβ”€β”€ components/
β”‚   β”‚   β”œβ”€β”€ VaultStats.tsx             # TVL, APY, performance
β”‚   β”‚   β”œβ”€β”€ AllocationChart.tsx        # Pie chart of allocations
β”‚   β”‚   β”œβ”€β”€ AIInsights.tsx             # AI reasoning display
β”‚   β”‚   β”œβ”€β”€ PerformanceGraph.tsx       # Historical APY graph
β”‚   β”‚   β”œβ”€β”€ RebalanceHistory.tsx       # Past rebalancing events
β”‚   β”‚   β”œβ”€β”€ StrategyCard.tsx           # Individual strategy info
β”‚   β”‚   β”œβ”€β”€ DepositWithdraw.tsx        # User interaction
β”‚   β”‚   └── ConnectWallet.tsx          # Wallet connection
β”‚   β”œβ”€β”€ lib/
β”‚   β”‚   β”œβ”€β”€ firebase.ts                # Firebase/Firestore config
β”‚   β”‚   β”œβ”€β”€ contracts.ts               # Contract ABIs & addresses
β”‚   β”‚   β”œβ”€β”€ wagmi.ts                   # Wagmi configuration
β”‚   β”‚   └── utils.ts                   # Utility functions
β”‚   β”œβ”€β”€ public/
β”‚   β”œβ”€β”€ .env.local.example
β”‚   β”œβ”€β”€ package.json
β”‚   β”œβ”€β”€ tailwind.config.ts
β”‚   └── README.md
β”‚
β”œβ”€β”€ docs/                               # Additional documentation
β”‚   β”œβ”€β”€ ARCHITECTURE.md                # Detailed architecture
β”‚   β”œβ”€β”€ DEPLOYMENT.md                  # Deployment guide
β”‚   β”œβ”€β”€ TESTING.md                     # Testing guide
β”‚   └── AI_STRATEGY.md                 # AI decision-making explained
β”‚
β”œβ”€β”€ .github/
β”‚   └── workflows/
β”‚       β”œβ”€β”€ test.yml                   # CI/CD for smart contracts
β”‚       └── deploy.yml                 # Automated deployment
β”‚
β”œβ”€β”€ README.md                          # This file
β”œβ”€β”€ LICENSE
└── .gitignore

CRE Workflow Integration

Overview

Chainlink Runtime Environment (CRE) serves as the autonomous orchestration layer that enables ReVaultron to operate 24/7 without human intervention.

CRE Workflow Components

graph LR
    A[Event Listener] -->|Deposit/Withdraw Events| B[Trigger Handler]
    B --> C[Strategy Data Fetcher]
    C --> D[AI Analyzer]
    D --> E[Decision Engine]
    E --> F{Rebalance Needed?}
    F -->|Yes| G[Gas Cost Calculator]
    F -->|No| H[Wait Next Cycle]
    G --> I{Profitable?}
    I -->|Yes| J[Transaction Executor]
    I -->|No| H
    J --> K[Multi-Chain Executor]
    K --> L[Firestore Logger]
    L --> H
    
    style D fill:#ff9900
    style K fill:#00ff00
Loading

Workflow Execution Flow

1. Initialization & Listening

// cre-workflow/revaultron-orchestrator/src/workflow.ts

export async function initializeWorkflow() {
  // Listen for deposit events
  const depositListener = await setupEventListener({
    contract: REVAULTRON_ADDRESS,
    event: "Deposit",
    chains: ["ethereum-testnet-sepolia", "base-testnet-sepolia"]
  });
  
  // Scheduled execution every 6 hours
  const scheduler = setupScheduler({
    interval: "0 */6 * * *",  // Every 6 hours
    handler: analyzeAndRebalance
  });
  
  console.log("ReVaultron CRE Workflow initialized βœ…");
}

2. Strategy Data Fetching

// Fetch real-time data from multiple chains in parallel
async function fetchStrategyData(): Promise<StrategyData[]> {
  const [ethereumData, baseData] = await Promise.all([
    fetchEthereumStrategies(),
    fetchBaseStrategies()
  ]);
  
  return [...ethereumData, ...baseData];
}

async function fetchEthereumStrategies(): Promise<StrategyData[]> {
  // Fetch Aave APY
  const aaveAPY = await fetchAaveAPY(AAVE_USDC_POOL);
  
  // Fetch Yearn APY
  const yearnAPY = await fetchYearnAPY(YEARN_USDC_VAULT);
  
  return [
    {
      id: "aave-eth",
      protocol: "Aave",
      chain: "ethereum",
      apy: aaveAPY,
      tvl: await getAaveTVL(),
      risk: "low"
    },
    {
      id: "yearn-eth",
      protocol: "Yearn",
      chain: "ethereum",
      apy: yearnAPY,
      tvl: await getYearnTVL(),
      risk: "medium"
    }
  ];
}

3. AI Analysis via Gemini

// cre-workflow/revaultron-orchestrator/src/aiAnalyzer.ts

async function analyzeStrategies(
  strategies: StrategyData[],
  currentAllocations: Allocation[]
): Promise<AIRecommendation> {
  
  const prompt = `
You are a DeFi yield optimization AI analyzing strategies for ReVaultron vault.

CURRENT STRATEGIES:
${JSON.stringify(strategies, null, 2)}

CURRENT ALLOCATIONS:
${JSON.stringify(currentAllocations, null, 2)}

MARKET CONTEXT:
- Fed Funds Rate: 4.5%
- ETH Price: $2,850 (volatility: high)
- USDC Market Cap: $34B
- Gas Prices: Ethereum 35 gwei, Base 0.05 gwei

HISTORICAL PERFORMANCE (Last 30 days):
- Aave: Stable 4.0-4.5% APY, never dropped below 3.8%
- Yearn: Volatile 4.5-6.2% APY, trending upward (+0.8% this week)
- Uniswap V3: High fees due to volatility, 7-12% APY, IL risk
- Beefy: Auto-compounding, steady 5.5-6.5% APY

YOUR TASK:
Recommend optimal allocation considering:
1. Expected APY over next 7 days (predict, don't just use current)
2. Risk-adjusted returns (penalize high volatility)
3. Gas costs for rebalancing (favor Base if similar APY)
4. Diversification (don't put 100% in one strategy)
5. Impermanent loss risk for LP positions

Respond ONLY with valid JSON:
{
  "allocations": {
    "aave-eth": <0-100>,
    "yearn-eth": <0-100>,
    "uniswap-base": <0-100>,
    "beefy-base": <0-100>
  },
  "reasoning": "<detailed explanation>",
  "confidence": <0.0-1.0>,
  "expectedAPY": "<percentage>",
  "riskLevel": "low|medium|high",
  "rebalanceRecommended": true|false
}

IMPORTANT: Allocations must sum to exactly 100.
`;

  const response = await callGemini({
    model: "gemini-2.0-flash-exp",
    prompt: prompt,
    temperature: 0.3  // Lower temperature for consistent financial decisions
  });
  
  return parseAIResponse(response);
}

4. Decision Engine & Gas Optimization

async function shouldRebalance(
  current: Allocation[],
  recommended: Allocation[],
  strategies: StrategyData[]
): Promise<{ shouldRebalance: boolean; netProfit: number }> {
  
  // Calculate expected profit from rebalancing
  const expectedProfit = calculateExpectedProfit(current, recommended, strategies);
  
  // Estimate gas costs
  const rebalancingTxns = calculateRebalancingTxns(current, recommended);
  const gasCost = await estimateGasCost(rebalancingTxns);
  
  // Need 50% margin over gas cost
  const netProfit = expectedProfit - (gasCost * 1.5);
  
  return {
    shouldRebalance: netProfit > 0,
    netProfit
  };
}

5. Multi-Chain Transaction Execution

async function executeRebalancing(
  rebalancePlan: RebalancePlan
): Promise<ExecutionResult> {
  
  const results: TransactionResult[] = [];
  
  // Execute Ethereum operations
  if (rebalancePlan.ethereum.length > 0) {
    const ethResults = await executeEthereumRebalance(rebalancePlan.ethereum);
    results.push(...ethResults);
  }
  
  // Execute Base operations
  if (rebalancePlan.base.length > 0) {
    const baseResults = await executeBaseRebalance(rebalancePlan.base);
    results.push(...baseResults);
  }
  
  // Log all transactions to Firestore
  await logExecutionToFirestore({
    timestamp: Date.now(),
    transactions: results,
    totalGas: sumGasCosts(results),
    netProfit: calculateNetProfit(results)
  });
  
  return {
    success: results.every(r => r.success),
    transactions: results
  };
}

CRE Configuration

# cre-workflow/project.yaml

name: revaultron-orchestrator
version: 1.0.0

environments:
  local-simulation:
    rpcs:
      - chain-name: ethereum-testnet-sepolia
        url: ${ETHEREUM_SEPOLIA_RPC}
      - chain-name: base-testnet-sepolia
        url: ${BASE_SEPOLIA_RPC}
    
  production:
    rpcs:
      - chain-name: ethereum-testnet-sepolia
        url: ${ETHEREUM_SEPOLIA_RPC}
      - chain-name: base-testnet-sepolia
        url: ${BASE_SEPOLIA_RPC}

workflows:
  - name: revaultron-orchestrator
    entry: src/workflow.ts
    triggers:
      - type: event
        contracts:
          - address: ${REVAULTRON_ETH_ADDRESS}
            chain: ethereum-testnet-sepolia
            events: ["Deposit", "Withdraw"]
          - address: ${REVAULTRON_BASE_ADDRESS}
            chain: base-testnet-sepolia
            events: ["Deposit", "Withdraw"]
      - type: schedule
        cron: "0 */6 * * *"  # Every 6 hours

Technical Implementation

Smart Contract Details

ReVaultron Main Vault

// contracts/src/ReVaultron.sol

contract ReVaultron is ERC4626, ReceiverTemplate, Ownable {
    using SafeERC20 for IERC20;
    
    struct Strategy {
        address strategyAddress;
        uint256 targetAllocation;  // Basis points (10000 = 100%)
        uint256 currentBalance;
        uint8 chainId;
        bool isActive;
        string name;
    }
    
    Strategy[] public strategies;
    
    // Events
    event StrategyAdded(address indexed strategy, string name);
    event Rebalanced(uint256[] oldAllocations, uint256[] newAllocations);
    event AIDecisionReceived(bytes32 indexed decisionHash, uint256 timestamp);
    
    constructor(
        IERC20 _asset,
        string memory _name,
        string memory _symbol
    ) ERC4626(_asset) ERC20(_name, _symbol) {}
    
    /// @notice Rebalance vault based on AI recommendation from CRE
    function rebalance(
        uint256[] calldata newAllocations,
        bytes calldata aiProof
    ) external onlyForwarder {
        require(newAllocations.length == strategies.length, "Invalid allocations");
        require(_sumAllocations(newAllocations) == 10000, "Must sum to 100%");
        
        uint256[] memory oldAllocations = _getCurrentAllocations();
        
        // Execute rebalancing
        _executeRebalance(oldAllocations, newAllocations);
        
        emit Rebalanced(oldAllocations, newAllocations);
        emit AIDecisionReceived(keccak256(aiProof), block.timestamp);
    }
    
    /// @notice Get total assets under management across all strategies
    function totalAssets() public view override returns (uint256) {
        uint256 total = asset.balanceOf(address(this));  // Idle funds
        
        for (uint256 i = 0; i < strategies.length; i++) {
            if (strategies[i].isActive) {
                total += IStrategy(strategies[i].strategyAddress).balanceOf();
            }
        }
        
        return total;
    }
}

Strategy Interface

// contracts/src/interfaces/IStrategy.sol

interface IStrategy {
    /// @notice Deposit assets into the strategy
    function deposit(uint256 amount) external returns (uint256 sharesReceived);
    
    /// @notice Withdraw assets from the strategy
    function withdraw(uint256 amount) external returns (uint256 assetsReceived);
    
    /// @notice Harvest and compound rewards
    function harvest() external returns (uint256 harvested);
    
    /// @notice Get current balance of assets in strategy
    function balanceOf() external view returns (uint256);
    
    /// @notice Get current APY (in basis points)
    function apy() external view returns (uint256);
    
    /// @notice Get strategy name
    function name() external view returns (string memory);
}

Key Features Implementation

Gas-Optimized Batch Rebalancing

function _executeRebalance(
    uint256[] memory oldAllocations,
    uint256[] memory newAllocations
) internal {
    uint256 totalValue = totalAssets();
    
    // Step 1: Withdraw from over-allocated strategies
    for (uint256 i = 0; i < strategies.length; i++) {
        if (newAllocations[i] < oldAllocations[i]) {
            uint256 targetValue = (totalValue * newAllocations[i]) / 10000;
            uint256 currentValue = strategies[i].currentBalance;
            uint256 withdrawAmount = currentValue - targetValue;
            
            IStrategy(strategies[i].strategyAddress).withdraw(withdrawAmount);
        }
    }
    
    // Step 2: Deposit to under-allocated strategies
    for (uint256 i = 0; i < strategies.length; i++) {
        if (newAllocations[i] > oldAllocations[i]) {
            uint256 targetValue = (totalValue * newAllocations[i]) / 10000;
            uint256 currentValue = strategies[i].currentBalance;
            uint256 depositAmount = targetValue - currentValue;
            
            asset.safeApprove(strategies[i].strategyAddress, depositAmount);
            IStrategy(strategies[i].strategyAddress).deposit(depositAmount);
        }
    }
}

Historical Performance Tracking

// Frontend performance calculation
interface PerformanceMetrics {
  totalDeposits: number;
  totalWithdrawals: number;
  currentValue: number;
  roi: number;
  apyActual: number;
  aiPredictedAPY: number;
  aiAccuracy: number;
}

async function calculatePerformance(
  vaultAddress: string,
  userAddress: string
): Promise<PerformanceMetrics> {
  
  // Fetch user's deposit/withdrawal history
  const events = await fetchVaultEvents(vaultAddress, userAddress);
  
  // Calculate time-weighted returns
  const twr = calculateTimeWeightedReturn(events);
  
  // Fetch AI predictions vs actual results
  const aiAccuracy = await calculateAIPredictionAccuracy(vaultAddress);
  
  return {
    totalDeposits: sumDeposits(events),
    totalWithdrawals: sumWithdrawals(events),
    currentValue: await getCurrentValue(vaultAddress, userAddress),
    roi: twr,
    apyActual: annualizeReturn(twr),
    aiPredictedAPY: await getLatestAIPrediction(vaultAddress),
    aiAccuracy: aiAccuracy
  };
}

Quick Start

Prerequisites

Required Software:

Required Accounts & Keys:

Installation

1. Clone Repository

git clone https://github.com/yourusername/revaultron-protocol.git
cd revaultron-protocol

2. Install Contract Dependencies

cd contracts
forge install

3. Set Contract Environment Variables

# In contracts directory
cp .env.example .env

# Edit .env with your values:
# PRIVATE_KEY=0x...
# ETHEREUM_SEPOLIA_RPC=https://...
# BASE_SEPOLIA_RPC=https://...
# ETHERSCAN_API_KEY=...
# BASESCAN_API_KEY=...

4. Deploy Smart Contracts

# Deploy to Ethereum Sepolia
forge script script/Deploy.s.sol:DeployReVaultron \
  --rpc-url $ETHEREUM_SEPOLIA_RPC \
  --broadcast \
  --verify

# Note the deployed ReVaultron address

# Deploy strategies
forge script script/DeployStrategies.s.sol:DeployStrategies \
  --rpc-url $ETHEREUM_SEPOLIA_RPC \
  --broadcast \
  --verify

5. Install CRE Workflow Dependencies

cd ../cre-workflow/revaultron-orchestrator
bun install

6. Configure CRE Workflow

# Copy example config
cp .env.example .env

# Edit .env:
# CRE_ETH_PRIVATE_KEY=0x...
# CRE_TARGET=local-simulation
# GEMINI_API_KEY_VAR=...
# FIREBASE_API_KEY_VAR=...
# FIREBASE_PROJECT_ID_VAR=...
# ETHEREUM_SEPOLIA_RPC=https://...
# BASE_SEPOLIA_RPC=https://...

Edit config.json with your deployed contract addresses:

{
  "geminiModel": "gemini-2.0-flash-exp",
  "rebalanceIntervalHours": 6,
  "gasMarginPercent": 50,
  "vaults": [
    {
      "address": "0xYourReVaultronAddress",
      "chain": "ethereum-testnet-sepolia",
      "strategies": [
        {
          "id": "aave-eth",
          "address": "0xAaveStrategyAddress",
          "protocol": "Aave"
        },
        {
          "id": "yearn-eth",
          "address": "0xYearnStrategyAddress",
          "protocol": "Yearn"
        }
      ]
    }
  ]
}

7. Test CRE Workflow Simulation

# Simulate workflow locally
cre workflow simulate revaultron-orchestrator --target local-simulation

# When prompted, use a test transaction or create one by depositing to the vault

8. Install Frontend Dependencies

cd ../../frontend
bun install

9. Configure Frontend

cp .env.local.example .env.local

# Edit .env.local:
# NEXT_PUBLIC_ETHEREUM_SEPOLIA_RPC=https://...
# NEXT_PUBLIC_BASE_SEPOLIA_RPC=https://...
# NEXT_PUBLIC_REVAULTRON_ETH_ADDRESS=0x...
# NEXT_PUBLIC_FIREBASE_API_KEY=...
# NEXT_PUBLIC_FIREBASE_PROJECT_ID=...

10. Run Frontend

bun run dev

Visit http://localhost:3000 to see your ReVaultron dashboard!


User Flow

Complete User Journey

graph TD
    A[User Visits Dashboard] --> B{Has Wallet?}
    B -->|No| C[Connect Wallet]
    B -->|Yes| D[View Vault Performance]
    C --> D
    
    D --> E[See Current Strategies]
    E --> F{Want to Deposit?}
    
    F -->|Yes| G[Enter Amount]
    F -->|No| M[Monitor Performance]
    
    G --> H[Approve USDC]
    H --> I[Deposit to Vault]
    I --> J[Receive Vault Shares]
    
    J --> K[CRE Detects Deposit]
    K --> L[AI Analyzes Strategies]
    L --> N[Funds Allocated Across Chains]
    
    N --> M
    M --> O{Every 6 Hours}
    
    O --> P[CRE Checks Strategies]
    P --> Q[AI Re-analyzes]
    Q --> R{Better Allocation?}
    
    R -->|Yes| S[Rebalance Executed]
    R -->|No| T[Continue Monitoring]
    
    S --> M
    T --> M
    
    M --> U{Want to Withdraw?}
    U -->|Yes| V[Request Withdrawal]
    U -->|No| M
    
    V --> W[Harvest from All Strategies]
    W --> X[Bridge Funds if Needed]
    X --> Y[Burn Vault Shares]
    Y --> Z[Receive USDC + Yields]
    
    style L fill:#ff9900
    style P fill:#00ff00
    style Q fill:#ff9900
Loading

Step-by-Step Example

Scenario: Alice deposits 1000 USDC

Step 1: Initial Deposit

  • Alice connects wallet to ReVaultron dashboard
  • Approves 1000 USDC for ReVaultron contract
  • Clicks "Deposit" β†’ Receives 1000 rvUSDC shares (1:1 ratio for first deposit)

Step 2: CRE Workflow Activated

  • CRE detects Deposit event on Ethereum
  • Fetches current APYs:
    • Aave (ETH): 4.2%
    • Yearn (ETH): 5.1%
    • Uniswap V3 (Base): 8.5%
    • Beefy (Base): 6.3%

Step 3: AI Analysis

  • Gemini analyzes strategies + market conditions
  • Recommendation:
    {
      "allocations": {
        "aave-eth": 30,      // 300 USDC
        "yearn-eth": 35,     // 350 USDC
        "uniswap-base": 25,  // 250 USDC
        "beefy-base": 10     // 100 USDC
      },
      "reasoning": "Yearn showing strong momentum. Uniswap LP benefiting from high volatility but capping at 25% due to IL risk. Base strategies get 35% total for lower gas costs.",
      "confidence": 0.85,
      "expectedAPY": "5.8%"
    }

Step 4: Allocation Execution

  • CRE deposits to Ethereum strategies (650 USDC total)
  • CRE bridges 350 USDC to Base
  • CRE deposits to Base strategies

Step 5: Monitoring (6 hours later)

  • CRE re-analyzes strategies
  • Yearn APY dropped to 3.8% (algo farm ended)
  • Uniswap LP APY increased to 10.2% (more volume)
  • AI recommends: Move 15% from Yearn to Uniswap

Step 6: Rebalancing

  • Gas cost estimated: 0.003 ETH ($8.50)
  • Expected profit: $15 (0.3% improvement on $1000 for 1 week)
  • Net profit: $6.50 β†’ βœ… Execute rebalance
  • Withdraw 150 USDC from Yearn
  • Deposit 150 USDC to Uniswap on Base

Step 7: Alice Checks Dashboard

  • Current allocation: 30% Aave, 20% Yearn, 40% Uniswap, 10% Beefy
  • Current APY: 6.1% (vs 5.1% if she only used Yearn)
  • Total value: 1003.50 USDC (0.35% gain in first week)
  • AI insight: "Portfolio rebalanced 6 hours ago. High confidence in current allocation (87%)."

Step 8: Withdrawal (30 days later)

  • Alice's 1000 USDC grew to 1048 USDC (4.8% over 30 days)
  • Alice clicks "Withdraw All"
  • CRE harvests rewards from all strategies
  • Funds bridged back to Ethereum if needed
  • Alice receives 1048 USDC, burns 1000 rvUSDC shares
  • Net APY achieved: 58.4% annualized (extrapolated from 30-day performance)

Demo

Video Walkthrough

πŸŽ₯ Watch the 4-minute demo: Link to video

Demo Highlights:

  1. Problem intro (0:00-0:30): Manual DeFi yield management pain points
  2. Solution overview (0:30-1:00): ReVaultron AI-powered approach
  3. Live deposit (1:00-1:30): User deposits USDC, CRE triggers
  4. AI analysis (1:30-2:15): Show Gemini reasoning, allocation decision
  5. Multi-chain execution (2:15-2:45): Funds allocate across Ethereum & Base
  6. Rebalancing (2:45-3:15): AI detects better opportunity, rebalances
  7. Performance results (3:15-3:45): Dashboard showing yields earned
  8. Architecture showcase (3:45-4:00): CRE workflow, smart contracts

Live Testnet Demo

Try it yourself:

  1. Visit: https://revaultron-demo.vercel.app
  2. Connect wallet (Ethereum Sepolia or Base Sepolia)
  3. Get testnet USDC from faucet
  4. Deposit any amount
  5. Watch AI allocate your funds in real-time
  6. Check back in 6 hours to see rebalancing

Deployed Contracts:

  • ReVaultron Vault (ETH Sepolia): 0x...
  • Aave Strategy: 0x...
  • Yearn Strategy: 0x...
  • ReVaultron Satellite (Base Sepolia): 0x...
  • Uniswap V3 Strategy: 0x...
  • Beefy Strategy: 0x...

Security Considerations

Smart Contract Security

βœ… OpenZeppelin Standards

  • Using audited ERC-4626 implementation
  • SafeERC20 for all token transfers
  • Ownable/AccessControl for privileged functions

βœ… CRE Forwarder Protection

modifier onlyForwarder() {
    require(msg.sender == forwarderAddress, "Only CRE forwarder");
    _;
}

βœ… Reentrancy Guards

  • All external calls protected
  • Checks-Effects-Interactions pattern

βœ… Emergency Functions

function pause() external onlyOwner {
    _pause();
}

function emergencyWithdraw(address strategy) external onlyOwner {
    // Withdraw all funds from specific strategy
}

Future Roadmap

Phase 1: MVP (Current) βœ…

  • βœ… Core vault functionality
  • βœ… 2 chains (Ethereum, Base)
  • βœ… 4 strategies (Aave, Yearn, Uniswap, Beefy)
  • βœ… AI-powered allocation
  • βœ… CRE orchestration
  • βœ… Basic frontend

Phase 2: Enhanced MVP (Post-Hackathon)

  • Add Arbitrum, Optimism chains
  • Integrate 10+ protocols
  • Advanced AI models (ensemble voting)
  • Historical backtesting dashboard
  • Gas optimization improvements
  • Mobile-responsive UI

Phase 3: Production Ready

  • Professional security audit
  • Mainnet deployment
  • Insurance integration (Nexus Mutual)
  • DAO governance
  • Performance fee mechanism
  • API for integrations

Phase 4: Advanced Features

  • Custom strategy builder
  • Social trading (copy top performers)
  • Automated tax reporting
  • Notifications (Telegram, Discord)
  • Risk-adjusted portfolio options
  • NFT-gated premium strategies

Contributing

We welcome contributions! Please see CONTRIBUTING.md for guidelines.

Development Setup

# Run tests
cd contracts && forge test

# Local CRE simulation
cd cre-workflow && cre workflow simulate revaultron-orchestrator --target local-simulation

# Run frontend locally
cd frontend && bun run dev

License

This project is licensed under the MIT License - see LICENSE file for details.


Acknowledgments

  • Chainlink for CRE infrastructure
  • Google for Gemini AI API
  • Firebase for data storage
  • OpenZeppelin for smart contract libraries
  • Aave, Yearn, Uniswap, Beefy for DeFi protocols

Contact

Team: [Your Name]
Twitter: @YourHandle
Email: your.email@example.com
Discord: YourUsername#1234

Project Links:


Built with ❀️ for Chainlink Convergence Hackathon

Revolutionizing DeFi yield optimization with AI and cross-chain orchestration

Get Started β€’ Watch Demo β€’ Read Docs

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors