Skip to main content
Glama
EmanuelJr
by EmanuelJr

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
NameRequiredDescriptionDefault
tokenAddressYes
chainIdYes
walletAddressYes

Implementation Reference

  • 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),
      };
    };
  • 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",
          },
        ],
      };
    }

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/EmanuelJr/web3-mcp-server'

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