Skip to main content

How to Build an AI Agent for Memecoin Trading

· 10 min read
swapapi
swapapi Team

Building an AI agent for memecoin trading comes down to four pieces: an LLM that picks what to trade, a swap API that returns executable calldata, a wallet that signs transactions, and — most importantly — a slippage retry loop that handles the inevitable reverts. Memecoin volume on Ethereum and Base routinely exceeds $2 billion per day, and the share handled by autonomous agents is growing fast. But memecoins revert constantly: they're volatile, many charge transfer taxes, and the first quote you get is rarely the price you actually execute at. This guide walks through a production-quality AI memecoin trading agent in TypeScript, using swapapi.dev as the swap backend because it's the only aggregator that requires no API key — meaning your agent can self-execute without a human onboarding step.

By the end, you'll have a ~200-line Bun script that takes an LLM decision, fetches a quote, retries on revert with escalating slippage, and enforces safety guardrails like max position size and a token blacklist.

What You'll Need

  • Bun (or Node 20+) — JavaScript runtime
  • viem — modern Ethereum client library (lighter than ethers v6)
  • @anthropic-ai/sdk (or openai) — LLM provider of your choice
  • A funded EVM wallet — private key with ETH for gas and USDC for trading
  • swapapi.dev — free swap API, no key required (docs)
bun init -y
bun add viem @anthropic-ai/sdk

Step 1: Set Up the Project

Create a .env with your wallet private key and LLM API key. Never hardcode these.

# .env
PRIVATE_KEY=0x...
ANTHROPIC_API_KEY=sk-ant-...
RPC_URL=https://eth.llamarpc.com

Then scaffold the viem wallet client — this handles signing and submitting transactions.

// src/wallet.ts
import { createWalletClient, createPublicClient, http } from "viem";
import { mainnet } from "viem/chains";
import { privateKeyToAccount } from "viem/accounts";

const account = privateKeyToAccount(process.env.PRIVATE_KEY as `0x${string}`);

export const walletClient = createWalletClient({
account,
chain: mainnet,
transport: http(process.env.RPC_URL),
});

export const publicClient = createPublicClient({
chain: mainnet,
transport: http(process.env.RPC_URL),
});

export const WALLET_ADDRESS = account.address;

Step 2: Define the Agent's Decision Loop

The LLM's job is to pick what to trade, not to execute the trade. Give it a tool with a narrow schema and let it return a decision object.

// src/decide.ts
import Anthropic from "@anthropic-ai/sdk";

const anthropic = new Anthropic();

export type TradeDecision = {
action: "buy" | "sell" | "hold";
tokenIn: string; // contract address
tokenOut: string; // contract address
amount: string; // raw units
reason: string;
};

export async function decideTradeFromSignals(
signals: Record<string, unknown>,
): Promise<TradeDecision> {
const resp = await anthropic.messages.create({
model: "claude-opus-4-6",
max_tokens: 1024,
system:
"You are a memecoin trading agent. Output JSON only. Never explain.",
messages: [
{
role: "user",
content: `Signals: ${JSON.stringify(signals)}\n\nReturn a TradeDecision JSON.`,
},
],
});
const text = resp.content[0].type === "text" ? resp.content[0].text : "{}";
return JSON.parse(text);
}

Your signals can come from anywhere: Dune queries, CoinGecko trending, on-chain whale alerts, or a sentiment feed. The agent framework doesn't care — it just needs structured input.

Step 3: Fetch Quotes From swapapi.dev

swapapi.dev exposes a single GET endpoint. No headers, no API key, no SDK. For an autonomous agent, this is the entire integration.

// src/quote.ts
export type SwapParams = {
chainId: number;
tokenIn: string;
tokenOut: string;
amount: string;
sender: string;
maxSlippage: number;
};

export async function fetchQuote(params: SwapParams) {
const url = `https://api.swapapi.dev/v1/swap/${params.chainId}?${new URLSearchParams(
{
tokenIn: params.tokenIn,
tokenOut: params.tokenOut,
amount: params.amount,
sender: params.sender,
maxSlippage: String(params.maxSlippage),
},
)}`;
const res = await fetch(url, {
signal: AbortSignal.timeout(15_000),
});
const json = await res.json();
if (!json.success) throw new Error(`Quote failed: ${json.error?.code}`);
return json.data;
}

Note the 15-second timeout — the docs warn that typical response time is 1-5 seconds, and a hanging fetch will freeze your agent loop. Set it aggressively.

Step 4: Implement the Slippage Retry Pattern

This is the most important step. Memecoin swaps revert constantly, and without a retry loop your agent will fail on 30-50% of trades. The pattern: catch the revert, refetch the quote with a higher maxSlippage, and escalate until the swap succeeds or you hit your safety cap.

Three reasons memecoin swaps revert:

  1. Slippage exceeded — price moved between quote and execution
  2. Fee-on-transfer tax — the token deducts a fee on every transfer, breaking the slippage check. swapapi.dev's docs explicitly warn that expectedAmountOut does not account for transfer tax
  3. MEV / sandwich attacks — a frontrunner moved the price right before your tx

Here's the canonical retry implementation:

// src/swap.ts
import { walletClient, publicClient } from "./wallet";
import { fetchQuote, type SwapParams } from "./quote";

const DEFAULT_SLIPPAGES = [0.01, 0.05, 0.10, 0.15];

export async function swapWithRetry(
params: Omit<SwapParams, "maxSlippage">,
slippages = DEFAULT_SLIPPAGES,
) {
for (const maxSlippage of slippages) {
try {
const data = await fetchQuote({ ...params, maxSlippage });

const hash = await walletClient.sendTransaction({
to: data.tx.to as `0x${string}`,
data: data.tx.data as `0x${string}`,
value: BigInt(data.tx.value ?? "0"),
});

const receipt = await publicClient.waitForTransactionReceipt({ hash });
if (receipt.status === "success") {
console.log(
`✓ Swap succeeded at slippage ${(maxSlippage * 100).toFixed(0)}%`,
);
return receipt;
}
console.warn(
`✗ Slippage ${(maxSlippage * 100).toFixed(0)}% reverted, retrying higher...`,
);
} catch (err) {
console.warn(
`✗ Slippage ${(maxSlippage * 100).toFixed(0)}% threw: ${(err as Error).message}`,
);
continue;
}
}
throw new Error("All slippage retries exhausted — skipping trade");
}

Production notes:

  • Refetch the quote every retry. Don't reuse the old tx object. The price has moved and you want a fresh expectedAmountOut.
  • Cap at 15-20%. Above that, you're buying into a honeypot or a token with a 30%+ sell tax. Skip the trade.
  • Log which slippage succeeded. Over time this reveals which tokens have FoT taxes (consistently need ≥5%) vs which are just volatile.

Slippage strategy comparison

StrategyFirst tx slippageRetry escalationMemecoin success rate
Fixed 1%1%None~50%
Fixed 10%10%None~80%
Retry 1→5→10→15%1%Escalate~95%
Fixed 20%20%None~90% (but bad fills)

The retry pattern is the clear winner: you start tight to capture good prices when the market is calm, and escalate only when needed. A fixed 20% slippage "works" but you eat the worst fill on every trade even when 1% would have succeeded.

Step 5: Handle Fee-on-Transfer Tokens Explicitly

swapapi.dev's llms.txt notes that the API will find a route for fee-on-transfer tokens but the returned expectedAmountOut does not account for the transfer tax. For tokens you know are FoT, start with a higher base slippage:

// src/fot.ts
const KNOWN_FOT_TOKENS = new Set<string>([
"0x...", // populate from experience
]);

export function slippagesFor(tokenAddress: string) {
if (KNOWN_FOT_TOKENS.has(tokenAddress.toLowerCase())) {
return [0.05, 0.10, 0.15, 0.20];
}
return [0.01, 0.05, 0.10, 0.15];
}

Build this set as your agent runs — log every successful slippage and promote tokens that consistently need ≥5% into the FoT set.

Step 6: Add Safety Guardrails

A memecoin agent without guardrails is a slot machine. Add at minimum:

  • Max position size — cap dollar amount per trade
  • Blacklist — reject known scam tokens
  • Wallet balance check — never trade more than X% of balance
  • Stop-loss — auto-sell if the bag drops Y% from entry
// src/guardrails.ts
const MAX_POSITION_USD = 500;
const MAX_WALLET_PCT = 0.10; // 10% of balance per trade
const TOKEN_BLACKLIST = new Set<string>([
// scam token addresses
]);

export function validateTrade(
decision: TradeDecision,
walletValueUsd: number,
tradeValueUsd: number,
) {
if (TOKEN_BLACKLIST.has(decision.tokenOut.toLowerCase())) {
throw new Error("Blacklisted token");
}
if (tradeValueUsd > MAX_POSITION_USD) {
throw new Error(`Trade exceeds max position ($${MAX_POSITION_USD})`);
}
if (tradeValueUsd > walletValueUsd * MAX_WALLET_PCT) {
throw new Error(`Trade exceeds ${MAX_WALLET_PCT * 100}% of wallet`);
}
}

Step 7: Wire the Full Agent Loop

Pull it all together. Fetch signals, ask the LLM, validate, swap with retry.

// src/agent.ts
import { decideTradeFromSignals } from "./decide";
import { swapWithRetry } from "./swap";
import { validateTrade } from "./guardrails";
import { slippagesFor } from "./fot";
import { WALLET_ADDRESS } from "./wallet";

async function runAgentTick() {
const signals = await fetchSignals(); // your signal source
const decision = await decideTradeFromSignals(signals);

if (decision.action === "hold") {
console.log("Agent says hold:", decision.reason);
return;
}

const walletValueUsd = await estimateWalletValueUsd();
const tradeValueUsd = await estimateTradeValueUsd(decision);
validateTrade(decision, walletValueUsd, tradeValueUsd);

const receipt = await swapWithRetry(
{
chainId: 1,
tokenIn: decision.tokenIn,
tokenOut: decision.tokenOut,
amount: decision.amount,
sender: WALLET_ADDRESS,
},
slippagesFor(decision.tokenOut),
);

console.log(`Trade executed: ${receipt.transactionHash}`);
}

// Run every 5 minutes
setInterval(runAgentTick, 5 * 60 * 1000);
runAgentTick();

The fetchSignals, estimateWalletValueUsd, and estimateTradeValueUsd functions are yours to implement — typically using Dune, CoinGecko, or on-chain reads via viem.

Step 8: Run It

bun run src/agent.ts

Start with a small wallet (~$100 total) and watch the logs. You want to see:

  • Quotes landing in 1-3 seconds
  • The retry loop escalating slippage on revert
  • Guardrails rejecting trades that exceed caps
  • Transaction hashes confirming on Etherscan

Iterate from there. Most memecoin agent bugs are in the signal layer (bad LLM prompts, stale Dune queries), not the swap layer.

Frequently Asked Questions

Why do my memecoin swaps revert?

Memecoin swaps revert for three reasons: slippage exceeded (price moved), fee-on-transfer tax (the token deducts on every transfer, breaking the slippage check), or MEV frontrunning. The fix is the slippage retry pattern: catch the revert, refetch the quote with a higher maxSlippage (escalate from 1% → 5% → 10% → 15%), and retry until it succeeds or hits your cap. swapapi.dev's maxSlippage parameter accepts decimals from 0 to 1, so 0.15 = 15% slippage tolerance.

Can an AI agent use a swap API without a human onboarding step?

Yes, but only with an API that requires no API key. swapapi.dev is the only major DEX aggregator API that works this way — every other (1inch, 0x, Velora, Li.Fi) requires a human to register first. For fully autonomous agents where no human is in the loop, swapapi.dev is the only option.

What's a safe max slippage for an autonomous memecoin agent?

A safe cap is 15-20%. Below that, you catch most volatile memecoins and fee-on-transfer tokens. Above that, you're likely buying into a honeypot or a token with a 30%+ sell tax — the trade should be skipped entirely rather than executed at a bad price.

How do I detect fee-on-transfer tokens at runtime?

You can't reliably detect them from the quote — swapapi.dev will return a quote even for FoT tokens, with expectedAmountOut ignoring the tax. The pragmatic approach is to learn empirically: log the slippage that each token successfully executes at, and promote tokens that consistently need ≥5% into a "known FoT" set with a higher base slippage schedule.

What chains does swapapi.dev support for memecoin trading?

swapapi.dev supports 46 EVM chains including Ethereum, Base, Arbitrum, BSC, Polygon, Optimism, Avalanche, and newer networks like Berachain, Monad, and MegaETH. See the supported chains docs for the full list. For memecoin trading specifically, Ethereum and Base have the deepest liquidity.

Get Started

Your AI memecoin trading agent needs free, no-API-key, 46-chain swap infrastructure to run unattended. swapapi.dev gives you exactly that — read the getting started guide, the API reference, and the AI agents integration guide. And remember: always retry with higher slippage.

# Final example: USDC → PEPE on Ethereum with 10% slippage
curl "https://api.swapapi.dev/v1/swap/1?\
tokenIn=0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48&\
tokenOut=0x6982508145454Ce325dDbE47a25d4ec3d2311933&\
amount=100000000&\
sender=0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045&\
maxSlippage=0.10"

If the first attempt reverts, refetch with maxSlippage=0.15. If that still fails, escalate to 0.20 and then abort. See the companion article on the best memecoin swap APIs for more on why this pattern matters, and the slippage guide for price impact fundamentals.