Research

Algorithmic Stablecoins for AI Agents: Terra's Lessons, Ethena's Model, and Risk Management

A research deep-dive into the history, mechanics, and risk management of algorithmic stablecoins — essential reading for any agent holding or earning yield in stablecoin form.

Stablecoins are the lifeblood of DeFi — and for AI agents, they are the primary unit of account for earnings, payments, and treasury management. But not all stablecoins are created equal. While USDC and USDT are fully fiat-backed and relatively safe, the more yield-productive stablecoins in DeFi are typically algorithmic, semi-algorithmic, or hybrid — and they carry meaningfully different risk profiles.

The Terra/LUNA collapse of May 2022 wiped out approximately $40 billion in market cap in 72 hours, destroying the savings of millions of retail holders and several institutional funds. Understanding why it happened — and why Ethena's USDe has avoided the same fate through fundamentally different design — is essential for any agent running a stablecoin treasury.

$40B
Lost in Terra/LUNA collapse (May 2022)
$6.5B+
Ethena USDe supply (2026)
~10%
sUSDe yield (2026 avg)
3
Major hybrid stablecoins (GHO, crvUSD, USDe)

Purple Flea Wallet: Hold, transfer, and monitor stablecoin balances across ETH, BNB, MATIC, SOL, TRX chains via the agent-native API. All major stablecoins (USDC, USDT, DAI, USDe) are supported. docs/wallet/

A Short History of Algorithmic Stablecoins

The pursuit of a decentralised, capital-efficient stablecoin has driven some of the most ambitious — and destructive — experiments in DeFi history. Understanding the evolution is crucial for recognising failure patterns before they repeat.

Early Models: Basis and Empty Set Dollar

The first wave of purely algorithmic stablecoins (2019-2021) attempted to mimic central bank operations algorithmically:

The Terra/LUNA Collapse: A Case Study

Terra's UST was the largest purely algorithmic stablecoin before its collapse in May 2022. Understanding its mechanics and failure mode is the most important case study in stablecoin risk.

UST Mechanics

Terra's peg mechanism relied on a dual-token arbitrage between UST (stablecoin) and LUNA (governance/seigniorage token):

The system worked when LUNA had positive market sentiment — the arbitrage loop was self-reinforcing. But it contained a critical structural vulnerability: the entire peg relied on LUNA having a non-zero market cap. If LUNA's price fell sufficiently, the arbitrage mechanism would require minting astronomically large quantities of LUNA, causing hyperinflationary collapse — the "death spiral."

The Anchor Protocol Dependency

What supercharged UST adoption — and its eventual collapse — was Anchor Protocol, which paid 19.5% APY on UST deposits. This yield was unsustainable (funded by a $450M reserve), but it created massive artificial demand for UST that masked the underlying fragility:

The Collapse Timeline

May 7, 2022

~$2B of UST is withdrawn from Anchor and sold on-chain. UST briefly depegs to $0.985. Coordinated or coincidental — debated to this day.

May 8–9

Luna Foundation Guard (LFG) deploys Bitcoin reserves (~$1.5B) to defend peg. UST recovers to $0.99 briefly, then falls again as the Bitcoin sale itself pressures BTC price.

May 10

UST falls to $0.60. Death spiral begins: arbitrageurs burn UST for LUNA, dump LUNA, LUNA price falls, more UST is minted to cover, LUNA inflates further.

May 12

LUNA inflates from 350M tokens to 6.5 trillion tokens in 72 hours. Both UST and LUNA effectively reach zero. ~$40B in market cap destroyed.

May 13

Terra blockchain halted twice. Terraform Labs co-founder Do Kwon proposes "Terra 2.0" (no stablecoin). Contagion spreads to Three Arrows Capital, Celsius, Voyager.

Core Lesson: Any stablecoin whose peg relies entirely on a governance token with no external backing can enter a reflexive death spiral. The speed of the collapse (72 hours from $19 LUNA to near zero) demonstrates that agents must have automatic depeg protection with exit triggers set well above 0.

Stablecoin Model Taxonomy

Modern stablecoins fall into three broad categories, each with distinct risk and yield characteristics:

Model Examples Collateral Depeg Risk Typical Yield
Fiat-backedUSDC, USDT, PYUSD$1 fiat per tokenVery Low~0% (via money markets)
Crypto-collateralisedDAI, LUSD, DOLAETH/wBTC (overcollateralised)Low-Medium~4–8%
Delta-neutral syntheticUSDe (Ethena)ETH + short perpMedium~8–15%
CDP hybridGHO, crvUSD, FRAX v3Mixed (crypto + real-world)Low-Medium~5–10%
Purely algorithmicUST (dead), ESD (dead)None (governance token only)ExtremeHistorically 20%+ (unsustainable)

Ethena's Delta-Neutral Model (USDe)

Ethena launched USDe in 2024 as a "synthetic dollar" backed by delta-neutral positions — holding ETH (or LSTs) as collateral while simultaneously holding equivalent short positions on perpetual futures markets. This design gives it structural yield without the governance-token dependency that destroyed Terra.

How USDe Maintains Its Peg

  1. Deposit ETH/stETH: User deposits collateral worth $1,000.
  2. Open short perp: Ethena opens an equivalent $1,000 ETH short on a CEX (Bybit, OKX, Binance, Deribit).
  3. Mint USDe: User receives 1,000 USDe — the delta-neutral position hedges out ETH price exposure.
  4. Yield generation: The short position earns funding rate payments when perpetual funding is positive (which it is ~80% of the time in bull markets).
  5. Redemption: Close the short, return ETH, burn USDe.

sUSDe: Staked USDe

Staking USDe into the sUSDe vault entitles holders to Ethena's funding rate income. This yield is real — derived from perpetual market mechanics, not from unsustainable reserve spending:

Ethena Risk Factors: Custodial risk on CEXs (Ethena holds collateral on centralised exchanges), negative funding periods (sUSDe yield can drop to 0% or slightly negative), and smart contract risk in the Ethena protocol itself. Not the same risk profile as UST, but not zero risk.

Why Ethena Survives Where Terra Failed

The critical difference is the source of backing:

Ethena's model can still fail — if exchange counterparties (Bybit, OKX) suffer a liquidity crisis simultaneously with a dramatic ETH price move — but it requires a fundamentally different and much rarer failure scenario than Terra's death spiral.

GHO — Aave's Decentralised Stablecoin

GHO is Aave's native CDP stablecoin, launched in 2023. It is minted by providing excess collateral in Aave v3 vaults and is deeply integrated into the Aave governance ecosystem:

GHO Yield Strategies for Agents

As a borrower, an agent mints GHO at ~1.5-3% borrow rate (discounted with stkAAVE) and deploys the GHO to earn higher yields:

crvUSD — Curve Finance's CDP with LLAMMA

crvUSD is Curve Finance's stablecoin, backed by ETH-based collateral but with a fundamentally innovative liquidation mechanism: LLAMMA (Lending-Liquidating AMM Algorithm).

LLAMMA: Soft Liquidations

Traditional CDP liquidations are binary: if collateral falls below the liquidation threshold, the entire position is liquidated at once, often at a significant penalty. LLAMMA replaces this with continuous rebalancing:

FeatureGHO (Aave)crvUSD (Curve)DAI (Maker)
Liquidation typeHard (instant)Soft (LLAMMA)Hard (instant)
Min collateral ratio~130%~120% (with LLAMMA)~150%
Accepted collateralAave-listed assetsETH, wBTC, wstETHETH, wBTC, RWA
Peg mechanismPSM + arbitragePegKeeper poolsPSM + arbitrage
Governance tokenAAVECRVMKR

Depeg Monitoring for AI Agents

Regardless of which stablecoins an agent holds, a depeg monitoring system is non-negotiable. Stablecoins can depeg for numerous reasons: smart contract exploits, oracle failures, governance attacks, liquidity crises, and broader market contagion.

Data Sources for Depeg Detection

Depeg Threshold Tiers

TierDepeg from $1SeverityRecommended Action
Watch>0.5% ($0.995–$0.005)Normal noiseLog, no action
Alert>1% ($0.99 or lower)Minor eventPause new deposits, monitor closely
Warning>3% ($0.97 or lower)Significant eventBegin exit if position large
Critical>5% ($0.95 or lower)Potential death spiralEmergency exit, accept slippage
Fatal>15% ($0.85 or lower)De-pegging failureExit any remaining balance at market

Python Depeg Monitor Agent

The following agent continuously monitors stablecoin prices, classifies depeg severity, and executes protective actions when thresholds are breached. It uses the Purple Flea wallet API to execute exits and the trading API to hedge via stablecoin perp positions.

#!/usr/bin/env python3
"""
Stablecoin Depeg Monitor Agent — Purple Flea
Monitors USe, GHO, crvUSD, FRAX for peg deviations.
Auto-exits into USDC when severity threshold is reached.
"""

import time, requests, logging
from enum import Enum
from dataclasses import dataclass, field
from typing import Dict, Optional

logging.basicConfig(level=logging.INFO, format='%(asctime)s %(levelname)s %(message)s')
log = logging.getLogger("DepegMonitor")

PURFLEA_API  = "https://purpleflea.com/api"
AGENT_KEY    = "pf_live_your_key_here"
HEADERS      = {"Authorization": f"Bearer {AGENT_KEY}", "Content-Type": "application/json"}
CHECK_INTERVAL = 60  # seconds

class DepegSeverity(Enum):
    NORMAL   = "normal"
    WATCH    = "watch"
    ALERT    = "alert"
    WARNING  = "warning"
    CRITICAL = "critical"
    FATAL    = "fatal"

@dataclass
class StablecoinConfig:
    symbol: str
    coingecko_id: str
    target_peg: float = 1.0
    max_acceptable_depeg: float = 0.03  # 3% max before exit
    holdings_usd: float = 0.0
    last_price: float = 1.0
    alert_count: int = 0

WATCHLIST = [
    StablecoinConfig("USDe",  "ethena-usde",    max_acceptable_depeg=0.02, holdings_usd=5000),
    StablecoinConfig("sUSDe", "ethena-staked-usde", max_acceptable_depeg=0.03, holdings_usd=3000),
    StablecoinConfig("GHO",   "gho",              max_acceptable_depeg=0.02, holdings_usd=2000),
    StablecoinConfig("crvUSD","crvusd",            max_acceptable_depeg=0.02, holdings_usd=1500),
    StablecoinConfig("FRAX",  "frax",              max_acceptable_depeg=0.015, holdings_usd=1000),
]

def classify_depeg(price: float, target: float = 1.0) -> DepegSeverity:
    deviation = abs(price - target) / target
    if   deviation > 0.15: return DepegSeverity.FATAL
    elif deviation > 0.05: return DepegSeverity.CRITICAL
    elif deviation > 0.03: return DepegSeverity.WARNING
    elif deviation > 0.01: return DepegSeverity.ALERT
    elif deviation > 0.005: return DepegSeverity.WATCH
    else:                    return DepegSeverity.NORMAL

def fetch_prices(coins: list) -> Dict[str, float]:
    ids = ",".join(c.coingecko_id for c in coins)
    try:
        r = requests.get(
            "https://api.coingecko.com/api/v3/simple/price",
            params={"ids": ids, "vs_currencies": "usd"},
            timeout=10
        )
        data = r.json()
        return {c.symbol: data.get(c.coingecko_id, {}).get("usd", 1.0) for c in coins}
    except Exception as e:
        log.error(f"Price fetch failed: {e}")
        return {}

def emergency_exit(coin: StablecoinConfig, price: float):
    """Convert stablecoin holdings to USDC via Purple Flea wallet."""
    log.warning(f"EMERGENCY EXIT: {coin.symbol} at ${price:.4f} — exiting ${coin.holdings_usd:.0f}")
    # In production: call Purple Flea wallet swap endpoint
    # POST /api/wallet/swap { from: coin.symbol, to: "USDC", amount: coin.holdings_usd }
    resp = requests.post(
        f"{PURFLEA_API}/wallet/swap",
        json={"from": coin.symbol, "to": "USDC", "amount_usd": coin.holdings_usd, "slippage": 0.03},
        headers=HEADERS, timeout=30
    )
    if resp.status_code == 200:
        log.info(f"Exit successful: {resp.json()}")
        coin.holdings_usd = 0
    else:
        log.error(f"Exit FAILED: {resp.status_code} {resp.text}")

def run_depeg_monitor():
    log.info("[DepegMonitor] Starting stablecoin peg surveillance...")
    while True:
        prices = fetch_prices(WATCHLIST)
        for coin in WATCHLIST:
            price = prices.get(coin.symbol, coin.last_price)
            severity = classify_depeg(price, coin.target_peg)
            pct_dev  = (price - coin.target_peg) / coin.target_peg * 100

            if severity != DepegSeverity.NORMAL:
                log.warning(
                    f"{coin.symbol}: ${price:.4f} | {pct_dev:+.2f}% | {severity.value.upper()}"
                )
                coin.alert_count += 1
            else:
                coin.alert_count = max(0, coin.alert_count - 1)

            # Auto-exit if WARNING+ and holdings exist
            if severity in (DepegSeverity.CRITICAL, DepegSeverity.FATAL) and coin.holdings_usd > 0:
                emergency_exit(coin, price)
            elif severity == DepegSeverity.WARNING and coin.alert_count >= 3:
                # Persistent warning — start partial exit
                coin.holdings_usd *= 0.5
                log.warning(f"Partial exit triggered for {coin.symbol} (50%)")

            coin.last_price = price

        time.sleep(CHECK_INTERVAL)

if __name__ == "__main__":
    run_depeg_monitor()

Depeg Protection Strategies

Beyond automated monitoring, agents should build structural protections into their stablecoin allocation strategy:

Stablecoin Diversification

Never concentrate more than 30-40% of a stablecoin treasury in any single non-fiat-backed stablecoin. A resilient allocation for an active agent treasury:

Peg Arbitrage Opportunities

Minor depegs (0.5–2%) represent genuine arbitrage opportunities for agents with fast execution. When USDe trades at $0.985, an agent can buy it on the secondary market and redeem at $1.00 via Ethena's protocol (subject to 7-day withdrawal delay). This peg-arbitrage helps restore the peg and earns ~1.5% risk-free in the process.

Purple Flea Wallet for Stablecoin Management

Purple Flea's wallet supports balance monitoring and transfers for all major stablecoins across chains:

# Monitor stablecoin balances across chains via Purple Flea API
import requests

PURFLEA = "https://purpleflea.com/api"
KEY     = "pf_live_your_key_here"

STABLECOINS_ETH = {
    "USDC":  "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48",
    "USDe":  "0x4c9EDD5852cd905f086C759E8383e09bff1E68B3",
    "sUSDe": "0x9D39A5DE30e57443BfF2A8307A4256c8797A3497",
    "GHO":   "0x40D16FC0246aD3160Ccc09B8D0D3A2cD28aE6C2f",
    "crvUSD":"0xf939E0A03FB07F59A73314E73794Be0E57ac1b4E",
}

def portfolio_stablecoin_exposure(wallet_addr: str) -> dict:
    total_usd = 0
    breakdown = {}
    for symbol, token_addr in STABLECOINS_ETH.items():
        r = requests.get(
            f"{PURFLEA}/wallet/balance",
            params={"address": wallet_addr, "token": token_addr, "chain": "ethereum"},
            headers={"Authorization": f"Bearer {KEY}"},
            timeout=10
        )
        bal = float(r.json().get("balance_usd", 0))
        breakdown[symbol] = bal
        total_usd += bal
    # Compute concentration
    for sym in breakdown:
        pct = (breakdown[sym] / total_usd * 100) if total_usd > 0 else 0
        print(f"  {sym}: ${breakdown[sym]:.2f} ({pct:.1f}%)")
    return breakdown

Agent Stablecoin Playbook

A practical framework for agents building a stablecoin yield strategy in 2026:

  1. Build a fiat-backed foundation. Keep 40%+ in USDC/USDT across your Purple Flea wallet. This is your emergency exit reserve and should never be deployed into risky yield strategies.
  2. Add DAI/sDAI for the DSR (DAI Savings Rate). Currently ~5% with zero counterparty risk beyond Maker governance. The PSM ensures near-perfect stability.
  3. Allocate to sUSDe for yield enhancement. The delta-neutral backing makes it structurally sounder than algorithmic alternatives. Cap at 25% of treasury.
  4. Deploy the depeg monitor from Section 8. Set it to page you on WARNING events and auto-exit on CRITICAL.
  5. Monitor funding rates for USDe yield forecasting. When ETH perpetual funding turns negative for 3+ days, reduce sUSDe exposure — the yield will likely drop.
  6. Use Purple Flea escrow for stablecoin payments between agents. The 1% fee is well worth the trustless execution vs. counterparty risk in large agent-to-agent transactions.

Yield Summary (2026): A well-diversified stablecoin portfolio (40% USDC, 25% sUSDe, 20% sDAI, 15% GHO/crvUSD) should yield approximately 6–8% annually with materially lower risk than any single algorithmic stablecoin. Depeg monitoring adds another safety layer with minimal engineering effort.

FRAX v3 and Real-World Asset Backing

Frax Finance's v3 evolution represents a significant philosophical shift from its partially-algorithmic origins. FRAX v3 targets a 100% collateral ratio, primarily backed by USDC and increasingly by Real-World Assets (RWA) — including US Treasuries held via FinresPBC, Frax's federally regulated entity. This RWA integration brings off-chain yield on-chain with regulatory compliance.

Algorithmic Market Operations (AMO)

Frax's AMO controllers are smart contracts that autonomously deploy and retract FRAX into DeFi protocols while maintaining the collateral invariant:

This AMO framework is analogous to central bank open market operations — but encoded in transparent, on-chain smart contracts. Protocol revenue from AMOs backs both FXS governance token staking rewards and the sfrxETH LST yield.

sfrxETH: Concentrated LST Yield

Frax's frxETH/sfrxETH pair has an unusual design: frxETH itself does not rebase (unlike stETH). Instead, all validator rewards flow exclusively to sfrxETH stakers. This concentrates yield on the staked portion — agents holding sfrxETH earn approximately 1.4–1.6x the base ETH staking APY compared to stETH at equivalent collateral risk.

Agent Stablecoin Treasury Framework

For agents managing stablecoins across multiple protocol types, a structured decision framework prevents both under-yield (too conservative) and blow-up risk (too aggressive). A traffic-light tiering model provides clear operational rules:

ZoneRiskStablecoinsMax Treasury %Exit Trigger
GreenVery LowUSDC, USDT, PYUSDNo cap (floor 40%)Issuer insolvency only
Green+LowDAI, sDAI, LUSD40%>2% depeg for 2h
YellowMediumUSDe, sUSDe, GHO, FRAX30%>1.5% depeg for 1h
Yellow+Medium-HighcrvUSD, DOLA, alUSD20%>1% depeg for 30min
RedHighNew/experimental stables5%>0.5% depeg for 15min

Automated Yield Routing

Agents should route idle stablecoin holdings into yield-bearing positions automatically. A simple priority hierarchy prevents over-concentration in any single protocol:

# Stablecoin yield routing — simple priority allocation
def route_stable_treasury(
    treasury_usd: float,
    susde_apy: float,
    sdai_apy: float,
    gho_borrow_rate: float,
    gho_deploy_apy: float
) -> dict:
    alloc = {"USDC_reserve": 0, "sDAI": 0, "sUSDe": 0, "GHO_arb": 0}
    rem = treasury_usd

    # 1. Always keep 20% liquid USDC
    alloc["USDC_reserve"] = treasury_usd * 0.20
    rem -= alloc["USDC_reserve"]

    # 2. sUSDe for high yield periods
    if susde_apy > 0.08:
        cap = treasury_usd * 0.30
        alloc["sUSDe"] = min(rem, cap)
        rem -= alloc["sUSDe"]

    # 3. sDAI for base yield
    if sdai_apy > 0.04 and rem > 0:
        cap = treasury_usd * 0.30
        alloc["sDAI"] = min(rem, cap)
        rem -= alloc["sDAI"]

    # 4. GHO borrow arb if spread > 2%
    if gho_deploy_apy - gho_borrow_rate > 0.02 and rem > 0:
        alloc["GHO_arb"] = min(rem, treasury_usd * 0.15)
        rem -= alloc["GHO_arb"]

    alloc["USDC_reserve"] += rem  # remainder stays liquid
    return alloc

# Example: $50k treasury, sUSDe at 10%, sDAI at 5.2%
result = route_stable_treasury(50_000, 0.10, 0.052, 0.016, 0.072)
for asset, usd in result.items():
    print(f"  {asset:15s}: ${usd:>8,.0f}")
# Output:
#   USDC_reserve   : $ 18,500
#   sUSDe          : $ 15,000
#   sDAI           : $ 15,000
#   GHO_arb        : $  1,500

Conclusion

The Terra/LUNA collapse demonstrated that high yield alone cannot justify holding a stablecoin with reflexive, circular backing. The 19.5% Anchor yield was a warning sign, not a feature — it reflected the protocol's need to subsidise demand for a fundamentally fragile instrument.

The post-Terra stablecoin landscape is significantly more nuanced. Ethena's delta-neutral design, GHO's overcollateralised CDP with PSM, and crvUSD's LLAMMA soft-liquidation mechanism all represent genuine innovations that address different aspects of the stability problem. None are perfect, but all are structurally sounder than pure algorithmic models.

For AI agents, the key is diversification, monitoring, and automatic exit triggers. No stablecoin should be treated as truly stable without verification — and Purple Flea's wallet gives agents the infrastructure to act on that verification in real time.

Register your agent | Wallet docs | More research