资讯动态

wagmi 的 useFeeHistory Hook 使用指南:在 React 中获取历史 Gas 费用信息

发布时间:2026/9/17 6:53:33 来源:尧图企业网站定制
wagmi 的 useFeeHistory Hook 使用指南在 React 中获取历史 Gas 费用信息【免费下载链接】wagmiReactive primitives for Ethereum apps项目地址: https://gitcode.com/GitHub_Trending/wa/wagmiuseFeeHistory 是 wagmi 提供的 React Hook用于获取一段区块范围内的历史 Gas 费用信息base fee、gas 使用比例与优先费分位数是构建 Gas 费用预估、交易费率分析与区块浏览器类功能的核心数据来源。读完本文你将掌握该 Hook 的导入方式、全部参数与返回类型并理解它如何与底层 getFeeHistory action 及 TanStack Query 协同工作。Import 导入方式在 React 应用中从wagmi包中导入useFeeHistoryimport { useFeeHistory } from wagmi该 Hook 是客户端组件其源码位于 packages/react/src/hooks/useFeeHistory.ts文件首行为use client指令意味着它依赖 React Hooks 与运行时上下文不能用于服务端渲染的组件边界之外。Usage 基本用法向useFeeHistory传入blockCount请求的区块数量与rewardPercentiles优先费分位数列表即可发起查询import { useFeeHistory } from wagmi function App() { const result useFeeHistory({ blockCount: 4, rewardPercentiles: [25, 75] }) }完整的配置示例如下通过createConfig创建配置并声明链与 transportimport { createConfig, http } from wagmi import { mainnet, sepolia } from wagmi/chains export const config createConfig({ chains: [mainnet, sepolia], transports: { [mainnet.id]: http(), [sepolia.id]: http(), }, })Hook 默认会从最近的WagmiProvider中读取 config。底层实际执行的是 viem 的getFeeHistoryaction其实现位于 packages/core/src/actions/getFeeHistory.ts通过config.getClient({ chainId })获取对应链的客户端再经getAction调用 viem 的getFeeHistory。Parameters 参数说明import { type UseFeeHistoryParameters } from wagmiUseFeeHistoryParameters由GetFeeHistoryOptions与ConfigParameter组合而成见 packages/react/src/hooks/useFeeHistory.ts。blockCountnumber | undefined请求范围内区块的数量。单次查询可请求 1 到 1024 个区块如果并非所有区块都可用返回的区块数可能少于请求数。import { useFeeHistory } from wagmi function App() { const result useFeeHistory({ blockCount: 4, // [!code focus] rewardPercentiles: [25, 75] }) }rewardPercentilesnumber[] | undefined一个单调递增的百分位值列表用于从每个区块的有效优先费per gas中采样按 gas 使用量加权结果按升序排列。它直接对应eth_feeHistoryRPC 方法中的rewardPercentiles参数。import { useFeeHistory } from wagmi function App() { const result useFeeHistory({ blockCount: 4, rewardPercentiles: [25, 75] // [!code focus] }) }blockNumberbigint | undefined请求范围中最高的区块号。未指定时默认使用链的 latest 区块。import { useFeeHistory } from wagmi function App() { const result useFeeHistory({ blockCount: 4, blockNumber: 1551231n, // [!code focus] rewardPercentiles: [25, 75] }) }注意 blockNumber 使用bigint字面量1551231n这是 wagmi/viem 在涉及区块号、金额等数值时的统一约定可避免 JavaScriptnumber的精度损失。blockTaglatest | earliest | pending | safe | finalized | undefined请求范围中最高的区块标签。未指定时默认使用latest。import { useFeeHistory } from wagmi function App() { const result useFeeHistory({ blockCount: 4, blockTag: safe, // [!code focus] rewardPercentiles: [25, 75] }) }chainIdconfig[chains][number][id] | undefined查询数据时所使用的链 ID。默认使用当前连接的链。import { useFeeHistory } from wagmi import { mainnet } from wagmi/core/chains function App() { const result useFeeHistory({ blockCount: 4, chainId: mainnet.id, // [!code focus] rewardPercentiles: [25, 75] }) }configConfig | undefined要使用的Config默认为从最近的WagmiProvider中获取。import { useFeeHistory } from wagmi import { config } from ./config // [!code focus] function App() { const result useFeeHistory({ blockCount: 4, rewardPercentiles: [25, 75] config, // [!code focus] }) }scopeKeystring | undefined将缓存限定到给定的上下文。具有相同上下文的 Hook 会共享同一份缓存。该参数在 packages/core/src/query/getFeeHistory.ts 中作为ScopeKeyParameter参与构建 query key。import { useFeeHistory } from wagmi import { config } from ./config // [!code focus] function App() { const result useFeeHistory({ blockCount: 4, rewardPercentiles: [25, 75] scopeKey: foo, // [!code focus] }) }queryTanStack Query 参数useFeeHistory内部基于 TanStack Query v5 的useQuery实现因此还支持一组 TanStack Query 参数详见 site/shared/query-options.md。需要注意queryFn与queryKey由 wagmi 内部使用不能覆盖其余参数均可使用包括enabledboolean | undefined设为false可禁用查询自动执行可用于依赖查询Dependent Queries。gcTimenumber | Infinity | undefined未使用/非活跃缓存数据在内存中的保留时间默认5 * 60 * 10005 分钟SSR 期间为Infinity设为Infinity则禁用垃圾回收。initialData/initialDataUpdatedAt为尚未创建的查询提供初始数据initialData会持久化到缓存默认视为过期。metaRecordstring, unknown | undefined向缓存条目附加额外信息。networkModeonline | always | offlineFirst | undefined默认online。notifyOnChangeProps控制组件仅在指定属性变化时重渲染。placeholderDatapending 状态下显示的占位数据不持久化到缓存。queryClient自定义QueryClient否则使用最近上下文中的实例。refetchInterval/refetchIntervalInBackground定时自动重新获取的频率毫秒及后台标签页是否继续。refetchOnMount默认true挂载时若数据过期则重新获取always则总是获取。refetchOnReconnect默认true网络重连时若数据过期则重新获取。refetchOnWindowFocus默认true窗口聚焦时若数据过期则重新获取。retry失败重试次数客户端默认3服务端默认0true无限重试false不重试。retryDelay重试间隔计算函数可组合指数退避如attempt Math.min(attempt 1 ? 2 ** attempt * 1000 : 1000, 30 * 1000)。retryOnMount默认true挂载时若查询含错误是否重试。select转换/选择查询返回数据影响返回的data不影响缓存内容。staleTime数据过期时间默认0Infinity表示永不过期。structuralSharing默认true控制查询结果间的结构共享以优化性能。Return Type 返回类型import { type UseFeeHistoryReturnType } from wagmiUseFeeHistoryReturnType本质上是UseQueryReturnTypeselectData, GetFeeHistoryErrorType见 packages/react/src/hooks/useFeeHistory.ts即 TanStack Query 的查询结果主要字段如下完整说明见 site/shared/query-result.mddataGetFeeHistoryData最近一次成功解析的数据默认undefined。其结构与 viemgetFeeHistory返回值一致包含baseFeePerGasbigint[]每个区块的基础费gasUsedRationumber[]每个区块 gas 使用量与上限的比值oldestBlockbigint返回范围内最旧的区块号rewardbigint[][]每个区块在各rewardPercentiles下采样的优先费。dataUpdatedAtnumber查询最近一次返回success状态的时间戳。errornull | GetFeeHistoryErrorType查询抛出的错误对象默认null。errorUpdatedAt/errorUpdateCount最近一次出错时间戳与累计错误次数。failureCount/failureReason失败次数与最近一次失败原因成功后重置。fetchStatusfetching | idle | paused表示查询函数执行状态。isError / isPending / isSuccess / isLoading / isFetching / isRefetching / isFetched / isStale / isPlaceholderData等布尔标志均由status/fetchStatus派生。statuserror | pending | success查询的当前状态。refetch手动重新获取查询的函数。底层实现与数据流useFeeHistory的数据流可以拆解为三层React Hook 层packages/react/src/hooks/useFeeHistory.ts通过useConfig获取 configuseChainId获取当前链 ID当未显式传入chainId时再调用getFeeHistoryQueryOptions生成查询选项并交给useQuery。Query 层packages/core/src/query/getFeeHistory.tsgetFeeHistoryQueryOptions构建 query key[feeHistory, {...}]、queryFn 与enabled逻辑。其中enabled被强制为Boolean(options.blockCount options.rewardPercentiles (options.query?.enabled ?? true))即blockCount与rewardPercentiles缺一不可否则查询保持 disabledpending 状态且不发起请求queryFn 中若缺少这两个参数还会抛出错误。Action 层packages/core/src/actions/getFeeHistory.ts最终委托给 viem 的getFeeHistory对指定链客户端执行eth_feeHistoryRPC 调用。该行为在测试中得到验证packages/react/src/hooks/useFeeHistory.test.ts 覆盖了默认用法、chainId、blockNumber、blockTag参数以及blockCount/rewardPercentiles由 undefined 变为定义值时从 disabled 转为 success 的动态行为还专门验证了“缺少属性时查询被禁用”behavior: disabled when properties missing。Action 对应关系useFeeHistory对应的底层 action 为getFeeHistory。当需要在非 React 环境如服务端、事件处理或纯逻辑层执行相同查询时可直接使用 core 的getFeeHistoryaction。常见用法提示查询默认 disabled只有同时提供blockCount与rewardPercentiles查询才会真正执行这两项是必需参数。数值统一使用 bigintblockNumber以及返回数据中的baseFeePerGas、oldestBlock、reward均为bigint展示时需自行转换为可读单位如 gwei/ether。数据刷新策略利用refetchInterval、refetchOnWindowFocus与staleTime控制历史 Gas 数据的时效性对频繁变化的费用信息可设置较短间隔自动刷新。多链查询通过chainId参数针对指定链发起查询适用于多链 Gas 对比场景。缓存隔离通过scopeKey将相同参数但不同业务上下文的查询隔离到不同缓存。【免费下载链接】wagmiReactive primitives for Ethereum apps项目地址: https://gitcode.com/GitHub_Trending/wa/wagmi创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考

读完文章,也想定制专属网站?

尧图设计师 24 小时内与您沟通定制方案

免费获取报价