Communitygithub.com

evm-token-decimals

EVM 체인에서 발생할 수 있는 토큰 소수점 자릿수 불일치 버그를 방지합니다. 런타임 소수점 조회, 체인 인식 캐싱, 브릿지 토큰 정밀도 드리프트, 봇/대시보드/디파이 도구를 위한 안전한 정규화를 다룹니다.

evm-token-decimals란 무엇인가요?

이 스킬은 EVM 체인에서 토큰의 소수점 자릿수(decimals)를 올바르게 처리하지 않아 발생하는 버그를 방지하는 방법을 제공합니다. 개발자들은 종종 특정 토큰(예: USDC)의 소수점 자릿수를 하드코딩하거나 잘못된 체인 정보로 인해 잔액이 실제보다 10^12 배 차이 나는 오류를 경험합니다. 이 스킬은 런타임 시 `decimals()` 함수를 직접 호출하고, `(chain_id, token_address)`를 키로 캐싱하여 항상 정확한 값을 사용하도록 합니다. 또한 브릿지 토큰이나 비표준 토큰처럼 예외적인 경우를 처리하고, Solidity 및 TypeScript를 포함한 여러 플랫폼에서 안전한 소수점 연산을 수행하는 방법을 제시합니다. Python, TypeScript, Solidity, CLI 환경에서 모두 활용 가능하며, 봇, 대시보드, 디파이 툴 등 토큰 잔액을 처리하는 모든 프로젝트에서 필수적으로 적용해야 할 패턴입니다.

지원 대상~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/affaan-m/everything-claude-code/tree/main/skills/evm-token-decimals

즐겨 사용하는 AI에게 물어보기

이 에이전트 스킬이 미리 로드된 새 채팅을 엽니다.

문서

EVM 토큰 소수점(Decimals)

소리 없는 소수점 불일치는 오류를 발생시키지 않으면서 잔액이나 USD 가치가 실제보다 수 자릿수 차이 나도록 만드는 가장 쉬운 방법 중 하나입니다.

사용 시점

  • Python, TypeScript, Solidity에서 ERC-20 잔액 읽기
  • 온체인 잔액으로 법정화폐 가치 계산
  • 여러 EVM 체인의 토큰 양 비교
  • 브릿지 자산 처리
  • 포트폴리오 트래커, 봇, 애그리게이터 구축

작동 방식

스테이블코인이 모든 곳에서 동일한 소수점을 사용한다고 가정하지 마십시오. 런타임에 decimals()를 조회하고, (chain_id, token_address)로 캐싱한 후, 소수점 안전 수학을 사용하여 값을 계산하십시오.

예제

런타임에 소수점 조회

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)

심볼이 보통 다른 곳에서 6자리 소수점을 가진다고 해서 1_000_000을 하드코딩하지 마십시오.

체인 및 토큰별 캐싱

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()

비정상 토큰 방어적으로 처리

try:
    decimals = contract.functions.decimals().call()
except Exception:
    logging.warning(
        "decimals()가 %s (체인 %s)에서 되돌아짐, 기본값 18 사용",
        token_address,
        chain_id,
    )
    decimals = 18

대체값을 로그에 기록하고 계속 확인하십시오. 오래되었거나 비표준 토큰은 여전히 존재합니다.

Solidity에서 18자리 WAD로 정규화

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);
}

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);
}

빠른 온체인 확인

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

규칙

  • 항상 런타임에 decimals()를 조회하십시오
  • 심볼이 아닌 체인과 토큰 주소로 캐싱하십시오
  • Decimal, BigInt 또는 이와 동등한 정확한 수학을 사용하고, float를 사용하지 마십시오
  • 브릿징 또는 래퍼 변경 후 소수점을 다시 조회하십시오
  • 비교 또는 가격 책정 전에 내부 회계를 일관되게 정규화하십시오

Individual skills in this repo

This repo contains 20 individual skills — each has its own dedicated page.

accessibility

Design, implement, and audit inclusive digital products using WCAG 2.2 Level AA. Use when building or auditing UI that must meet WCAG 2.2 Level AA, or when reviewing a change for keyboard, contrast, or screen-reader support.

affaan-m/claude-api

Anthropic Claude API patterns for Python and TypeScript. Covers Messages API, streaming, tool use, vision, extended thinking, batches, prompt caching, and Claude Agent SDK. Use when building applications with the Claude API or Anthropic SDKs.

affaan-m/everything-claude-code

End-to-end marketing campaign planning and execution. Covers audience research, positioning, campaign angle definition, landing page copy, email sequences, social posts, ad copy, short-form video scripts, and content calendars. Use as the orchestration layer for multi-channel product launches. Use when planning or executing a multi-channel product launch, or producing landing page, email, social, or ad copy.

affaan-m/everything-claude-code

Development conventions and patterns for everything-claude-code. JavaScript project with conventional commits.

affaan-m/everything-claude-code-conventions

Development conventions and patterns for everything-claude-code. JavaScript project with conventional commits.

affaan-m/frontend-design

Create distinctive, production-grade frontend interfaces with high design quality. Use when the user asks to build web components, pages, or applications and the visual direction matters as much as the code quality.

affaan-m/gget

gget CLI and Python workflow for quick genomic database queries, sequence lookup, BLAST-style searches, enrichment checks, and reproducible bioinformatics evidence logs.

affaan-m/literature-review

Systematic literature-review workflow for academic, biomedical, technical, and scientific topics, including search planning, source screening, synthesis, citation checks, and evidence logging.

affaan-m/motion-ui

Production-ready UI motion system for React/Next.js. Use when implementing animations, transitions, or motion patterns.

affaan-m/project-guidelines-example

Example project-specific skill template based on a real production application.

affaan-m/pubmed-database

Direct PubMed and NCBI E-utilities search workflows for biomedical literature, MeSH queries, PMID lookup, citation retrieval, and API-backed literature monitoring.

affaan-m/scholar-evaluation

Structured scholarly-work evaluation for papers, proposals, literature reviews, methods sections, evidence quality, citation support, and research-writing feedback.

affaan-m/uspto-database

USPTO patent and trademark data workflow for official record lookup, PatentSearch queries, TSDR checks, assignment data, and reproducible IP research logs.

agent-architecture-audit

Full-stack diagnostic for agent and LLM applications. Audits the 12-layer agent stack for wrapper regression, memory pollution, tool discipline failures, hidden repair loops, and rendering corruption. Produces severity-ranked findings with code-first fixes. Essential for developers building agent applications, autonomous loops, or any LLM-powered feature. Use when an agent or LLM feature misbehaves and the failing layer is unknown, or before shipping an agent stack.

agent-eval

Head-to-head comparison of coding agents (Claude Code, Aider, Codex, etc.) on custom tasks with pass rate, cost, time, and consistency metrics. Use when choosing between coding agents, or when a change to an agent setup needs measured pass rate, cost, and time rather than an impression.

agent-harness-construction

Design and optimize AI agent action spaces, tool definitions, and observation formatting for higher completion rates. Use when defining or revising an agent

agentic-engineering

Operate as an agentic engineer using eval-first execution, decomposition, and cost-aware model routing. Use when planning or executing engineering work that agents will carry out end to end.

agentic-os

Build persistent multi-agent operating systems on Claude Code. Covers kernel architecture, specialist agents, slash commands, file-based memory, scheduled automation, and state management without external databases. Use when building a persistent multi-agent system on Claude Code with its own memory, commands, and scheduling.

agent-introspection-debugging

Structured self-debugging workflow for AI agent failures using capture, diagnosis, contained recovery, and introspection reports. Use when an agent run fails and you need a reproducible diagnosis instead of a retry.

agent-payment-x402

Add x402 payment execution to AI agents with per-task budgets, spending controls, and non-custodial wallets. Supports Base through agentwallet-sdk and X Layer through OKX Payments / OKX Agent Payments Protocol. Use when an agent must pay for something itself and needs per-task budgets, spending controls, and a non-custodial wallet.

관련 스킬