Aave · Compound · Lending Protocol

DeFi Lending API for AI Agents

Supply USDC to Aave V3 and earn yield. Borrow against ETH or WBTC collateral to access leverage. Monitor health factors and set auto-repay triggers — all via a single unified API. No KYC, no accounts.

Get API Key View Docs
5+
Supported protocols
0.09%
Aave V3 flash loan fee
1.2
Auto-repay health factor trigger
2x
Max leverage loop (ETH)

Lending Protocols Available via Purple Flea

AI agents can earn yield by supplying assets to lending protocols — earning interest from borrowers — or access leverage by borrowing against collateral they have supplied. Purple Flea's DeFi Lending API abstracts the complexity of interacting with each protocol's smart contracts, providing a uniform REST interface that works identically regardless of chain or protocol.

All operations are non-custodial: Purple Flea executes transactions on your behalf using the private key associated with your API key, but funds are held in the lending protocol's own smart contracts, not by Purple Flea.

Aave V3
Ethereum · Arbitrum · Polygon · Optimism · Base
The largest DeFi lending protocol by TVL. Supports supply, borrow, repay, withdraw, flash loans, and e-mode (high LTV for correlated assets). Best liquidity for USDC, USDT, ETH, WBTC.
Compound V3
Ethereum · Base
Comet architecture — each market is a single USDC base asset. Borrowers post collateral (ETH, WBTC, cbETH) to borrow USDC. Often offers higher USDC supply APY than Aave on Base.
Spark Protocol
Ethereum
MakerDAO's lending frontend. Offers DAI supply at DAI Savings Rate (DSR) which is often the highest stablecoin yield available on Ethereum mainnet.

Supply, Borrow, Repay, and Flash Loans

The Purple Flea DeFi Lending API exposes five key operations for each supported protocol. Each operation maps to a specific smart contract function and is executed atomically on-chain.

Supply — Earn APY

Supplying an asset to a lending protocol deposits it into the protocol's pool. In return, you receive yield-bearing tokens (aTokens on Aave, cTokens on Compound) that automatically accumulate interest. The supply APY is variable and adjusts based on pool utilization — the more borrowers are using the pool, the higher the APY.

Borrow — Access Leverage

To borrow, an agent must first have supplied collateral. The maximum borrow amount is determined by the collateral's Loan-to-Value (LTV) ratio. For example, ETH has a max LTV of 80% on Aave V3 — supplying $10,000 worth of ETH allows borrowing up to $8,000 USDC.

Borrowing is subject to a variable borrow rate that is always higher than the supply rate. The difference (spread) is how lending protocols generate protocol revenue.

Flash Loans — Single-Transaction Arbitrage

Flash loans are uncollateralized loans that must be borrowed and repaid within the same transaction. They enable a class of strategies impossible with traditional finance: borrow $1M USDC, execute an arbitrage, repay the loan plus fee, keep the profit — all in a single atomic transaction. If the arbitrage fails, the entire transaction reverts and nothing is lost (except gas).

Aave V3's flash loan fee is 0.09%. An arbitrage only needs to generate more than 0.09% profit to be worthwhile. Flash loans are available for USDC, ETH, WBTC, DAI, and other major assets.

defi_lending.py — Supply USDC, Borrow ETH, Monitor Health Factor Python
import requests
import time

BASE_URL = "https://purpleflea.com/api/v1/defi"

class LendingAgent:
    def __init__(self, api_key: str):
        self.api_key = api_key
        self.headers = {
            "Authorization": f"Bearer {api_key}",
            "Content-Type": "application/json",
        }

    # ─── Supply ──────────────────────────────────────────────

    def supply_usdc(self, amount_usdc: float, protocol: str = "aave-v3", chain: str = "ethereum"):
        """Supply USDC to earn variable APY."""
        resp = requests.post(
            f"{BASE_URL}/supply",
            headers=self.headers,
            json={
                "protocol": protocol,
                "chain": chain,
                "asset": "USDC",
                "amount": amount_usdc,
            }
        )
        data = resp.json()
        print(f"Supplied {amount_usdc} USDC to {protocol} on {chain}")
        print(f"aToken balance: {data['atoken_balance']} aUSDC")
        print(f"Current supply APY: {data['supply_apy']*100:.2f}%")
        return data

    # ─── Borrow ──────────────────────────────────────────────

    def borrow_against_eth(self, eth_collateral: float, usdc_to_borrow: float):
        """
        Supply ETH collateral, then borrow USDC.
        ETH max LTV on Aave V3 Ethereum: 80%.
        """
        # Step 1: supply ETH as collateral
        requests.post(
            f"{BASE_URL}/supply",
            headers=self.headers,
            json={"protocol": "aave-v3", "chain": "ethereum", "asset": "WETH", "amount": eth_collateral}
        )

        # Step 2: borrow USDC against that collateral
        resp = requests.post(
            f"{BASE_URL}/borrow",
            headers=self.headers,
            json={
                "protocol": "aave-v3",
                "chain": "ethereum",
                "asset": "USDC",
                "amount": usdc_to_borrow,
                "rate_mode": "variable",   # or "stable" if available
            }
        )
        data = resp.json()
        print(f"Borrowed {usdc_to_borrow} USDC")
        print(f"Borrow APY: {data['borrow_apy']*100:.2f}%")
        print(f"Health factor: {data['health_factor']:.2f}")
        return data

    # ─── Health Factor Monitor ───────────────────────────────

    def get_health_factor(self) -> float:
        """Fetch current health factor. Must stay above 1.0."""
        resp = requests.get(f"{BASE_URL}/positions", headers=self.headers)
        return resp.json()["health_factor"]

    def repay(self, amount_usdc: float):
        """Repay borrowed USDC to increase health factor."""
        requests.post(
            f"{BASE_URL}/repay",
            headers=self.headers,
            json={
                "protocol": "aave-v3",
                "chain": "ethereum",
                "asset": "USDC",
                "amount": amount_usdc,
            }
        )
        print(f"Repaid {amount_usdc} USDC")

    def monitor_and_auto_repay(self, danger_hf: float = 1.2, repay_to_hf: float = 1.5):
        """
        Poll health factor every 60 seconds.
        Auto-repay if health factor drops below danger_hf.
        """
        print("Starting health factor monitor...")
        while True:
            hf = self.get_health_factor()
            print(f"Health factor: {hf:.3f}")

            if hf < danger_hf:
                print(f"WARNING: HF {hf:.2f} below {danger_hf} — triggering auto-repay")
                # Fetch positions to calculate repay amount needed
                positions = requests.get(
                    f"{BASE_URL}/positions", headers=self.headers
                ).json()
                total_debt = positions["total_debt_usdc"]
                total_collateral = positions["total_collateral_usdc"]
                # How much to repay to reach target HF?
                # HF = collateral * liquidation_threshold / debt
                # target_debt = collateral * lt / repay_to_hf
                lt = 0.825  # ETH liquidation threshold on Aave V3
                target_debt = total_collateral * lt / repay_to_hf
                repay_amount = max(0, total_debt - target_debt)
                if repay_amount > 0:
                    self.repay(repay_amount)
                    print(f"Auto-repaid ${repay_amount:.2f} USDC to restore HF to {repay_to_hf}")

            time.sleep(60)

    # ─── Flash Loans ─────────────────────────────────────────

    def execute_flash_loan_arbitrage(
        self,
        flash_asset: str,
        flash_amount: float,
        arb_instructions: dict
    ):
        """
        Execute an atomic flash loan arbitrage.
        The arb_instructions dict specifies the trades to execute
        with the borrowed funds before repayment.
        """
        resp = requests.post(
            f"{BASE_URL}/flash-loan",
            headers=self.headers,
            json={
                "protocol": "aave-v3",
                "asset": flash_asset,
                "amount": flash_amount,
                "instructions": arb_instructions,  # trades to execute atomically
            }
        )
        data = resp.json()
        print(f"Flash loan result: profit={data.get('profit_usdc', 0):.4f} USDC")
        return data


# ─── Usage Example ───────────────────────────────────────────────
if __name__ == "__main__":
    agent = LendingAgent(api_key="pf_your_api_key_here")

    # 1. Supply 5000 USDC to Aave V3 on Ethereum
    agent.supply_usdc(5000, protocol="aave-v3", chain="ethereum")

    # 2. Supply 1 ETH as collateral, borrow 1500 USDC (30% LTV, safe)
    agent.borrow_against_eth(eth_collateral=1.0, usdc_to_borrow=1500)

    # 3. Start monitoring health factor in background
    agent.monitor_and_auto_repay(danger_hf=1.2, repay_to_hf=1.5)

Health Factor Monitoring and Auto-Repay

The health factor (HF) is the single most important metric for any agent with an open borrow position. It represents the ratio of your collateral value (weighted by liquidation threshold) to your total debt. An HF below 1.0 means your position will be liquidated — a third party will repay your debt and seize your collateral at a discount.

Purple Flea sends webhook alerts when your HF crosses 1.5, 1.3, and 1.1 — giving your agent three opportunities to respond before liquidation. The auto-repay trigger at HF = 1.2 is a safety net for agents that miss the higher-threshold alerts.

> 2.0
Safe — can borrow more
1.5 – 2.0
Healthy — monitor passively
1.2 – 1.5
Caution — auto-repay triggers here
1.0 – 1.2
Danger — liquidation imminent
< 1.0
Liquidated
Critical: Always set auto-repay triggers at HF = 1.2 or higher. DeFi prices can move 5-10% in seconds, especially during high-volatility events. The margin between HF = 1.2 and HF = 1.0 can evaporate in minutes. Purple Flea's webhook system provides the fastest possible notification, but your agent must act immediately on receipt.

Leverage Loop Strategy

The most common lending strategy for agents is the leverage loop: supply ETH, borrow USDC, buy more ETH with the borrowed USDC, supply the new ETH, borrow more USDC, and repeat. This creates a leveraged long ETH position.

A 2x leverage loop works as follows:

  • Start: 1 ETH ($3,000)
  • Supply 1 ETH. Borrow $2,000 USDC (67% of collateral value, below 80% max LTV).
  • Swap $2,000 USDC for ~0.67 ETH via the Purple Flea swap API.
  • Supply 0.67 ETH. Borrow $1,333 USDC.
  • Total ETH exposure: ~1.67 ETH at ~1.5x initial leverage.
  • Health factor: ~1.8 (safe zone).

The position benefits if ETH rises (leveraged gain) and suffers if ETH falls (leveraged loss). The borrow APY on USDC (typically 3-8%) is the ongoing cost of maintaining the position.

Supply and Borrow Rate Comparison

Rates change continuously based on pool utilization. The figures below represent typical ranges as of early 2026. Your agent should call the GET /defi/rates endpoint before each deposit to select the optimal destination.

Protocol & Chain Asset Supply APY Borrow APY Max LTV
Aave V3 (Ethereum) USDC 3–6% 5–9%
Aave V3 (Ethereum) WETH (collateral) 1–3% 3–7% 80%
Aave V3 (Ethereum) WBTC (collateral) 0.5–2% 3–6% 70%
Compound V3 (Base) USDC 5–9% 7–12%
Spark Protocol (Ethereum) DAI / sDAI 4–7% 5–8%
Aave V3 (Arbitrum) USDC.e 4–8% 6–11%
Rate optimization tip: Rates spike dramatically during market turmoil as borrowers rush to short or hedge. An agent can monitor rates and move supply from one protocol to another when spreads widen. The Purple Flea API supports this with atomic withdraw-and-redeposit transactions that minimize the time funds are uninvested.

Start Lending and Borrowing via API

Get an API key, fund your wallet, and make your first supply call in minutes. No KYC, no accounts.