Skip to main content
Glama

SWAP

Execute token swaps across blockchain networks by specifying input/output tokens, amounts, and slippage tolerance to build swap transactions.

Instructions

Building swap transaction

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
chainNoThe blockchain network to execute the transaction on. uses fraxtal as defaultfraxtal
inTokenAddressYesThe token to swap from (address).
outTokenAddressYesThe token to swap to (address).
amountYesToken amount with decimals. For example, if 1 USDT is input, use 1000000 (1 USDT * 10^6).
slippageNoDefine the acceptable slippage level by inputting a percentage value within the range of 0.05 to 50. 1% slippage set as 1.1
accountYesuser's wallet address.

Implementation Reference

  • Registration of the SWAP tool, specifying name, description, input parameters schema, and the execute handler function.
    swap: { name: "SWAP", description: "Building swap transaction", parameters: getSwapParamsSchema, execute: swapExecute.swap },
  • The main handler function for the SWAP tool, which orchestrates chain info, gas price, and calls SwapService.swap to build the swap transaction.
    export const swap = async (args: z.infer<typeof getSwapParamsSchema>) => { try { const inputChain = args.chain.toLowerCase(); const chainObject = getChainFromName(inputChain); console.error(`[SWAP] Using chain: ${chainObject.name}`, args); const chainService = new ChainService(); const gasRes: any = await chainService.gasPrice(chainObject.id); const gasPrice = gasRes.data.fast; const swapService = new SwapService(); const swap: any = await swapService.swap( args.inTokenAddress, args.outTokenAddress, chainObject.id, args.amount, args.slippage ? Number(args.slippage) * 100 : 100, gasPrice, ); if (swap instanceof Error) { return `Error fetching swap: ${swap.message}`; } // return JSON.stringify(swap); return JSON.stringify(swap, null, 2); } catch (error: unknown) { const message = error instanceof Error ? error.message : "An unknown error occurred while fetching swap."; console.error(`[SWAP] Error: ${message}`); throw new Error(`Failed to fetch swap: ${message}`); } }
  • Zod schema for input parameters validation of the SWAP tool.
    export const getSwapParamsSchema = z.object({ chain: z .string() .optional() .describe( "The blockchain network to execute the transaction on. uses fraxtal as default", ) .default("fraxtal"), inTokenAddress: z .string() .refine(isAddress, { message: "Invalid inToken address" }) .describe("The token to swap from (address)."), outTokenAddress: z .string() .refine(isAddress, { message: "Invalid outToken address" }) .describe("The token to swap to (address)."), amount: z .string() .regex(/^\d+$/, { message: "Amount must be a string in wei (no decimals)" }) .describe("Token amount with decimals. For example, if 1 USDT is input, use 1000000 (1 USDT * 10^6). "), slippage: z .string() .optional() .describe("Define the acceptable slippage level by inputting a percentage value within the range of 0.05 to 50. 1% slippage set as 1.") .default('1'), account: z .string() .refine(isAddress, { message: "Invalid account address" }) .describe("user's wallet address.") });
  • Core helper function in SwapService that fetches the swap transaction details from the DEX API.
    async swap( inTokenAddress: string, outTokenAddress: string, chainId: number, amount: string, slippage: number, gasPrice: string ) { try { const response = await fetch(`${DEX_API_URL}/v2/${chainId}/swap?inTokenAddress=${inTokenAddress}&outTokenAddress=${outTokenAddress}&amount=${amount}&gasPrice=${gasPrice}&slippage=${slippage}&referrer=0xC5d4de874CfE6aac6BC9CAD5Cb6b2B35bd7b8392&flags=4`, { method: "GET", headers: { "Content-Type": "application/json", } }); const swapData: any = await response.json(); if (!response.ok) { const errorData = swapData as ErrorResponse; throw new Error( `Failed to fetch swap: ${errorData.detail} (Trace ID: ${errorData.traceId}, Error Code: ${errorData.errorCode})`, ); } const { inToken, outToken, inAmount, outAmount, estimatedGas, minOutAmount, from, to, value, data, blockNumber, price_impact } = swapData; return { inToken, outToken, inAmount, outAmount, estimatedGas, minOutAmount, from, to, value, data, gasPrice, blockNumber, price_impact, chainId } as SwapResponse; } catch (error) { console.error("Error fetching swap:", error); throw new Error( `Fatally Failed to fetch swap: ${(error as Error).message} with code ${ (error as { code?: string }).code || "unknown" }`, ); } } }

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/openocean-finance/openocean-mcp'

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