buy-token
Purchase Pump.fun meme tokens on Solana by specifying the token address and SOL amount. Execute transactions with configurable slippage tolerance and account selection.
Instructions
Buy a Pump.fun token
Input Schema
TableJSON Schema
| Name | Required | Description | Default |
|---|---|---|---|
| tokenAddress | Yes | The token's mint address | |
| buyAmount | Yes | Amount to buy in SOL | |
| accountName | No | Name of the account to use | default |
| slippageBasisPoints | No | Slippage tolerance in basis points (1% = 100) |
Implementation Reference
- src/buy-token.ts:15-128 (handler)Core handler function that performs the token buy operation using PumpFunSDK, handles account management, balance checks, and transaction execution.export async function buyToken( tokenAddress: string, buyAmount: number, accountName: string = "default", slippageBasisPoints: number = 100 ) { try { const { sdk, connection } = initializeSDK(); const keysFolder = path.resolve(rootDir, ".keys"); if (!fs.existsSync(keysFolder)) { try { fs.mkdirSync(keysFolder, { recursive: true }); } catch (mkdirError: any) { console.error(`Error creating keys folder:`, mkdirError); return { success: false, error: `Error creating keys folder: ${ mkdirError.message || JSON.stringify(mkdirError) }`, }; } } const account = getOrCreateKeypair(keysFolder, accountName); console.log(`Using account: ${account.publicKey.toString()}`); const balance = await connection.getBalance(account.publicKey); console.log(`Account balance: ${balance / LAMPORTS_PER_SOL} SOL`); const requiredBalance = buyAmount * LAMPORTS_PER_SOL + 0.001 * LAMPORTS_PER_SOL; console.log(`Required balance: ${requiredBalance / LAMPORTS_PER_SOL} SOL`); if (balance < requiredBalance) { const errorMessage = `Insufficient SOL balance. Account ${account.publicKey.toString()} has ${ balance / LAMPORTS_PER_SOL } SOL, but needs at least ${ requiredBalance / LAMPORTS_PER_SOL } SOL. Please send SOL to this address and try again.`; console.error(errorMessage); return { success: false, error: errorMessage }; } const mintPublicKey = new PublicKey(tokenAddress); console.log(`Token address: ${tokenAddress}`); const initialTokenBalance = (await getSPLBalance(connection, mintPublicKey, account.publicKey)) || 0; console.log(`Initial token balance: ${initialTokenBalance}`); console.log(`Buying ${buyAmount} SOL worth of tokens...`); const result = await sdk.buy( account, mintPublicKey, BigInt(buyAmount * LAMPORTS_PER_SOL), BigInt(slippageBasisPoints), DEFAULT_PRIORITY_FEES ); if (!result.success) { console.error(`Failed to buy token:`, result.error); return { success: false, error: result.error ? typeof result.error === "object" ? JSON.stringify(result.error) : result.error : "Unknown error", }; } console.log(`Transaction successful: ${result.signature}`); const newTokenBalance = (await getSPLBalance(connection, mintPublicKey, account.publicKey)) || 0; console.log(`New token balance: ${newTokenBalance}`); const tokensPurchased = newTokenBalance - initialTokenBalance; console.log(`Tokens purchased: ${tokensPurchased}`); return { success: true, tokenAddress, amountSpent: buyAmount, tokensPurchased, newBalance: newTokenBalance, signature: result.signature, pumpfunUrl: `https://pump.fun/${tokenAddress}`, }; } catch (error: any) { console.error("Error buying token:", error); console.error("Error stack:", error.stack); let errorMessage = "Unknown error"; if (error) { if (typeof error === "object") { if (error.message) { errorMessage = error.message; } else { try { errorMessage = JSON.stringify(error); } catch (e) { errorMessage = "Error object could not be stringified"; } } } else { errorMessage = String(error); } } return { success: false, error: errorMessage }; } }
- src/index.ts:155-166 (schema)Zod schema defining input parameters for the buy-token tool.{ tokenAddress: z.string().describe("The token's mint address"), buyAmount: z.number().min(0.0001).describe("Amount to buy in SOL"), accountName: z .string() .default("default") .describe("Name of the account to use"), slippageBasisPoints: z .number() .default(100) .describe("Slippage tolerance in basis points (1% = 100)"), },
- src/index.ts:152-193 (registration)MCP tool registration for 'buy-token', including description, input schema, and wrapper handler that delegates to buyToken function.server.tool( "buy-token", "Buy a Pump.fun token", { tokenAddress: z.string().describe("The token's mint address"), buyAmount: z.number().min(0.0001).describe("Amount to buy in SOL"), accountName: z .string() .default("default") .describe("Name of the account to use"), slippageBasisPoints: z .number() .default(100) .describe("Slippage tolerance in basis points (1% = 100)"), }, async ({ tokenAddress, buyAmount, accountName, slippageBasisPoints }) => { try { console.error(`Buying token: ${tokenAddress}, amount: ${buyAmount} SOL`); const result = await buyToken( tokenAddress, buyAmount, accountName, slippageBasisPoints ); const formattedResult = formatBuyResult(result); return createMcpResponse(formattedResult); } catch (error: any) { console.error("Error buying token:", error); return { content: [ { type: "text" as const, text: `Error buying token: ${error?.message || "Unknown error"}`, }, ], }; } } );
- src/buy-token.ts:130-146 (helper)Helper function to format the result of a buyToken operation into a human-readable string.export function formatBuyResult( result: ReturnType<typeof buyToken> extends Promise<infer T> ? T : never ) { if (!result.success) { return `Error buying token: ${result.error}`; } return [ `Successfully bought token!`, `Token Address: ${result.tokenAddress}`, `Amount Spent: ${result.amountSpent} SOL`, `Tokens Purchased: ${result.tokensPurchased}`, `New Balance: ${result.newBalance}`, `Transaction Signature: ${result.signature}`, `Pump.fun URL: ${result.pumpfunUrl}`, ].join("\n"); }