본문으로 건너뛰기
Skillpedia
머신러닝280k · #312

evm-token-decimals

하는 일

이 도구는 서로 다른 블록체인 네트워크에서 디지털 화폐(토큰) 값이 올바르게 계산되도록 돕습니다. 값이 실제보다 훨씬 크거나 작게 보이는 오류를 막아 줍니다.

사용하는 경우

  • ✓디지털 화폐의 잔액을 확인할 때.
  • ✓디지털 자산의 실제 화폐 가치를 계산할 때.
  • ✓서로 다른 블록체인 네트워크에서 디지털 화폐 값을 비교할 때.

스킬 링크

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

복사해서 AI(Claude, ChatGPT, Cursor)에 붙여넣고 지침을 따르도록 요청하세요.

사용 방법

가장 쉬운 방법입니다. 메시지를 복사해 AI에 붙여넣으세요. AI가 스킬을 읽고 지침을 따릅니다.

바로 붙여넣을 수 있는 메시지

Use this skill to help me: https://github.com/affaan-m/ECC/blob/main/skills/evm-token-decimals/SKILL.md Read the SKILL.md file at that link and follow its instructions for my task.
AI가 이런 스킬을 알아서 찾아 쓰길 원하시나요?무료 Skillpedia MCP를 설치하세요. 한 줄이면 작업마다 스킬 15,000+개 중에서 검색합니다.1분 만에 설치 →

AI에게 요청하는 예시

“제 지갑에 있는 Polygon 네트워크의 UNI 토큰 실제 잔액은 얼마인가요?”

매주 새 스킬 5개. 읽는 데 1분.

작동 방식

도구는 디지털 화폐에 대한 올바른 정보를 실시간으로 조회하고, 나중에 쓰기 위해 이 정보를 저장합니다. 같은 디지털 화폐라도 네트워크마다 표시 방식이 다를 수 있으므로, 계산이 항상 정확하게 유지되도록 합니다.

기술 내용 (원본 SKILL.md)

작성자의 영어 원문을 GitHub에서 그대로 가져왔습니다.

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
자주 묻는 질문

디지털 화폐 잔액이 왜 틀리게 보이나요?

블록체인 네트워크마다 같은 디지털 화폐를 나타낼 때 쓰는 '소수점 자릿수'가 다를 수 있기 때문입니다. 이 도구는 그 차이를 보정합니다.

디지털 화폐에서 '소수점 자릿수'는 무엇인가요?

디지털 화폐를 나누는 방식입니다. 예를 들어 1 Bitcoin은 정해진 소수점 자릿수에 따라 1,000,000,000,000,000,000개의 더 작은 단위로 표시될 수 있습니다.

이 도구는 모든 디지털 화폐에 작동하나요?

이 도구는 EVM(Ethereum Virtual Machine) 네트워크의 디지털 화폐를 위해 만들어졌습니다. 여기에는 Ethereum, Polygon, Binance Smart Chain 등 널리 쓰이는 네트워크가 포함됩니다.

상세 정보

작성자의 원본 설명

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

인기도

GitHub 스타
280k
순위
#312
라이선스
MIT
업데이트
2026. 10. 15.

이 스킬이 유용한가요?

0

로그인 투표하려면 로그인하세요.

댓글

  • …

이 저장소의 다른 스킬

비슷한 스킬