Skip to main content
Glama

swap_tokens_for_edu

Swap tokens for EDU on SailFish DEX using your wallet's private key, token address, slippage, and fee tier for efficient transactions on EDUCHAIN.

Instructions

Swap tokens for EDU on SailFish DEX

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
amountInYesAmount of tokens to swap
feeNoFee tier (100=0.01%, 500=0.05%, 3000=0.3%, 10000=1%)
privateKeyYesPrivate key of the sender wallet
slippagePercentageNoSlippage tolerance percentage (default: 0.5)
tokenInYesAddress of the input token

Implementation Reference

  • Core handler function that performs the token-to-EDU swap: handles approvals, quoting via QuoterV2, executes Uniswap V3 swap to WETH9, unwraps to native EDU, and returns transaction details.
    export async function swapExactTokensForEDU(
      privateKey: string,
      tokenIn: string,
      amountIn: string,
      slippagePercentage: number = 0.5, // Default 0.5% slippage
      fee?: number
    ): Promise<{
      hash: string;
      from: string;
      amountIn: string;
      amountOut: string;
      tokenIn: string;
      tokenInSymbol: string;
    }> {
      try {
        const provider = blockchain.getProvider();
        const wallet = new ethers.Wallet(privateKey, provider);
        const fromAddress = wallet.address;
        
        // If fee is not provided, find the best route
        const route = await findBestRoute(tokenIn, CONTRACTS.WETH9);
        const fee = parseInt(route.path[0].feeTier);
        
        // Get token details
        const tokenInContract = new ethers.Contract(tokenIn, ERC20_ABI, provider);
        const tokenInDecimals = await tokenInContract.decimals();
        const tokenInSymbol = await tokenInContract.symbol();
        
        // Convert amount to token units
        const amountInWei = ethers.parseUnits(amountIn, tokenInDecimals);
        
        // Approve router to spend tokens
        const approveTx = await tokenInContract.approve(CONTRACTS.SwapRouter, amountInWei);
        await approveTx.wait();
        
        // Get quote for token to WETH (since we'll be using WETH internally)
        const quoterContract = new ethers.Contract(CONTRACTS.QuoterV2, QUOTER_ABI, provider);
        const quoteParams = {
          tokenIn,
          tokenOut: CONTRACTS.WETH9,
          amountIn: amountInWei,
          fee,
          sqrtPriceLimitX96: 0 // No price limit
        };
        
        // Use a static call to get the quote without sending a transaction
        const quoterInterface = new ethers.Interface(QUOTER_ABI);
        const calldata = quoterInterface.encodeFunctionData('quoteExactInputSingle', [quoteParams]);
        
        const result = await provider.call({
          to: CONTRACTS.QuoterV2,
          data: calldata,
        });
        
        const decodedResult = quoterInterface.decodeFunctionResult('quoteExactInputSingle', result);
        const amountOutWei = decodedResult[0]; // Get the first return value (amountOut)
        
        // Calculate minimum amount out with slippage
        const slippageFactor = 1000 - (slippagePercentage * 10); // Convert percentage to basis points
        const minAmountOut = (amountOutWei * BigInt(slippageFactor)) / BigInt(1000);
        
        // Create swap router contract
        const swapRouter = new ethers.Contract(CONTRACTS.SwapRouter, SWAP_ROUTER_ABI, wallet);
        
        // Execute swap
        const deadline = Math.floor(Date.now() / 1000) + 60 * 20; // 20 minutes from now
        
        // We need to swap to WETH and then unwrap it to ETH
        const swapParams = {
          tokenIn,
          tokenOut: CONTRACTS.WETH9,
          fee,
          recipient: CONTRACTS.SwapRouter, // Send to router for unwrapping
          deadline,
          amountIn: amountInWei,
          amountOutMinimum: minAmountOut,
          sqrtPriceLimitX96: 0 // No price limit
        };
        
        const tx = await swapRouter.exactInputSingle(swapParams);
        
        // Unwrap WETH to ETH and send to user
        await swapRouter.unwrapWETH9(minAmountOut, fromAddress);
        
        const receipt = await tx.wait();
        
        if (!receipt) {
          throw new Error('Transaction failed');
        }
        
        return {
          hash: tx.hash,
          from: fromAddress,
          amountIn,
          amountOut: ethers.formatEther(minAmountOut),
          tokenIn,
          tokenInSymbol
        };
      } catch (error) {
        console.error('Error swapping tokens for EDU:', error);
        throw error;
      }
    }
  • src/index.ts:1222-1253 (registration)
    MCP CallToolRequestSchema handler case that invokes the swapExactTokensForEDU implementation with validated parameters and formats the response.
    case 'swap_tokens_for_edu': {
      if (!args.privateKey || typeof args.privateKey !== 'string') {
        throw new McpError(ErrorCode.InvalidParams, 'Private key is required');
      }
      
      if (!args.tokenIn || typeof args.tokenIn !== 'string') {
        throw new McpError(ErrorCode.InvalidParams, 'Input token address is required');
      }
      
      if (!args.amountIn || typeof args.amountIn !== 'string') {
        throw new McpError(ErrorCode.InvalidParams, 'Input amount is required');
      }
      
      const slippagePercentage = typeof args.slippagePercentage === 'number' ? args.slippagePercentage : 0.5;
      const fee = typeof args.fee === 'number' ? args.fee : 3000; // Default to 0.3%
      
      const result = await swap.swapExactTokensForEDU(
        args.privateKey,
        args.tokenIn,
        args.amountIn,
        slippagePercentage
      );
      
      return {
        content: [
          {
            type: 'text',
            text: JSON.stringify(result, null, 2),
          },
        ],
      };
    }
  • Tool schema definition in ListToolsRequestSchema response, specifying name, description, and input parameters for MCP tool invocation.
    name: 'swap_tokens_for_edu',
    description: 'Swap tokens for EDU on SailFish DEX',
    inputSchema: {
      type: 'object',
      properties: {
        privateKey: {
          type: 'string',
          description: 'Private key of the sender wallet',
        },
        tokenIn: {
          type: 'string',
          description: 'Address of the input token',
        },
        amountIn: {
          type: 'string',
          description: 'Amount of tokens to swap',
        },
        slippagePercentage: {
          type: 'number',
          description: 'Slippage tolerance percentage (default: 0.5)',
        },
        fee: {
          type: 'number',
          description: 'Fee tier (100=0.01%, 500=0.05%, 3000=0.3%, 10000=1%)',
        },
      },
      required: ['privateKey', 'tokenIn', 'amountIn'],
    },
  • src/index.ts:17-18 (registration)
    Import of swap module in index.ts, providing access to swapExactTokensForEDU function for tool handlers.
    import * as swap from './swap.js';
    import * as external_market from './external_market.js';
  • Helper function used by swapExactTokensForEDU to find the best liquidity route via subgraph queries.
    export async function findBestRoute(
      tokenA: string,
      tokenB: string
    ): Promise<routes.RouteInfo> {
      try {
        // Get the best route from the routes module
        const bestRoute = await routes.getBestRoute(tokenA, tokenB);
        
        if (!bestRoute) {
          throw new Error(`No route found for token pair ${tokenA}/${tokenB}`);
        }
        
        // Remove console.log to prevent interference with JSON parsing
        // console.log(`Found ${bestRoute.type} route for ${tokenA}/${tokenB} with fee: ${bestRoute.totalFee * 100}%`);
        
        return bestRoute;
      } catch (error) {
        console.error('Error finding best route:', error);
        throw error;
      }
    }
Behavior2/5

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

With no annotations provided, the description carries full burden but offers minimal behavioral insight. It implies a financial transaction ('Swap') but doesn't disclose critical traits like whether it's read-only or destructive (likely destructive given privateKey parameter), potential costs beyond the fee parameter, rate limits, error conditions, or what happens on success/failure. The description adds almost no context beyond the basic action.

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

Conciseness5/5

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

The description is a single, efficient sentence with zero wasted words. It's perfectly front-loaded with the core action and immediately communicates the essential purpose without unnecessary elaboration.

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

Completeness2/5

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

For a financial transaction tool with 5 parameters, no annotations, and no output schema, the description is inadequate. It doesn't explain what EDU is (presumably a token), what 'SailFish DEX' refers to, what happens after the swap, potential risks (slippage, failed transactions), or return values. The context signals indicate significant complexity that the description doesn't address.

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

Parameters3/5

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

Schema description coverage is 100%, so parameters are well-documented in the schema itself. The description adds no additional parameter semantics beyond what's in the schema (e.g., it doesn't explain tokenIn/amountIn relationships or privateKey security implications). Baseline 3 is appropriate when the schema does the heavy lifting.

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

Purpose4/5

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

The description clearly states the action ('Swap') and resources ('tokens for EDU on SailFish DEX'), making the purpose immediately understandable. It distinguishes from siblings like 'swap_tokens' (general token swap) and 'swap_edu_for_tokens' (reverse direction), though it doesn't explicitly mention these distinctions in the description itself.

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

Usage Guidelines2/5

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

The description provides no guidance on when to use this tool versus alternatives. It doesn't mention prerequisites (e.g., needing tokens to swap), differentiate from 'swap_tokens' (which might handle different token pairs), or explain why one would choose this specific EDU-focused swap over other swap tools in the sibling list.

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

Install Server

Other Tools

Related Tools

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/SailFish-Finance/educhain-ai-agent-kit'

If you have feedback or need assistance with the MCP directory API, please join our Discord server