Skip to main content
Glama

getERC20Balance

Retrieve ERC20 token balances for any Ethereum address by specifying the token contract and wallet address. Returns balance amount with token symbol for clear identification.

Instructions

Get the ERC20 token balance for a specific address. Returns the balance amount along with the token symbol for easy reading.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
contractAddressYesThe address of the ERC20 token contract
tokenAddressNoDEPRECATED: Use contractAddress instead. The address of the ERC20 token contract
ownerAddressYesThe Ethereum address whose balance to check
providerNoOptional. Either a network name or custom RPC URL. Use getAllNetworks to see available networks and their details, or getNetwork to get info about a specific network. You can use any network name returned by these tools as a provider value.
chainIdNoOptional. The chain ID to use. If provided with a named network and they don't match, the RPC's chain ID will be used.

Implementation Reference

  • Primary MCP tool handler for getERC20Balance. Validates and maps parameters, retrieves balance via ethersService, fetches token symbol, formats and returns text response.
    async (params) => { // Map deprecated parameters const mapped = mapParameters(params); try { const contractAddr = mapped.contractAddress || params.tokenAddress; if (!contractAddr) { throw new Error('Either contractAddress or tokenAddress must be provided'); } const balance = await ethersService.getERC20Balance( mapped.ownerAddress, contractAddr, mapped.provider, mapped.chainId ); // Get token info to format the response const tokenInfo = await ethersService.getERC20TokenInfo( contractAddr, mapped.provider, mapped.chainId ); return { content: [{ type: "text", text: `${mapped.ownerAddress} has a balance of ${balance} ${tokenInfo.symbol}` }] }; } catch (error) { return { isError: true, content: [{ type: "text", text: `Error getting token balance: ${error instanceof Error ? error.message : String(error)}` }] }; }
  • MCP server tool registration for getERC20Balance, defining name, description, input schema, and handler reference. Called from tools index.
    server.tool( "getERC20Balance", "Get the ERC20 token balance for a specific address. Returns the balance amount along with the token symbol for easy reading.", { contractAddress: contractAddressSchema, tokenAddress: tokenAddressSchema.optional(), // Deprecated ownerAddress: z.string().describe( "The Ethereum address whose balance to check" ), provider: providerSchema, chainId: chainIdSchema }, async (params) => { // Map deprecated parameters const mapped = mapParameters(params); try { const contractAddr = mapped.contractAddress || params.tokenAddress; if (!contractAddr) { throw new Error('Either contractAddress or tokenAddress must be provided'); } const balance = await ethersService.getERC20Balance( mapped.ownerAddress, contractAddr, mapped.provider, mapped.chainId ); // Get token info to format the response const tokenInfo = await ethersService.getERC20TokenInfo( contractAddr, mapped.provider, mapped.chainId ); return { content: [{ type: "text", text: `${mapped.ownerAddress} has a balance of ${balance} ${tokenInfo.symbol}` }] }; } catch (error) { return { isError: true, content: [{ type: "text", text: `Error getting token balance: ${error instanceof Error ? error.message : String(error)}` }] }; } }
  • Standalone JSON schema definition for getERC20Balance tool inputs, matching the registered schema (with tokenAddress instead of contractAddress).
    { name: "getERC20Balance", description: "Get the ERC20 token balance of a wallet", inputSchema: { type: "object", properties: { tokenAddress: { type: "string", description: "The address of the ERC20 token contract" }, ownerAddress: { type: "string", description: "The Ethereum address whose balance to check" }, provider: { type: "string", description: "Optional. Either a network name or custom RPC URL. Use getSupportedNetworks to get a list of supported networks." }, chainId: { type: "number", description: "Optional. The chain ID to use. If provided with a named network and they don't match, the RPC's chain ID will be used." } }, required: ["tokenAddress", "ownerAddress"] }
  • Alternative handler implementation in dedicated handlers module, using Zod validation with friendly errors and common schemas.
    getERC20Balance: async (args: unknown) => { const schema = z.object({ contractAddress: contractAddressSchema.optional(), tokenAddress: tokenAddressSchema, // Deprecated ownerAddress: CommonSchemas.ethereumAddress.describe('Address to check balance for'), provider: providerSchema, chainId: chainIdSchema }); try { // First validate with friendly errors const validatedParams = validateWithFriendlyErrors( schema, args, 'Get ERC20 Balance' ); // Then map deprecated parameters for backward compatibility const mapped = mapParameters(validatedParams); // Ensure we have a contract address (from either new or old parameter name) const contractAddr = mapped.contractAddress || validatedParams.tokenAddress; if (!contractAddr) { throw new Error('Contract address is required. Please provide either contractAddress or tokenAddress.'); } const balance = await ethersService.getERC20Balance(validatedParams.ownerAddress, contractAddr, mapped.provider, mapped.chainId); // Get token info to format the response const tokenInfo = await ethersService.getERC20TokenInfo(contractAddr, mapped.provider, mapped.chainId); return { content: [{ type: "text", text: `${validatedParams.ownerAddress} has a balance of ${balance} ${tokenInfo.symbol}` }] }; } catch (error) { return createErrorResponse(error, 'getting token balance'); }
  • Core ERC20 balance retrieval helper function (getBalance) with comprehensive features: caching (30s TTL), rate limiting, ethers Contract balanceOf call, decimals-based formatting, detailed error handling and logging. Called internally by EthersService.getERC20Balance.
    export async function getBalance( ethersService: EthersService, tokenAddress: string, ownerAddress: string, provider?: string, chainId?: number ): Promise<string> { metrics.incrementCounter('erc20.getBalance'); return timeAsync('erc20.getBalance', async () => { try { // Check rate limiting const identity = `${tokenAddress}:${ownerAddress}`; if (!rateLimiter.consume('token', identity)) { throw new ERC20Error('Rate limit exceeded for token operations'); } // Create cache key const cacheKey = createTokenCacheKey( CACHE_KEYS.ERC20_BALANCE, tokenAddress, ownerAddress, chainId ); // Check cache first const cachedBalance = balanceCache.get(cacheKey); if (cachedBalance) { return cachedBalance; } // Get provider from ethers service const ethersProvider = ethersService['getProvider'](provider, chainId); // Create contract instance const contract = new ethers.Contract(tokenAddress, ERC20_ABI, ethersProvider); // Get raw balance let balance; try { balance = await contract.balanceOf(ownerAddress); } catch (error: any) { // Check for empty response (0x) which often indicates a non-ERC20 contract if (error.code === 'BAD_DATA' && error.value === '0x') { logger.debug('Contract returned empty data for balanceOf call', { tokenAddress, errorCode: error.code, errorValue: error.value, errorMessage: error.message }); throw new ERC20Error( `Contract at ${tokenAddress} does not appear to be a valid ERC20 token. It returned empty data for the balanceOf call. Error code: ${error.code}` ); } // Log other errors with full context logger.debug('Error calling balanceOf on contract', { tokenAddress, ownerAddress, errorCode: error.code, errorMessage: error.message, errorValue: error.value }); // Re-throw the original error throw error; } // Get token decimals for formatting const tokenInfo = await getTokenInfo(ethersService, tokenAddress, provider, chainId); // Format the balance based on decimals const formattedBalance = ethers.formatUnits(balance, tokenInfo.decimals); // Cache result for future use (30 second TTL) balanceCache.set(cacheKey, formattedBalance, { ttl: 30000 }); return formattedBalance; } catch (error) { logger.debug('Error getting ERC20 balance', { tokenAddress, ownerAddress, error }); throw handleTokenError(error, 'Failed to get token balance'); } });

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/crazyrabbitLTC/mcp-ethers-server'

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