Communitygithub.com

evm-token-decimals

EVM 체인 전반에서 발생하는 소수점 불일치 버그를 방지합니다. 런타임 소수점 조회, 체인 인식 캐싱, 브리지 토큰 정밀도 드리프트 및 봇, 대시보드, DeFi 도구를 위한 안전한 정규화를 다룹니다. EVM 체인 간 토큰 금액을 처리하거나 잔액, 가격, 전송 금액이 예상과 크게 다를 때 사용하세요.

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

이 스킬은 EVM 호환 블록체인에서 토큰의 소수점 자릿수(decimals)를 안전하게 처리하도록 설계되었습니다. 토큰의 소수점 자릿수를 하드코딩하지 않고 런타임에 `decimals()` 함수를 호출하여 조회하며, `(chain_id, token_address)` 쌍을 기준으로 캐싱하여 성능과 정확성을 보장합니다. 브리지된 자산이나 비표준 토큰을 처리할 때 발생할 수 있는 소수점 불일치로 인한 잔액, 가격, 전송 금액의 오류를 방지합니다. Python, TypeScript, Solidity 등 다양한 언어와 환경에서 사용할 수 있으며, float 대신 `Decimal`이나 `BigInt`와 같은 정확한 산술 연산을 사용하여 값 계산의 정밀도를 유지합니다.

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

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

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

문서

EVM 토큰 소수점 처리

묵시적 소수점 불일치는 오류 없이 잔액이나 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()를 조회하십시오
  • 심볼이 아닌 체인과 토큰 주소로 캐싱하십시오
  • float 대신 Decimal, BigInt 또는 동등한 정확한 수학을 사용하십시오
  • 브리징 또는 래퍼 변경 후 소수점을 다시 조회하십시오
  • 비교 또는 가격 책정 전에 내부 회계를 일관되게 정규화하십시오

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/content-engine

Create platform-native content systems for X, LinkedIn, TikTok, YouTube, newsletters, and repurposed multi-platform campaigns. Use when the user wants social posts, threads, scripts, content calendars, or one source asset adapted cleanly across platforms.

affaan-m/ECC

Multi-platform content distribution across X, LinkedIn, Threads, and Bluesky. Adapts content per platform using content-engine patterns. Never posts identical content cross-platform. Use when the user wants to distribute content across social platforms.

affaan-m/fal-ai-media

Unified media generation via fal.ai MCP — image, video, and audio. Covers text-to-image (Nano Banana), text/image-to-video (Seedance, Kling, Veo 3), text-to-speech (CSM-1B), and video-to-audio (ThinkSound). Use when the user wants to generate images, videos, or audio with AI.

affaan-m/manim-video

日本語翻訳:このファイルは manim-video 用の日本語翻訳が必要です

affaan-m/remotion-video-creation

Remotion のベストプラクティス - React で動画を作成する。3D、アニメーション、音声、字幕、チャート、トランジションなどをカバーするドメイン固有の29のルール。

affaan-m/video-editing

AI-assisted video editing workflows for cutting, structuring, and augmenting real footage. Covers the full pipeline from raw capture through FFmpeg, Remotion, ElevenLabs, fal.ai, and final polish in Descript or CapCut. Use when the user wants to edit video, cut footage, create vlogs, or build video content.

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.

agent-self-evaluation

Use after completing any non-trivial task. The agent self-rates its output on 5 axes — accuracy, completeness, clarity, actionability, conciseness — with concrete evidence per criterion. Produces a structured 1-5 scorecard with specific improvement suggestions.

agent-sort

Build an evidence-backed ECC install plan for a specific repo by sorting skills, commands, rules, hooks, and extras into DAILY vs LIBRARY buckets using parallel repo-aware review passes. Use when ECC should be trimmed to what a project actually needs instead of loading the full bundle.

ai-first-engineering

Engineering operating model for teams where AI agents generate a large share of implementation output. Use when setting team process, review gates, or ownership rules for a codebase largely written by agents.

ai-regression-testing

Regression testing strategies for AI-assisted development. Sandbox-mode API testing without database dependencies, automated bug-check workflows, and patterns to catch AI blind spots where the same model writes and reviews code. Use when adding regression coverage to AI-assisted code, or when the same model both wrote and reviewed a change.

android-clean-architecture

Clean Architecture patterns for Android and Kotlin Multiplatform projects — module structure, dependency rules, UseCases, Repositories, and data layer patterns. Use when structuring modules, layers, or data flow in an Android or KMP project.

angular-developer

Generates Angular code and provides architectural guidance. Trigger when creating projects, components, or services, or for best practices on reactivity (signals, linkedSignal, resource), forms, dependency injection, routing, SSR, accessibility (ARIA), animations, styling (component styles, Tailwind CSS), testing, or CLI tooling.

관련 스킬