Skip to main content
Glama

evm_execute_swap

Execute a DEX token swap with built-in slippage protection and transaction deadline, reverting if the received amount falls below your minimum acceptable output.

Instructions

Execute token swap on DEX with automatic slippage protection and deadline.

Broadcasts swap transaction to DEX router. Requires prior token approval. Protects against price movement with slippage tolerance. Transaction fails if output below minimum acceptable amount.

CRITICAL RULES:

  • MUST approve tokenIn for DEX router BEFORE swapping (use evm_approve_token)

  • Requires gas in native token (ETH, POL, etc.)

  • Slippage protection prevents unfavorable execution

  • Transaction has deadline (typically 20 minutes)

  • Actual output may be less than quote due to price movement

  • Irreversible once confirmed

PARAMETERS:

  • chain: EVM chain to execute swap on (required)

    • Must have gas in native token

    • Different gas costs per chain

  • dex: DEX protocol name (required)

    • Must be deployed on selected chain

    • Examples: "uniswap", "quickswap", "pancakeswap"

  • tokenIn: Input token to swap from (required)

    • Token you're selling

    • Must approve this token for router first

    • Format: 0x followed by 40 hex characters

  • tokenOut: Output token to receive (required)

    • Token you're buying

    • Format: 0x followed by 40 hex characters

    • Must have liquidity pair with tokenIn

  • amountIn: Amount to swap (required)

    • Human-readable format: "100" = 100 tokens

    • Must have sufficient balance

    • Examples: "1.0", "100", "0.5"

  • slippageTolerance: Maximum price slippage (required)

    • Percentage as decimal: "0.5" = 0.5%

    • Common values: "0.5" (low), "1" (medium), "5" (high)

    • Higher slippage = more likely to succeed but worse price

    • Lower slippage = better price but may fail

  • privateKey: Transaction signer's private key (required, KEEP SECRET)

    • Must be address holding tokenIn

    • Must have gas for transaction

    • Never expose, share, or log

EXAMPLES: ✅ Swap 100 USDC to WETH on Polygon with 0.5% slippage: {chain: "polygon", dex: "quickswap", tokenIn: "0x2791Bca1f2de4661ED88A30C99A7a9449Aa84174", tokenOut: "0x7ceB23fD6bC0adD59E62ac25578270cFf1b9f619", amountIn: "100", slippageTolerance: "0.5", privateKey: "0xac0974..."}

✅ Swap 1 ETH to USDC on Ethereum with 1% slippage: {chain: "ethereum", dex: "uniswap", tokenIn: "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2", tokenOut: "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48", amountIn: "1.0", slippageTolerance: "1", privateKey: "0x..."}

✅ High slippage for volatile tokens (BSC): {chain: "bsc", dex: "pancakeswap", tokenIn: "0xToken...", tokenOut: "0xBUSD...", amountIn: "50", slippageTolerance: "5", privateKey: "0x..."}

❌ Invalid - no token approval: {amountIn: "100"} // Must approve tokenIn first

❌ Invalid - insufficient balance: {amountIn: "10000"} // Only have 100 tokens

SUPPORTED EVM CHAINS (7 networks): • ethereum (Sepolia) - EIP-1559 enabled, ~12s blocks, moderate gas costs • polygon (Amoy) - Low fees, fast finality (~2s), layer 2 • avalanche (Fuji C-Chain) - Sub-second finality, dynamic fees • bsc (BNB Testnet) - 3s blocks, low gas costs, Binance ecosystem • arbitrum (Sepolia) - Optimistic rollup, low fees, Ethereum security • base (Sepolia) - Coinbase layer 2, EIP-1559, low fees • worldchain (World Sepolia) - World Network testnet, EIP-1559

CRITICAL GAS CONSIDERATIONS:

  • Ethereum: High gas costs, use gas oracle for timing

  • Polygon/BSC: Very low gas, safe for frequent transactions

  • Arbitrum/Base: L2 optimizations, ~10-50x cheaper than Ethereum

  • Avalanche: Dynamic fees, can spike during congestion

  • Always check gas price before executing transactions

TESTNET TOKENS: All chains use testnet tokens with NO REAL VALUE. Faucets available for all supported networks.

OUTPUT STRUCTURE: • success: Boolean indicating swap success • chain: Chain where swap executed • transactionHash: Transaction hash for tracking • dex: DEX protocol used • tokenIn: Input token address • tokenOut: Output token address • amountIn: Amount swapped (formatted) • amountOut: Amount received (formatted) • priceImpact: Actual price impact percentage • gasUsed: Gas consumed • executionTime: Time taken in milliseconds

COMMON MISTAKES:

  • Forgetting to approve tokens before swap (will fail)

  • Insufficient gas for transaction

  • Slippage too low (transaction fails)

  • Not checking quote before swap

  • Swapping during high volatility (large slippage)

USE CASES:

  • Trade tokens for different tokens

  • Rebalance portfolio

  • Take profits or cut losses

  • Arbitrage between chains

  • Convert tokens for DeFi operations

PRE-SWAP CHECKLIST:

  1. Check tokenIn balance (evm_get_token_balance)

  2. Check gas balance (evm_get_balance)

  3. Get quote (evm_get_dex_quote)

  4. Approve tokenIn for router (evm_approve_token)

  5. Execute swap (this tool)

SLIPPAGE TOLERANCE GUIDE:

  • 0.1-0.5%: Stable pairs (USDC/USDT), low volatility

  • 0.5-1%: Normal conditions, major tokens

  • 1-3%: Moderate volatility, medium liquidity

  • 3-5%: High volatility, low liquidity

  • 5%+: Extreme volatility or very low liquidity

TRANSACTION FLOW:

  1. Get quote for amountOut estimate

  2. Calculate minAmountOut = quote * (1 - slippage/100)

  3. Approve tokenIn if needed

  4. Execute swap with slippage protection

  5. Transaction reverts if output < minAmountOut

  6. Deadline prevents pending transactions

GAS COSTS:

  • Simple swap (direct pair): 150,000-200,000 gas

  • Multi-hop swap: 250,000-350,000 gas

  • Ethereum Sepolia: ~0.003-0.005 ETH

  • Polygon: ~0.0001 POL

  • BSC: ~0.0003 BNB

PRICE IMPACT: Large swaps move price:

  • Monitor priceImpact in output

  • Consider splitting large orders

  • Check liquidity before swapping

  • Higher impact = worse execution price

FAILED TRANSACTIONS: Common failure reasons:

  • Insufficient approval

  • Slippage exceeded

  • Deadline passed

  • Insufficient liquidity

  • Transaction reverted

SECURITY NOTES:

  • Verify token addresses carefully

  • Check DEX router address is official

  • Start with small test swaps

  • Monitor transaction on explorer

  • Beware of fake tokens with similar names

Running on Linux.

LINUX-SPECIFIC NOTES:

  • Package manager: apt (Ubuntu/Debian), yum (RHEL/CentOS), or pacman (Arch)

  • Python 3 is typically 'python3' command

  • GNU tools are standard

  • Use 'xdg-open' command to open files/applications

Tool call template

Replace each placeholder with a value matching the input schema. Only required parameters are included; add optional parameters as needed.

{
  "id": 1,
  "jsonrpc": "2.0",
  "method": "tools/call",
  "params": {
    "arguments": {
      "chain": "<chain>",
      "dex": "<dex>",
      "tokenIn": "<tokenIn>",
      "tokenOut": "<tokenOut>",
      "amountIn": "<amountIn>",
      "slippageTolerance": "<slippageTolerance>",
      "privateKey": "<privateKey>"
    },
    "name": "evm_execute_swap"
  }
}

Input Schema

NameRequiredDescriptionDefault
dexYesDEX name (e.g., "uniswap", "quickswap", "traderjoe", "pancakeswap")
chainYesEVM chain to execute on
tokenInYesInput token address (0x...)
amountInYesInput amount (in ether units, e.g., "1.0")
tokenOutYesOutput token address (0x...)
privateKeyYesPrivate key to sign transaction (0x...)
slippageToleranceYesSlippage tolerance percentage (e.g., "0.5" for 0.5%)

Schema Changelog

Changes observed during successful MCP inspections.

  1. First observedv1.0.0

TDQS

A4.6/5.0
Behavior5/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations, the description carries the full burden and does so: it discloses irreversibility, the ~20-minute deadline, revert-on-insufficient-output semantics, gas requirements per chain, and expected gas ranges (150k–350k). It also flags private-key sensitivity and the approval prerequisite, which are exactly the behavioral facts an agent needs before a destructive write.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness2/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The definition is roughly 1,500 words and repeats the same facts across overlapping sections (slippage appears in PARAMETERS, SLIPPAGE GUIDE, TRANSACTION FLOW, COMMON MISTAKES, and FAILED TRANSACTIONS; gas appears three times). It also ends with off-topic "Running on Linux / LINUX-SPECIFIC NOTES" content that has nothing to do with a DEX swap and dilutes the signal.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness5/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

For a 7-required-parameter mutation tool with no annotations and no output schema, the description covers everything an agent needs: prerequisites, failure modes, chain support, slippage selection, and an inline OUTPUT STRUCTURE listing returned fields including transactionHash and priceImpact.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters4/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema coverage is already 100%, so the baseline is 3, but the description adds real meaning beyond the schema: slippage is explained as a risk trade-off with concrete ranges (0.1–0.5% stable pairs through 5%+ extreme volatility), and worked examples show valid per-parameter values. Marginal deduction for the amountIn/privateKey sections largely restating schema text.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

"Execute token swap on DEX" states a specific verb and resource, and the description immediately names the distinguishing constraints (broadcasts a real transaction, requires prior approval). The agent can tell this apart from evm_get_dex_quote and evm_approve_token without opening any schema.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines5/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

It supplies an explicit PRE-SWAP CHECKLIST naming the exact prerequisite siblings (evm_get_token_balance, evm_get_balance, evm_get_dex_quote, evm_approve_token) in order, plus when-not-to-use signals such as missing approval, insufficient gas, or slippage too low. This is the strongest form of routing guidance.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Deploy Server

Other Tools