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');
        }
      });
Behavior2/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

No annotations are provided, so the description carries the full burden. It mentions the return format (balance amount and token symbol) but fails to disclose critical behavioral traits such as whether this is a read-only operation, potential rate limits, authentication needs, or error conditions. The description is insufficient for a tool with multiple parameters and no annotation coverage.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is a single, well-structured sentence that efficiently conveys the tool's purpose and return value without unnecessary details. It is front-loaded and wastes no words, making it highly concise and effective.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness3/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given the tool's complexity (5 parameters, no output schema, no annotations), the description is minimally adequate. It covers the basic purpose and return format but lacks details on behavioral transparency, usage guidelines, and error handling. It meets the minimum viable threshold but has clear gaps in context.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema description coverage is 100%, so the schema already documents all parameters thoroughly. The description does not add any meaningful semantic details beyond what the schema provides, such as explaining parameter interactions or usage examples. Baseline 3 is appropriate when the schema does the heavy lifting.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the specific action ('Get the ERC20 token balance') and resource ('for a specific address'), and distinguishes it from siblings like 'erc20_balanceOf' by specifying it returns the balance amount along with the token symbol for easy reading, making the purpose explicit and differentiated.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines2/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description provides no guidance on when to use this tool versus alternatives like 'erc20_balanceOf' or 'getWalletBalance', nor does it mention prerequisites or exclusions. It lacks explicit usage context, relying solely on the tool's name and description for inference.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Install Server

Other Tools

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