useWalletBalance
useWalletBalance 是一个 独立 hook——它不需要 OneProvider 或任何其他上下文包装器。你可以将它放入任何 React 组件中,获取钱包地址在一条或多条链上的代币余额。
导入
import { useWalletBalance } from '@one_deploy/sdk';
签名
function useWalletBalance(
walletAddress: string,
options?: UseWalletBalanceOptions
): UseWalletBalanceReturn;
参数
| 参数 | 类型 | 必需 | 描述 |
|---|---|---|---|
walletAddress | string | 是 | 要获取余额的钱包地址(例如 "0x1234...abcd")。 |
options | UseWalletBalanceOptions | 否 | 链、自动刷新和 API 连接的配置。 |
选项
interface UseWalletBalanceOptions {
/** Array of chain IDs to fetch balances from.
* Defaults to all supported chains (Base, Ethereum, Polygon, Arbitrum, Optimism). */
chains?: number[];
/** Enable automatic polling for updated balances.
* Defaults to false. */
autoRefresh?: boolean;
/** Polling interval in milliseconds when autoRefresh is true.
* Defaults to 30000 (30 seconds). Minimum: 5000. */
refreshInterval?: number;
/** Override the ONE Engine API URL.
* Defaults to 'https://engine.one23.io'. */
engineUrl?: string;
/** Your ONE project client ID. Required only when calling outside
* of OneProvider (the provider supplies this automatically). */
clientId?: string;
}
返回类型
interface UseWalletBalanceReturn {
/** Array of token balances across all requested chains. */
balances: TokenBalance[];
/** Aggregated USD total across all tokens and chains (formatted string). */
totalUsd: string;
/** Whether the initial fetch is in progress. */
isLoading: boolean;
/** Error object if the fetch failed, or null on success. */
error: OneSDKError | null;
/** Manually trigger a balance refetch. Returns a promise that resolves
* when the new data is loaded. */
refetch: () => Promise<void>;
}
TokenBalance 类型
balances 数组中的每个条目描述单条链上的单个代币:
interface TokenBalance {
/** Token ticker symbol (e.g. 'ETH', 'USDC'). */
token: string;
/** Display symbol (usually same as token). */
symbol: string;
/** Full token name (e.g. 'Ethereum', 'USD Coin'). */
name: string;
/** Formatted balance as a decimal string (e.g. '1.2345'). */
balance: string;
/** USD equivalent of the balance (e.g. '2469.00'). */
balanceUsd: string;
/** Chain ID where this balance was fetched. */
chainId: number;
/** Token decimal places. */
decimals: number;
/** ERC-20 contract address, or null for native tokens (ETH, MATIC, etc.). */
contractAddress: string | null;
/** URL to the token logo image. */
logoUri: string;
}
基本用法
import { useWalletBalance } from '@one_deploy/sdk';
function WalletOverview({ address }: { address: string }) {
const { balances, totalUsd, isLoading, error, refetch } = useWalletBalance(address);
if (isLoading) return <p>Loading balances...</p>;
if (error) return <p>Error: {error.message}</p>;
return (
<div>
<h2>Total Balance: ${totalUsd}</h2>
<table>
<thead>
<tr>
<th>Token</th>
<th>Balance</th>
<th>USD</th>
<th>Chain</th>
</tr>
</thead>
<tbody>
{balances.map((b) => (
<tr key={`${b.chainId}-${b.contractAddress ?? b.symbol}`}>
<td>{b.symbol}</td>
<td>{b.balance}</td>
<td>${b.balanceUsd}</td>
<td>{b.chainId}</td>
</tr>
))}
</tbody>
</table>
<button onClick={refetch}>Refresh</button>
</div>
);
}
自动刷新
启用轮询以保持余额数据最新:
import { useWalletBalance } from '@one_deploy/sdk';
function LiveBalance({ address }: { address: string }) {
const { balances, totalUsd, isLoading } = useWalletBalance(address, {
autoRefresh: true,
refreshInterval: 15000, // poll every 15 seconds
});
return (
<div>
<h3>${totalUsd}</h3>
{isLoading && <span>(updating...)</span>}
<ul>
{balances.map((b) => (
<li key={`${b.chainId}-${b.symbol}`}>
{b.symbol}: {b.balance}
</li>
))}
</ul>
</div>
);
}
提示
当 autoRefresh 激活时,isLoading 仅在 初始 请求时为 true。后续的轮询会静默更新 balances,不会将 isLoading 重新设为 true。
多链余额
默认情况下,useWalletBalance 会查询所有支持的链。要将查询限制在特定链上,请传入 chains 选项:
import { useWalletBalance, CHAIN_IDS } from '@one_deploy/sdk';
function BaseAndEthBalance({ address }: { address: string }) {
const { balances, totalUsd } = useWalletBalance(address, {
chains: [CHAIN_IDS.BASE, CHAIN_IDS.ETHEREUM],
});
return (
<div>
<p>Total (Base + Ethereum): ${totalUsd}</p>
{balances.map((b) => (
<p key={`${b.chainId}-${b.symbol}`}>
[{b.chainId}] {b.symbol}: {b.balance} (${b.balanceUsd})
</p>
))}
</div>
);
}
自定义 Engine URL
当连接到自托管或预发布环境的 ONE Engine 实例时:
import { useWalletBalance } from '@one_deploy/sdk';
function StagingBalance({ address }: { address: string }) {
const { balances, totalUsd } = useWalletBalance(address, {
engineUrl: 'https://engine-staging.one23.io',
clientId: 'my_staging_client_id',
});
return <p>Staging balance: ${totalUsd}</p>;
}
无需 Provider
与大多数 ONE SDK hooks 不同,useWalletBalance 无需 将你的应用包裹在 OneProvider 中即可工作。它直接调用 ONE Engine API。
import { useWalletBalance } from '@one_deploy/sdk';
// This component can be rendered anywhere -- no OneProvider ancestor needed
function StandaloneWidget() {
const { totalUsd, isLoading } = useWalletBalance(
'0x1234567890abcdef1234567890abcdef12345678'
);
if (isLoading) return <span>...</span>;
return <span>Portfolio: ${totalUsd}</span>;
}
如果你 确实 在 OneProvider 内部,该 hook 仍然可以工作——它只是不从 provider 上下文读取数据。
错误处理
import { useWalletBalance } from '@one_deploy/sdk';
function SafeBalance({ address }: { address: string }) {
const { balances, totalUsd, isLoading, error, refetch } = useWalletBalance(address);
if (isLoading) return <p>Loading...</p>;
if (error) {
return (
<div>
<p>Failed to load balances: {error.message} ({error.code})</p>
<button onClick={refetch}>Retry</button>
</div>
);
}
if (balances.length === 0) {
return <p>No tokens found for this address.</p>;
}
return <p>Total: ${totalUsd} across {balances.length} tokens</p>;
}
另请参阅
- Hooks 概览 -- 所有 hook 类别。
- 余额展示 -- 基于此 hook 构建的
OneWalletBalance组件。 - useTokenPrice & useTokenPrices -- 独立价格 hooks。
- Provider Hooks -- 需要
OneProvider的 hooks。