AI-Powered Multi-Chain Yield Optimization Vault with Autonomous Rebalancing
Built with Chainlink Runtime Environment (CRE) Γ Gemini AI
π Built for Chainlink Convergence Hackathon
π― Tracks: DeFi & Tokenization | CRE & AI | Top 10 Projects
- Problem Statement
- Solution
- Architecture Overview
- Protocol Design
- Key Innovations
- Repository Structure
- CRE Workflow Integration
- Technical Implementation
- Quick Start
- User Flow
- Demo
- Security Considerations
- Future Roadmap
-
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
-
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
-
High Rebalancing Costs
- Manual rebalancing wastes gas fees
- Small accounts can't afford frequent rebalancing
- Timing rebalances optimally requires constant attention
-
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.
ReVaultron is an ERC-4626 compliant vault that uses Chainlink Runtime Environment (CRE) to orchestrate AI-powered yield optimization across multiple blockchains.
β
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
User deposits USDC β ReVaultron analyzes strategies via AI β
CRE allocates across chains β AI monitors 24/7 β
Autonomous rebalancing β User earns optimal yields
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
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
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
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
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.
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.
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.
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.
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
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
Chainlink Runtime Environment (CRE) serves as the autonomous orchestration layer that enables ReVaultron to operate 24/7 without human intervention.
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
// 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 β
");
}// 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"
}
];
}// 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);
}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
};
}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-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// 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;
}
}// 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);
}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);
}
}
}// 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
};
}Required Software:
- Git
- Node.js v20+
- Bun (JavaScript runtime)
- Foundry (Solidity development)
- Chainlink CRE CLI
Required Accounts & Keys:
- Gemini API Key (Free tier available)
- Firebase Project with Firestore enabled
- Ethereum Sepolia testnet ETH (faucet)
- Base Sepolia testnet ETH (faucet)
- Sepolia USDC tokens (swap from ETH on testnet Uniswap)
git clone https://github.com/yourusername/revaultron-protocol.git
cd revaultron-protocolcd contracts
forge install# 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=...# 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 \
--verifycd ../cre-workflow/revaultron-orchestrator
bun install# 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"
}
]
}
]
}# Simulate workflow locally
cre workflow simulate revaultron-orchestrator --target local-simulation
# When prompted, use a test transaction or create one by depositing to the vaultcd ../../frontend
bun installcp .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=...bun run devVisit http://localhost:3000 to see your ReVaultron dashboard!
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
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
Depositevent 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)
π₯ Watch the 4-minute demo: Link to video
Demo Highlights:
- Problem intro (0:00-0:30): Manual DeFi yield management pain points
- Solution overview (0:30-1:00): ReVaultron AI-powered approach
- Live deposit (1:00-1:30): User deposits USDC, CRE triggers
- AI analysis (1:30-2:15): Show Gemini reasoning, allocation decision
- Multi-chain execution (2:15-2:45): Funds allocate across Ethereum & Base
- Rebalancing (2:45-3:15): AI detects better opportunity, rebalances
- Performance results (3:15-3:45): Dashboard showing yields earned
- Architecture showcase (3:45-4:00): CRE workflow, smart contracts
Try it yourself:
- Visit: https://revaultron-demo.vercel.app
- Connect wallet (Ethereum Sepolia or Base Sepolia)
- Get testnet USDC from faucet
- Deposit any amount
- Watch AI allocate your funds in real-time
- 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...
β 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
}- β Core vault functionality
- β 2 chains (Ethereum, Base)
- β 4 strategies (Aave, Yearn, Uniswap, Beefy)
- β AI-powered allocation
- β CRE orchestration
- β Basic frontend
- Add Arbitrum, Optimism chains
- Integrate 10+ protocols
- Advanced AI models (ensemble voting)
- Historical backtesting dashboard
- Gas optimization improvements
- Mobile-responsive UI
- Professional security audit
- Mainnet deployment
- Insurance integration (Nexus Mutual)
- DAO governance
- Performance fee mechanism
- API for integrations
- Custom strategy builder
- Social trading (copy top performers)
- Automated tax reporting
- Notifications (Telegram, Discord)
- Risk-adjusted portfolio options
- NFT-gated premium strategies
We welcome contributions! Please see CONTRIBUTING.md for guidelines.
# 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 devThis project is licensed under the MIT License - see LICENSE file for details.
- 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
Team: [Your Name]
Twitter: @YourHandle
Email: your.email@example.com
Discord: YourUsername#1234
Project Links:
- π Website: https://revaultron.xyz
- π GitHub: https://github.com/yourusername/revaultron-protocol
- πΊ Demo Video: https://youtu.be/...
- π Documentation: https://docs.revaultron.xyz
Built with β€οΈ for Chainlink Convergence Hackathon
Revolutionizing DeFi yield optimization with AI and cross-chain orchestration
Get Started β’ Watch Demo β’ Read Docs