Back to list
Memecoin 取引のための AI エージェントの構築方法
How to Build an AI Agent for Memecoin Trading
Translated: 2026/4/20 11:22:59
Japanese Translation
Memecoin 取引用の AI エージェントを構築するには、以下の 4 つの要素が必要です:取引先を選ぶための LLM(大規模言語モデル)、実行可能な calldata(コードデータ)を返すスワップ API、取引を検証するウォレット、そして最優先事項として、返値処理を対応する増大式スリッページ再試行ループです。Ethereum と Base 市場では、Memecoin の日常取引額が 20 億ドルを超え、自律エージェントによる取引シェアは急速に成長しています。しかし、Memecoin は頻繁に返値します:ボラティリティが激しく、多くのトークンが転送税を課し、最初取得されたクォートquote は実際の取引価格とは異なることがほとんどです。本ガイドでは、TypeScript を使用して、swapapi.dev(API キーなしで動作する唯一の集約業者のため、人間の手動登録プロセスなしで自己実行が可能)をスワップバックエンドとして使用した、本格的な AI Memecoin 取引エージェントの構築方法を案内します。終了時点で、LLM による判断を取得、クォートを取得、返値時に増大式スリッページで再試行し、最大ポジションサイズやトークンブラックリストなどの安全制限を強制する、約 200 行の Bun スクリプトを構築できているはずです。
Bun (または Node 20+) — JavaScript の実行環境
viem — 最新の Ethereum クライアントライブラリ(ethers v6 より軽量)
@anthropic-ai/sdk (または openai) — 選択した LLM プロバイダー
資金が十分な EVM ウォレット — 手数料料金(ETH)と取引(USDC)用のプライベートキー
swapapi.dev — API キー不要の無料スワップ API (ドキュメント)
```bash
bun init -y
bun add viem @anthropic-ai/sdk
```
.env ファイルを作成し、ウォレットのプライベートキーと LLM の API キーを登録してください。これらの情報はハードコードするべきではありません。
# .env
PRIVATE_KEY=0x...
ANTHROPIC_API_KEY=sk-ant-
...
RPC_URL=https://eth.llamarpc.com
次に、viem ウォレットクライアントの構造化を作成します——これは取引の署名と送信を処理します。
// 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;
LLM の役割は取引を実行することではなく、何を行うかを選ぶことです。ツールに狭いスキーマを与え、判断オブジェクトを返させるようにしてください。
// src/decide.ts
import Anthropic from "@anthropic-ai/sdk";
const anthropic = new Anthropic();
export type TradeDecision = {
action: "buy" | "sell" | "hold";
tokenIn: string; // コントラクトアドレス
tokenOut: string; // コントラクトアドレス
amount: string; // 生ユニット
reason: string;
};
export async function decideTradeFromSignals(
signals: Record,
): Promise<TradeDecision> {
const resp = await anthropic.messages.create({
model: "claude-opus-4-6",
max_tokens: 1024,
system: "あなたは Memecoin 取引エージェントです。JSON のみ出力してください。説明はしないでください。",
messages: [
{
role: "user",
content: `信号:${JSON.stringify(signals)}\n
取引判断 JSON を返してください。`,
},
],
});
const text =
resp.content[0].type === "text"
? resp.content[0].text
: "{}";
return JSON.parse(text);
}
信号は Dune クエリ、CoinGecko トレンド、チェーン上の whale アラート、またはセンチメントフィードのどこからでも来ることができます。エージェントフレームワークはそれを気にしません——構造化された入力が必要なだけです。
swapapi.dev は単一の GET エンドポイントを公開します。ヘッダーも API キーも、SDK も不要です。自律エージェントにとって、これが統合のすべてです。
// 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(`クォート失敗:${json.error?.code}`);
}
return json.data;
}
注記してください 15 秒のタイムアウト——t
Original Content
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. 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 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; 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, ): Promise { 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. 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. 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: Slippage exceeded — price moved between quote and execution 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 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, 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. Strategy First tx slippage Retry escalation Memecoin 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. 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([ "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. 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([ // 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`); } } 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. 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. 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. 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. 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. 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. 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. 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.