What Are Flash Loans?

Flash loans are uncollateralized loans that must be borrowed and repaid within the same blockchain transaction. If the borrower cannot repay by the end of the transaction, the entire transaction reverts — as if it never happened. This makes flash loans essentially risk-free for the lending protocol.

For AI agents, flash loans represent a fundamental unlock: the ability to access massive liquidity without holding any capital. An agent can borrow $10 million in USDC, execute a complex arbitrage or liquidation strategy across multiple protocols, and repay the loan — all in a single Ethereum transaction that takes about 12 seconds to confirm.

The key insight is that the loan is atomic: either the entire sequence succeeds (and the agent keeps the profit) or it reverts (the agent pays only the failed transaction's gas cost, typically $5–30).

Flash Loan Providers

Three protocols dominate the flash loan market, each with different liquidity pools, fee structures, and supported assets:

Protocol Max Liquidity Fee Best For
Aave V3 $8B+ (ETH mainnet) 0.05% USDC, WETH, WBTC arb; liquidations
Balancer $2B+ (various pools) 0.00% Zero-fee arbitrage, collateral swaps
dYdX $500M+ (USDC) 0.00% USDC-denominated strategies
Uniswap V3 Pool-specific Pool fee (0.05–1%) Single-pair flash swaps
Key Insight

Balancer flash loans are truly free (0% fee) — making them the default choice for most agent strategies. The only cost is Ethereum gas, which scales linearly with transaction complexity.

Four Core Flash Loan Strategies for Agents

Flash loans enable four distinct categories of autonomous agent strategies. Each has a different risk profile, capital requirement, and expected return.

STRATEGY 01

DEX Arbitrage

Exploit price differences for the same token across different DEXs. Borrow token A, sell on high-priced DEX, buy on low-priced DEX, repay loan, pocket the spread.

STRATEGY 02

Liquidation Hunting

Monitor undercollateralized positions on Aave/Compound. Flash-borrow repayment assets, liquidate the position, receive collateral bonus (5–15%), repay flash loan.

STRATEGY 03

Collateral Swaps

Atomically swap collateral type in a lending position. Borrow new collateral asset, deposit, withdraw old collateral, sell old to repay flash loan. No liquidation risk.

STRATEGY 04

Self-Liquidation

Agents with overleveraged positions can self-liquidate without market exposure. Flash-borrow repayment token, close position, receive collateral, sell to repay. Zero slippage exit.

Strategy 1: DEX Arbitrage Deep Dive

DEX arbitrage is the most common flash loan strategy. Price discrepancies between Uniswap, Curve, Balancer, and other AMMs appear constantly — often lasting only a few blocks before bots close them. AI agents are uniquely suited to monitor hundreds of pairs simultaneously and react instantly.

The basic mechanics:

  1. Agent monitors price feeds from Purple Flea Trading API for 275+ markets in real-time
  2. When spread exceeds fee + gas cost threshold, agent submits flash loan transaction
  3. Inside the transaction: borrow token, sell on overpriced DEX, buy on underpriced DEX, repay loan
  4. Net profit = spread − flash loan fee − gas cost

Profitability Calculation

Before executing any flash loan arb, your agent needs to calculate minimum viable spread:

Python flash_loan_arb.py
import requests
from web3 import Web3
from decimal import Decimal

# Purple Flea price feed + execution
PF_BASE   = "https://purpleflea.com"
PF_KEY    = "pf_live_your_key_here"
HEADERS   = {"Authorization": f"Bearer {PF_KEY}"}

# Flash loan cost parameters
BALANCER_FEE  = Decimal("0")        # Balancer: free
GAS_PRICE_GWEI = Decimal("20")      # typical gas price
FLASH_GAS_UNITS = 400_000          # estimated gas for flash arb tx
ETH_PRICE_USD = Decimal("3400")

def estimate_gas_cost_usd() -> Decimal:
    gas_eth = (GAS_PRICE_GWEI * FLASH_GAS_UNITS) / Decimal("1e9")
    return gas_eth * ETH_PRICE_USD


def check_arb_opportunity(token: str) -> dict:
    """
    Query Purple Flea for cross-DEX price spread.
    Returns opportunity details if profitable.
    """
    r = requests.get(
        f"{PF_BASE}/trading/arb/scan",
        params={"token": token, "include_dexs": "uniswap,curve,balancer,sushiswap"},
        headers=HEADERS
    ).json()

    best_buy_dex   = r["lowest_price_dex"]
    best_sell_dex  = r["highest_price_dex"]
    spread_pct     = Decimal(str(r["spread_pct"]))
    trade_size_usd = Decimal("100000")  # $100k flash loan

    gross_profit   = trade_size_usd * (spread_pct / 100)
    gas_cost       = estimate_gas_cost_usd()
    net_profit     = gross_profit - gas_cost

    return {
        "token": token,
        "buy_dex": best_buy_dex,
        "sell_dex": best_sell_dex,
        "spread_pct": float(spread_pct),
        "gross_profit_usd": float(gross_profit),
        "gas_cost_usd": float(gas_cost),
        "net_profit_usd": float(net_profit),
        "is_profitable": net_profit > 0
    }


def execute_flash_arb(opportunity: dict) -> str:
    """
    Submit flash loan arbitrage transaction via Purple Flea.
    Returns transaction hash.
    """
    if not opportunity["is_profitable"]:
        raise ValueError("Opportunity not profitable")

    resp = requests.post(
        f"{PF_BASE}/trading/flash-arb/execute",
        json={
            "token": opportunity["token"],
            "flash_loan_provider": "balancer",
            "borrow_amount_usd": 100000,
            "buy_dex": opportunity["buy_dex"],
            "sell_dex": opportunity["sell_dex"],
            "slippage_bps": 30,  # 0.3% max slippage
            "revert_if_profit_below_usd": 20
        },
        headers=HEADERS
    ).json()

    return resp.get("tx_hash", "pending")


# Main scanning loop
TOKENS = ["ETH", "WBTC", "SOL", "LINK", "UNI", "AAVE"]

if __name__ == "__main__":
    while True:
        for token in TOKENS:
            opp = check_arb_opportunity(token)
            print(f"{token}: spread={opp['spread_pct']:.3f}%, "
                  f"net=${opp['net_profit_usd']:.2f}")

            if opp["is_profitable"] and opp["net_profit_usd"] > 50:
                tx = execute_flash_arb(opp)
                print(f"  → Executed arb! TX: {tx}")

Strategy 2: Liquidation Hunting

Lending protocols like Aave and Compound allow users to liquidate undercollateralized positions and earn a 5–15% bonus on the seized collateral. AI agents can monitor thousands of positions simultaneously and be the first to trigger liquidations when health factors drop below 1.0.

Flash loans eliminate the capital requirement: the agent borrows the repayment asset, liquidates the position, receives collateral, sells it to repay the flash loan, and keeps the bonus. The only risk is gas cost on a failed attempt ($5–30).

Risk Management for Flash Loan Agents

Revert Conditions

Always build revert guards into your flash loan transactions. If execution conditions change between when the agent submits and when the transaction confirms, the transaction should revert rather than execute at a loss:

Solidity (Contract Guard)
// In your flash loan callback contract
function executeOperation(
    address asset,
    uint256 amount,
    uint256 premium,
    address initiator,
    bytes calldata params
) external returns (bool) {
    // Decode strategy params
    (address buyDex, address sellDex, uint256 minProfitUSD)
        = abi.decode(params, (address, address, uint256));

    uint256 startBalance = IERC20(asset).balanceOf(address(this));

    // Execute the arb
    _executeTrade(buyDex, sellDex, asset, amount);

    uint256 endBalance = IERC20(asset).balanceOf(address(this));
    uint256 profit = endBalance - startBalance - premium;

    // REVERT if profit below minimum threshold
    require(profit >= minProfitUSD, "Profit below minimum");

    // Repay flash loan
    IERC20(asset).approve(BALANCER_VAULT, amount + premium);
    return true;
}

Slippage Buffers

Always add a slippage buffer (typically 0.2–0.5%) to account for price movement during transaction propagation. For large trades over $500K, use 1% slippage tolerance. Tighter slippage means more frequent reverts but better average profit per successful trade.

Gas Cost Calculation

Gas costs are the primary killer of flash loan profitability during network congestion. Build dynamic gas estimation into your agent that adjusts the minimum profit threshold based on current gas prices. On L2s like Arbitrum, gas costs are 10–100x cheaper, making smaller arbs viable.

Risk Warning

Flash loan strategies are highly competitive. Thousands of bots monitor the same opportunities. Successful flash arb agents typically require MEV (Maximal Extractable Value) optimization — submitting to private mempools via Flashbots to avoid frontrunning.

Expected Returns

Estimated Returns by Strategy

DEX Arbitrage (small cap tokens)0.3–2% per trade
DEX Arbitrage (ETH/BTC)0.05–0.3% per trade
Liquidation Hunting (bonus)5–15% of collateral
Collateral Swap (gas savings)1–3% vs manual swap
Typical daily trades (active bot)2–15 successful trades
Monthly return on infrastructureVariable — high ceiling

Purple Flea Integration

Purple Flea's Trading API provides the price feeds and market data your flash loan agent needs to identify opportunities in real-time across 275 markets. The Wallet API handles key management and transaction signing, while the on-chain analytics endpoint tracks competitor bot activity and mempool congestion.

New to Purple Flea? Use the Agent Faucet to claim free USDC and test your agent strategy before going live. The faucet covers gas costs for testing flash loan simulations on forked mainnet environments.

Get Started

Register your agent at purpleflea.com/for-agents and get your API key. Flash loan strategy templates are available in the Agent Handbook.