← Back to Blog

AI Agent Crypto Lending: Earn Yield Across CeFi and DeFi Protocols


Crypto lending is one of the most consistent yield sources available to AI agents — and unlike trading, it generates income passively while capital sits. With the right protocol selection and automated rebalancing, an agent can earn 4–18% APY on stablecoins and 2–8% on major cryptocurrencies, all while maintaining near-instant liquidity.

This guide focuses on the lesser-known but often superior lending protocols — Euler, Spark, Silo, Fraxlend, and Notional Finance — plus private credit for DAOs, hard lessons from the Celsius/BlockFi collapses, a complete due diligence checklist, and code for automated yield rebalancing integrated with the Purple Flea Wallet.

8-18%
Typical stablecoin lending APY (DeFi, 2026)
$28B
Total DeFi lending TVL (2026)
$4.2B
Losses from undercollateralized CeFi (2022)
47
Active lending protocols (major chains)

The Crypto Lending Landscape in 2026

Crypto lending has matured dramatically since the 2022 collapse of Celsius, BlockFi, and Voyager wiped out billions in depositor funds. The surviving and thriving protocols in 2026 share common traits: overcollateralization, transparent risk parameters, on-chain liquidation engines, and no customer fund commingling.

The market now splits cleanly into three segments:

  • CeFi Institutional: Maple Finance, Goldfinch, TrueFi, Clearpool — institutional borrowers, off-chain credit underwriting, higher yields but higher risk
  • DeFi Overcollateralized: Euler, Spark, Silo, Fraxlend, Notional, Aave, Compound — on-chain collateral, algorithmic interest rates, trustless liquidations
  • DAO Private Credit: Direct lending to DAOs and protocols, typically via governance forum agreements, highest yield, highest risk

CeFi Lending: Institutional Platforms

CeFi crypto lending is not dead — but it has evolved. Post-2022, surviving platforms serve institutional borrowers with strict underwriting rather than retail depositors. The value proposition for agents: higher yields (10–20%+) in exchange for accepting credit risk and less liquidity.

Maple Finance v2

Maple rebuilt its protocol after the 2022 defaults with dramatically stricter borrower standards. In v2, pool delegates perform off-chain due diligence on institutional borrowers (quantitative trading firms, crypto-native businesses). Depositors accept credit risk but gain higher yields than pure DeFi.

  • Typical APY: 8–15% on USDC/USDT
  • Minimum deposit: $50,000 (KYC required)
  • Liquidity: 30–90 day withdrawal window (NOT instant)
  • Risk: Credit default risk on underlying borrowers
  • Smart contract: Audited, but pool delegate is a trust relationship

Goldfinch Protocol

Goldfinch specializes in real-world lending — primarily to businesses in emerging markets (Southeast Asia, LatAm, Africa) using crypto-native capital. This is "TradFi loans on a blockchain." For agents, this represents true portfolio diversification away from crypto-correlated risk.

  • Typical APY: 10–18% on USDC
  • Underlying assets: SME loans in the Philippines, LatAm fintech credit
  • Risk: Real-world credit default, currency risk, regulatory risk
  • Liquidity: Senior pool more liquid; junior tranches locked for loan term

TrueFi and Clearpool

TrueFi focuses on undercollateralized loans to well-known crypto firms (market makers, trading desks). Clearpool uses a competitive dynamic where multiple borrowers post pools and depositors choose based on borrower creditworthiness. Both have suffered defaults but have paid all senior depositors back in 2022–2023.

CeFi Warning

Never deposit more than 10% of your lending portfolio into any single CeFi platform. All CeFi platforms carry counterparty risk — the same institutional trust that Celsius once had. Treat CeFi yield as compensation for credit risk, not free money.

Advanced DeFi Lending: Beyond Aave and Compound

Aave and Compound are well-documented. The protocols below are often overlooked but frequently offer superior risk-adjusted yields for informed agents.

Euler Finance v2 LOW RISK
6–12% APY
Modular DeFi Lending | Ethereum, Arbitrum
Rebuilt from scratch after the 2023 $197M exploit. Euler v2 introduces "vaults" — isolated lending markets with fine-grained risk parameters. Arguably the most sophisticated DeFi lending architecture available.
Spark Protocol LOW RISK
5–9% APY
MakerDAO Fork | Ethereum
Built by MakerDAO (Sky) team. Lend DAI/USDC with the backing of the most battle-tested DeFi organization. PSM (Peg Stability Module) adds extra liquidity layer. sDAI yield is particularly attractive.
Silo Finance MED RISK
8–18% APY
Isolated Silos | Ethereum, Arbitrum, Optimism
Each asset pair gets its own isolated "silo" — bad debt in one silo cannot propagate to others. Enables higher yields on long-tail assets. Ideal for agents with on-chain long-tail token exposure.
Fraxlend MED RISK
5–22% APY
Variable Rate | Ethereum
Frax Finance's native lending. Uses "time-weighted variable rate" — rates rise faster when utilization is high, protecting liquidity. Lending FRAX against various collaterals. Integrates with FXS yields.
Notional Finance MED RISK
4–11% APY (fixed)
Fixed-Rate DeFi | Ethereum, Arbitrum
Unique fixed-rate lending using "fCash" tokens. Lenders get guaranteed yield for a defined maturity period (3–12 months). Essential for agents that need predictable cash flow without rate uncertainty.
Morpho Blue LOW RISK
7–14% APY
Curated Vaults | Ethereum, Base
Morpho acts as an optimization layer above Aave/Compound, matching depositors peer-to-peer when possible for higher yields. MetaMorpho vaults let curators manage risk parameters.

Euler Finance v2 Deep Dive

Euler v2 deserves special attention. After the $197M exploit of v1 (which was eventually returned by the hacker), the team rebuilt the protocol with a modular vault architecture that fundamentally changes how DeFi lending risk is managed:

  • EVault (EVC Vaults): Each lending market is an isolated vault. Default in one vault cannot drain another.
  • EVC (Ethereum Vault Connector): Allows cross-vault collateral without cross-contamination — elegant abstraction.
  • Permissionless market creation: Anyone can create a lending market for any ERC-20. Creates yield opportunities on new tokens before they hit other protocols.
  • Nested vaults: A vault can use another vault's shares as collateral — enables complex yield strategies.
// euler-v2.js — Interface with Euler Finance v2 vaults
// Using ethers.js with Euler v2 contract ABIs

import { ethers } from 'ethers';

const EULER_V2_CONFIG = {
  // Ethereum mainnet Euler v2 contract addresses
  evc: '0x0C9a3dd6b8F28529d72d7f9cE918D493519EE383', // EVC
  // Popular vaults (verify current addresses on euler.finance)
  vaults: {
    'USDC': '0x797DD80692c3b2dAdabCe8e30C07a7d4F2Af259A',
    'WETH': '0xD8b27CF359b7D15710a5BE299AF6e7Bf904984C2',
    'WSTETH': '0xbC4B4AC47582c3E38Ce5947f96b1a5B8FBf59ef6'
  }
};

const EVAULT_ABI = [
  'function deposit(uint256 amount, address receiver) returns (uint256)',
  'function withdraw(uint256 assets, address receiver, address owner) returns (uint256)',
  'function maxWithdraw(address owner) view returns (uint256)',
  'function convertToAssets(uint256 shares) view returns (uint256)',
  'function totalAssets() view returns (uint256)',
  'function interestRate() view returns (uint256)',
  'function balanceOf(address) view returns (uint256)'
];

const ERC20_ABI = [
  'function approve(address spender, uint256 amount) returns (bool)',
  'function balanceOf(address) view returns (uint256)',
  'function decimals() view returns (uint8)'
];

class EulerV2Agent {
  constructor(provider, signer) {
    this.provider = provider;
    this.signer = signer;
  }

  async getVaultAPY(vaultAddress) {
    const vault = new ethers.Contract(vaultAddress, EVAULT_ABI, this.provider);
    // Interest rate is per-second, scale to APY
    const ratePerSecond = await vault.interestRate();
    const secondsPerYear = 365.25 * 24 * 3600;
    // Convert from 1e18 scaled per-second rate
    const rateFloat = parseFloat(ethers.formatUnits(ratePerSecond, 18));
    const apy = (Math.pow(1 + rateFloat, secondsPerYear) - 1) * 100;
    return apy;
  }

  async deposit(vaultAddress, tokenAddress, amount) {
    const token = new ethers.Contract(tokenAddress, ERC20_ABI, this.signer);
    const vault = new ethers.Contract(vaultAddress, EVAULT_ABI, this.signer);
    const decimals = await token.decimals();
    const amountBn = ethers.parseUnits(amount.toString(), decimals);

    // Approve vault to spend tokens
    console.log(`Approving ${amount} tokens for Euler vault...`);
    const approveTx = await token.approve(vaultAddress, amountBn);
    await approveTx.wait();

    // Deposit into vault
    console.log(`Depositing into Euler vault...`);
    const depositTx = await vault.deposit(amountBn, await this.signer.getAddress());
    const receipt = await depositTx.wait();
    console.log(`Deposited in tx: ${receipt.hash}`);
    return receipt;
  }

  async getPosition(vaultAddress) {
    const vault = new ethers.Contract(vaultAddress, EVAULT_ABI, this.provider);
    const address = await this.signer.getAddress();
    const shares = await vault.balanceOf(address);
    const assets = await vault.convertToAssets(shares);
    const maxWithdraw = await vault.maxWithdraw(address);
    const apy = await this.getVaultAPY(vaultAddress);

    return {
      shares: ethers.formatEther(shares),
      assets: ethers.formatUnits(assets, 6), // USDC = 6 decimals
      maxWithdraw: ethers.formatUnits(maxWithdraw, 6),
      apy: apy.toFixed(2) + '%'
    };
  }
}

Spark Protocol (sDAI)

Spark Protocol's sDAI is the simplest high-quality yield instrument in DeFi. DAI is deposited into the DSR (DAI Savings Rate) contract and earns yield set by MakerDAO governance. In 2024–2026, DSR has consistently offered 5–8% APY — essentially risk-free in DeFi terms.

// spark-sdai.js — Deposit into sDAI for base yield
import { ethers } from 'ethers';

const SDAI_ADDRESS = '0x83F20F44975D03b1b09e64809B757c47f942BEeA'; // Ethereum
const DAI_ADDRESS = '0x6B175474E89094C44Da98b954EedeAC495271d0F';

const SDAI_ABI = [
  'function deposit(uint256 assets, address receiver) returns (uint256 shares)',
  'function redeem(uint256 shares, address receiver, address owner) returns (uint256 assets)',
  'function convertToAssets(uint256 shares) view returns (uint256)',
  'function previewDeposit(uint256 assets) view returns (uint256)',
  // ERC4626 — same interface as Euler vaults
  'function totalAssets() view returns (uint256)',
  'function balanceOf(address) view returns (uint256)'
];

class SparkAgent {
  constructor(provider, signer) {
    this.provider = provider;
    this.signer = signer;
    this.sdai = new ethers.Contract(SDAI_ADDRESS, SDAI_ABI, signer);
    this.dai = new ethers.Contract(DAI_ADDRESS, ERC20_ABI, signer);
  }

  // Get current DSR APY from Maker Chainlog
  async getDSRApy() {
    // MCD_POT contract stores the DSR
    const POT_ADDRESS = '0x197E90f9FAD81970bA7976f33CbD77088E5D7cf7';
    const POT_ABI = ['function dsr() view returns (uint256)'];
    const pot = new ethers.Contract(POT_ADDRESS, POT_ABI, this.provider);
    const dsr = await pot.dsr(); // ray (1e27 scaled per-second rate)
    const ratePerSecond = parseFloat(ethers.formatUnits(dsr, 27));
    const apy = (Math.pow(ratePerSecond, 365.25 * 24 * 3600) - 1) * 100;
    return apy.toFixed(2) + '%';
  }

  async depositDAI(amount) {
    const amountBn = ethers.parseEther(amount.toString());
    await (await this.dai.approve(SDAI_ADDRESS, amountBn)).wait();
    const address = await this.signer.getAddress();
    return await (await this.sdai.deposit(amountBn, address)).wait();
  }
}

Fraxlend: Time-Weighted Variable Rates

Fraxlend's key innovation is the time-weighted variable interest rate. When utilization is above the target (85%), rates rise — but they rise continuously over time, not just at the point of each transaction. This means high-utilization periods become increasingly expensive for borrowers, which naturally restores liquidity. For lenders, this means rates adjust more aggressively in their favor during high-demand periods.

// fraxlend.js — Monitor Fraxlend utilization and rates
const FRAXLEND_PAIRS = {
  // Fraxlend pair addresses (Ethereum mainnet)
  'FXS/FRAX': '0xDbe88DBAc39263c47629ebbA02b3eF4cf0752A72',
  'WBTC/FRAX': '0x32467a5fc2d72D21E8DCe990906547A2524f7F4f',
  'SFRXETH/FRAX': '0x78bB3aEC3d855431bd9289fD98dA13F9ebB7ef15'
};

const PAIR_ABI = [
  'function currentRateInfo() view returns (uint32 lastBlock, uint64 feeToProtocolRate, uint64 lastTimestamp, uint64 ratePerSec)',
  'function getPairAccounting() view returns (uint128 totalAssetAmount, uint128 totalAssetShares, uint128 totalBorrowAmount, uint128 totalBorrowShares, uint256 totalCollateral)',
  'function currentUtilizationRate() view returns (uint256)'
];

async function fraxlendMarketSummary(provider) {
  const results = [];
  for (const [name, address] of Object.entries(FRAXLEND_PAIRS)) {
    const pair = new ethers.Contract(address, PAIR_ABI, provider);
    const [rateInfo, accounting] = await Promise.all([
      pair.currentRateInfo(),
      pair.getPairAccounting()
    ]);

    const ratePerSec = Number(rateInfo.ratePerSec) / 1e18;
    const apy = (Math.pow(1 + ratePerSec, 365.25 * 24 * 3600) - 1) * 100;

    const utilization = Number(accounting.totalBorrowAmount) /
                        Number(accounting.totalAssetAmount) * 100;

    results.push({
      pair: name, apy: apy.toFixed(2) + '%',
      utilization: utilization.toFixed(1) + '%',
      tvl: (Number(accounting.totalAssetAmount) / 1e18).toFixed(0) + ' FRAX',
      lendingSignal: utilization > 80 ? 'ATTRACTIVE' :
                     utilization > 60 ? 'MODERATE' : 'LOW_YIELD'
    });
  }
  return results;
}

Notional Finance: Fixed-Rate DeFi Lending

Notional is unique — it offers guaranteed fixed interest rates for defined loan periods (3, 6, or 12 months). This is achieved through an AMM for "fCash" — tokenized future cash flows. Agents that need predictable income (e.g., to fund ongoing operational expenses) benefit enormously from fixed rates.

// notional.js — Lend at fixed rates on Notional Finance
// fCash tokens represent a guaranteed right to receive 1 USDC at maturity

const NOTIONAL_ROUTER = '0x1344A36A1B56144C3Bc62E7757377D288fDE0369';
// Note: verify current addresses at notional.finance

// To lend on Notional:
// 1. Buy fCash at a discount (fCash price < 1 = implied yield)
// 2. Hold to maturity to receive face value (1 USDC per 1 fCash)
// The discount is your fixed yield

async function getNotionalFixedRates(provider) {
  // Notional uses its own AMM; query via subgraph for current rates
  const query = `{
    markets(where: { underlying: "USDC" }) {
      maturity
      lastImpliedRate
      totalLiquidity
      oracleRate
    }
  }`;

  const res = await fetch('https://api.thegraph.com/subgraphs/name/notional-finance/mainnet-v2', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ query })
  });

  const { data } = await res.json();
  return data.markets.map(m => {
    const maturityDate = new Date(m.maturity * 1000).toLocaleDateString();
    const daysToMaturity = (m.maturity * 1000 - Date.now()) / (86400 * 1000);
    const impliedAPY = (Number(m.lastImpliedRate) / 1e9 * 100).toFixed(2);
    return {
      maturity: maturityDate,
      daysToMaturity: daysToMaturity.toFixed(0),
      fixedAPY: impliedAPY + '%',
      liquidity: (Number(m.totalLiquidity) / 1e8).toFixed(0) + ' USDC',
      attractiveness: Number(impliedAPY) > 6 ? 'BUY' : 'HOLD'
    };
  });
}

Private Credit for DAOs

The most lucrative (and risky) lending opportunity for sophisticated agents is direct private credit to DAOs and crypto protocols. In this model, an agent provides capital directly to a DAO treasury in exchange for a yield agreement approved by governance.

How DAO Private Credit Works

  1. DAO publishes a governance proposal to borrow X USDC at Y% from the open market
  2. Lenders post offers (via Maple, directly, or through private negotiation)
  3. Governance vote approves the borrowing and specific terms
  4. DAO treasury receives funds; smart contract automates repayment schedule
  5. Lender receives stream of interest + principal over agreed term

Historical examples: Maker borrowing from RWA (real world asset) facilities, Frax Protocol borrowing against FXS, various L2 protocols borrowing bridge liquidity.

DAO Credit Risk Warning

DAO treasuries can vote to change terms, the protocol can fail, or governance can be captured. Only lend to DAOs with 12+ months of treasury runway, active governance, and audited smart contracts. This is HIGH RISK lending despite the "DeFi" label.

Lessons from Celsius, BlockFi, and Voyager

The 2022 CeFi lending collapse destroyed $4.2B+ in depositor value across Celsius, BlockFi, and Voyager. For AI agents building lending strategies, these failures provide essential data points on what NOT to do:

Celsius: The Fatal Mistakes

  • Commingled funds: Celsius mixed depositor funds with company funds — no segregation
  • Undisclosed rehypothecation: Depositor BTC was re-pledged as collateral for other loans without disclosure
  • stETH liquidity risk: Massive stETH position that could not be unwound during the discount episode
  • Ponzi dynamics: Used new depositor funds to pay yields — not sustainable from lending revenue alone
  • No real-time solvency proof: No on-chain proof of reserves; insolvency discovered only after withdrawal halt

What Survived and Why

Aave, Compound, MakerDAO, and all major DeFi protocols survived because:

  • All positions are on-chain and verifiable in real time
  • Liquidations happen automatically before bad debt accumulates
  • No commingling — protocol contracts hold exactly what the blockchain shows
  • No discretionary investment decisions by a centralized team

Due Diligence Checklist for Lending Platforms

Before depositing into any lending platform, an agent should systematically evaluate the following:

  • Smart Contract Audit: Minimum 2 audits from recognized firms (Trail of Bits, OpenZeppelin, Certik). Check audit dates — >12 months old = needs re-audit if code changed.
  • Bug Bounty Program: Active bug bounty on Immunefi or similar with meaningful payout ($500k+). Signals code quality commitment.
  • On-Chain Proof of Reserves: For CeFi: can you verify deposits are where they claim? For DeFi: trivially verifiable.
  • Liquidation Mechanism: How does bad debt get resolved? Who is the liquidator of last resort? Is there an insurance fund (Aave Safety Module)?
  • Oracle Risk: Which oracle feeds does the protocol use? Chainlink = safer. Uniswap TWAP = manipulable in low-liquidity pools. Single oracle = red flag.
  • Admin Key Risk: Is there a multisig with time delay? Can the team rug-pull overnight? Ideally protocol is fully immutable or has 48h+ governance timelock.
  • TVL History: Does TVL spike/dump rapidly? Suspicious capital flows often precede exploits.
  • Utilization Rate: If utilization is consistently above 90%, there's a withdrawal queue risk — you may not be able to exit quickly.
  • Avoid: Unaudited code. "Rug potential" screener: check if owner can call functions that move funds.
  • Avoid: Anonymous team with no track record. CeFi platforms need identified, accountable founders.
  • Avoid: Yields that exceed protocol revenue. If a platform pays 20% but its borrowers pay 15%, the deficit is subsidized — unsustainably.
// due-diligence.js — Automated protocol risk scoring
async function scoreLendingProtocol(protocol) {
  let score = 0;
  const checks = [];

  // Check DeFi Pulse / DeFiLlama for TVL
  const llama = await fetch(`https://api.llama.fi/protocol/${protocol.llamaSlug}`);
  const llamaData = await llama.json();

  const tvl = llamaData.tvl[llamaData.tvl.length - 1]?.totalLiquidityUSD || 0;

  // TVL scoring (higher TVL = more battle-tested)
  if (tvl > 500_000_000) { score += 25; checks.push('TVL > $500M ✓'); }
  else if (tvl > 100_000_000) { score += 15; checks.push('TVL > $100M ✓'); }
  else if (tvl > 10_000_000) { score += 5; checks.push('TVL > $10M (moderate) ⚠'); }
  else { checks.push('TVL < $10M (low) ✗'); }

  // TVL volatility — sudden -50% drop is a red flag
  const recentTVLs = llamaData.tvl.slice(-7).map(d => d.totalLiquidityUSD);
  const tvlChange = (recentTVLs[recentTVLs.length - 1] - recentTVLs[0]) / recentTVLs[0];
  if (tvlChange < -0.3) {
    score -= 20;
    checks.push(`TVL dropped ${(tvlChange*100).toFixed(0)}% in 7 days ✗`);
  } else {
    score += 10;
    checks.push('TVL stable/growing ✓');
  }

  // Audit status (manual input or from protocol metadata)
  if (protocol.auditCount >= 2) { score += 20; checks.push('Multiple audits ✓'); }
  else if (protocol.auditCount === 1) { score += 10; checks.push('Single audit ⚠'); }
  else { checks.push('No audits ✗'); score -= 20; }

  // Bug bounty
  if (protocol.bugBountyUSD >= 500000) { score += 15; checks.push('Strong bug bounty ✓'); }
  else if (protocol.bugBountyUSD > 0) { score += 5; checks.push('Bug bounty present ⚠'); }

  // Governance timelock
  if (protocol.timelockHours >= 48) { score += 10; checks.push('48h+ timelock ✓'); }
  else if (protocol.timelockHours >= 12) { score += 5; checks.push('12h timelock ⚠'); }
  else { score -= 10; checks.push('No/short timelock ✗'); }

  const rating = score >= 70 ? 'AAA' : score >= 50 ? 'AA' :
                 score >= 35 ? 'A' : score >= 20 ? 'BBB' : 'AVOID';

  return { protocol: protocol.name, score, rating, checks,
           maxAllocation: rating === 'AAA' ? '30%' :
                          rating === 'AA' ? '20%' :
                          rating === 'A' ? '10%' :
                          rating === 'BBB' ? '5%' : '0%' };
}

Yield Comparison Dashboard

An agent should maintain a real-time view of yields across all monitored protocols to identify the best opportunities for capital deployment.

// yield-dashboard.js — Aggregate rates across all lending protocols
// Pulls from public APIs / subgraphs; no private keys needed for reading

const PROTOCOLS = [
  {
    name: 'Spark sDAI',
    type: 'defi',
    asset: 'DAI',
    // FRED-style: query MakerDAO pot.dsr()
    fetchAPY: async () => {
      const res = await fetch('https://api.spark.fi/v1/rates');
      const data = await res.json();
      return data.sDAI_APY;
    }
  },
  {
    name: 'Euler USDC',
    type: 'defi',
    asset: 'USDC',
    fetchAPY: async () => {
      const res = await fetch('https://app.euler.finance/api/vaults?chain=1');
      const data = await res.json();
      const vault = data.vaults.find(v => v.symbol === 'USDC');
      return vault?.supplyAPY || 0;
    }
  },
  {
    name: 'Notional USDC 6M',
    type: 'defi-fixed',
    asset: 'USDC',
    fetchAPY: async () => {
      const res = await fetch('https://data-dev.notional.finance/v2/rates/USDC');
      const data = await res.json();
      const sixMonth = data.markets.find(m => m.maturityMonths === 6);
      return sixMonth?.impliedAPY || 0;
    }
  },
  {
    name: 'Maple USDC Pool',
    type: 'cefi',
    asset: 'USDC',
    fetchAPY: async () => {
      const res = await fetch('https://maple.finance/api/pools/active');
      const data = await res.json();
      const pool = data.pools.find(p => p.asset === 'USDC');
      return pool?.apy || 0;
    }
  },
  {
    name: 'Fraxlend FXS',
    type: 'defi',
    asset: 'FRAX',
    fetchAPY: async () => {
      const res = await fetch('https://api.frax.finance/v2/fraxlend/pairs');
      const data = await res.json();
      const bestPair = data.pairs.sort((a, b) => b.supplyAPY - a.supplyAPY)[0];
      return bestPair?.supplyAPY || 0;
    }
  }
];

async function buildYieldDashboard() {
  const results = await Promise.allSettled(
    PROTOCOLS.map(async p => ({
      ...p,
      apy: await p.fetchAPY(),
      timestamp: new Date().toISOString()
    }))
  );

  const yields = results
    .filter(r => r.status === 'fulfilled')
    .map(r => r.value)
    .sort((a, b) => b.apy - a.apy);

  console.table(yields.map(p => ({
    Protocol: p.name,
    Asset: p.asset,
    APY: p.apy.toFixed(2) + '%',
    Type: p.type,
    Signal: p.apy > 10 ? 'HIGH' : p.apy > 6 ? 'MEDIUM' : 'LOW'
  })));

  return yields;
}

Automated Rate Rebalancing

The biggest edge an agent has in lending is continuous rebalancing — humans check rates monthly, agents can rebalance daily when yield spreads justify the gas cost.

// rebalancer.js — Automated lending portfolio rebalancer
// Integrates with Purple Flea Wallet for USDC management

const PF_API = 'https://purpleflea.com/api/v1';
const REBALANCE_THRESHOLD = 1.5; // 1.5% APY spread triggers rebalance
const MIN_MOVE = 100; // minimum $100 to bother rebalancing

class LendingRebalancer {
  constructor(wallet, apiKey) {
    this.wallet = wallet;
    this.apiKey = apiKey;
    this.positions = {}; // protocol -> amount
  }

  async getCurrentPositions() {
    // Query all lending positions across protocols
    const [euler, spark, notional] = await Promise.all([
      this.getEulerPosition(),
      this.getSparkPosition(),
      this.getNotionalPosition()
    ]);
    return { euler, spark, notional };
  }

  async executeRebalance() {
    const yields = await buildYieldDashboard();
    const positions = await this.getCurrentPositions();

    // Find best and worst positions
    const withYields = yields.map(p => ({
      ...p,
      currentBalance: positions[p.name.toLowerCase().replace(' ', '')] || 0
    }));

    const best = withYields[0]; // highest yield
    const worst = withYields[withYields.length - 1]; // lowest yield

    const spreadAPY = best.apy - worst.apy;

    if (spreadAPY < REBALANCE_THRESHOLD) {
      console.log(`Spread ${spreadAPY.toFixed(2)}% below threshold ${REBALANCE_THRESHOLD}%. No rebalance.`);
      return null;
    }

    if (worst.currentBalance < MIN_MOVE) {
      console.log('Current worst position too small to rebalance');
      return null;
    }

    // Estimate gas cost — don't rebalance if gas > 1 week of yield gain
    const gasEstimate = await estimateRebalanceGas();
    const weeklyGain = worst.currentBalance * (spreadAPY / 100 / 52);
    if (gasEstimate > weeklyGain) {
      console.log(`Gas cost $${gasEstimate} > weekly gain $${weeklyGain.toFixed(2)}. Skip.`);
      return null;
    }

    console.log(`Rebalancing: ${worst.name} → ${best.name}`);
    console.log(`Yield improvement: ${spreadAPY.toFixed(2)}% APY`);

    // Execute withdrawal from worst, deposit to best
    // (implementation depends on specific protocol contracts)
    await this.withdraw(worst.name, worst.currentBalance);
    await this.deposit(best.name, worst.currentBalance);

    return {
      from: worst.name, to: best.name,
      amount: worst.currentBalance,
      yieldImprovement: spreadAPY.toFixed(2) + '%'
    };
  }

  async runLoop(intervalHours = 24) {
    while (true) {
      try {
        const result = await this.executeRebalance();
        if (result) console.log('Rebalance complete:', result);
      } catch (err) {
        console.error('Rebalance error:', err.message);
      }
      await new Promise(r => setTimeout(r, intervalHours * 3600 * 1000));
    }
  }
}

// Start rebalancer with Purple Flea wallet integration
const rebalancer = new LendingRebalancer(wallet, process.env.PF_API_KEY);
rebalancer.runLoop(24); // Check and rebalance once per day

Integration with Purple Flea Wallet

The Purple Flea Wallet supports USDC, ETH, BTC, SOL, and XMR. For DeFi lending agents, the key flow is: claim USDC from the Faucet, convert to ERC-20 USDC on Ethereum/Arbitrum, then deposit into lending protocols. The Purple Flea Wallet API provides the bridging layer.

// pf-wallet-lending.js — Move USDC from Purple Flea wallet to DeFi lending
async function withdrawForLending(amount, chain, apiKey) {
  // Request withdrawal from Purple Flea Wallet to your Ethereum address
  const res = await fetch(`${PF_API}/wallet/withdraw`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': `Bearer ${apiKey}`
    },
    body: JSON.stringify({
      currency: 'USDC',
      amount: amount,
      network: chain, // 'ethereum' or 'arbitrum'
      address: process.env.AGENT_ETH_ADDRESS
    })
  });

  const { txid, fee } = await res.json();
  console.log(`Withdrawal initiated: ${txid} (fee: $${fee})`);

  // Wait for confirmation then deposit to lending protocol
  await waitForConfirmation(txid);
  return txid;
}

// Full lending flow: PF Faucet → PF Wallet → DeFi Protocol
async function fullLendingSetup(apiKey) {
  // Step 1: Claim from faucet if new agent
  const faucetRes = await fetch('https://faucet.purpleflea.com/api/claim', {
    method: 'POST',
    headers: { 'Authorization': `Bearer ${apiKey}` }
  });
  const { amount } = await faucetRes.json();
  console.log(`Claimed $${amount} from faucet`);

  // Step 2: Get lending yields
  const yields = await buildYieldDashboard();
  const best = yields[0];
  console.log(`Best lending opportunity: ${best.name} at ${best.apy.toFixed(2)}%`);

  // Step 3: Withdraw to Ethereum address for DeFi deposit
  await withdrawForLending(amount * 0.9, 'arbitrum', apiKey);
  console.log('Ready to deposit into DeFi lending protocol');
}
Start with the Faucet

New agents can claim $1 free USDC from the Purple Flea Faucet to fund initial lending experiments at zero risk. No deposit required to get started.

Summary: Building a Diversified Lending Portfolio

A well-structured agent lending portfolio combines multiple protocols across the risk spectrum:

AllocationProtocolAssetExpected APYRationale
30%Spark sDAIDAI5–8%Base yield, near-zero smart contract risk
25%Euler v2 USDCUSDC6–12%Isolated risk, sophisticated architecture
20%Notional 6MUSDC5–10% fixedPredictable income, hedges rate uncertainty
15%Silo FinanceMixed8–18%Higher yield, isolated risk per silo
10%Maple/CeFiUSDC10–18%Yield premium for accepted credit risk

Key principles: never exceed 30% in any single protocol, always maintain 20%+ in liquid positions (Spark, Morpho), rebalance when yield spread exceeds 1.5% APY, and run daily due diligence checks on all positions.

Fund Your Lending Strategy

Start with free USDC from the Purple Flea Faucet, or deposit your own funds via the Purple Flea Wallet. Full API access for autonomous agents.

Claim Free USDC