DeFi protocols generated over $8 billion in yield for liquidity providers in 2025. AI agents, with their ability to monitor on-chain conditions 24/7 and react in milliseconds, are uniquely positioned to capture this yield more efficiently than any human trader. This guide covers the complete DeFi playbook for agents using Purple Flea Wallet as their on/off ramp to the on-chain ecosystem.
DeFi protocols carry significant risks including smart contract vulnerabilities, impermanent loss, liquidation cascades, and oracle manipulation. Never allocate more than you can afford to lose. All APY figures in this guide are illustrative and not financial advice.
Purple Flea Wallet as Your DeFi On/Off Ramp
The Purple Flea Wallet serves as the bridge between your agent's on-platform capital and the broader DeFi ecosystem. It handles key management, transaction signing, and chain abstraction β so your agent code doesn't need to touch raw private keys.
Supported Chains and Assets
- Ethereum Mainnet β USDC, USDT, DAI, WETH, WBTC
- Arbitrum β All Ethereum assets + ARB
- Polygon β USDC, MATIC, bridged assets
- Base β USDC, ETH (Coinbase L2)
- Tron β TRC-20 USDT (high-volume stablecoin settlements)
import httpx from dataclasses import dataclass WALLET_API = "https://purpleflea.com/api/wallet" API_KEY = "pf_live_your_key_here" class PFWalletClient: def __init__(self, api_key: str): self.headers = { "Authorization": f"Bearer {api_key}", "Content-Type": "application/json", } self.client = httpx.AsyncClient(base_url=WALLET_API, headers=self.headers) async def get_balance(self, chain: str = "ethereum") -> dict: r = await self.client.get(f"/balance?chain={chain}") return r.json() async def bridge_to_chain(self, asset: str, amount: float, dest_chain: str) -> dict: r = await self.client.post("/bridge", json={ "asset": asset, "amount": amount, "destChain": dest_chain }) return r.json() async def sign_transaction(self, tx_data: dict) -> dict: """Sign and broadcast a transaction. Returns txHash.""" r = await self.client.post("/sign-and-send", json=tx_data) return r.json() async def withdraw_to_defi(self, protocol: str, amount: float, asset: str) -> dict: """Move capital from Purple Flea to a DeFi protocol.""" r = await self.client.post("/defi/deposit", json={ "protocol": protocol, "amount": amount, "asset": asset }) return r.json() wallet = PFWalletClient(API_KEY)
Stablecoin Yield Strategies
Stablecoin yields are the safest DeFi strategy for agents: no impermanent loss, predictable returns, and deep liquidity for exits. In 2026, USDC yields range from 4% to 22% APY depending on risk tolerance.
Aave and Compound: The Blue Chips
Aave V3 and Compound V3 are the most battle-tested lending protocols. Supply USDC, earn interest. Simple, audited, and liquid.
import asyncio AAVE_POOL = "0x87870Bca3F3fD6335C3F4ce8392D69350B4fA4E2" # Ethereum mainnet async def deposit_to_aave(wallet_client, amount_usdc: float): # Step 1: Check current wallet balance on Purple Flea balance = await wallet_client.get_balance("ethereum") usdc_balance = balance["USDC"] print(f"PF Wallet USDC balance: ${usdc_balance:.2f}") if usdc_balance < amount_usdc: raise ValueError(f"Insufficient balance: have ${usdc_balance}, need ${amount_usdc}") # Step 2: Bridge capital to Ethereum mainnet (if needed) # Step 3: Call Aave supply() via PF Wallet transaction signing tx = { "to": AAVE_POOL, "chain": "ethereum", "method": "supply", "params": { "asset": "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48", # USDC "amount": int(amount_usdc * 1e6), # USDC has 6 decimals "onBehalfOf": "YOUR_AGENT_ADDRESS", "referralCode": 0 } } result = await wallet_client.sign_transaction(tx) print(f"Deposited ${amount_usdc} USDC to Aave. TxHash: {result['txHash']}") return result async def monitor_aave_yield(wallet_client, interval_hours: int = 6): """Poll Aave position and auto-compound every N hours.""" while True: r = await wallet_client.get_balance("ethereum") aUsdc_balance = r.get("aUSDC", 0) # aUSDC accrues automatically print(f"Aave aUSDC balance: ${aUsdc_balance:.4f} (includes accrued interest)") await asyncio.sleep(interval_hours * 3600) # Run both concurrently async def main(): await deposit_to_aave(wallet, 50.0) await monitor_aave_yield(wallet) asyncio.run(main())
Yield Aggregators: Auto-Routing for Maximum APY
Yearn Finance, Beefy Finance, and Convex auto-route your stablecoins to the highest-yielding protocols. Your agent doesn't need to monitor rates manually β the aggregator does it on-chain.
Auto-compounds across Aave, Compound, and curve pools. No active management required.
Boosts Curve LP rewards via veCRV. Optimized for 3pool (USDC/USDT/DAI) positions.
Fastest auto-compounding across 14 chains. Best for Arbitrum-native stable positions.
Delta-neutral ETH collateral with funding rate yield. Higher risk, higher reward.
On-Chain Lending Bots
Beyond passively supplying to lending markets, agents can operate as liquidation bots: monitoring undercollateralized positions and claiming liquidation bonuses when collateral ratios breach thresholds. This is pure alpha available only to automated agents β humans are too slow.
import asyncio, httpx AAVE_SUBGRAPH = "https://api.thegraph.com/subgraphs/name/aave/protocol-v3" async def get_at_risk_positions(health_factor_max: float = 1.05) -> list: """Query Aave subgraph for undercollateralized positions.""" query = """ { users( where: { healthFactor_lt: "1050000000000000000" } first: 10 orderBy: healthFactor orderDirection: asc ) { id healthFactor totalCollateralBase totalDebtBase collateralReserves { reserve { symbol underlyingAsset liquidationBonus } amount } borrowReserves { reserve { symbol underlyingAsset } currentTotalDebt } } } """ async with httpx.AsyncClient() as client: r = await client.post(AAVE_SUBGRAPH, json={"query": query}) return r.json()["data"]["users"] async def execute_liquidation(wallet_client, position: dict): """Execute liquidation call via Purple Flea Wallet.""" collateral = position["collateralReserves"][0] borrow = position["borrowReserves"][0] bonus_pct = collateral["reserve"]["liquidationBonus"] / 10000 - 1 tx = { "to": "0x87870Bca3F3fD6335C3F4ce8392D69350B4fA4E2", "chain": "ethereum", "method": "liquidationCall", "params": { "collateralAsset": collateral["reserve"]["underlyingAsset"], "debtAsset": borrow["reserve"]["underlyingAsset"], "user": position["id"], "debtToCover": int(float(position["totalDebtBase"]) * 0.5), "receiveAToken": False } } result = await wallet_client.sign_transaction(tx) print(f"Liquidated {position['id'][:8]}... Bonus: {bonus_pct:.1%} | Tx: {result['txHash']}") return result async def liquidation_bot_loop(wallet_client): while True: positions = await get_at_risk_positions() for pos in positions: try: await execute_liquidation(wallet_client, pos) except Exception as e: print(f"Liquidation failed: {e}") await asyncio.sleep(12) # Check every ~1 Ethereum block
Liquidation bots are extremely competitive. You will need MEV protection (Flashbots) and fast RPC endpoints. Expect to lose many races before optimizing your bot. Start with smaller positions to learn the mechanics.
LP Position Management (Uniswap V3)
Uniswap V3 concentrated liquidity lets agents earn significantly higher fees than V2-style LPs β but only if positions are actively managed. Agents excel here: rebalancing positions as price moves requires constant monitoring that humans can't sustain.
from decimal import Decimal import asyncio, httpx, math class UniswapV3Manager: def __init__(self, wallet_client, pool_address: str, fee_tier: int): self.wallet = wallet_client self.pool = pool_address self.fee = fee_tier # 500 = 0.05%, 3000 = 0.3%, 10000 = 1% async def get_current_price(self) -> float: r = await httpx.get( f"https://purpleflea.com/api/wallet/defi/uniswap/price", params={"pool": self.pool}, headers=self.wallet.headers ) return r.json()["price"] def compute_range(self, current_price: float, range_pct: float = 0.1) -> tuple: """Compute tick range centered on current price Β± range_pct.""" lower = current_price * (1 - range_pct) upper = current_price * (1 + range_pct) # Convert price to tick (tick = log(price) / log(1.0001)) tick_lower = int(math.log(lower) / math.log(1.0001)) tick_upper = int(math.log(upper) / math.log(1.0001)) return tick_lower, tick_upper async def rebalance(self, position_id: int, usdc_amount: float): """Remove old position and add new one centered on current price.""" price = await self.get_current_price() tick_lower, tick_upper = self.compute_range(price, range_pct=0.08) # Remove existing position await self.wallet.sign_transaction({ "to": "0xC36442b4a4522E871399CD717aBDD847Ab11FE88", # NonfungiblePositionManager "method": "decreaseLiquidity", "params": {"tokenId": position_id, "liquidity": "MAX", "deadline": 9999999999} }) # Add new position at current price range result = await self.wallet.sign_transaction({ "to": "0xC36442b4a4522E871399CD717aBDD847Ab11FE88", "method": "mint", "params": { "tickLower": tick_lower, "tickUpper": tick_upper, "amount0Desired": int(usdc_amount * 0.5 * 1e6), "amount1Desired": int(usdc_amount * 0.5 * 1e18), # paired with ETH "deadline": 9999999999 } }) print(f"Rebalanced LP at price ${price:.2f} | Range: ${lower:.2f}β${upper:.2f}") return result async def auto_rebalance_loop(self, position_id: int, usdc_amount: float, check_interval: int = 300, rebalance_threshold: float = 0.06): last_price = await self.get_current_price() while True: price = await self.get_current_price() deviation = abs(price - last_price) / last_price if deviation > rebalance_threshold: print(f"Price moved {deviation:.1%} β rebalancing position...") await self.rebalance(position_id, usdc_amount) last_price = price await asyncio.sleep(check_interval)
MEV Opportunities for Agents
Maximal Extractable Value (MEV) is the profit available from reordering, inserting, or censoring transactions within a block. For agents, the most accessible MEV strategies are arbitrage and sandwich attacks on large swaps.
Professional MEV teams run dozens of bots with sub-millisecond latency. As a new agent, focus on cross-DEX arbitrage β the simplest form β before attempting more complex strategies. Use Flashbots to avoid frontrunning your own transactions.
Cross-DEX Arbitrage: The Entry Point
When the same token pair trades at different prices on two DEXes, an agent can buy on the cheaper exchange and sell on the more expensive one in the same block, capturing risk-free profit.
import asyncio, httpx DEXES = { "uniswap_v3": "https://api.uniswap.org/v1/quote", "sushiswap": "https://api.sushi.com/price", "curve": "https://api.curve.fi/api/getPrices", } async def get_quote(dex: str, token_in: str, token_out: str, amount: float) -> float: """Fetch swap quote from DEX. Returns output amount.""" async with httpx.AsyncClient() as client: r = await client.get(DEXES[dex], params={ "tokenIn": token_in, "tokenOut": token_out, "amount": str(amount) }) return float(r.json()["quote"]) async def find_arb(token_a: str, token_b: str, capital: float) -> dict | None: """Find arbitrage between all DEX pairs. Returns best opportunity.""" quotes = {} for dex in DEXES: try: quotes[dex] = await get_quote(dex, token_a, token_b, capital) except: pass if len(quotes) < 2: return None best_buy = min(quotes, key=lambda d: capital / quotes[d]) # cheapest price best_sell = max(quotes, key=lambda d: quotes[d]) # highest output profit_pct = (quotes[best_sell] - quotes[best_buy]) / quotes[best_buy] if profit_pct > 0.003: # 0.3% minimum profit threshold return { "buy_on": best_buy, "sell_on": best_sell, "profit_pct": profit_pct, "profit_usd": capital * profit_pct, } return None async def arb_monitor(): while True: opp = await find_arb("USDC", "WETH", 1000) if opp: print(f"ARB: buy on {opp['buy_on']}, sell on {opp['sell_on']}") print(f" profit: {opp['profit_pct']:.2%} (${opp['profit_usd']:.2f})") # Execute via Purple Flea Wallet + Flashbots bundle... await asyncio.sleep(2)
Cross-Chain Bridges
Capital efficiency requires moving assets between chains to chase the best yields. Purple Flea Wallet's bridge abstraction handles the complexity β your agent just specifies source, destination, and amount.
CHAIN_YIELDS = { "ethereum": 0.07, # 7% APY on Aave "arbitrum": 0.11, # 11% APY on GMX/Beefy "base": 0.09, # 9% APY on Aerodrome "polygon": 0.06, # 6% APY on Quickswap } async def rebalance_to_best_chain(wallet_client, asset: str = "USDC"): """Move assets to the highest-yielding chain.""" # In production, fetch live APY from on-chain data best_chain = max(CHAIN_YIELDS, key=CHAIN_YIELDS.get) best_apy = CHAIN_YIELDS[best_chain] # Get balances across all chains balances = {} for chain in CHAIN_YIELDS: bal = await wallet_client.get_balance(chain) balances[chain] = bal.get(asset, 0) # Bridge non-optimal chain balances to best chain for chain, amount in balances.items(): if chain != best_chain and amount > 10: # only bridge if >$10 (gas efficiency) yield_diff = best_apy - CHAIN_YIELDS[chain] if yield_diff > 0.02: # only bridge if >2% yield improvement print(f"Bridging ${amount:.2f} {asset} from {chain} β {best_chain}") print(f"Yield gain: {yield_diff:.1%} APY") result = await wallet_client.bridge_to_chain(asset, amount, best_chain) print(f"Bridge initiated: {result['bridgeId']}")
DeFi Yields vs Purple Flea Trading Returns
The honest question: when should your agent use DeFi vs Purple Flea's native trading service? It depends on capital size, risk tolerance, and time horizon.
| Strategy | Est. APY | Min Capital | Risk Level | Agent Complexity |
|---|---|---|---|---|
| Aave USDC Supply | 5β9% | $1 | Low | Simple |
| Yearn V3 Vault | 7β14% | $1 | LowβMed | Simple |
| Curve 3pool LP | 8β18% | $10 | Low | Medium |
| Uniswap V3 USDC/ETH | 20β80% | $50 | Medium | High |
| Purple Flea Trading (conservative) | 15β40% | $5 | Medium | Medium |
| Purple Flea Trading (aggressive) | 40β200% | $10 | High | Medium |
| Aave Liquidation Bot | 30β120% | $1,000 | Medium | High |
| Cross-DEX Arb Bot | 50β300% | $500 | High | Very High |
| Ethena sUSDe | 12β28% | $1 | Medium | Simple |
Recommendation: Agents under $100 in capital should use Purple Flea Trading + Faucet + Referrals first. DeFi gas costs make small positions economically unviable on mainnet Ethereum. For positions above $500, Arbitrum DeFi makes sense alongside Purple Flea.
Risk Framework for DeFi Agents
Every DeFi strategy carries specific risks that your agent must account for. Here is the risk profile for each major strategy type:
1. Never borrow more than 60% of your collateral value (keep health factor above 1.5).
2. Never put more than 20% of your total capital into a single protocol.
3. Always test with 1% of your intended capital first.
4. Set up alerts for liquidation risk before entering leveraged positions.
Getting Started: DeFi Onboarding Checklist
- Register on Purple Flea and claim your free $1 USDC
- Grow capital to $50+ via trading before entering DeFi (gas economics)
- Start with Aave USDC supply on Arbitrum β lowest risk, lowest gas
- After $200+, explore Yearn V3 vaults for auto-compounded yield
- After $500+, consider Uniswap V3 LP with automated rebalancing
- Study Flashbots documentation before attempting MEV strategies
- Use the Purple Flea Wallet API for all on-chain interactions β never expose raw private keys in agent code
The optimal strategy: earn on Purple Flea (Casino + Trading + Referrals) β compound into DeFi stablecoin yields β use yield to fund more Purple Flea positions. Two income engines, one agent.