getBalance.tsā¢3.1 kB
import { Tool } from "@modelcontextprotocol/sdk/types.js";
import { getAptosClient } from "../../config.js";
import { formatAPT, formatAddress } from "../../utils/format.js";
export const GET_APT_BALANCE: Tool = {
name: "get_apt_balance",
description: "Get the native APT token balance of an Aptos account. This is used for checking the current balance of APT tokens in an account. Returns the account balance in both Octas and APT.",
inputSchema: {
type: "object",
properties: {
account_address: {
type: "string",
description: "Aptos account address, e.g., 0x1 or 0x742d35Cc6634C0532925a3b8D6Ac0C4db9c8b3",
},
},
required: ["account_address"],
},
};
/**
* Gets the native APT token balance of an Aptos account
* @param args The arguments containing the account address
* @returns The APT balance information
*/
export async function getAptBalanceHandler(args: Record<string, any> | undefined) {
if (!isGetAptBalanceArgs(args)) {
throw new Error("Invalid arguments for get_apt_balance");
}
const { account_address } = args;
try {
const results = await performGetAptBalance(account_address);
return {
content: [{ type: "text", text: results }],
isError: false,
};
} catch (error) {
return {
content: [
{
type: "text",
text: `Error getting APT balance: ${error instanceof Error ? error.message : String(error)}`,
},
],
isError: true,
};
}
}
/**
* Gets the native APT token balance of an Aptos account
* @param accountAddress The Aptos account address
* @returns The APT balance information as a formatted string
*/
export async function performGetAptBalance(accountAddress: string): Promise<string> {
try {
const aptos = getAptosClient();
// Get account APT balance
const balance = await aptos.getAccountAPTAmount({ accountAddress });
return `APT Balance Information:
Account: ${formatAddress(accountAddress)}
Balance: ${balance} Octas
Balance: ${formatAPT(balance)} APT
Full Account Address: ${accountAddress}`;
} catch (error) {
console.error('Error getting APT balance:', error);
// Check if account doesn't exist
if (error instanceof Error && error.message.includes('not found')) {
return `APT Balance Information:
Account: ${formatAddress(accountAddress)}
Balance: 0 Octas (0 APT)
Status: Account does not exist or has not been initialized
Note: Account needs to receive at least one transaction to be initialized on-chain`;
}
throw new Error(`Failed to get APT balance: ${error instanceof Error ? error.message : String(error)}`);
}
}
/**
* Checks if the provided arguments are valid for the getAptBalance tool
* @param args The arguments to check
* @returns True if the arguments are valid, false otherwise
*/
export function isGetAptBalanceArgs(args: unknown): args is { account_address: string } {
return (
typeof args === "object" &&
args !== null &&
"account_address" in args &&
typeof (args as any).account_address === "string"
);
}