Skip to main content
Glama

swap_edu_for_tokens

Swap EDU for tokens on SailFish DEX by providing the sender's private key, output token address, and EDU amount. Set slippage tolerance and fee tier to complete the transaction securely.

Instructions

Swap EDU for tokens on SailFish DEX

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
amountInYesAmount of EDU 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)
tokenOutYesAddress of the output token

Implementation Reference

  • Core handler function that executes the swap of EDU for tokens on SailFish DEX using Uniswap V3 SwapRouter. Handles both direct and multi-hop routes.
    // Swap EDU to token
    export async function swapExactEDUForTokens(
      privateKey: string,
      tokenOut: string,
      amountIn: string,
      slippagePercentage: number = 0.5 // Default 0.5% slippage
    ): Promise<{
      hash: string;
      from: string;
      amountIn: string;
      amountOut: string;
      tokenOut: string;
      tokenOutSymbol: string;
      route: routes.RouteInfo;
    }> {
      try {
        const provider = blockchain.getProvider();
        const wallet = new ethers.Wallet(privateKey, provider);
        const fromAddress = wallet.address;
        
        // Get quote and route information
        const quote = await getSwapQuote(CONTRACTS.WETH9, tokenOut, amountIn, slippagePercentage);
        const route = quote.route;
        
        // Convert EDU amount to wei
        const amountInWei = ethers.parseEther(amountIn);
        const minAmountOut = ethers.getBigInt(quote.minimumAmountOut);
        
        // Create swap router contract
        const swapRouter = new ethers.Contract(CONTRACTS.SwapRouter, SWAP_ROUTER_ABI, wallet);
        
        // Execute swap based on route type
        const deadline = Math.floor(Date.now() / 1000) + 60 * 20; // 20 minutes from now
        let tx;
        
        try {
          // Transaction details are logged to server console only, not mixed with JSON response
          
          if (route.type === 'direct') {
            // Direct route (single hop)
            const fee = parseInt(route.path[0].feeTier);
            
            const swapParams = {
              tokenIn: CONTRACTS.WETH9,
              tokenOut,
              fee,
              recipient: fromAddress,
              deadline,
              amountIn: amountInWei,
              amountOutMinimum: minAmountOut,
              sqrtPriceLimitX96: 0 // No price limit
            };
            
            // Check if the value is reasonable (not excessively large)
            if (amountInWei > ethers.parseEther('1000000')) {
              throw new Error(`Amount too large: ${ethers.formatEther(amountInWei)} EDU`);
            }
            
            // Use a gas limit to prevent excessive gas usage
            tx = await swapRouter.exactInputSingle(swapParams, { 
              value: amountInWei,
              gasLimit: 500000 // Set a reasonable gas limit
            });
          } else {
            // Indirect route (multi-hop)
            const intermediaryToken = route.intermediaryToken!;
            
            // Encode the path for multi-hop swap
            const path = ethers.solidityPacked(
              ['address', 'uint24', 'address', 'uint24', 'address'],
              [
                CONTRACTS.WETH9,
                parseInt(route.path[0].feeTier),
                intermediaryToken.address,
                parseInt(route.path[1].feeTier),
                tokenOut
              ]
            );
            
            const swapParams = {
              path,
              recipient: fromAddress,
              deadline,
              amountIn: amountInWei,
              amountOutMinimum: minAmountOut
            };
            
            // Check if the value is reasonable (not excessively large)
            if (amountInWei > ethers.parseEther('1000000')) {
              throw new Error(`Amount too large: ${ethers.formatEther(amountInWei)} EDU`);
            }
            
            // Use a gas limit to prevent excessive gas usage
            tx = await swapRouter.exactInput(swapParams, { 
              value: amountInWei,
              gasLimit: 500000 // Set a reasonable gas limit
            });
          }
        } catch (error: any) {
          console.error('Error executing swap transaction:', error);
          
          // Provide more detailed error information
          if (error.message && error.message.includes('insufficient funds')) {
            throw new Error(`Insufficient funds for transaction. Make sure you have enough EDU for the swap amount (${amountIn} EDU) plus gas fees.`);
          }
          
          throw error;
        }
        
        const receipt = await tx.wait();
        
        if (!receipt) {
          throw new Error('Transaction failed');
        }
        
        return {
          hash: tx.hash,
          from: fromAddress,
          amountIn,
          amountOut: quote.formattedMinimumAmountOut,
          tokenOut,
          tokenOutSymbol: quote.tokenOutSymbol,
          route
        };
      } catch (error) {
        console.error('Error swapping EDU for tokens:', error);
        throw error;
      }
    }
  • src/index.ts:1189-1220 (registration)
    MCP tool dispatch/registration in the CallToolRequestSchema handler. Validates inputs and calls the swapExactEDUForTokens function from swap module.
    case 'swap_edu_for_tokens': {
      if (!args.privateKey || typeof args.privateKey !== 'string') {
        throw new McpError(ErrorCode.InvalidParams, 'Private key is required');
      }
      
      if (!args.tokenOut || typeof args.tokenOut !== 'string') {
        throw new McpError(ErrorCode.InvalidParams, 'Output 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.swapExactEDUForTokens(
        args.privateKey,
        args.tokenOut,
        args.amountIn,
        slippagePercentage
      );
      
      return {
        content: [
          {
            type: 'text',
            text: JSON.stringify(result, null, 2),
          },
        ],
      };
    }
  • Tool schema definition including inputSchema with properties and required fields for the swap_edu_for_tokens tool, listed in ListToolsRequestSchema handler.
      name: 'swap_edu_for_tokens',
      description: 'Swap EDU for tokens on SailFish DEX',
      inputSchema: {
        type: 'object',
        properties: {
          privateKey: {
            type: 'string',
            description: 'Private key of the sender wallet',
          },
          tokenOut: {
            type: 'string',
            description: 'Address of the output token',
          },
          amountIn: {
            type: 'string',
            description: 'Amount of EDU 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', 'tokenOut', 'amountIn'],
      },
    },
  • Helper function getSwapQuote used by the handler to get swap quotes, routes, price impact, and apply slippage before executing the swap.
    export async function getSwapQuote(
      tokenIn: string,
      tokenOut: string,
      amountIn: string,
      slippagePercentage: number = 0.5
    ): Promise<{
      amountOut: string;
      formattedAmountOut: string;
      minimumAmountOut: string;
      formattedMinimumAmountOut: string;
      tokenInSymbol: string;
      tokenOutSymbol: string;
      tokenInDecimals: number;
      tokenOutDecimals: number;
      route: routes.RouteInfo;
      priceImpact: number;
      midPrice: string;
    }> {
      try {
        // Find the best route for the token pair
        const route = await findBestRoute(tokenIn, tokenOut);
        
        const provider = blockchain.getProvider();
        
        // Get token details
        const tokenInContract = new ethers.Contract(tokenIn, ERC20_ABI, provider);
        const tokenOutContract = new ethers.Contract(tokenOut, ERC20_ABI, provider);
        
        const [tokenInDecimals, tokenOutDecimals, tokenInSymbol, tokenOutSymbol] = await Promise.all([
          tokenInContract.decimals(),
          tokenOutContract.decimals(),
          tokenInContract.symbol(),
          tokenOutContract.symbol(),
        ]);
        
        // Convert amount to token units
        const amountInWei = ethers.parseUnits(amountIn, tokenInDecimals);
        
        // Get quote based on route type
        let amountOutWei: bigint;
        let midPrice: string;
        
        if (route.type === 'direct') {
          // Direct route (single hop)
          const pool = route.path[0];
          const fee = parseInt(pool.feeTier);
          
          // Get quote using the QuoterV2 contract
          const quoterContract = new ethers.Contract(CONTRACTS.QuoterV2, QUOTER_ABI, provider);
          const quoteParams = {
            tokenIn,
            tokenOut,
            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);
          amountOutWei = decodedResult[0]; // Get the first return value (amountOut)
          
          // Get mid price from the pool
          if (pool.token0.address.toLowerCase() === tokenIn.toLowerCase()) {
            midPrice = pool.token1Price || '0';
          } else {
            midPrice = pool.token0Price || '0';
          }
        } else {
          // Indirect route (multi-hop)
          // For simplicity, we'll use the direct route approach for each hop and multiply the results
          // In a production environment, you would use the exactInput function with a path
          
          // First hop
          const pool1 = route.path[0];
          const fee1 = parseInt(pool1.feeTier);
          const intermediaryToken = route.intermediaryToken!;
          
          // Second hop
          const pool2 = route.path[1];
          const fee2 = parseInt(pool2.feeTier);
          
          // Get quote for first hop
          const quoterContract = new ethers.Contract(CONTRACTS.QuoterV2, QUOTER_ABI, provider);
          
          // First hop quote
          const quoteParams1 = {
            tokenIn,
            tokenOut: intermediaryToken.address,
            amountIn: amountInWei,
            fee: fee1,
            sqrtPriceLimitX96: 0
          };
          
          const quoterInterface = new ethers.Interface(QUOTER_ABI);
          const calldata1 = quoterInterface.encodeFunctionData('quoteExactInputSingle', [quoteParams1]);
          
          const result1 = await provider.call({
            to: CONTRACTS.QuoterV2,
            data: calldata1,
          });
          
          const decodedResult1 = quoterInterface.decodeFunctionResult('quoteExactInputSingle', result1);
          const intermediateAmountWei = decodedResult1[0];
          
          // Second hop quote
          const quoteParams2 = {
            tokenIn: intermediaryToken.address,
            tokenOut,
            amountIn: intermediateAmountWei,
            fee: fee2,
            sqrtPriceLimitX96: 0
          };
          
          const calldata2 = quoterInterface.encodeFunctionData('quoteExactInputSingle', [quoteParams2]);
          
          const result2 = await provider.call({
            to: CONTRACTS.QuoterV2,
            data: calldata2,
          });
          
          const decodedResult2 = quoterInterface.decodeFunctionResult('quoteExactInputSingle', result2);
          amountOutWei = decodedResult2[0];
          
          // Calculate mid price for multi-hop (approximate)
          const midPrice1 = pool1.token0.address.toLowerCase() === tokenIn.toLowerCase() 
            ? pool1.token1Price || '0'
            : pool1.token0Price || '0';
            
          const midPrice2 = pool2.token0.address.toLowerCase() === intermediaryToken.address.toLowerCase()
            ? pool2.token1Price || '0'
            : pool2.token0Price || '0';
            
          midPrice = (parseFloat(midPrice1) * parseFloat(midPrice2)).toString();
        }
        
        // Format amount out
        const formattedAmountOut = ethers.formatUnits(amountOutWei, tokenOutDecimals);
        
        // Calculate minimum amount out with slippage
        const minimumAmountOut = applySlippage(amountOutWei.toString(), slippagePercentage);
        const formattedMinimumAmountOut = ethers.formatUnits(minimumAmountOut, tokenOutDecimals);
        
        // Calculate price impact
        const priceImpact = calculatePriceImpact(
          amountIn,
          formattedAmountOut,
          midPrice,
          tokenInDecimals,
          tokenOutDecimals
        );
        
        return {
          amountOut: amountOutWei.toString(),
          formattedAmountOut,
          minimumAmountOut,
          formattedMinimumAmountOut,
          tokenInSymbol,
          tokenOutSymbol,
          tokenInDecimals,
          tokenOutDecimals,
          route,
          priceImpact,
          midPrice
        };
      } catch (error) {
        console.error('Error getting swap quote:', 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