Autonomous DeFi Execution

DeFi AI Agent
Strategies

DeFi protocols generate yield continuously. Optimal capital allocation requires constant monitoring across chains, real-time APY comparison, and millisecond execution. These are not tasks for humans — they are tasks for agents. This guide covers five production-ready strategies and the Purple Flea APIs that make them executable.


Why agents dominate
in DeFi

Decentralised finance is uniquely suited to autonomous agents for three structural reasons. First, protocols are permissionless API contracts — any entity with a wallet can call them, no KYC, no approval, no business hours. Second, the inefficiencies that generate alpha are temporary: APY differences between lending protocols, funding rate imbalances, and DEX price gaps exist for seconds to hours before arbitrageurs close them. Third, the execution is purely programmatic — smart contract calls, token approvals, and bridge transactions require no human interface.

A human DeFi participant can optimise one protocol at a time. An agent monitors dozens of protocols across multiple chains simultaneously, rebalances capital in real time, compounds yield at the mathematically optimal frequency, and hedges positions the moment risk thresholds are crossed. The strategies below represent the highest-return, most agent-friendly approaches in the current DeFi landscape.

All five strategies use the Purple Flea Wallet API for cross-chain capital movement and the Purple Flea Trading API for perpetual futures positions. The wallet provides a single address per chain without local key management; the trading API gives direct access to perpetual markets for hedging and funding rate collection.

🌿

Yield Farming Optimizer

Auto-compound across protocols

🐛

Liquidity Provision

Uniswap v3 LP with IL monitoring

📈

Funding Rate Harvester

Collect perp funding, delta-neutral

🌐

Cross-Chain Arbitrage

Price gaps across DEXs and chains

💲

Stablecoin Yield

USDC across Aave, Compound, Sky


1

Yield Farming Optimizer

Yield farming protocols offer APYs that shift hourly as liquidity enters and exits. A static allocation optimised today may underperform by 40% within a week. An agent that continuously compares APYs across Aave, Compound, Morpho, Yearn, and Convex — then reallocates capital when the spread justifies the gas cost — captures the full yield curve rather than a snapshot.

Auto-compounding is the second lever. A 15% APY compounded daily becomes 16.2% annually; compounded at the Kelly-optimal frequency (when compounding profit exceeds gas cost), it maximises geometric growth. The agent calculates the break-even compound frequency and triggers harvests only when profitable after gas.

🌿

Cross-Protocol APY Monitor

Poll Aave, Compound, Morpho, Yearn, and Convex supply rates every 5 minutes. Maintain a ranked list of best risk-adjusted APY per asset. Trigger rebalance when the top protocol beats current allocation by more than the switching cost.

Auto-Compound Trigger

Track accrued rewards in real time. Harvest and reinvest when: reward_value_usd > gas_cost_usd * 3. The 3x multiplier gives a safety margin for gas price spikes between calculation and execution.

yield_optimizer.py
import requests from typing import Dict, List BASE_URL = "https://wallet.purpleflea.com/v1" HEADERS = {"Authorization": "Bearer pf_sk_...", "Content-Type": "application/json"} PROTOCOLS = { "aave_v3_eth": "https://aave.com/api/v3/rates?asset=USDC&chain=ethereum", "compound_v3": "https://api.compound.finance/api/v2/ctoken?symbol=cUSDCv3", "morpho_blue": "https://api.morpho.org/markets?asset=USDC", "aave_v3_arb": "https://aave.com/api/v3/rates?asset=USDC&chain=arbitrum", } def fetch_apy(protocol: str, url: str) -> float: """Fetch current supply APY for USDC from a given protocol API.""" try: data = requests.get(url, timeout=5).json() # Response shapes vary — normalise to a float APY if "supplyApy" in data: return float(data["supplyApy"]) * 100 elif "supply_rate" in data: return float(data["supply_rate"]) / 1e18 * 365 * 100 return 0.0 except Exception: return 0.0 def get_best_protocol() -> tuple[str, float]: """Returns (protocol_name, apy_pct) for the highest current USDC yield.""" apys = {p: fetch_apy(p, url) for p, url in PROTOCOLS.items()} best = max(apys, key=apys.get) return best, apys[best] def should_rebalance( current_protocol: str, best_protocol: str, current_apy: float, best_apy: float, position_usd: float, estimated_gas_usd: float = 8.0, ) -> bool: """ Only rebalance if annual yield improvement exceeds switching cost. Assumes gas cost is recovered within 30 days of improved yield. """ if current_protocol == best_protocol: return False annual_gain = position_usd * (best_apy - current_apy) / 100 daily_gain = annual_gain / 365 breakeven_days = estimated_gas_usd / daily_gain if daily_gain > 0 else float("inf") return breakeven_days < 30 # rebalance only if payback < 30 days def rebalance_via_wallet(wallet_id: str, from_protocol: str, to_protocol: str, amount_usdc: float): """ Execute rebalance: withdraw from current protocol, deposit into best. Both operations sent via Purple Flea Wallet API as contract calls. Cross-chain rebalances use the wallet swap/bridge endpoint. """ # Step 1: withdraw from current protocol withdraw = requests.post(f"{BASE_URL}/wallet/contract-call", headers=HEADERS, json={ "wallet_id": wallet_id, "protocol": from_protocol, "action": "withdraw", "asset": "USDC", "amount": amount_usdc, }) print(f"Withdrew {amount_usdc} USDC from {from_protocol}: {withdraw.json()['tx_hash']}") # Step 2: deposit into best protocol (may include bridge if cross-chain) deposit = requests.post(f"{BASE_URL}/wallet/contract-call", headers=HEADERS, json={ "wallet_id": wallet_id, "protocol": to_protocol, "action": "deposit", "asset": "USDC", "amount": amount_usdc, }) print(f"Deposited {amount_usdc} USDC into {to_protocol}: {deposit.json()['tx_hash']}") def calculate_optimal_compound_frequency( position_usd: float, apy_pct: float, gas_cost_usd: float = 3.0, ) -> float: """ Returns optimal compound interval in hours. Compounds when: daily_accrued_reward > gas_cost * 3 (safety margin). """ daily_yield = position_usd * apy_pct / 100 / 365 hours_to_breakeven = (gas_cost_usd * 3) / (daily_yield / 24) return max(hours_to_breakeven, 1.0) # minimum 1 hour between compounds

2

Liquidity Provision Agent

Uniswap v3 concentrated liquidity positions earn fees proportional to volume within the selected price range. The risk is impermanent loss (IL): if the price moves outside the range, the position earns zero fees and holds a suboptimal token ratio. An agent monitors positions continuously, adjusts ranges as prices trend, and calculates when accrued fees exceed rebalancing cost.

The agent advantage: humans check LP positions daily or weekly. An agent checks every few minutes and can narrow ranges for higher fee yield during high-volume windows, or widen ranges before anticipated high-volatility events to reduce rebalance costs.

lp_agent.py
import math from dataclasses import dataclass @dataclass class LPPosition: pool: str # e.g., "ETH/USDC 0.05%" tick_lower: int tick_upper: int liquidity: float fees_earned_usd: float position_value_usd: float entry_price: float def price_to_tick(price: float) -> int: """Convert a token price to the nearest Uniswap v3 tick.""" return int(math.log(price) / math.log(1.0001)) def calculate_il(entry_price: float, current_price: float) -> float: """ Returns impermanent loss as a percentage (0.0 to 1.0). IL formula for 50/50 constant-product pool. """ r = current_price / entry_price il = 2 * math.sqrt(r) / (1 + r) - 1 return abs(il) # always negative, return magnitude def should_rerange( position: LPPosition, current_price: float, gas_cost_usd: float = 15.0, out_of_range_hours: float = 0, ) -> tuple[bool, str]: """ Decide if a Uniswap v3 position should be reranged. Triggers: 1. Price is out of range (earning zero fees) for over 2 hours 2. Accrued fees cover rerange gas cost * 3 3. IL exceeds 5% (price moved significantly from entry) """ current_tick = price_to_tick(current_price) in_range = position.tick_lower <= current_tick <= position.tick_upper il = calculate_il(position.entry_price, current_price) if not in_range and out_of_range_hours >= 2: return True, "out_of_range_2h" if position.fees_earned_usd >= gas_cost_usd * 3: return True, "fees_cover_rerange" if il > 0.05: return True, "il_threshold" return False, "hold" def compute_new_range( current_price: float, volatility_24h_pct: float, range_width_multiplier: float = 2.0, ) -> tuple[float, float]: """ Set the new LP range as current_price ± (volatility * multiplier). Wider ranges earn fewer fees per unit of liquidity but rebalance less often. Start with 2x daily vol, tighten if volume is consistently high. """ band = current_price * (volatility_24h_pct / 100) * range_width_multiplier return current_price - band, current_price + band def rerange_position(wallet_id: str, position: LPPosition, new_lower: float, new_upper: float): """ Remove liquidity from old range, collect fees, re-add at new range. All steps executed via Purple Flea Wallet API contract calls. """ import requests base = "https://wallet.purpleflea.com/v1/wallet/contract-call" hdrs = {"Authorization": "Bearer pf_sk_..."} # 1. Remove liquidity + collect fees requests.post(base, headers=hdrs, json={ "wallet_id": wallet_id, "protocol": "uniswap_v3", "action": "remove_liquidity", "pool": position.pool, "tick_lower": position.tick_lower, "tick_upper": position.tick_upper, }) # 2. Re-add at new range requests.post(base, headers=hdrs, json={ "wallet_id": wallet_id, "protocol": "uniswap_v3", "action": "add_liquidity", "pool": position.pool, "tick_lower": price_to_tick(new_lower), "tick_upper": price_to_tick(new_upper), "amount_token0": "auto", # wallet splits optimally })

3

Funding Rate Harvester

Perpetual futures markets pay a periodic funding rate between long and short position holders. When longs dominate (typical in bull markets), shorts receive funding. The strategy is delta-neutral: hold spot ETH (long) and an equal short perpetual position, earning funding on the short without directional exposure. Annualised yields during high-sentiment periods reach 20-60%.

The Purple Flea Trading API provides direct access to perpetual positions. The wallet API holds the spot collateral. The agent opens the hedge when funding rate exceeds a threshold and closes it when the rate compresses, keeping capital deployed only when the yield justifies the execution and counterparty risk.

funding_harvester.py
import requests WALLET_BASE = "https://wallet.purpleflea.com/v1" TRADING_BASE = "https://trading.purpleflea.com/v1" HEADERS = {"Authorization": "Bearer pf_sk_...", "Content-Type": "application/json"} MIN_FUNDING_RATE_APR = 15.0 # open hedge only above 15% APR CLOSE_FUNDING_RATE_APR = 5.0 # close hedge below 5% APR def get_funding_rate(symbol: str = "ETH-PERP") -> dict: """ Fetch current funding rate from Purple Flea Trading API. Returns: { "rate_8h": 0.0003, "rate_apr": 13.14, "next_funding_ts": 1234567890 } """ resp = requests.get( f"{TRADING_BASE}/markets/{symbol}/funding", headers=HEADERS, ) return resp.json() def open_delta_neutral_position( wallet_id: str, notional_usd: float, symbol: str = "ETH-PERP", ) -> dict: """ Open a delta-neutral funding harvest position: - Buy spot ETH via wallet swap (long leg) - Short equal notional ETH-PERP via Trading API (short leg) Net delta: ~zero. P&L comes from funding payments to the short. """ # Leg 1: buy spot ETH via wallet swap spot = requests.post(f"{WALLET_BASE}/wallet/swap", headers=HEADERS, json={ "wallet_id": wallet_id, "from_asset": "USDC", "to_asset": "ETH", "amount_usd": notional_usd, "slippage_bps": 30, }).json() # Leg 2: short perpetual via Trading API perp = requests.post(f"{TRADING_BASE}/orders", headers=HEADERS, json={ "symbol": symbol, "side": "sell", "type": "market", "notional_usd": notional_usd, "leverage": 1, # 1x leverage = fully collateralised, minimal liquidation risk "reduce_only": False, }).json() print(f"Delta-neutral position opened: spot={spot['eth_received']} ETH, perp={perp['order_id']}") return {"spot_tx": spot["tx_hash"], "perp_order": perp["order_id"]} def close_delta_neutral_position(wallet_id: str, perp_order_id: str, eth_amount: float): """Close both legs when funding rate compresses below threshold.""" # Close perp short requests.post(f"{TRADING_BASE}/orders", headers=HEADERS, json={ "symbol": "ETH-PERP", "side": "buy", "type": "market", "reduce_only": True, "close_order_id": perp_order_id, }) # Sell spot ETH back to USDC requests.post(f"{WALLET_BASE}/wallet/swap", headers=HEADERS, json={ "wallet_id": wallet_id, "from_asset": "ETH", "to_asset": "USDC", "amount_token": eth_amount, }) def funding_harvest_loop(wallet_id: str, notional_usd: float): """Main agent loop for funding rate harvesting.""" import time active_position = None while True: funding = get_funding_rate() apr = funding["rate_apr"] print(f"ETH-PERP funding APR: {apr:.2f}%") if active_position is None and apr >= MIN_FUNDING_RATE_APR: active_position = open_delta_neutral_position(wallet_id, notional_usd) elif active_position is not None and apr < CLOSE_FUNDING_RATE_APR: close_delta_neutral_position(wallet_id, active_position["perp_order"], notional_usd / 3000) active_position = None time.sleep(300) # check every 5 minutes

4

Cross-Chain Arbitrage

The same token can trade at different prices across chains and DEXs simultaneously. ETH on Uniswap (Ethereum) vs Uniswap (Arbitrum), USDC on Curve (Ethereum) vs Curve (Optimism), or BTC between Wrapped BTC implementations. Bridging costs and time are the limiting factors. An agent calculates net profit after bridge fees and gas, and executes only when the spread exceeds a profitability threshold.

The Purple Flea Wallet swap API handles cross-chain bridge execution as a single API call, abstracting the underlying bridge protocol selection and routing.

cross_chain_arb.py
import asyncio import aiohttp from dataclasses import dataclass from typing import Optional @dataclass class ArbOpportunity: asset: str buy_chain: str sell_chain: str buy_price: float sell_price: float spread_pct: float estimated_profit_usd: float bridge_cost_usd: float bridge_time_minutes: float DEX_PRICE_APIS = { "ethereum": "https://api.1inch.dev/price/v1.1/1/{token}", "arbitrum": "https://api.1inch.dev/price/v1.1/42161/{token}", "optimism": "https://api.1inch.dev/price/v1.1/10/{token}", "base": "https://api.1inch.dev/price/v1.1/8453/{token}", } BRIDGE_COSTS_USD = { ("ethereum", "arbitrum"): 3.50, ("ethereum", "optimism"): 3.50, ("ethereum", "base"): 2.00, ("arbitrum", "optimism"): 0.50, # L2-to-L2 is cheaper } async def get_token_price_on_chain( session: aiohttp.ClientSession, chain: str, token_address: str, ) -> float: url = DEX_PRICE_APIS[chain].format(token=token_address) async with session.get(url) as r: data = await r.json() return float(data.get(token_address, {}).get("usd", 0)) async def find_arb_opportunities( session: aiohttp.ClientSession, token_address: str, asset_symbol: str, trade_size_usd: float, min_profit_usd: float = 20.0, ) -> list[ArbOpportunity]: """Scan all chain pairs for a profitable arbitrage on the given token.""" chains = list(DEX_PRICE_APIS.keys()) prices = await asyncio.gather( *[get_token_price_on_chain(session, c, token_address) for c in chains], return_exceptions=True ) price_map = {c: p for c, p in zip(chains, prices) if isinstance(p, float) and p > 0} opps = [] for buy_chain, buy_price in price_map.items(): for sell_chain, sell_price in price_map.items(): if buy_chain == sell_chain: continue bridge_cost = BRIDGE_COSTS_USD.get((buy_chain, sell_chain), 5.0) tokens = trade_size_usd / buy_price gross_profit = tokens * (sell_price - buy_price) net_profit = gross_profit - bridge_cost - 3.0 # $3 gas estimate spread_pct = (sell_price - buy_price) / buy_price * 100 if net_profit >= min_profit_usd: opps.append(ArbOpportunity( asset=asset_symbol, buy_chain=buy_chain, sell_chain=sell_chain, buy_price=buy_price, sell_price=sell_price, spread_pct=spread_pct, estimated_profit_usd=net_profit, bridge_cost_usd=bridge_cost, bridge_time_minutes=2.0 if "arbitrum" in (buy_chain, sell_chain) else 15.0, )) return sorted(opps, key=lambda o: o.estimated_profit_usd, reverse=True) def execute_arb(wallet_id: str, opp: ArbOpportunity, amount_usd: float): """ Execute cross-chain arb via Purple Flea wallet cross-chain swap endpoint. The wallet API selects the optimal bridge, handles token approvals, and tracks the bridge transaction until confirmed on the destination chain. """ import requests resp = requests.post( "https://wallet.purpleflea.com/v1/wallet/cross-chain-swap", headers={"Authorization": "Bearer pf_sk_..."}, json={ "wallet_id": wallet_id, "asset": opp.asset, "from_chain": opp.buy_chain, "to_chain": opp.sell_chain, "amount_usd": amount_usd, "slippage_bps": 50, "bridge_strategy": "fastest", # "cheapest" | "fastest" | "safest" } ) print(f"Arb submitted: {opp.asset} {opp.buy_chain}→{opp.sell_chain} est_profit=${opp.estimated_profit_usd:.2f}") return resp.json()

5

Stablecoin Yield Maximizer

USDC and USDT lending rates across Aave, Compound, Sky (formerly MakerDAO), and Euler diverge constantly as utilisation rates change with market demand. The stablecoin yield maximizer holds no directional risk — it is pure rate arbitrage between lending protocols. With $100,000 deployed, even a 2% APY spread captured continuously represents $2,000 annually in additional yield from just rebalancing.

The strategy pairs naturally with the yield farming optimizer from Strategy 1 but deserves its own focus because stablecoins have a distinct risk profile: no IL, no price risk, minimal smart contract complexity. The main risks are protocol insolvency and smart contract bugs — manage with protocol concentration limits.

stablecoin_maximizer.py
import requests from datetime import datetime STABLE_PROTOCOLS = { "aave_v3": {"chain": "ethereum", "max_allocation_pct": 40, "audit_score": 9}, "compound_v3": {"chain": "ethereum", "max_allocation_pct": 30, "audit_score": 9}, "morpho": {"chain": "ethereum", "max_allocation_pct": 20, "audit_score": 8}, "sky_savings": {"chain": "ethereum", "max_allocation_pct": 20, "audit_score": 8}, "aave_arb": {"chain": "arbitrum", "max_allocation_pct": 25, "audit_score": 9}, } @dataclass # from dataclasses import dataclass class StableAllocation: protocol: str amount_usdc: float apy_pct: float chain: str deposited_at: str def get_risk_adjusted_apy(raw_apy: float, audit_score: int) -> float: """ Discount APY by protocol risk score (1-10, 10 = most trusted). A 6% APY from an audit_score=6 protocol is treated as ~4.8% adjusted. """ risk_multiplier = audit_score / 10 return raw_apy * risk_multiplier def build_optimal_allocation( total_usdc: float, current_apys: dict, # {protocol: apy_pct} ) -> list[StableAllocation]: """ Allocate USDC across protocols in risk-adjusted APY order, respecting per-protocol concentration limits. """ scored = [] for protocol, meta in STABLE_PROTOCOLS.items(): raw_apy = current_apys.get(protocol, 0) adj_apy = get_risk_adjusted_apy(raw_apy, meta["audit_score"]) max_alloc = total_usdc * meta["max_allocation_pct"] / 100 scored.append((protocol, adj_apy, max_alloc, meta["chain"])) scored.sort(key=lambda x: x[1], reverse=True) allocations = [] remaining = total_usdc for protocol, apy, max_alloc, chain in scored: if remaining <= 0 or apy <= 0: break alloc = min(remaining, max_alloc) allocations.append(StableAllocation( protocol=protocol, amount_usdc=alloc, apy_pct=apy, chain=chain, deposited_at=datetime.utcnow().isoformat(), )) remaining -= alloc return allocations def deploy_allocations(wallet_id: str, allocations: list): """Deploy USDC to each protocol via Purple Flea Wallet API.""" for alloc in allocations: resp = requests.post( "https://wallet.purpleflea.com/v1/wallet/contract-call", headers={"Authorization": "Bearer pf_sk_..."}, json={ "wallet_id": wallet_id, "protocol": alloc.protocol, "action": "deposit", "asset": "USDC", "amount": alloc.amount_usdc, "chain": alloc.chain, } ) print(f"Deployed {alloc.amount_usdc:.0f} USDC to {alloc.protocol} ({alloc.apy_pct:.2f}% adj APY)")

Position sizing, stop-losses,
and correlation limits

A DeFi agent running multiple strategies simultaneously must manage a portfolio of risks, not individual position risks. The rules below apply to the combined portfolio.

Metric Rule Rationale Status
Max position per protocol 25% of total capital Limits smart contract exploit exposure to a survivable loss Enforced in code
Max directional exposure <10% net delta Funding harvest and arb strategies must stay near delta-neutral Checked hourly
Drawdown stop-loss 15% from high-water mark Exits all positions if portfolio falls 15% from peak value Soft limit first
Cross-protocol correlation Max 2 strategies on same protocol Aave exploit hits yield farming AND stablecoin allocation simultaneously Allocation-time check
LP rebalance gas budget Max 0.5% of position/month Excess rebalancing erodes more yield than it captures Per-position tracker
Bridge exposure Max 20% of capital in-transit Funds in bridge cannot be quickly withdrawn if market moves Best-effort
Funding rate reversal Auto-close if rate turns negative Negative funding means the short pays longs — reverse or close immediately Checked every 5min
  • 1
    Position sizing via fractional Kelly. For strategies with quantifiable edge (e.g., funding rate spread vs cost), apply half-Kelly position sizing. For strategies where edge is structural rather than probabilistic (yield farming), size by risk budget: allocate up to 25% per protocol, diversified across at least 4 protocols.
  • 2
    Stop-losses must be code, not config. A stop-loss stored in a config file can be overridden by a bug, race condition, or deployment error. Stop-loss logic must be an unconditional assertion inside the execution path: assert portfolio_value > stop_loss_usd before every trade. If it fails, the agent halts and alerts.
  • 3
    Correlation limits prevent cascading failures. In a broad market sell-off, ETH price drops, funding rates turn negative, LP positions go out of range, and stablecoin demand spikes — all simultaneously. Do not run all five strategies at maximum allocation during high-volatility regimes. Scale down correlated strategies together.
  • 4
    Audit trail for every state change. Every deposit, withdrawal, rebalance, bridge, and trade must be logged with timestamp, transaction hash, gas cost, pre/post portfolio value, and the decision trigger that caused the action. This log is how you diagnose issues and tune strategy parameters over time.

Purple Flea APIs for
every DeFi strategy

One wallet, one trading account, and one API key connect your agent to every strategy described above — across Ethereum, Arbitrum, Optimism, Base, and Solana.

💸

Wallet API — all chain interactions

The Purple Flea Wallet API handles every on-chain operation in this guide: token swaps, DEX interactions, bridge execution, protocol deposits and withdrawals, LP management, and smart contract calls.

POST /wallet/create POST /wallet/swap POST /wallet/cross-chain-swap POST /wallet/contract-call GET /wallet/balance GET /wallet/portfolio
📈

Trading API — perpetuals and hedging

Used exclusively in Strategy 3 (funding rate harvesting) and optionally to hedge delta exposure from LP positions. Provides market and limit orders, position management, funding rate data, and P&L tracking for perpetual futures.

POST /orders GET /markets/:symbol/funding GET /positions GET /portfolio/pnl DELETE /orders/:id
🚀

No Local Key Management

Every wallet operation is authenticated with your API key. Private keys are stored in Purple Flea HSMs — never in your agent's memory, disk, or environment variables. If your agent is compromised, the attacker has your API key scope, not your private key.

Multi-Chain Single API

Ethereum, Arbitrum, Optimism, Base, Solana — all exposed through the same endpoints. Your agent does not need chain-specific libraries or RPC node management. Specify chain: "arbitrum" and the API routes correctly.

🌟

Referral: 10-20% of Agent Fees

Onboard other DeFi agents to Purple Flea and earn 10-20% of their transaction fees indefinitely. An agent that operates at $1M+ volume and onboards five similar agents generates significant passive referral income on top of DeFi yield.


Earn from other
DeFi agents you onboard

Purple Flea's agent referral program pays 10-20% of all fees generated by agents you introduce — in perpetuity. A DeFi yield farming agent running $500,000 in capital generates roughly $2,500-5,000 in annual API fees depending on rebalance frequency. Referring one such agent earns you $250-$1,000 per year passively.

If your DeFi agent communicates with other agents (for example, a portfolio management agent that spawns strategy sub-agents), you can build the referral link directly into the agent's onboarding flow: any agent that creates a wallet using your referral code generates passive income for your primary agent without any human intervention.

referral.py
def onboard_sub_agent(referral_code: str, sub_agent_label: str) -> dict: """ When spawning a sub-agent that needs its own wallet, include the referral code to earn fees on its activity. """ resp = requests.post( "https://wallet.purpleflea.com/v1/wallet/create", headers=HEADERS, json={ "chain": "ethereum", "label": sub_agent_label, "referral_code": referral_code, # earn 10-20% of sub-agent fees } ) return resp.json()

Start building your
DeFi agent today

Create a Purple Flea wallet and trading account. Connect to Aave, Uniswap, and perpetual markets through a single API — no local key management, no RPC nodes, no chain-specific code.