Skip to main content
Glama

read.wallet.balances

Read-onlyIdempotent

Check native ETH and ERC20 token balances for a wallet address using multicall. Returns raw and formatted balances to verify sufficient tokens before deposit or adding liquidity.

Instructions

Get native ETH and ERC20 token balances for a wallet address. Reads directly from chain via RPC multicall. Use before write.account.add_liquidity or write.account.deposit to verify the wallet has sufficient tokens. Returns both raw balance (smallest unit/wei) and formatted (human-readable) per token.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
wallet_addressYesWallet address to check balances for
token_addressesYesERC20 token contract addresses to check
chain_idNoChain ID: 8453 (Base), 130 (Unichain), or 10 (Optimism)

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault
nativeYes
tokensYes

Implementation Reference

  • The main handler function for the 'read.wallet.balances' tool. It validates inputs, builds multicall contracts for each ERC20 token (balanceOf, decimals, symbol), fetches native ETH balance in parallel, and returns formatted token balances along with native ETH balance. Returns JSON content with structured output.
    async ({ wallet_address, token_addresses, chain_id }) => {
      try {
        const validChainId = validateChainId(chain_id);
        const wallet = validateAddress(wallet_address, "wallet_address");
        const client = getPublicClient(validChainId, chains);
    
        // Build multicall: for each token get balanceOf, decimals, symbol
        const calls = token_addresses.flatMap((addr) => [
          {
            address: addr as `0x${string}`,
            abi: erc20Abi,
            functionName: "balanceOf" as const,
            args: [wallet],
          },
          { address: addr as `0x${string}`, abi: erc20Abi, functionName: "decimals" as const },
          { address: addr as `0x${string}`, abi: erc20Abi, functionName: "symbol" as const },
        ]);
    
        const [nativeBalance, ...multicallResults] = await Promise.all([
          client.getBalance({ address: wallet }),
          ...(calls.length > 0 ? [client.multicall({ contracts: calls, allowFailure: true })] : []),
        ]);
    
        const results = (multicallResults[0] ?? []) as { status: string; result?: unknown }[];
        const tokens = token_addresses.map((addr, i) => {
          const balRes = results[i * 3];
          const decRes = results[i * 3 + 1];
          const symRes = results[i * 3 + 2];
    
          const balance = balRes?.status === "success" ? String(balRes.result) : "0";
          const decimals = decRes?.status === "success" ? Number(decRes.result) : 18;
          const symbol = symRes?.status === "success" ? String(symRes.result) : "???";
    
          return {
            address: addr,
            symbol,
            decimals,
            balance,
            formatted: formatUnits(BigInt(balance), decimals),
          };
        });
    
        const result = {
          native: {
            symbol: "ETH",
            balance: String(nativeBalance),
            formatted: formatUnits(nativeBalance, 18),
          },
          tokens,
        };
    
        return {
          content: [{ type: "text" as const, text: JSON.stringify(result, null, 2) }],
          structuredContent: result,
        };
      } catch (err) {
        return {
          content: [
            {
              type: "text" as const,
              text: `Error: ${err instanceof Error ? err.message : String(err)}`,
            },
          ],
          isError: true,
        };
      }
    },
  • The 'registerWalletTools' function registers the 'read.wallet.balances' tool on the MCP server via server.registerTool(), along with its metadata (annotations, description, input/output schemas).
    export function registerWalletTools(
      server: McpServer,
      chains: Record<ChainId, ChainConfig>,
      api: ArcadiaApiClient,
    ) {
      server.registerTool(
        "read.wallet.balances",
        {
          annotations: {
            title: "Get Wallet Balances",
            readOnlyHint: true,
            destructiveHint: false,
            idempotentHint: true,
            openWorldHint: true,
          },
          description:
            "Get native ETH and ERC20 token balances for a wallet address. Reads directly from chain via RPC multicall. Use before write.account.add_liquidity or write.account.deposit to verify the wallet has sufficient tokens. Returns both raw balance (smallest unit/wei) and formatted (human-readable) per token.",
          inputSchema: {
            wallet_address: z.string().describe("Wallet address to check balances for"),
            token_addresses: z.array(z.string()).describe("ERC20 token contract addresses to check"),
            chain_id: z.number().default(8453).describe(CHAIN_ID_DESCRIPTION),
          },
          outputSchema: WalletBalancesOutput,
        },
        async ({ wallet_address, token_addresses, chain_id }) => {
          try {
            const validChainId = validateChainId(chain_id);
            const wallet = validateAddress(wallet_address, "wallet_address");
            const client = getPublicClient(validChainId, chains);
    
            // Build multicall: for each token get balanceOf, decimals, symbol
            const calls = token_addresses.flatMap((addr) => [
              {
                address: addr as `0x${string}`,
                abi: erc20Abi,
                functionName: "balanceOf" as const,
                args: [wallet],
              },
              { address: addr as `0x${string}`, abi: erc20Abi, functionName: "decimals" as const },
              { address: addr as `0x${string}`, abi: erc20Abi, functionName: "symbol" as const },
            ]);
    
            const [nativeBalance, ...multicallResults] = await Promise.all([
              client.getBalance({ address: wallet }),
              ...(calls.length > 0 ? [client.multicall({ contracts: calls, allowFailure: true })] : []),
            ]);
    
            const results = (multicallResults[0] ?? []) as { status: string; result?: unknown }[];
            const tokens = token_addresses.map((addr, i) => {
              const balRes = results[i * 3];
              const decRes = results[i * 3 + 1];
              const symRes = results[i * 3 + 2];
    
              const balance = balRes?.status === "success" ? String(balRes.result) : "0";
              const decimals = decRes?.status === "success" ? Number(decRes.result) : 18;
              const symbol = symRes?.status === "success" ? String(symRes.result) : "???";
    
              return {
                address: addr,
                symbol,
                decimals,
                balance,
                formatted: formatUnits(BigInt(balance), decimals),
              };
            });
    
            const result = {
              native: {
                symbol: "ETH",
                balance: String(nativeBalance),
                formatted: formatUnits(nativeBalance, 18),
              },
              tokens,
            };
    
            return {
              content: [{ type: "text" as const, text: JSON.stringify(result, null, 2) }],
              structuredContent: result,
            };
          } catch (err) {
            return {
              content: [
                {
                  type: "text" as const,
                  text: `Error: ${err instanceof Error ? err.message : String(err)}`,
                },
              ],
              isError: true,
            };
          }
        },
      );
  • The WalletBalancesOutput Zod schema defining the output shape: a 'native' object (symbol, balance, formatted) and a 'tokens' array (address, symbol, decimals, balance, formatted).
    export const WalletBalancesOutput = z.object({
      native: z.object({
        symbol: z.string(),
        balance: z.string(),
        formatted: z.string(),
      }),
      tokens: z.array(
        z.object({
          address: z.string(),
          symbol: z.string(),
          decimals: z.number(),
          balance: z.string(),
          formatted: z.string(),
        }),
      ),
    });
  • The 'registerAllTools' function calls 'registerWalletTools(server, chains, api)' on line 46 to wire up all wallet tools including 'read.wallet.balances'.
    export function registerAllTools(
      server: McpServer,
      api: ArcadiaApiClient,
      chains: Record<ChainId, ChainConfig>,
    ) {
      // Read tools
      registerAccountTools(server, api, chains);
      registerPoolTools(server, api);
      registerAssetTools(server, api);
      registerStrategyTools(server, api);
      registerPointsTools(server, api);
      registerGuideTools(server);
      registerWalletTools(server, chains, api);
      registerAssetManagerTools(server);
    
      // Write tools — account
      registerCreateTool(server, chains);
      registerDepositTool(server, chains);
      registerWithdrawTool(server, chains);
      registerBorrowTool(server, chains, api);
      registerRepayTool(server, chains);
      registerAddLiquidityTool(server, api, chains);
      registerRemoveLiquidityTool(server, api);
      registerSwapTool(server, api);
      registerDeleverageTool(server, api);
      registerStakeTool(server, api);
      registerCloseTool(server, api, chains);
    
      // Write tools — wallet
      registerApproveTool(server, chains);
    
      // Write tools — pool (lending tranches, ERC-4626)
      registerPoolDepositTool(server, chains);
      registerPoolRedeemTool(server, chains);
    
      // Write tools — asset managers
      registerRebalancerTool(server, chains);
      registerCompounderTools(server, chains);
      registerYieldClaimerTools(server, chains);
      registerCowSwapperTool(server, chains);
      registerMerklOperatorTool(server, chains);
      registerSetAssetManagersTool(server, chains);
    
      // Dev tools
      registerSendTool(server, chains);
    }
  • The getPublicClient helper used by the handler to create/retrieve a viem public client for the given chain, which executes RPC calls (getBalance, multicall).
    export function getPublicClient(chainId: ChainId, chainConfigs: Record<ChainId, ChainConfig>) {
      let client = clients.get(chainId);
      if (!client) {
        const config = chainConfigs[chainId];
        client = createPublicClient({
          chain: viemChains[chainId],
          transport: http(config.rpcUrl),
        });
        clients.set(chainId, client);
      }
      return client;
    }
Behavior4/5

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

Annotations already indicate read-only, non-destructive, idempotent, and open-world behavior. The description adds value by explaining the on-chain RPC multicall method and the dual return format (raw and human-readable), which are not captured by annotations.

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 two sentences long, front-loaded with the main action, and every sentence provides essential information without redundancy.

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

Completeness4/5

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

Given the presence of an output schema (not shown but indicated), the description sufficiently explains the return values. It could include more detail on edge cases or errors, but overall it is adequate for the tool's complexity.

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?

The input schema has 100% description coverage for all three parameters, so the description adds minimal extra semantics. It does mention the return format but does not elaborate on parameter constraints beyond the schema.

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 it retrieves native ETH and ERC20 token balances for a wallet, with a specific method (RPC multicall). This distinguishes it from sibling tools like read.wallet.accounts or read.wallet.allowances.

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

Usage Guidelines4/5

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

The description explicitly recommends using this tool before write.account.add_liquidity or write.account.deposit to verify sufficient tokens. This provides clear context, though it does not include explicit when-not-to-use scenarios.

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/arcadia-finance/mcp-server'

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