Chuyển đến nội dung
Skillpedia
Học máy280k · #312

evm-token-decimals

Skill này làm gì

Công cụ này giúp đảm bảo giá trị tiền kỹ thuật số (token) trên các mạng blockchain khác nhau được tính đúng. Nó ngăn lỗi làm giá trị hiển thị lớn hơn hoặc nhỏ hơn nhiều so với thực tế.

Khi nào nên dùng

  • ✓Khi kiểm tra số dư tiền kỹ thuật số.
  • ✓Khi tính giá trị thực bằng tiền thật của tài sản số của bạn.
  • ✓Khi so sánh giá trị tiền kỹ thuật số trên các mạng blockchain khác nhau.

Liên kết skill

https://github.com/affaan-m/ECC/blob/main/skills/evm-token-decimals/SKILL.md

Sao chép rồi dán vào AI của bạn (Claude, ChatGPT hoặc Cursor) và nhờ nó làm theo hướng dẫn.

Cách dùng

Cách dễ nhất: sao chép tin nhắn và dán vào AI của bạn. AI sẽ đọc skill và làm theo hướng dẫn.

Tin nhắn có sẵn để dán

Hãy dùng skill này để giúp tôi: https://github.com/affaan-m/ECC/blob/main/skills/evm-token-decimals/SKILL.md Đọc tệp SKILL.md tại liên kết đó và làm theo hướng dẫn cho việc của tôi.
Bạn muốn AI tự tìm những skill như thế này?Cài MCP Skillpedia miễn phí: chỉ một dòng, và AI sẽ tìm trong 15.000+ skill trước mỗi việc.Cài đặt trong 1 phút →

Ví dụ cách nhờ AI

“Số dư token UNI thực tế trong ví của tôi trên mạng Polygon là bao nhiêu?”

5 skill mới mỗi tuần. Đọc chỉ 1 phút.

Cách hoạt động

Công cụ truy vấn thông tin chính xác về tiền kỹ thuật số theo thời gian thực và lưu lại để dùng sau. Nhờ vậy các phép tính luôn chính xác, kể cả khi cùng một loại tiền có cách biểu diễn khác nhau trên các mạng khác nhau.

Nội dung kỹ thuật (SKILL.md gốc)

Lấy nguyên văn từ GitHub, do tác giả viết bằng tiếng Anh.

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
Câu hỏi thường gặp

Tại sao số dư tiền kỹ thuật số có vẻ sai?

Điều này có thể xảy ra vì các mạng blockchain khác nhau dùng số lượng “chữ số thập phân” khác nhau để biểu diễn cùng một loại tiền. Công cụ này điều chỉnh sự khác biệt đó.

“Chữ số thập phân” trong tiền kỹ thuật số là gì?

Đó là cách chia nhỏ đơn vị tiền. Ví dụ, 1 Bitcoin có thể được biểu diễn bằng 100.000.000 đơn vị nhỏ hơn, tùy theo số chữ số thập phân được định nghĩa.

Công cụ này có hoạt động với mọi loại tiền kỹ thuật số không?

Nó được thiết kế cho tiền kỹ thuật số trên các mạng EVM (Ethereum Virtual Machine), bao gồm các mạng phổ biến như Ethereum, Polygon, Binance Smart Chain và một số mạng khác.

Chi tiết

Mô tả gốc của tác giả

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.

repo: affaan-m/ECC

Độ phổ biến

Sao GitHub
280k
Vị trí xếp hạng
#312
Giấy phép
MIT
Cập nhật
15/10/2026

Skill này có hữu ích không?

0

Đăng nhập để bình chọn.

Bình luận

  • …

Thêm skill từ kho mã này

Skill tương tự