Token Balance Display on Website

Our company is engaged in the development, support and maintenance of sites of any complexity. From simple one-page sites to large-scale cluster systems built on micro services. Experience of developers is confirmed by certificates from vendors.

Development and maintenance of all types of websites:

Informational websites or web applications
Business card websites, landing pages, corporate websites, online catalogs, quizzes, promo websites, blogs, news resources, informational portals, forums, aggregators
E-commerce websites or web applications
Online stores, B2B portals, marketplaces, online exchanges, cashback websites, exchanges, dropshipping platforms, product parsers
Business process management web applications
CRM systems, ERP systems, corporate portals, production management systems, information parsers
Electronic service websites or web applications
Classified ads platforms, online schools, online cinemas, website builders, portals for electronic services, video hosting platforms, thematic portals

These are just some of the technical types of websites we work with, and each of them can have its own specific features and functionality, as well as be customized to meet the specific needs and goals of the client.

Our competencies:

Development stages

Latest works

  • image_website-b2b-advance_0.png
    B2B ADVANCE company website development
    1262
  • image_web-applications_feedme_466_0.webp
    Development of a web application for FEEDME
    1171
  • image_websites_belfingroup_462_0.webp
    Website development for BELFINGROUP
    874
  • image_ecommerce_furnoro_435_0.webp
    Development of an online store for the company FURNORO
    1094
  • image_crm_enviok_479_0.webp
    Development of a web application for Enviok
    831
  • image_bitrix-bitrix-24-1c_fixper_448_0.png
    Website development for FIXPER company
    851

Implementing Token Balance Display on Website

Displaying a token balance — three lines of code. Displaying it correctly — a different story: formatting with decimals, real-time updates, multi-chain context, cache with invalidation. Let's go from simple to complex.

Getting Native Token Balance

import { formatEther } from 'ethers';
import { usePublicClient } from 'wagmi';

async function getNativeBalance(address: string, chainId: number): Promise<string> {
  const client = createPublicClient({
    chain: mainnet,
    transport: http(process.env.ETH_RPC_URL),
  });

  const balance = await client.getBalance({ address: address as `0x${string}` });
  return formatEther(balance); // "1.234567890123456789"
}

getBalance returns bigint in wei. formatEther divides by 10^18. For display, usually need to round to 4–6 significant digits.

ERC-20 Balance with Decimals

Different tokens have different decimals: USDC — 6, most ERC-20 — 18, WBTC — 8. Using formatEther for USDC will give incorrect results.

import { erc20Abi, formatUnits } from 'viem';

async function getTokenBalance(
  tokenAddress: `0x${string}`,
  walletAddress: `0x${string}`,
  client: PublicClient,
): Promise<{ formatted: string; raw: bigint; decimals: number }> {
  const [balance, decimals] = await client.multicall({
    contracts: [
      {
        address: tokenAddress,
        abi: erc20Abi,
        functionName: 'balanceOf',
        args: [walletAddress],
      },
      {
        address: tokenAddress,
        abi: erc20Abi,
        functionName: 'decimals',
      },
    ],
  });

  const raw = balance.result as bigint;
  const dec = decimals.result as number;

  return {
    raw,
    decimals: dec,
    formatted: formatUnits(raw, dec),
  };
}

multicall — one RPC call instead of two. On projects with 10+ tokens, this is critical for performance.

Component with Auto-Update via wagmi

// components/TokenBalance.tsx
import { useBalance, useReadContract } from 'wagmi';
import { erc20Abi, formatUnits } from 'viem';

interface TokenBalanceProps {
  address: `0x${string}`;
  tokenAddress?: `0x${string}`; // if not set — show native token
  symbol?: string;
}

export function TokenBalance({ address, tokenAddress, symbol }: TokenBalanceProps) {
  // Native balance
  const { data: nativeBalance } = useBalance({
    address,
    query: { refetchInterval: 12_000 }, // update every block (~12s on Ethereum)
  });

  // ERC-20 balance
  const { data: tokenBalance } = useReadContract({
    address: tokenAddress,
    abi: erc20Abi,
    functionName: 'balanceOf',
    args: [address],
    query: { enabled: !!tokenAddress, refetchInterval: 12_000 },
  });

  const { data: decimals } = useReadContract({
    address: tokenAddress,
    abi: erc20Abi,
    functionName: 'decimals',
    query: { enabled: !!tokenAddress, staleTime: Infinity }, // decimals don't change
  });

  if (tokenAddress && tokenBalance != null && decimals != null) {
    const formatted = formatUnits(tokenBalance as bigint, decimals as number);
    return <BalanceDisplay value={formatted} symbol={symbol ?? 'TOKEN'} />;
  }

  if (nativeBalance) {
    return <BalanceDisplay value={nativeBalance.formatted} symbol={nativeBalance.symbol} />;
  }

  return <BalanceSkeleton />;
}

Formatting for UI

Raw formatUnits returns a string with 18 decimal places. For display, need logic:

export function formatTokenAmount(
  value: string | bigint,
  decimals: number,
  opts?: { maxDecimals?: number; compact?: boolean },
): string {
  const raw = typeof value === 'bigint' ? formatUnits(value, decimals) : value;
  const num = parseFloat(raw);

  if (num === 0) return '0';

  const maxDec = opts?.maxDecimals ?? 4;

  if (opts?.compact && num >= 1_000_000) {
    return `${(num / 1_000_000).toFixed(2)}M`;
  }
  if (opts?.compact && num >= 1_000) {
    return `${(num / 1_000).toFixed(2)}K`;
  }

  // For very small values — show significant figures
  if (num < 0.0001 && num > 0) {
    return num.toExponential(2);
  }

  return num.toLocaleString('en-US', {
    maximumFractionDigits: maxDec,
    minimumFractionDigits: 0,
  });
}

Displaying Multiple Tokens

When need to show portfolio — balances of 10–20 tokens — important not to make 20 separate RPC requests. multicall3 contract (deployed on most EVM networks) aggregates all requests into one:

import { multicall } from 'viem/actions';

async function getPortfolioBalances(
  tokens: Array<{ address: `0x${string}`; decimals: number; symbol: string }>,
  walletAddress: `0x${string}`,
  client: PublicClient,
) {
  const calls = tokens.map(token => ({
    address: token.address,
    abi: erc20Abi,
    functionName: 'balanceOf' as const,
    args: [walletAddress] as [`0x${string}`],
  }));

  const results = await multicall(client, { contracts: calls });

  return tokens.map((token, i) => ({
    ...token,
    balance: results[i].result as bigint,
    formatted: formatUnits(results[i].result as bigint, token.decimals),
  }));
}

Timeline: one token with real-time updates — half a day. Full portfolio widget with multiple tokens, formatting, skeleton loading, and block updates — 1–2 days.