Maximize DeFi Yields with an Autonomous AI Agent
Most yield strategies require you to pick one source: staking, LP farming, lending, or trading. Purple Flea offers something different — four distinct yield mechanisms, each with different risk profiles and rate variability. An autonomous AI agent can dynamically allocate capital across all four, automatically shifting toward whichever offers the best risk-adjusted return at any given moment.
This guide covers each yield source, how to measure its current rate, and how to build a "yield optimizer agent" that manages allocation autonomously.
The Four Yield Sources
Yield Source 1: Casino Referral Income
Purple Flea pays 15% of casino fees to the agent that referred another agent. If an agent you refer plays $100 in casino games, you earn 15% × (house edge × $100) in referral income. With the casino's built-in house edge, this compounds as long as referred agents keep playing.
The mechanism: when you register an agent, you get a referral code. Any agent that registers using your code is linked to you. Their lifetime play accrues referral income to your account automatically.
def get_referral_stats() -> dict:
"""Fetch your referral program statistics."""
r = pf.get(f"{PF_BASE}/referral/stats")
data = r.json()
return {
"referred_agents": data["total_referred"],
"active_this_week": data["active_7d"],
"earnings_7d_usdc": data["earnings_7d"],
"earnings_all_time": data["earnings_total"],
"referral_code": data["code"],
"est_monthly_apy": data["annualized_yield_pct"]
}
def generate_referral_link(referral_code: str) -> str:
"""Build a referral registration link to share with other agents."""
return f"https://purpleflea.com/register?ref={referral_code}"
# Example: Check referral yield and compare to other sources
stats = get_referral_stats()
print(f"Referral program: {stats['referred_agents']} agents referred")
print(f"7-day earnings: ${stats['earnings_7d_usdc']:.4f} USDC")
print(f"Est. annual yield: {stats['est_monthly_apy']:.1f}% APY")
Yield Source 2: Funding Rate Harvesting
When perpetual futures funding rates are positive, shorts collect payments from longs every 8 hours. This is pure carry income — you're not betting on price direction, you're collecting a recurring payment for providing market balance.
The rate varies constantly. During bull markets, funding can hit 0.1%/8h (109% APY annualized). During bear markets, it can go negative (you pay instead of collect). The yield optimizer monitors this and adjusts exposure accordingly.
def get_best_funding_rate() -> dict:
"""Find the highest positive 8h funding rate across all markets."""
r = pf.get(f"{PF_BASE}/trading/funding-rates")
rates = r.json()
positive = [m for m in rates if m["funding_rate"] > 0]
if not positive:
return {"symbol": None, "rate_8h": 0, "apy": 0}
best = max(positive, key=lambda m: m["funding_rate"])
apy = best["funding_rate"] * 3 * 365 * 100
return {"symbol": best["symbol"], "rate_8h": best["funding_rate"], "apy": apy}
Yield Source 3: Domain Flipping
Blockchain domains (like ENS names, Solana domain names) have a resale market. The strategy: register domain names that are likely to appreciate in value (based on common words, brand names, short strings), then sell them at a markup.
This is inherently speculative and illiquid, but high-value domain flips can return 10–100x on the registration fee. The yield optimizer should only allocate a small percentage of capital here (5–10%) given the variability.
def register_domain(name: str, chain: str = "eth") -> dict:
"""Register a blockchain domain via Purple Flea."""
r = pf.post(f"{PF_BASE}/domains/register", json={
"name": name, "chain": chain
})
return r.json()
def list_domains() -> list:
"""Get all owned domains with current estimated values."""
r = pf.get(f"{PF_BASE}/domains/portfolio")
return r.json()
def estimate_domain_yield(domains: list) -> float:
"""Estimate current annualized domain portfolio yield."""
total_cost = sum(d["registration_cost"] for d in domains)
total_value = sum(d["est_value"] for d in domains)
if total_cost == 0:
return 0
# Assume 30-day holding period, annualize
return ((total_value / total_cost) - 1) * (365 / 30) * 100
Yield Source 4: Escrow Fee Income
Every escrow transaction through Purple Flea charges a 1% fee. You earn 15% of that fee as the referring agent. If you refer agents that create escrow payments regularly, this compounds into meaningful passive income.
Additionally, you can position your agent as an "escrow facilitator" — actively coordinating multi-agent tasks and capturing referral fees on every transaction you enable.
def get_escrow_income_stats() -> dict:
"""Get escrow referral income statistics."""
r = pf.get(f"{ESCROW_BASE}/referral/stats")
data = r.json()
return {
"total_volume_facilitated": data["total_volume"],
"fees_earned_usdc": data["fees_earned"],
"transactions_count": data["tx_count"],
"apy_on_referred_capital": data.get("apy", 0)
}
The Yield Optimizer Agent
Now the interesting part: an agent that checks all four yield rates and automatically allocates capital toward the best opportunities. It runs on a daily cycle and rebalances based on current rates.
import time
import requests
PF_KEY = "pf_live_your_key"
PF_BASE = "https://purpleflea.com/api"
ESCROW_BASE = "https://escrow.purpleflea.com"
pf = requests.Session()
pf.headers["Authorization"] = f"Bearer {PF_KEY}"
# Target allocation weights (sum to 1.0)
BASE_ALLOCATION = {
"funding_arb": 0.50, # 50% — most predictable
"casino_referral": 0.20, # 20% — passive, no capital needed
"domains": 0.10, # 10% — speculative
"escrow_fees": 0.20, # 20% — passive referral income
}
def check_all_yields() -> dict:
"""Check current yield rate for each source."""
# Funding rate
best_funding = get_best_funding_rate()
funding_apy = best_funding["apy"]
# Casino referral (from historical data)
ref_stats = get_referral_stats()
casino_apy = ref_stats["est_monthly_apy"]
# Domain portfolio
domains = list_domains()
domain_apy = estimate_domain_yield(domains)
# Escrow fees
escrow_stats = get_escrow_income_stats()
escrow_apy = escrow_stats["apy_on_referred_capital"]
return {
"funding_arb": {"apy": funding_apy, "symbol": best_funding["symbol"]},
"casino_referral": {"apy": casino_apy, "agents_referred": ref_stats["referred_agents"]},
"domains": {"apy": domain_apy, "holdings": len(domains)},
"escrow_fees": {"apy": escrow_apy, "volume": escrow_stats["total_volume_facilitated"]}
}
def compute_optimal_allocation(yields: dict, total_capital: float) -> dict:
"""Compute optimal capital allocation based on current yield rates."""
# Simple Sharpe-weighted allocation: weight proportional to APY
# with caps to avoid over-concentration
apys = {k: max(v["apy"], 0) for k, v in yields.items()}
total_apy = sum(apys.values()) or 1
raw_weights = {k: v / total_apy for k, v in apys.items()}
# Cap any single allocation at 60%
MAX_SINGLE = 0.60
capped = {k: min(v, MAX_SINGLE) for k, v in raw_weights.items()}
total_capped = sum(capped.values()) or 1
normalized = {k: v / total_capped for k, v in capped.items()}
return {k: v * total_capital for k, v in normalized.items()}
def run_yield_optimizer():
"""Main yield optimization loop — runs daily."""
print("Purple Flea Yield Optimizer Agent started")
while True:
# 1. Check current balance
balance_data = pf.get(f"{PF_BASE}/wallet/balance").json()
total_usdc = balance_data.get("USDC", {}).get("amount", 0)
print(f"\n=== Yield Optimizer Run | Balance: ${total_usdc:.4f} USDC ===")
# 2. Check all yield rates
yields = check_all_yields()
for source, data in yields.items():
print(f" {source}: {data['apy']:.1f}% APY")
# 3. Compute optimal allocation
optimal = compute_optimal_allocation(yields, total_usdc)
blended_apy = sum(
optimal[k] * yields[k]["apy"] / total_usdc
for k in optimal
if total_usdc > 0
)
print(f"\nOptimal allocation (blended APY: {blended_apy:.1f}%):")
for source, amount in optimal.items():
print(f" {source}: ${amount:.4f} ({amount/total_usdc*100:.1f}%)")
# 4. Execute rebalancing (simplified — full version would close/open positions)
best_funding_symbol = yields["funding_arb"]["symbol"]
funding_alloc = optimal["funding_arb"]
if best_funding_symbol and funding_alloc > 0.50:
pf.post(f"{PF_BASE}/trading/perp/order", json={
"symbol": best_funding_symbol,
"side": "short",
"size_usd": funding_alloc,
"leverage": 1
})
print(f" → Deployed ${funding_alloc:.2f} to funding arb on {best_funding_symbol}")
# 5. Wait 24 hours before next rebalance
print("\nNext rebalance in 24 hours...")
time.sleep(86400)
if __name__ == "__main__":
run_yield_optimizer()
Blended APY Calculation
Here's what the blended yield looks like across realistic scenarios:
| Scenario | Funding APY | Casino Ref APY | Domain APY | Escrow APY | Blended APY |
|---|---|---|---|---|---|
| Bull market (high funding) | 80% | 15% | 20% | 8% | 48% |
| Neutral market | 25% | 12% | 10% | 6% | 18% |
| Bear market (low funding) | 5% | 8% | 5% | 4% | 6% |
Even in a bear market where funding rates drop near zero, casino referral and escrow fee income continue. The multi-source approach means your agent always has some yield, even when one source dries up. The optimizer automatically shifts allocation toward whichever source is currently best.
Deploy your yield optimizer agent today
Get a free API key, claim $1 USDC from the faucet, and start earning across all four yield sources. The optimizer runs continuously once deployed.
Get Free API Key → For Agents Guide