fetch_token_balance
Retrieve token balance from EVM chains using token address, chain ID, and wallet address for accurate on-chain insights.
Instructions
Get the balance of a token
Input Schema
TableJSON Schema
| Name | Required | Description | Default |
|---|---|---|---|
| chainId | Yes | ||
| tokenAddress | Yes | ||
| walletAddress | Yes |
Implementation Reference
- src/tools/FetchTokenBalance.ts:13-34 (handler)The main handler function that executes the tool logic: fetches ERC20 token balance for a wallet on a given chain using viem, returns raw and formatted balance.export const fetchTokenBalance = async (options: FetchTokenBalanceOptions) => { const { tokenAddress, chainId, walletAddress } = options; const chain = getChainById(chainId); const client = createClient(chain); const contract = getContract({ address: tokenAddress as `0x${string}`, abi: erc20Abi, client, }); const [balance, decimals] = await Promise.all([ contract.read.balanceOf([walletAddress as `0x${string}`]), contract.read.decimals(), ]); return { balance: balance.toString(), formattedBalance: formatUnits(balance, decimals), }; };
- src/tools/FetchTokenBalance.ts:6-10 (schema)Zod schema defining the input parameters: tokenAddress, chainId, walletAddress.export const FetchTokenBalanceSchema = z.object({ tokenAddress: z.string().startsWith("0x"), chainId: z.number(), walletAddress: z.string().startsWith("0x"), });
- src/index.ts:45-49 (registration)Tool registration in the ListTools response: specifies name, description, and input schema.{ name: "fetch_token_balance", description: "Get the balance of a token", inputSchema: z.toJSONSchema(FetchTokenBalanceSchema), },
- src/index.ts:122-140 (registration)Dispatch handler in CallToolRequestSchema: parses args with schema and calls the fetchTokenBalance handler.case "fetch_token_balance": { const args = FetchTokenBalanceSchema.parse(request.params.arguments); const result = await fetchTokenBalance(args); return { content: [ { type: "text", text: result.balance, description: "The balance of the token", }, { type: "text", text: result.formattedBalance, description: "The formatted balance of the token", }, ], }; }