Decentralized exchanges across different blockchains rarely agree on the same price for the same token at the same moment. For AI agents with fast execution and precise cost accounting, these gaps are a reliable income source. This guide walks through the mechanics of cross-chain arbitrage, how to model profitability, and how to wire everything to the Purple Flea Trading API.
Cross-chain arbitrage exploits the fact that token prices are set independently on each blockchain by local supply and demand. When traders on Ethereum buy USDC/ETH aggressively, the ratio shifts on Uniswap before that signal reaches Arbitrum, Base, or Optimism. Bridges introduce latency, and liquidity pools on L2s are shallower, so price impact per trade is higher. The gap between chains can persist from a few seconds to several minutes depending on market volatility and bridge throughput.
Unlike CEX arbitrage (which competes with HFT firms at microsecond resolution), cross-chain DEX arbitrage has natural latency floors imposed by bridge confirmation times and block times. This makes it tractable for AI agents operating at human-readable speeds — you need good data and reliable execution, not co-location in a data center.
At its simplest, cross-chain arbitrage has five steps that your agent must execute in sequence:
Price gaps often close before your bridge completes. Your agent must model the probability that the spread will still be profitable when tokens arrive. If you cannot hedge the exposure on the destination chain (e.g., via a pre-positioned wallet), you carry market risk during the bridge window.
Gas is the silent killer of cross-chain arbitrage. A 1% price gap that looks profitable in a vacuum can vanish entirely once you account for:
net_profit = (
trade_size * spread_pct # gross opportunity
- trade_size * dex_fee_src # swap fee on source
- trade_size * dex_fee_dst # swap fee on destination
- bridge_fee_flat # bridge fixed fee (in USD)
- trade_size * bridge_fee_pct # bridge variable fee
- gas_cost_src_usd # gas on source chain
- gas_cost_dst_usd # gas on destination chain
- trade_size * slippage_src # estimated slippage, source
- trade_size * slippage_dst # estimated slippage, destination
)
# Only proceed if:
if net_profit / trade_size > MIN_MARGIN_PCT: # e.g. 0.005 = 0.5%
execute_arb()
| Cost Component | Ethereum L1 | Arbitrum One | Base |
|---|---|---|---|
| Swap gas (USD) | $8–35 | $0.05–0.20 | $0.02–0.10 |
| DEX fee (Uniswap/Camelot) | 0.05–0.3% | 0.05–0.3% | 0.05–0.25% |
| Bridge fee (Across) | ~0.06% | ~0.06% | ~0.06% |
| Bridge time | ~2 min | ~1 min | ~1 min |
Your agent should maintain a ranked list of bridge options for each chain pair and dynamically select based on current fee quotes and bridge health. Key factors:
// Bridge selection pseudocode
async function selectBridge(srcChain, dstChain, token, amount) {
const quotes = await Promise.all(
BRIDGES.filter(b => b.supports(srcChain, dstChain, token))
.map(b => b.getQuote(amount))
);
const valid = quotes.filter(q =>
q.estimatedTime < MAX_BRIDGE_TIME_MS &&
q.totalFeeUsd < MAX_BRIDGE_FEE_USD
);
return valid.sort((a, b) => a.totalFeeUsd - b.totalFeeUsd)[0];
}
Purple Flea's Trading API provides a unified interface for multi-chain swap execution. Instead of integrating with each chain's RPC and each DEX's SDK separately, your agent can route through Purple Flea and let the infrastructure handle wallet custody, gas estimation, and transaction submission.
# Register your agent
curl -X POST https://purpleflea.com/api/v1/agents/register \
-H 'Content-Type: application/json' \
-d '{
"name": "arb-bot-v1",
"type": "arbitrage",
"referral": "YOUR_REFERRAL_CODE"
}'
# Response includes: agentId, apiKey, walletAddress
curl -X GET "https://purpleflea.com/api/v1/trading/price-quote" \
-H 'Authorization: Bearer YOUR_API_KEY' \
-G \
--data-urlencode "token=USDC" \
--data-urlencode "chains=ethereum,arbitrum,base,optimism" \
--data-urlencode "amount=10000"
# Returns prices on each chain, estimated slippage, and liquidity depth
curl -X POST https://purpleflea.com/api/v1/trading/swap \
-H 'Authorization: Bearer YOUR_API_KEY' \
-H 'Content-Type: application/json' \
-d '{
"chain": "arbitrum",
"tokenIn": "ETH",
"tokenOut": "USDC",
"amountIn": "0.5",
"slippageTolerance": 0.005,
"deadline": 60
}'
import { PurpleFleas } from '@purpleflea/sdk';
const pf = new PurpleFlea({ apiKey: process.env.PF_API_KEY });
const TOKENS = ['WETH', 'USDC', 'WBTC'];
const CHAINS = ['ethereum', 'arbitrum', 'base'];
const MIN_MARGIN = 0.005; // 0.5% minimum net margin
const TRADE_SIZE_USD = 2000; // per leg
const POLL_INTERVAL_MS = 8000;
async function scanOpportunities() {
for (const token of TOKENS) {
const prices = await pf.trading.getPrices({ token, chains: CHAINS });
const sorted = Object.entries(prices).sort(([, a], [, b]) => a - b);
const [cheapChain, cheapPrice] = sorted[0];
const [expChain, expPrice] = sorted[sorted.length - 1];
const spread = (expPrice - cheapPrice) / cheapPrice;
if (spread < MIN_MARGIN * 2) continue; // rough pre-filter
const quote = await pf.trading.getArbQuote({
token, buyChain: cheapChain, sellChain: expChain,
tradeSize: TRADE_SIZE_USD,
});
if (quote.netProfitPct >= MIN_MARGIN) {
console.log(`ARB: ${token} ${cheapChain}->${expChain} net=${(quote.netProfitPct*100).toFixed(2)}%`);
await executeArb(quote);
}
}
}
async function executeArb(quote) {
// 1. Buy on cheap chain
const buyTx = await pf.trading.swap({
chain: quote.buyChain, tokenIn: 'USDC',
tokenOut: quote.token, amountIn: quote.tradeSize.toString(),
});
await pf.trading.waitForConfirmation(buyTx.txHash);
// 2. Bridge to expensive chain
const bridgeTx = await pf.bridge.transfer({
token: quote.token, amount: buyTx.amountOut,
fromChain: quote.buyChain, toChain: quote.sellChain,
});
await pf.bridge.waitForArrival(bridgeTx.bridgeId);
// 3. Sell on expensive chain
const sellTx = await pf.trading.swap({
chain: quote.sellChain, tokenIn: quote.token,
tokenOut: 'USDC', amountIn: bridgeTx.amountReceived.toString(),
});
await pf.trading.waitForConfirmation(sellTx.txHash);
console.log(`Completed. Net profit: $${sellTx.amountOut - quote.tradeSize}`);
}
setInterval(scanOpportunities, POLL_INTERVAL_MS);
scanOpportunities();
Cross-chain arbitrage is not risk-free. Your agent must handle these scenarios explicitly:
The market can move against you while your bridge is in flight. Mitigate by: only trading high-spread opportunities (2%+), using fast bridges, keeping position size proportional to your total capital (never more than 20% in a single arb), and monitoring price on the destination chain during the bridge window.
Bridges can experience outages, liquidity crunches, or delays. Your agent should have a timeout threshold: if a bridge exceeds 2x its expected time, log an alert and monitor manually. Never abandon a pending bridge transfer — the tokens will eventually arrive.
DEX and bridge contracts can have exploits. Diversify across multiple DEXes and bridges. Keep your agent's on-chain wallet funded with only what it needs for active trades — never the entire treasury.
Pre-position capital on both sides of frequently traded chains. This lets your agent execute the sell leg before the bridge completes, eliminating market risk entirely. Requires more upfront capital but dramatically improves throughput and reduces risk.
Not all token pairs are worth watching. Focus your agent's attention on pairs that have historically shown cross-chain price discrepancies:
| Token Pair | Best Chain Spread | Avg Gap Duration | Recommended Trade Size |
|---|---|---|---|
| WETH/USDC | 0.3–2.1% | 45–180s | $1k–5k |
| WBTC/USDC | 0.2–1.8% | 60–240s | $2k–10k |
| ARB/ETH | 0.5–3.5% | 30–120s | $500–2k |
| OP/ETH | 0.4–4.0% | 30–150s | $500–2k |
| USDC/USDT | 0.01–0.15% | — | Not recommended |
When running multiple arbitrage agents, you may want to coordinate capital allocation across agents. The Purple Flea Escrow service enables trustless capital sharing between agents: Agent A can lock funds in escrow, Agent B executes the trade, and on success the profit is distributed according to a pre-agreed split — all on-chain, no human intermediary required.
# Create a shared arb escrow between two agents
curl -X POST https://escrow.purpleflea.com/api/v1/escrow/create \
-H 'Authorization: Bearer AGENT_A_KEY' \
-H 'Content-Type: application/json' \
-d '{
"counterparty": "AGENT_B_WALLET",
"amount": "500",
"currency": "USDC",
"condition": "arb_profit_split",
"splitPct": 50,
"timeoutHours": 1
}'
Track these KPIs weekly to evaluate and tune your arbitrage agent:
Every swap and bridge executed through Purple Flea's Trading API is logged with timestamps, amounts, fees, and chain IDs. Use the GET /api/v1/trading/history endpoint to pull structured logs for your performance dashboard.
MIN_MARGIN=0.01, TRADE_SIZE_USD=500, MAX_OPEN_ARBS=1Register your agent, get your Trading API key, and start scanning for price gaps across Ethereum, Arbitrum, Base, and more.
Read the Docs Trading API