Skip to main content
Glama

BORROW

Borrow tokens directly from a BAMM position on the Fraxtal blockchain by specifying the BAMM contract address, token details, and desired amount. Simplify borrowing against LP tokens using this tool.

Instructions

Borrow tokens from a BAMM position

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
amountYesThe amount to borrow
bammAddressYesThe address of the BAMM contract
borrowTokenNoThe address of the token to borrow
borrowTokenSymbolNoThe symbol of the token to borrow (e.g., 'IQT')

Implementation Reference

  • The execute function of the BORROW tool handler, which orchestrates wallet setup, service call, and response formatting.
    export const borrowTool: Tool<undefined, typeof borrowToolParams> = {
    	name: "BORROW",
    	description: "Borrow tokens from a BAMM position",
    	parameters: borrowToolParams,
    	execute: async (params) => {
    		try {
    			if (!params.borrowToken && !params.borrowTokenSymbol) {
    				return "Error: Either borrowToken address or borrowTokenSymbol is required";
    			}
    
    			const privateKey = process.env.WALLET_PRIVATE_KEY;
    			if (!privateKey) {
    				return "Error: WALLET_PRIVATE_KEY environment variable is not set. Please set it with your wallet's private key (without 0x prefix).";
    			}
    
    			const walletService = new WalletService(privateKey);
    			const borrowService = new BorrowService(walletService);
    
    			const result = await borrowService.execute({
    				bammAddress: params.bammAddress as Address,
    				borrowToken: params.borrowToken as Address | undefined,
    				borrowTokenSymbol: params.borrowTokenSymbol,
    				amount: params.amount,
    			});
    
    			return dedent`
            ✅ Borrowing Successful
    
            🌐 BAMM Address: ${params.bammAddress}
            💸 Amount: ${formatNumber(Number(params.amount))}
            🪙 Token: ${params.borrowTokenSymbol ?? params.borrowToken}
            🔗 Transaction: ${result.txHash}
    
            Tokens have been borrowed from your BAMM position.
          `;
    		} catch (error) {
    			if (error instanceof Error) {
    				return dedent`
              ❌ Borrowing Failed
    
              Error: ${error.message}
    
              Please verify your inputs and try again.
            `;
    			}
    			return "An unknown error occurred while borrowing tokens";
    		}
    	},
    };
  • Zod schema defining the input parameters for the BORROW tool.
    const borrowToolParams = z.object({
    	bammAddress: z
    		.string()
    		.regex(/^0x[a-fA-F0-9]{40}$/)
    		.describe("The address of the BAMM contract"),
    	amount: z.string().min(1).describe("The amount to borrow"),
    	borrowToken: z
    		.string()
    		.regex(/^0x[a-fA-F0-9]{40}$/)
    		.optional()
    		.describe("The address of the token to borrow"),
    	borrowTokenSymbol: z
    		.string()
    		.optional()
    		.describe("The symbol of the token to borrow (e.g., 'IQT')"),
    });
  • src/index.ts:20-20 (registration)
    Registration of the borrowTool in the MCP server.
    server.addTool(borrowTool);
  • The BorrowService class with the core logic for executing the borrow operation, including token validation, approvals, rent calculation, and BAMM contract interaction.
    export class BorrowService {
    	constructor(private walletService: WalletService) {}
    
    	async execute(params: BorrowParams): Promise<{ txHash: string }> {
    		let { bammAddress, borrowToken, borrowTokenSymbol, amount } = params;
    
    		if (!borrowToken && !borrowTokenSymbol) {
    			throw new Error("Either borrowToken or borrowTokenSymbol is required");
    		}
    		const publicClient = this.walletService.getPublicClient();
    		const walletClient = this.walletService.getWalletClient();
    
    		if (!walletClient || !walletClient.account) {
    			throw new Error("Wallet client is not initialized");
    		}
    
    		const userAddress = walletClient.account.address;
    		const amountInWei = BigInt(Math.floor(Number(amount) * 1e18));
    
    		try {
    			if (borrowTokenSymbol) {
    				borrowToken = await getTokenAddressFromSymbol(borrowTokenSymbol);
    			}
    
    			if (!borrowToken) {
    				throw new Error("Could not resolve borrow token address");
    			}
    
    			const tokenValidation = await validateTokenAgainstBAMM(
    				bammAddress,
    				borrowToken,
    				publicClient,
    			);
    
    			const collateralBalance: bigint = await publicClient.readContract({
    				address: borrowToken,
    				abi: erc20Abi,
    				functionName: "balanceOf",
    				args: [userAddress],
    			});
    			if (collateralBalance < amountInWei) {
    				throw new Error("Insufficient collateral token balance");
    			}
    
    			await checkTokenBalance(
    				borrowToken,
    				userAddress,
    				amountInWei,
    				publicClient,
    			);
    			await ensureTokenApproval(
    				borrowToken,
    				bammAddress,
    				amountInWei,
    				publicClient,
    				walletClient,
    			);
    
    			const rentedMultiplier: bigint = await publicClient.readContract({
    				address: bammAddress,
    				abi: BAMM_ABI,
    				functionName: "rentedMultiplier",
    				args: [],
    			});
    
    			// Calculate rent based on borrowed amount and rentedMultiplier
    			const rent = (amountInWei * rentedMultiplier) / BigInt(1e18);
    
    			const currentTime = Math.floor(Date.now() / 1000);
    			const deadline = BigInt(currentTime + 300);
    
    			const action = {
    				token0Amount: tokenValidation.isToken0 ? -amountInWei : 0n,
    				token1Amount: tokenValidation.isToken1 ? -amountInWei : 0n,
    				rent: rent,
    				to: userAddress,
    				token0AmountMin: 0n,
    				token1AmountMin: 0n,
    				closePosition: false,
    				approveMax: false,
    				v: 0,
    				r: "0x0000000000000000000000000000000000000000000000000000000000000000" as `0x${string}`,
    				s: "0x0000000000000000000000000000000000000000000000000000000000000000" as `0x${string}`,
    				deadline,
    			};
    
    			const { request: executeRequest } = await publicClient.simulateContract({
    				address: bammAddress,
    				abi: BAMM_ABI,
    				functionName: "executeActions",
    				args: [action],
    				account: walletClient.account,
    			});
    			const txHash = await walletClient.writeContract(executeRequest);
    			await publicClient.waitForTransactionReceipt({ hash: txHash });
    
    			return { txHash };
    		} catch (error) {
    			console.error("Error in borrow service", error);
    			throw error;
    		}
    	}
  • src/index.ts:4-4 (registration)
    Import statement for the borrowTool.
    import { borrowTool } from "./tools/borrow.js";
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 the action ('Borrow') but doesn't explain critical traits such as whether this is a read-only or mutative operation, what permissions or conditions are needed (e.g., collateral requirements), potential risks (e.g., interest rates, liquidation), or the expected outcome. This leaves significant gaps for a financial transaction tool.

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 that directly states the tool's purpose without any fluff or redundancy. It's front-loaded with the core action and resource, making it easy to parse and understand quickly.

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 borrowing tool with no annotations and no output schema, the description is incomplete. It lacks information on behavioral traits (e.g., mutative effects, requirements), usage context, and what the tool returns, which are essential for safe and effective agent operation in this domain.

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?

The schema description coverage is 100%, so the schema already documents all parameters (amount, bammAddress, borrowToken, borrowTokenSymbol) with their purposes and formats. The description doesn't add any semantic details beyond what's in the schema, such as explaining relationships between parameters (e.g., that borrowToken and borrowTokenSymbol should match), but this is acceptable given the high schema coverage.

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 ('Borrow') and the resource ('tokens from a BAMM position'), which is specific and understandable. However, it doesn't explicitly differentiate from sibling tools like LEND or REPAY, which would require mentioning that this is for obtaining tokens rather than providing or returning them.

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., having a BAMM position), exclusions, or compare it to siblings like LEND (for providing tokens) or REPAY (for returning borrowed tokens), leaving the agent to infer usage from context 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

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/IQAIcom/mcp-bamm'

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