Evm Token Decimals

affaan-m/ECC/skills/evm-token-decimals

作者 affaan-mef648e01899ba3e8dc6371642deaaf64b4477775无许可证275K 个星标收录于 2026年10月9日更新于 2026年10月9日仓库4天前更新

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.

AI 生成的概览

指导如何正确读取 EVM 各链上 ERC-20 代币精度,避免静默的小数位不匹配错误。

功能
说明应在运行时查询 ERC-20 代币的 decimals(),而不是假定固定值,并按链 ID 与代币地址缓存结果。提供 Python、TypeScript 和 Solidity 示例,涵盖余额读取、精确小数运算、异常回退处理以及归一化为 18 位 WAD。还列出在跨链桥或包装代币变更后重新查询精度等规则。
适用场景
适用于读取 ERC-20 余额、根据链上数量计算法币价值、跨多条 EVM 链比较代币数量,或处理跨链桥资产时。也适用于余额、价格或转账金额出现数量级偏差的情况。
运行要求
不附带脚本,仅为说明与代码示例。示例涉及 Python 的 web3 与 decimal、TypeScript 的 ethers、Solidity 以及 cast 命令行工具,并需要访问 EVM 链的 RPC。

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

python
from decimal import Decimalfrom 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

python
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

python
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

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

typescript
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

bash
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

来源与署名

来源:affaan-m/ECC位于skills/evm-token-decimals提交ef648e0

许可证: 无许可证

内容归原作者所有。SourceWeft 从公开仓库中收录这些内容。

举报或申请下架