evm-token-decimals
affaan-m/ecc
Prevent silent decimal mismatch bugs across EVM chains with runtime lookup and chain-aware caching.
What is evm-token-decimals?
Handles ERC-20 token decimal precision safely across multiple EVM chains. Use this when reading balances, calculating fiat values, comparing amounts across chains, or handling bridged assets to avoid off-by-magnitude errors.
- Query token decimals at runtime instead of hardcoding assumptions
- Cache decimals by (chain_id, token_address) pair to avoid repeated calls
- Normalize token amounts to consistent precision (e.g., 18-decimal WAD) for safe math
- Handle non-standard or reverted decimals() calls with defensive fallbacks
- Support Python, TypeScript, Solidity, and CLI workflows
How to install evm-token-decimals
npx skills add null --skill evm-token-decimalsHow to use evm-token-decimals
- 1.Query decimals() at runtime for each token on each chain instead of assuming a fixed value
- 2.Implement caching keyed by (chain_id, token_address) to avoid redundant RPC calls
- 3.Use exact-precision math libraries (Decimal in Python, BigInt in TypeScript, uint math in Solidity) instead of floats
- 4.Wrap decimals() calls in try-catch to handle non-standard tokens; log and default to 18 if the call reverts
- 5.Normalize all internal token amounts to a consistent decimal scale (e.g., 18-decimal WAD) before comparison or pricing
Use cases
- Building portfolio trackers that aggregate balances across multiple EVM chains
- Calculating USD values from on-chain token balances without precision loss
- Comparing stablecoin amounts when the same symbol has different decimals on different chains
- Handling bridged or wrapped token variants that may have precision drift
- Automating DeFi bots that need exact balance math for swaps or liquidations
- DeFi developers building bots, dashboards, or aggregators
- Smart contract engineers normalizing token amounts in Solidity
- Python/TypeScript backend engineers reading on-chain balances
- Portfolio tracker maintainers handling multi-chain assets
evm-token-decimals FAQ
The same symbol (e.g., USDC) often has different decimals on different chains, and bridged versions may differ from the original. Hardcoding silently produces off-by-magnitude errors.
Cache by (chain_id, token_address) with an LRU cache or similar. Re-query if a token is wrapped, bridged, or upgraded, but caching prevents redundant calls for the same token on the same chain.
Wrap the call in try-catch, log a warning with the token address and chain, and default to 18. Keep the fallback visible so you know which tokens are non-standard.
No. Use Decimal (Python), BigInt (TypeScript), or uint (Solidity) to avoid rounding errors. Float math will silently lose precision on large balances.
Divide by 10^decimals to get a human-readable amount, or multiply by 10^(18-decimals) to normalize to 18-decimal WAD for internal accounting before comparison.
Full instructions (SKILL.md)
Source of truth, from affaan-m/ecc.
name: evm-token-decimals description: 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. metadata: origin: ECC direct-port adaptation version: "1.0.0"
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
Related skills
More from affaan-m/ecc and the wider catalog.
exa-search
Neural search via Exa MCP for web, code, companies, and people research.
fal-ai-media
Generate images, videos, and audio with fal.ai models via MCP.
fastapi-patterns
Production-grade FastAPI patterns: project structure, Pydantic v2, dependency injection, async handlers, auth, and testing.
finance-billing-ops
Evidence-first revenue, pricing, and billing-model truth for operators—code-backed diagnostics instead of generic payments advice.
flox-environments
Declarative, reproducible development environments for macOS/Linux using Nix — no containers needed.
flutter-dart-code-review
Library-agnostic Flutter/Dart code review checklist for widgets, state management, and clean architecture.