Skip to main content
Glama

getBalance

Retrieve native and ERC-20 token balances for any wallet address across multiple EVM chains, with USD value conversion included.

Instructions

지갑 주소의 네이티브 토큰 + ERC-20 토큰 잔고를 조회합니다 (USD 환산 포함)

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
addressYes조회할 지갑 주소 (0x...)
chainNoEVM 체인ethereum
tokensNo조회할 토큰 심볼 목록 (기본: USDC, USDT, DAI, WETH)

Implementation Reference

  • The handler function retrieves the balance of native and ERC-20 tokens for a given address.
    async function handler(args: z.infer<typeof inputSchema>): Promise<ToolResult<BalanceData>> {
      const { address, chain, tokens } = args;
    
      if (!isAddress(address)) {
        return makeError(`Invalid address: ${address}`, "INVALID_INPUT");
      }
    
      const cacheKey = `balance:${chain}:${address}`;
      const cached = cache.get<BalanceData>(cacheKey);
      if (cached.hit) return makeSuccess(chain, cached.data, true);
    
      try {
        const client = getClient(chain);
        const chainConfig = chains[chain];
    
        // 네이티브 잔고 조회
        const nativeBalanceWei = await client.getBalance({ address: address as Address });
        const nativeFormatted = formatUnits(nativeBalanceWei, 18);
    
        // 네이티브 토큰 USD 가격
        let nativeValueUsd = 0;
        try {
          const nativeId = chainConfig?.nativeCurrency?.coingeckoId;
          if (nativeId) {
            const price = await getPrice(nativeId);
            nativeValueUsd = parseFloat(nativeFormatted) * price.priceUsd;
          }
        } catch {
          // 가격 조회 실패 무시
        }
    
        // ERC-20 토큰 잔고 조회
        const tokenSymbols = tokens ?? DEFAULT_TOKENS;
        const tokenBalances: TokenBalance[] = [];
    
        for (const symbol of tokenSymbols) {
          const tokenInfo = tokensData.find(
            (t) => t.symbol.toLowerCase() === symbol.toLowerCase(),
          );
          if (!tokenInfo) continue;
    
          const tokenAddress = tokenInfo.addresses[chain];
          if (!tokenAddress) continue;
    
          try {
            const balance = await client.readContract({
              address: tokenAddress as Address,
              abi: ERC20_ABI,
              functionName: "balanceOf",
              args: [address as Address],
            });
    
            const formatted = formatUnits(balance, tokenInfo.decimals);
    
            let valueUsd = 0;
            try {
              const price = await getPrice(tokenInfo.coingeckoId);
              valueUsd = parseFloat(formatted) * price.priceUsd;
            } catch {
              // 가격 조회 실패 무시
            }
    
            tokenBalances.push({
              symbol: tokenInfo.symbol,
              address: tokenAddress,
              balance: balance.toString(),
              balanceFormatted: formatted,
              decimals: tokenInfo.decimals,
              valueUsd: Math.round(valueUsd * 100) / 100,
            });
          } catch {
            // 개별 토큰 조회 실패는 건너뜀
          }
        }
    
        const totalValueUsd =
          Math.round(
            (nativeValueUsd + tokenBalances.reduce((sum, t) => sum + t.valueUsd, 0)) * 100,
          ) / 100;
    
        const data: BalanceData = {
          address,
          nativeBalance: {
            symbol: chainConfig?.nativeCurrency?.symbol ?? "ETH",
            balance: nativeBalanceWei.toString(),
            balanceFormatted: nativeFormatted,
            valueUsd: Math.round(nativeValueUsd * 100) / 100,
          },
          tokenBalances,
          totalValueUsd,
        };
    
        cache.set(cacheKey, data, BALANCE_CACHE_TTL);
        return makeSuccess(chain, data, false);
      } catch (err) {
        const message = sanitizeError(err);
        return makeError(`Failed to fetch balance: ${message}`, "RPC_ERROR");
      }
    }
  • Input schema validation for the getBalance tool.
    const inputSchema = z.object({
      address: z.string().describe("조회할 지갑 주소 (0x...)"),
      chain: z.enum(SUPPORTED_CHAINS).default("ethereum").describe("EVM 체인"),
      tokens: z.array(z.string()).optional().describe("조회할 토큰 심볼 목록 (기본: USDC, USDT, DAI, WETH)"),
    });
  • Registration of the getBalance tool with the MCP server.
    export function register(server: McpServer) {
      server.tool(
        "getBalance",
        "지갑 주소의 네이티브 토큰 + ERC-20 토큰 잔고를 조회합니다 (USD 환산 포함)",
        inputSchema.shape,
        async (args) => {
          const result = await handler(args as z.infer<typeof inputSchema>);
          return { content: [{ type: "text" as const, text: JSON.stringify(result, null, 2) }] };
        },
      );
    }
Behavior3/5

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

With no annotations provided, the description carries the full burden of behavioral disclosure. It adds valuable context that USD conversion is included in the response, which helps set expectations. However, it omits other critical behavioral details such as whether the tool performs real-time blockchain queries or uses cached data, timeout behavior, or what happens if invalid token symbols are provided.

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

Conciseness4/5

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

The description is a single, efficient sentence that front-loads the core action. However, given the absence of annotations and output schema, it errs on being overly terse rather than appropriately informative for agent decision-making.

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?

With 3 parameters, no annotations, and no output schema, the description provides minimum viable context by mentioning USD conversion. However, it lacks information on return structure, array handling for multiple tokens, error responses, or chain-specific behaviors that would help an agent invoke the tool correctly.

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?

Input schema has 100% description coverage with clear parameter documentation. The description mentions 'native token + ERC-20 token' which loosely maps to the 'tokens' array parameter semantics, but does not add syntax details, examples, or constraints beyond what the schema already provides. Baseline 3 is appropriate given high schema coverage.

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

Purpose4/5

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

The description clearly states the tool queries (조회합니다) native token and ERC-20 token balances with USD conversion. It specifies the resource (wallet address balances) and scope (native + ERC-20). However, it does not explicitly differentiate from sibling 'getPortfolio' which may also return balance-related data.

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?

No usage guidance is provided. There is no indication of when to use this versus 'getPortfolio' or 'getTokenInfo', no prerequisites (e.g., address format validation), and no mention of error conditions or rate limits.

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/calintzy/evmscope'

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