Catalog
affaan-m/evm-token-decimals

affaan-m

evm-token-decimals

Prevent silent decimal mismatch bugs across EVM chains. Covers runtime decimal lookup, chain-aware caching, bridged-token precision drift, and safe normalization for bots, dashboards, and DeFi tools. Use when handling token amounts across EVM chains, or when a balance, price, or transfer amount is off by orders of magnitude.

NewUpdated Sep 9, 2026

EVM Token Decimals

Silent decimal mismatches are one of the easiest ways to ship balances or USD values that are off by orders of magnitude without throwing an error.

When to Use

  • Reading ERC-20 balances in Python, TypeScript, or Solidity
  • Calculating fiat values from on-chain balances
  • Comparing token amounts across multiple EVM chains
  • Handling bridged assets
  • Building portfolio trackers, bots, or aggregators

How It Works

Never assume stablecoins use the same decimals everywhere. Query decimals() at runtime, cache by (chain_id, token_address), and use decimal-safe math for value calculations.

Examples

Query decimals at runtime

from decimal import Decimal
from web3 import Web3

ERC20_ABI = [
    {"name": "decimals", "type": "function", "inputs": [],
     "outputs": [{"type": "uint8"}], "stateMutability": "view"},
    {"name": "balanceOf", "type": "function",
     "inputs": [{"name": "account", "type": "address"}],
     "outputs": [{"type": "uint256"}], "stateMutability": "view"},
]

def get_token_balance(w3: Web3, token_address: str, wallet: str) -> Decimal:
    contract = w3.eth.contract(
        address=Web3.to_checksum_address(token_address),
        abi=ERC20_ABI,
    )
    decimals = contract.functions.decimals().call()
    raw = contract.functions.balanceOf(Web3.to_checksum_address(wallet)).call()
    return Decimal(raw) / Decimal(10 ** decimals)

Do not hardcode 1_000_000 because a symbol usually has 6 decimals somewhere else.

Cache by chain and token

from functools import lru_cache

@lru_cache(maxsize=512)
def get_decimals(chain_id: int, token_address: str) -> int:
    w3 = get_web3_for_chain(chain_id)
    contract = w3.eth.contract(
        address=Web3.to_checksum_address(token_address),
        abi=ERC20_ABI,
    )
    return contract.functions.decimals().call()

Handle odd tokens defensively

try:
    decimals = contract.functions.decimals().call()
except Exception:
    logging.warning(
        "decimals() reverted on %s (chain %s), defaulting to 18",
        token_address,
        chain_id,
    )
    decimals = 18

Log the fallback and keep it visible. Old or non-standard tokens still exist.

Normalize to 18-decimal WAD in Solidity

interface IERC20Metadata {
    function decimals() external view returns (uint8);
}

function normalizeToWad(address token, uint256 amount) internal view returns (uint256) {
    uint8 d = IERC20Metadata(token).decimals();
    if (d == 18) return amount;
    if (d < 18) return amount * 10 ** (18 - d);
    return amount / 10 ** (d - 18);
}

TypeScript with ethers

import { Contract, formatUnits } from 'ethers';

const ERC20_ABI = [
  'function decimals() view returns (uint8)',
  'function balanceOf(address) view returns (uint256)',
];

async function getBalance(provider: any, tokenAddress: string, wallet: string): Promise<string> {
  const token = new Contract(tokenAddress, ERC20_ABI, provider);
  const [decimals, raw] = await Promise.all([
    token.decimals(),
    token.balanceOf(wallet),
  ]);
  return formatUnits(raw, decimals);
}

Quick on-chain check

cast call <token_address> "decimals()(uint8)" --rpc-url <rpc>

Rules

  • Always query decimals() at runtime
  • Cache by chain plus token address, not symbol
  • Use Decimal, BigInt, or equivalent exact math, not float
  • Re-query decimals after bridging or wrapper changes
  • Normalize internal accounting consistently before comparison or pricing
Files1
1 files · 1.0 KB

Select a file to preview

Overall Score

88/100

Grade

A

Excellent

Grades are signals, not a certification. Always review a skill yourself before use.

Safety

92

Quality

87

Clarity

86

Completeness

83

Summary

This skill teaches developers how to safely handle ERC-20 token decimal mismatches across EVM chains. It covers runtime decimal lookup via contract calls, chain+token caching strategies, bridged-token precision handling, and safe normalization patterns. The skill provides practical code examples in Python, Solidity, and TypeScript to prevent off-by-magnitude errors in balance calculations and fiat value conversions.

Detected Capabilities

web3-rpc-callsmart-contract-readcaching-patternexception-handlingmulti-chain-coordination

Trigger Keywords

Phrases that agents use to match this skill to user intent.

erc-20 decimal mismatchtoken balance precisioncross-chain token handlingbridged asset normalizationdecimal-aware calculation

Use Cases

  • Querying ERC-20 balances with correct decimal scaling across different EVM chains
  • Building portfolio trackers that aggregate token holdings from multiple chains without decimal drift
  • Implementing DeFi bots that handle bridged assets and wrapped token precision consistently
  • Calculating fiat values from on-chain balances using the correct decimal normalization
  • Integrating token data into dashboards where symbol normalization alone would cause orders-of-magnitude errors

Quality Notes

  • Skill directly teaches why the problem matters—silent failures are the core insight, not just 'remember to call decimals()'
  • All code examples are read-only contract calls with no state mutations, writes, or privilege escalation
  • Clear defensive programming pattern: explicit error handling and fallback logic for non-standard tokens
  • Caching strategy is well-scoped (chain_id + token_address), preventing cross-chain collisions
  • Examples span multiple languages (Python, Solidity, TypeScript) and tools (web3.py, ethers, cast), making the skill broadly applicable
  • Includes both positive (correct patterns) and negative (what not to do) guidance—e.g., 'do not hardcode 1_000_000'
  • Decimal normalization is consistently emphasized before comparison or pricing operations
  • Fallback logic includes logging to maintain visibility when non-standard tokens behave unexpectedly
Model: claude-haiku-4-5-20251001Analyzed: Sep 9, 2026

Reviews

Add this skill to your library to leave a review.

No reviews yet

Be the first to share your experience.

Version History

  1. v2.0

    Contract changed: description

    ✦ AIDescription expanded to clarify activation triggers: explicit use cases for decimal handling across EVM chains.

    triggering2026-09-09

    LATEST
  2. v1.2

    Content updated

    ✦ AINo behavioral changes detected.

    2026-07-14

    View This Version
  3. v1.1

    Content updated

    ✦ AIAdds LICENSE file.

    2026-04-20

    View This Version
  4. v1.0

    2026-04-12

    View This VersionInitial version

Use affaan-m/evm-token-decimals in your dev environment

Command Palette

Search for a command to run...