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

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

Input Schema (JSON Schema)

{ "properties": { "amountIn": { "description": "Amount of tokens to swap", "type": "string" }, "fee": { "description": "Fee tier (100=0.01%, 500=0.05%, 3000=0.3%, 10000=1%)", "type": "number" }, "privateKey": { "description": "Private key of the sender wallet", "type": "string" }, "slippagePercentage": { "description": "Slippage tolerance percentage (default: 0.5)", "type": "number" }, "tokenIn": { "description": "Address of the input token", "type": "string" } }, "required": [ "privateKey", "tokenIn", "amountIn" ], "type": "object" }

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; } }

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