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"
    				}`,
    			);
    		}
    	}
    }
Behavior2/5

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

With no annotations provided, the description carries the full burden of behavioral disclosure. It states 'building swap transaction,' which implies a write operation (transaction creation), but doesn't clarify if this executes the transaction, requires user approval, involves costs, or has rate limits. This is a significant gap for a financial tool with potential real-world impact.

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 extremely concise ('Building swap transaction')—a single phrase that front-loads the core purpose without unnecessary elaboration. Every word earns its place, making it efficient for quick understanding.

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?

Given the complexity of a financial swap tool with no annotations and no output schema, the description is inadequate. It doesn't cover behavioral aspects (e.g., execution, costs), output expectations, or integration with sibling tools. For a 6-parameter tool that likely involves blockchain transactions, more context is needed to ensure safe and effective use.

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 the schema already documents all parameters thoroughly. The description adds no additional parameter semantics beyond what's in the schema (e.g., it doesn't explain relationships between parameters like inTokenAddress and outTokenAddress). 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 verb ('building') and resource ('swap transaction'), making the purpose understandable. However, it doesn't differentiate from sibling tools like QUOTE (which might provide price quotes) or GET_TRANSACTION (which might retrieve transaction details), leaving room for ambiguity about when to choose this specific tool.

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?

No explicit guidance is provided on when to use this tool versus alternatives like QUOTE or TOKEN_LIST. The description lacks context about prerequisites (e.g., needing token addresses from TOKEN_LIST) or exclusions, leaving the agent to infer usage from the tool name and parameters alone.

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

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