Files
assetx/webapp/hooks/useTokenDecimals.ts
default 2ee4553b71 init: 初始化 AssetX 项目仓库
包含 webapp(Next.js 用户端)、webapp-back(Go 后端)、
antdesign(管理后台)、landingpage(营销落地页)、
数据库 SQL 和配置文件。
2026-03-27 11:26:43 +00:00

39 lines
1.1 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import { useReadContract } from 'wagmi'
/** 最小 ERC20 decimals ABI无需引入完整 ABI 文件 */
const DECIMALS_ABI = [
{
inputs: [],
name: 'decimals',
outputs: [{ internalType: 'uint8', name: '', type: 'uint8' }],
stateMutability: 'view',
type: 'function',
},
] as const
/**
* 从合约地址直接读取精度(适用于产品 API 返回 contractAddress 的场景)
* 优先从合约 decimals() 读取,失败时回退到 fallback通常是 token.decimals
*
* @param contractAddress 合约地址,直接来自产品/Token 对象
* @param fallback 备用精度(来自 token.decimals 或链配置)
*/
export function useTokenDecimalsFromAddress(
contractAddress: string | undefined,
fallback: number = 18
): number {
const { data, isError } = useReadContract({
address: contractAddress as `0x${string}` | undefined,
abi: DECIMALS_ABI,
functionName: 'decimals',
query: {
enabled: !!contractAddress,
staleTime: Infinity,
gcTime: Infinity,
retry: 2,
},
})
return (data !== undefined && !isError) ? Number(data) : fallback
}