useTokenPrice & useTokenPrices
两个用于获取实时加密货币价格的 独立 hooks。两者都不需要 OneProvider——可以在 React 树中的任意位置使用。
两个 hooks 内部都使用 PriceService,该服务提供:
- 多源价格聚合,在 provider 之间自动回退。
- 客户端缓存,避免短时间内的重复网络请求。
- 自动重试,应对临时性故障。
导入
import { useTokenPrice, useTokenPrices } from '@one_deploy/sdk';
useTokenPrice
获取单个代币符号的实时 USD 价格。
签名
function useTokenPrice(
symbol: string,
options?: UseTokenPriceOptions
): UseTokenPriceReturn;
参数
| 参数 | 类型 | 必需 | 描述 |
|---|---|---|---|
symbol | string | 是 | 代币符号(例如 'ETH'、'BTC'、'USDC')。不区分大小写。 |
options | UseTokenPriceOptions | 否 | 轮询、货币和 API 连接的配置。 |
选项
interface UseTokenPriceOptions {
/** Target fiat currency for the price.
* Defaults to 'USD'. Supports ISO 4217 codes. */
currency?: string;
/** Enable automatic polling for price updates.
* Defaults to false. */
autoRefresh?: boolean;
/** Polling interval in milliseconds.
* Defaults to 30000 (30 seconds). Minimum: 5000. */
refreshInterval?: number;
/** Override the ONE Engine API URL. */
engineUrl?: string;
/** Your ONE project client ID (optional when inside OneProvider). */
clientId?: string;
}
返回类型
interface UseTokenPriceReturn {
/** The current price as a number, or null if not yet loaded. */
price: number | null;
/** Formatted price string (e.g. '3245.67'). */
priceFormatted: string | null;
/** The fiat currency the price is denominated in. */
currency: string;
/** 24-hour price change as a percentage (e.g. 2.34 for +2.34%). */
change24h: number | null;
/** Whether the initial fetch is in progress. */
isLoading: boolean;
/** Error object if the fetch failed, or null. */
error: OneSDKError | null;
/** Manually trigger a price refetch. */
refetch: () => Promise<void>;
/** ISO 8601 timestamp of the last successful update. */
lastUpdated: string | null;
}
基本用法
import { useTokenPrice } from '@one_deploy/sdk';
function EthPrice() {
const { price, change24h, isLoading, error } = useTokenPrice('ETH');
if (isLoading) return <span>Loading price...</span>;
if (error) return <span>Price unavailable</span>;
return (
<div>
<h2>ETH: ${price?.toLocaleString()}</h2>
<span style={{ color: (change24h ?? 0) >= 0 ? 'green' : 'red' }}>
{(change24h ?? 0) >= 0 ? '+' : ''}{change24h?.toFixed(2)}%
</span>
</div>
);
}
自动刷新的实时价格
import { useTokenPrice } from '@one_deploy/sdk';
function LiveBtcPrice() {
const { price, priceFormatted, lastUpdated, isLoading } = useTokenPrice('BTC', {
autoRefresh: true,
refreshInterval: 10000, // update every 10 seconds
});
return (
<div>
<h3>BTC: ${priceFormatted ?? '...'}</h3>
{lastUpdated && <small>Updated: {new Date(lastUpdated).toLocaleTimeString()}</small>}
</div>
);
}