fetch_token_balance
Retrieve token balances for specific wallets on EVM chains by providing token address, chain ID, and wallet address.
Instructions
Get the balance of a token
Input Schema
TableJSON Schema
| Name | Required | Description | Default |
|---|---|---|---|
| tokenAddress | Yes | ||
| chainId | Yes | ||
| walletAddress | Yes |
Implementation Reference
- src/tools/FetchTokenBalance.ts:13-34 (handler)The main asynchronous handler function that fetches the ERC20 token balance for a given wallet on a specific chain using viem library.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, and walletAddress with validation.export const FetchTokenBalanceSchema = z.object({ tokenAddress: z.string().startsWith("0x"), chainId: z.number(), walletAddress: z.string().startsWith("0x"), });
- src/index.ts:46-49 (registration)Registration of the tool in the ListToolsRequestSchema handler, specifying 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 the CallToolRequestSchema switch statement that parses arguments, calls fetchTokenBalance, and formats the response.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", }, ], }; }