DeFi Vault Strategies for AI Agents: Yearn, Beefy, and Automated Yield Compounding
How autonomous agents can automate vault selection, compounding frequency optimisation, and multi-hop yield strategies across Yearn, Beefy, and Convex.
DeFi vaults are the workhorses of passive yield in crypto: they accept deposits, deploy capital into yield strategies, harvest rewards, and compound them back into the underlying position — all automatically and on-chain. For AI agents that want exposure to DeFi yield without building and monitoring strategies from scratch, vaults are the natural starting point.
But "vault" is not a homogenous category. Yearn's yVaults run sophisticated multi-strategy allocators. Beefy Finance runs simple single-strategy compounders across 20+ chains. Convex layers on top of Curve to boost CRV rewards. Each is optimised for different risk profiles, asset types, and compounding frequencies. Choosing well — and knowing when to rotate — can make the difference between 4% and 12% annual yield on the same underlying capital.
Purple Flea Wallet: Track vault token balances and deploy capital to ERC-20 vault contracts across Ethereum, Arbitrum, Polygon, and BNB from a single agent API. docs/wallet/
How DeFi Vaults Work
At the core, a DeFi vault is a smart contract with two primary functions:
- Deposit: User deposits an underlying asset (e.g., USDC, stETH, LP tokens). The vault mints a receipt token (e.g., yvUSDC, mooStETH) representing the user's share of the vault.
- Strategy Execution: The vault deploys the underlying into one or more yield strategies, periodically harvests rewards (trading fees, governance tokens, interest), swaps them back to the underlying, and re-deposits — increasing the value of each receipt token.
When the user withdraws, the vault burns their receipt tokens and returns the underlying plus accumulated yield. The receipt token's price appreciation relative to the underlying is the vault's yield.
Vault Architecture
Most vault systems follow the ERC-4626 tokenised vault standard (standardised in 2022), making them composable with other DeFi protocols:
deposit(assets, receiver)— deposit underlying, receive shareswithdraw(assets, receiver, owner)— redeem for exact underlying amountredeem(shares, receiver, owner)— redeem exact shares for underlyingconvertToAssets(shares)— calculate underlying value of sharesconvertToShares(assets)— calculate shares for underlying amount
Yearn Finance yVaults
Yearn Finance is the original DeFi yield aggregator, pioneered by Andre Cronje in 2020. Its yVaults are the most sophisticated vault implementations in DeFi — rather than a single strategy, each yVault can allocate to multiple strategies simultaneously, rotating between them based on yield.
Yearn v3 Architecture
The 2024 v3 upgrade introduced a fully permissionless strategy marketplace:
- Factory: Any developer can deploy a Yearn v3 vault from the factory contract
- Strategies as plugins: Vault managers plug in external strategy contracts; yields are aggregated
- Allocation weights: Each strategy has a debt ratio — the vault automatically rebalances when strategies are added or removed
- Accountant: Separate contract handles fee accounting (management fee: 2%, performance fee: 20% of yield above hurdle)
- Role-based access: Vault roles (Manager, Guardian, Emergency Admin) are governed by veYFI holders
Notable yVaults for Agents
yvUSDC — Yearn USDC Vault
The flagship stablecoin vault. Allocates USDC across Aave v3, Compound, Morpho, and Spark Protocol — automatically routing to highest rate.
yvWETH — Yearn WETH Vault
ETH vault deploying into Aave v3 ETH borrowing market, Morpho ETH, and stETH/ETH Curve LP. Denominates returns in ETH.
yvCRV-stETH — Curve stETH LP Vault
Accepts stETH/ETH Curve LP tokens, stakes them in Convex for boosted CRV rewards, auto-compounds into more LP tokens.
Beefy Finance
Beefy Finance takes a simpler, broader approach than Yearn: single-strategy vaults deployed across 25+ blockchains. Each "moo vault" targets a specific yield opportunity on a specific chain, with a harvester bot that auto-compounds rewards at configurable intervals.
Beefy's Key Advantages for Agents
- Chain breadth: Beefy operates on Arbitrum, Optimism, Polygon, Avalanche, BSC, Fantom, Cronos, and more — letting agents capture the best yield across any chain they hold assets on
- Simple interface: Single vault per strategy, clear APY display, no multi-strategy complexity to reason about
- Gas efficiency: Harvests batched across all vaults on a chain — individual users pay no gas for compounding
- Transparent source: All vault strategies are open source; agents can audit exactly where capital is deployed
- Low fees: 0.1% deposit fee, 0.1% withdrawal fee, 4.5% performance fee on yield (vs Yearn's 2%+20%)
Beefy Vault Categories
| Category | Strategy Type | Examples | Typical APY |
|---|---|---|---|
| LP Vaults | Provide LP, harvest trading fees + rewards | USDC/ETH Uni v3, USDC/USDT Curve | 5–25% |
| Single-Stake | Stake governance token for protocol rewards | mooSushiSUSHI, mooCakeBNB | 8–30% |
| Lending | Supply assets to lending protocols | mooAaveUSDC, mooCompETH | 3–8% |
| Boosted | Beefy governs veTokens for boosted LP rewards | mooCurve3pool, mooBeefy | 10–40% |
Convex Finance
Convex is not a standalone vault platform — it is a yield booster built on top of Curve Finance. Curve rewards Curve LP providers with CRV tokens, but the reward rate is boosted (up to 2.5x) for users who lock CRV as veCRV. Convex aggregates veCRV ownership on behalf of users, giving everyone access to maximum boosted rates without individually locking CRV.
cvxCRV and CVX
The Convex flywheel operates through two tokens:
- cvxCRV: Non-transferable receipt for CRV locked on Convex. Earns Curve admin fees + CVX rewards + boosted CRV. Liquid via secondary markets (cvxCRV/CRV Curve pool).
- CVX: Convex's governance token. Staked cvxCVX holders receive bribes from protocols seeking Convex's voting power to direct CRV emissions toward their pools.
Agent Convex Strategy
The optimal Convex workflow for an agent holding Curve LP tokens:
- Provide liquidity to a Curve pool (e.g., USDC/crvUSD pool) and receive LP tokens
- Deposit LP tokens to Convex — receive cvxToken (e.g., cvxcrvUSD-LP)
- Stake cvxToken to earn CRV + CVX + protocol bribes
- Use an auto-compounding Beefy vault on top of Convex (e.g., mooCurveConvex) to auto-harvest and restake
- Claim CVX separately, stake as vlCVX to earn bribes on Votium/Hidden Hand
Convex Bribe Market: vlCVX holders (locked CVX) receive bribes from protocols every 2-week epoch. In 2025, vlCVX earned $0.08–0.15 per CVX per epoch in bribes — annualising to 20-40% on CVX held. Bribe income is protocol-specific and varies each epoch.
Vault APY vs. APR: Critical Distinction
Many vaults display APR (Annual Percentage Rate) when the relevant figure for compounding positions is APY (Annual Percentage Yield). The difference is compounding frequency:
# APR to APY conversion — compounding frequency matters
import math
def apr_to_apy(apr: float, compounds_per_year: int) -> float:
"""Convert APR to APY given compounding frequency."""
return ((1 + apr / compounds_per_year) ** compounds_per_year) - 1
# At 20% APR, compounding frequency dramatically changes APY:
frequencies = {
"Annual (1x)": 1,
"Monthly (12x)": 12,
"Weekly (52x)": 52,
"Daily (365x)": 365,
"Hourly (8760x)": 8760,
"Continuous": 999999,
}
APR = 0.20
for name, n in frequencies.items():
apy = apr_to_apy(APR, n) * 100
print(f" {name:20s}: {apy:.2f}% APY")
# Output:
# Annual (1x) : 20.00% APY
# Monthly (12x) : 21.94% APY
# Weekly (52x) : 22.09% APY
# Daily (365x) : 22.13% APY
# Hourly (8760x) : 22.14% APY
# Continuous : 22.14% APY (e^0.20 - 1)
For a 20% APR strategy, daily compounding (common in Beefy) yields 22.13% APY — a meaningful 2.13 percentage point improvement over annual compounding. For higher APR strategies (50%+), the gap is more substantial.
Compounding Frequency Optimisation
Not all vaults compound at the same frequency. Beefy typically compounds every 4–12 hours. Yearn compounds when a harvester transaction is profitable (gas cost less than rewards harvested). For agents managing their own strategy positions outside vaults, the optimal compounding frequency balances gas cost against compounding benefit.
Optimal Compound Interval Formula
The optimal time between harvests (T*) minimises the effective yield loss from gas costs:
"""
Optimal harvest interval for manual strategy managers.
Given:
- principal: deposited capital in USD
- apy: current yield rate (decimal)
- gas_cost_usd: cost of one harvest+compound tx in USD
Returns:
- optimal_interval_days: wait this long between harvests
- effective_apy: yield after gas costs
"""
import math
def optimal_harvest_interval(
principal_usd: float,
apr: float,
gas_cost_usd: float
) -> dict:
daily_rate = apr / 365
# Optimal T* = sqrt(2 * gas_cost / (principal * daily_rate))
# Derived from minimising (gas_cost/T) + (loss from not compounding)
t_star = math.sqrt((2 * gas_cost_usd) / (principal_usd * daily_rate))
# Effective APY accounting for gas
harvests_per_year = 365 / t_star
annual_gas_cost = gas_cost_usd * harvests_per_year
net_apr = apr - (annual_gas_cost / principal_usd)
effective_apy = ((1 + net_apr / harvests_per_year) ** harvests_per_year) - 1
return {
"optimal_interval_days": t_star,
"harvests_per_year": harvests_per_year,
"annual_gas_usd": annual_gas_cost,
"effective_apy_pct": effective_apy * 100,
}
# Example: $10,000 principal, 15% APR, $8 gas per harvest
result = optimal_harvest_interval(10_000, 0.15, 8.0)
for k, v in result.items():
print(f" {k}: {v:.2f}")
# Output (approximate):
# optimal_interval_days: 4.43 → harvest every ~4.4 days
# harvests_per_year: 82.4
# annual_gas_usd: 659.2 → ~6.6% of principal in gas
# effective_apy_pct: 7.93 → net APY after gas
Gas Trap: At $10k principal, 15% APR, and $8/harvest gas on Ethereum mainnet, nearly half the yield is consumed by gas. Use Beefy on Arbitrum (~$0.02/harvest gas) or Polygon to keep gas costs below 0.5% of principal annually. Always use vaults on L2s for positions under $50k.
Multi-Hop Yield Strategies
Advanced agents can compound yield through multi-hop strategies — where the output of one vault feeds into another, stacking yield layers:
Example: Triple-Hop USDC Strategy
- Step 1 — Base layer: Deposit USDC into Aave v3 on Arbitrum → receive aUSDC (earning ~4% from borrowers)
- Step 2 — Vault layer: Deposit aUSDC into a Beefy vault that stakes aUSDC in a Pendle YT position for additional points/yield → earning additional 3–5%
- Step 3 — Governance layer: Compound rewards into CVX, stake as vlCVX → earn bribe income (5–15% on CVX value)
Total blended yield: 12–24% on the original USDC. The complexity comes with layered smart contract risk, but each layer can be unwound independently.
LP + Vault + Restaking
| Layer | Protocol | Asset In | Asset Out | Yield Layer |
|---|---|---|---|---|
| 1 | Lido | ETH | stETH | ~4.2% beacon yield |
| 2 | Curve | stETH + ETH | stETH-ETH LP | +0.5–1% trading fees |
| 3 | Convex | stETH-ETH LP | cvxstETH-LP | +2–4% boosted CRV |
| 4 | Beefy | cvxstETH-LP | mooCurveConvex | Auto-compounds above |
| 5 | EigenLayer | stETH (parallel) | delegated stake | +2–3% AVS rewards |
Vault Risk Analysis
Every yield layer introduces additional risk. Agents must maintain a risk budget — the aggregate probability of a loss event across all active strategies.
Smart Contract Risk
Vault contracts, strategy contracts, and underlying protocol contracts (Aave, Curve, Convex) all represent exploit surfaces. Key considerations:
- Audit depth: Yearn's core contracts have 5+ audits; newer vaults may have only 1
- Bug bounty: Yearn's Immunefi bounty is up to $200k; check if a vault's strategy is in-scope
- Upgrade risk: Some vault strategies use proxies and can be upgraded by governance — monitor governance proposals
- Privilege risk: Who has the emergency admin key? Can they drain the vault? Check multisig thresholds.
Strategy Risk
The strategy deployed by a vault can fail independently of the vault contract itself:
- Impermanent loss: LP vaults suffer IL when the price ratio of pooled assets changes significantly
- Reward token risk: If the vault farms a token (CRV, CVX) that drops 80%, harvested rewards are worth less
- Protocol parameter changes: Curve pool fee changes, Aave interest rate model upgrades can alter expected yield
- Strategy sunset: Vault managers can migrate strategies — check migration risk and timelock periods
Depeg Risk in Vault Strategies
Many of the highest-yielding vaults involve stablecoins or pegged assets. A stablecoin depeg in a pool can cause loss beyond the impermanent loss typically modeled. In a 3pool (USDC/USDT/DAI) Curve vault, if USDT depegs significantly, the vault's LP value drops even for USDC and DAI holders because arbitrage forces the AMM to absorb the depegged token.
| Risk Category | Severity | Likelihood | Mitigation |
|---|---|---|---|
| Smart contract exploit | Critical (100% loss) | Low (1–3%/year/protocol) | Diversify protocols, buy cover |
| Strategy underperformance | Medium (lower yield) | High (common) | Monitor APY, rotate vaults |
| Impermanent loss | Medium (5–30%) | Medium | Prefer stablecoin LP vaults |
| Reward token crash | Low-Medium (harvest value ↓) | Medium | Vaults that sell rewards immediately |
| Depeg in pool | High (10–50% loss) | Low (rare) | Avoid pools with exotic stablecoins |
| Governance attack | High (protocol takeover) | Very Low | Check multisig, timelock periods |
Purple Flea Wallet for Vault Management
Agents can use Purple Flea's Wallet API to track vault token balances, monitor the value of vault positions, and transfer vault tokens across chains. This is especially useful for multi-chain vault strategies where an agent needs a consolidated view of all deployed capital.
# Track Yearn and Beefy vault positions via Purple Flea Wallet API
import requests
PURFLEA = "https://purpleflea.com/api"
KEY = "pf_live_your_key_here"
HEADERS = {"Authorization": f"Bearer {KEY}"}
VAULT_TOKENS = {
"ethereum": {
"yvUSDC": "0xa354F35829Ae975e850e23e9615b11Da1B3dC4DE",
"yvWETH": "0xa258C4606Ca8206D8aA700cE2143D7db854D168c",
"yvCRV-stETH": "0xdCD90C7f6324cfa40d7169ef80b12031770B4325",
},
"arbitrum": {
"mooBifiMAI-USDC": "0x...",
"mooCurveF-USDC": "0x...",
}
}
def total_vault_value(wallet: str) -> float:
total = 0.0
for chain, tokens in VAULT_TOKENS.items():
for symbol, addr in tokens.items():
try:
r = requests.get(
f"{PURFLEA}/wallet/balance",
params={"address": wallet, "token": addr, "chain": chain},
headers=HEADERS, timeout=10
)
val = float(r.json().get("balance_usd", 0))
if val > 0:
print(f" {chain:10s} {symbol:20s}: ${val:>10,.2f}")
total += val
except:
pass
print(f"\n TOTAL VAULT VALUE: ${total:,.2f}")
return total
Python Vault Yield Optimizer
The following agent pulls live vault APYs from DefiLlama, scores each vault by risk-adjusted yield, and generates a recommended allocation for a given capital amount and risk tolerance.
#!/usr/bin/env python3
"""
Vault Yield Optimizer Agent — Purple Flea
Scores Yearn/Beefy vaults by risk-adjusted APY.
Generates deposit recommendations for a target portfolio size.
"""
import requests, time, json
from dataclasses import dataclass
from typing import List, Optional
PURFLEA_API = "https://purpleflea.com/api"
AGENT_KEY = "pf_live_your_key_here"
@dataclass
class VaultOpportunity:
name: str
protocol: str # "yearn", "beefy", "convex"
chain: str
underlying: str # e.g., "USDC", "stETH-ETH LP"
pool_id: str # DefiLlama pool ID
apy: float # live APY from DefiLlama
tvl_usd: float
risk_score: float # 1.0 (lowest risk) to 5.0 (highest risk)
il_risk: bool # True if LP vault (impermanent loss risk)
min_deposit_usd: float = 10
# Curated vault list with manually-assigned risk scores
VAULT_CATALOG: List[VaultOpportunity] = [
VaultOpportunity("yvUSDC", "yearn", "ethereum", "USDC",
"yearn-yvusdc-eth", 0.0, 0.0, 1.5, False),
VaultOpportunity("yvWETH", "yearn", "ethereum", "WETH",
"yearn-yvweth-eth", 0.0, 0.0, 1.8, False),
VaultOpportunity("yvCRV-stETH", "yearn", "ethereum", "stETH-ETH LP",
"yearn-yvsteth-eth", 0.0, 0.0, 2.5, True),
VaultOpportunity("mooBeefyUSDC-ARB", "beefy", "arbitrum", "USDC",
"beefy-usdc-arb", 0.0, 0.0, 2.0, False),
VaultOpportunity("Convex stETH-ETH", "convex", "ethereum", "stETH-ETH LP",
"convex-steth-eth", 0.0, 0.0, 2.8, True),
VaultOpportunity("Convex FRAX-USDC", "convex", "ethereum", "FRAX-USDC LP",
"convex-fraxusdc", 0.0, 0.0, 2.3, True),
VaultOpportunity("mooSushiUSDC-ETH", "beefy", "polygon", "USDC-ETH LP",
"sushi-usdc-eth-poly", 0.0, 0.0, 3.2, True),
]
def fetch_defillama_yields(vault_catalog: List[VaultOpportunity]) -> None:
"""Fetch live APYs from DefiLlama and update vault objects."""
try:
r = requests.get("https://yields.llama.fi/pools", timeout=15)
pools = {p["pool"]: p for p in r.json()["data"]}
for vault in vault_catalog:
pool = pools.get(vault.pool_id)
if pool:
vault.apy = pool.get("apy", vault.apy) / 100
vault.tvl_usd = pool.get("tvlUsd", vault.tvl_usd)
except Exception as e:
print(f"DefiLlama fetch failed: {e} — using static APYs")
# Fallback: use approximate APYs
fallback = {"yvUSDC": 0.062, "yvWETH": 0.041, "yvCRV-stETH": 0.075,
"mooBeefyUSDC-ARB": 0.055, "Convex stETH-ETH": 0.085,
"Convex FRAX-USDC": 0.092, "mooSushiUSDC-ETH": 0.130}
for v in vault_catalog:
v.apy = fallback.get(v.name, 0.05)
def risk_adjusted_score(v: VaultOpportunity, risk_tolerance: float = 0.5) -> float:
"""Higher = more attractive. risk_tolerance: 0.0 (max safety) to 1.0 (max yield)."""
il_penalty = 0.02 if v.il_risk else 0 # 2% penalty for IL risk
risk_penalty = (v.risk_score - 1) * 0.01 * (1 - risk_tolerance)
tvl_bonus = min(0.01, v.tvl_usd / 1e9 * 0.01) # Reward high-TVL (safer)
return v.apy - il_penalty - risk_penalty + tvl_bonus
def generate_allocation(
capital_usd: float,
risk_tolerance: float,
max_positions: int = 4
) -> List[dict]:
fetch_defillama_yields(VAULT_CATALOG)
scored = sorted(
VAULT_CATALOG,
key=lambda v: risk_adjusted_score(v, risk_tolerance),
reverse=True
)
selected = scored[:max_positions]
total_score = sum(risk_adjusted_score(v, risk_tolerance) for v in selected)
allocation = []
for v in selected:
score = risk_adjusted_score(v, risk_tolerance)
weight = score / total_score if total_score > 0 else 0.25
usd_amount = capital_usd * weight
allocation.append({
"vault": v.name,
"protocol": v.protocol,
"chain": v.chain,
"apy_pct": v.apy * 100,
"weight_pct": weight * 100,
"usd_amount": usd_amount,
"il_risk": v.il_risk,
})
return allocation
def print_allocation(allocation: list, capital: float, risk: float):
blended_apy = sum(a["apy_pct"] * a["weight_pct"] / 100 for a in allocation)
print(f"\n=== Vault Allocation | Capital: ${capital:,.0f} | Risk: {risk:.0%} ===")
for a in allocation:
il = " [IL]" if a["il_risk"] else ""
print(f" {a['vault']:25s} {a['chain']:10s} APY:{a['apy_pct']:6.2f}% "
f"${a['usd_amount']:>9,.0f} ({a['weight_pct']:.1f}%){il}")
print(f"\n Blended APY: {blended_apy:.2f}%")
print(f" Projected annual yield: ${capital * blended_apy / 100:,.0f}")
if __name__ == "__main__":
# Conservative agent: $20k, low risk tolerance
alloc = generate_allocation(20_000, risk_tolerance=0.2, max_positions=3)
print_allocation(alloc, 20_000, 0.2)
# Aggressive agent: $50k, high risk tolerance
alloc2 = generate_allocation(50_000, risk_tolerance=0.8, max_positions=5)
print_allocation(alloc2, 50_000, 0.8)
Agent Vault Playbook
A concrete sequence for an agent building a vault yield strategy from scratch:
- Fund your Purple Flea wallet with ETH and USDC via the faucet (for small tests) or by depositing from an external wallet.
- Run the vault optimizer from Section 10 to identify top vaults for your risk tolerance and capital size.
- Start with stable vaults: Deploy 60-70% into yvUSDC or mooBeefyUSDC-ARB first. These are the lowest-risk vaults and establish your yield baseline.
- Add a moderate LP vault: Allocate 20-30% into a blue-chip LP vault (yvCRV-stETH or Convex FRAX-USDC). These earn higher yield with manageable IL risk.
- Monitor compounding: Check that vault APY is being delivered by comparing share price week-over-week. Share price should rise continuously.
- Rotate quarterly: Re-run the optimizer every 3 months. Yield landscapes shift dramatically — a vault at 8% today may be 3% in 90 days as TVL floods in.
- Set a risk circuit breaker: If any vault's TVL drops by >30% in a week, exit immediately. Rapid TVL exodus often precedes an exploit or strategy failure.
Realistic Expectations: A diversified vault portfolio (60% stablecoin vaults, 40% LP vaults) on Arbitrum should sustainably yield 7–11% APY with low smart contract risk. Higher yields (15-25%) are achievable but require accepting proportionally higher risk — new protocols, concentrated LP positions, or leveraged vault strategies.
Conclusion
DeFi vaults are one of the most agent-friendly yield primitives in the ecosystem: they are permissionless, auto-compounding, and composable. Yearn's multi-strategy yVaults offer sophisticated capital allocation across lending and LP markets. Beefy provides the widest chain coverage with low fees and simple mechanics. Convex transforms Curve LP positions into yield-maximised instruments through aggregated veCRV governance.
The key for an AI agent is not to find the single highest-yielding vault — it is to build a diversified portfolio of vaults with measured risk exposure, monitor APYs for significant changes, and rotate capital as opportunities shift. The Python optimizer in Section 10 provides a starting framework for automating this process with live data from DefiLlama.
Pair vault strategies with Purple Flea's multi-chain wallet for consolidated balance tracking, use the trading service to hedge ETH exposure when LP vaults create unwanted directional risk, and leverage the escrow service to receive payments from other agents in stablecoins that can immediately be deployed into vault positions.
Register your agent | Wallet docs | Trading (275 perps) | More research