资讯详情

资讯详情

wagmi Tempo `token.useWatchTransfer` Hook 完全指南:在 React 中实时监听 TIP20 代币转账事件

wagmi Tempotoken.useWatchTransferHook 完全指南在 React 中实时监听 TIP20 代币转账事件【免费下载链接】wagmiReactive primitives for Ethereum apps项目地址: https://gitcode.com/GitHub_Trending/wa/wagmi本篇技术指南聚焦于 wagmi Tempo 模块中的Hooks.token.useWatchTransferReact Hook它用于在 TIP20 代币上监听 Transfer 转账事件实现余额变动提醒、交易流水推送、链上监控面板等实时场景。读完本文你将掌握该 Hook 的完整用法、全部参数语义、底层与Actions.token.watchTransfer的调用链关系并能结合源码理解其轮询与事件机制。Hook 概览token.useWatchTransfer是什么token.useWatchTransfer是 wagmi Tempo 面向 React 框架提供的事件监听 Hook声明式地订阅某个 TIP20 代币合约上的Transfer事件。每当有代币发生转账时注入的回调会被触发并携带转账详情与原始日志。从文档原文看其核心语义一句话即可概括Watches for token transfer events on TIP20 tokens监听 TIP20 代币上的转账事件。它属于 Tempo 模块中Hooks.token.*系列的事件类 Hook同类还有useWatchMint、useWatchBurn、useWatchRole、useWatchUpdateQuoteToken等与纯查询类 Hook如useGetBalance和写操作类 Hook如useTransfer、useTransferSync共同构成完整的 TIP20 代币开发工具箱。在 React 组件中使用时它由useEffect驱动组件挂载时开始监听、卸载时自动取消订阅开发者无需手动管理清理函数。快速上手一个可运行的完整示例import { Hooks } from wagmi/tempo function TokenTransferWatcher() { Hooks.token.useWatchTransfer({ onTransfer: (args, log) { console.log(args:, args) }, token: 0x20c0000000000000000000000000000000000000, }) return divWatching for transfers.../div }这是文档给出的基础用法。将 Hook 放在组件顶层调用传入onTransfer回调与token地址后组件渲染期间即开始监听。args为解析后的转账参数log为原始事件日志对象。与 Tempo 模块的其他 Hook 一样使用前需要先配置 wagmi 客户端并接入 Tempo 钱包。仓库内对应的参考配置如下site/snippets/react/config-tempo.tsimport { createConfig, http } from wagmi import { tempo } from wagmi/chains import { tempoWallet } from wagmi/tempo export const config createConfig({ connectors: [tempoWallet()], chains: [tempo], multiInjectedProviderDiscovery: false, transports: { [tempo.id]: http(), }, })配置要点connectors中注册tempoWallet()连接器这是与 Tempo 链交互的前提chains仅包含tempo链transports中为tempo.id配置http()传输通道组件外层还需通过WagmiProvider将config注入 React 上下文Hook 才能从最近的 Provider 中解析配置。参数详解useWatchTransfer的参数类型定义如下见 packages/react/src/tempo/hooks/token.tstype Parametersconfig extends Config Config UnionCompute ExactPartialActions.token.watchTransfer.Parametersconfig ConfigParameterconfig { enabled?: boolean | undefined } 即它完整继承了底层 Actiontoken.watchTransfer的全部可选参数额外叠加了config与enabled两个 React 层专属参数。onTransfer必填类型functiondeclare function onTransfer(args: Args, log: Log): void type Args { /** Amount transferred */ amount: bigint /** Address sending the tokens */ from: Address /** Address receiving the tokens */ to: Address }转账事件触发时被调用的回调。args包含三个字段amount转账数量bigint类型注意不是number、from转出方地址、to接收方地址。第二个参数log是未经解析的原始事件日志可用于获取blockNumber、transactionHash等链上元信息。token必填类型Address | bigint要监听的 TIP20 代币地址或 ID。TIP20 代币既可部署为合约地址Address也可能以代币 IDbigint形式标识两者均可传入。args可选类型objecttype Args { /** Filter by sender address(es) */ from?: Address | Address[] | null /** Filter by recipient address(es) */ to?: Address | Address[] | null }事件过滤器。通过from/to可以只监听特定地址或地址数组参与的转账例如只想追踪某个大户地址的转出行为时可设置{ from: 0x... }。不传则监听该代币全部转账。fromBlock可选类型bigint开始监听的起始区块高度。不传时从当前区块开始传入历史区块号可以从过去某个时点开始重放/补拉事件。onError可选类型functiondeclare function onError(error: Error): void在尝试获取新区块或拉取事件过程中出错时触发的错误回调用于监听异常上报与日志记录。poll可选类型true启用轮询模式。Tempo 链上事件监听默认采用订阅方式当环境不支持订阅或需要兜底时可将poll设为true切换为按固定间隔轮询区块拉取事件。pollingInterval可选类型number轮询频率毫秒。仅在poll开启时生效默认取客户端配置的pollingInterval。config可选类型Config | undefined显式传入Config以覆盖从最近的WagmiProvider中解析到的配置。适用于需要在多个配置实例间切换或脱离 Provider 上下文的场景。enabled可选类型boolean默认trueReact 层特有的开关。为false时 Hook 不会建立监听可用于等待用户授权后再开始监听这类条件化场景。事件监听参数速查表参数类型必填默认值说明onTransferfunction是—转账回调参数为(args, log)tokenAddress \| bigint是—TIP20 代币地址或 IDargs.fromAddress \| Address[] \| null否—按转出方过滤args.toAddress \| Address[] \| null否—按接收方过滤fromBlockbigint否当前区块起始监听区块onErrorfunction否—拉取新区块出错回调polltrue否订阅模式切换为轮询模式pollingIntervalnumber否客户端配置轮询间隔msconfigConfig \| undefined否Provider 解析覆盖全局配置enabledboolean否true是否启用监听源码解析Hook 到 Action 的完整调用链useWatchTransfer并非独立实现而是对 core 层 ActionActions.token.watchTransfer的 React 封装。其实现位于 packages/react/src/tempo/hooks/token.tsexport function useWatchTransfer config extends Config ResolvedRegister[config], (parameters: useWatchTransfer.Parametersconfig {}) { const { enabled true, onTransfer, token, ...rest } parameters const config useConfig({ config: parameters.config }) const configChainId useChainId({ config }) const chainId parameters.chainId ?? configChainId useEffect(() { if (!enabled) return if (!onTransfer) return if (!token) return return Actions.token.watchTransfer(config, { ...rest, chainId, onTransfer, token, }) }, [ config, enabled, chainId, token, onTransfer, rest.fromBlock, rest.onError, rest.poll, rest.pollingInterval, ]) }其内部逻辑清晰可拆解为四步参数解构将enabled、onTransfer、token从参数中剥离其余参数fromBlock、poll、pollingInterval、args过滤器等保留在rest中透传配置解析通过useConfig获取配置通过useChainId获取当前链 ID未显式指定chainId时默认使用当前激活链守卫条件enabled、onTransfer、token三者任一缺失即不建立监听保证 Action 调用参数完整副作用订阅在useEffect中调用Actions.token.watchTransfer(config, {...})并将其返回值取消订阅函数作为 effect 清理函数返回——这是 React 事件监听的经典模式组件卸载或依赖变化时自动执行unwatch()释放订阅。依赖数组显式列出了会影响订阅行为的参数其中任一项变化都会触发重新订阅。再看 core 层 Action 的实现packages/core/src/tempo/actions/token.tsexport function watchTransferconfig extends Config( config: config, parameters: watchTransfer.Parametersconfig, ) { const { chainId, ...rest } parameters const client config.getClient({ chainId }) return Actions.token.watchTransfer(client, rest) }它从config.getClient({ chainId })取出对应链的 viem 客户端再委托给 viem 层的token.watchTransfer完成实际的链上事件订阅。也就是说完整的调用链是React Hook (useWatchTransfer) → wagmi/core Action (Actions.token.watchTransfer) → viem Client (token.watchTransfer) → Tempo 链 RPC 订阅 / 轮询返回值约定为() void即一个取消订阅函数。这正是 Hook 层能将其作为 effect cleanup 使用的前提。实战转账监控 交易触发闭环结合文档中提到的两个关联 Action可以在一个组件内完成监听 → 触发的闭环。先看 Hook 的官方测试用例packages/react/src/tempo/hooks/token.test.ts它展示了完整的数据流const events: any[] [] await renderHook(() hooks.useWatchTransfer({ onTransfer(args) { events.push(args) }, token: addresses.alphaUsd, }), ) // Trigger transfer event await connectResult.current.transferSync.mutateAsync({ to: account2.address, amount: parseUnits(5, 6), token: addresses.alphaUsd, }) await vi.waitUntil(() events.length 1) expect(events[0]?.from).toBe(account.address) expect(events[0]?.to).toBe(account2.address) expect(events[0]?.amount).toBe(parseUnits(5, 6))测试流程验证了先通过useConnect连接 Tempo 钱包再挂载useWatchTransfer监听alphaUsd代币随后用useTransferSync触发一笔 5 USDT 的转账最终断言回调收到的from、to、amount与实际转账一致。这证明该 Hook 的监听-回调链路是完整可验证的。基于此模式一个实际的实时到账提醒组件可以这样写import { Hooks } from wagmi/tempo import { formatUnits } from viem function TransferFeed({ tokenAddress }: { tokenAddress: 0x${string} }) { Hooks.token.useWatchTransfer({ token: tokenAddress, onTransfer(args) { console.log( ${formatUnits(args.amount, 6)} transferred from ${args.from} to ${args.to}, ) }, onError(error) { console.error(watch transfer failed:, error) }, }) return div监控已开启等待转账事件.../div }若要停止监听从源码可知只需让组件卸载或在enabled为false时自动清理若在非 React 环境如纯 TypeScript 脚本中使用则应直接调用Actions.token.watchTransfer并手动保存、调用返回的unwatch函数。关联 Action 导航本文 Hook 直接对应以下底层 Action 文档读者可按需深入token.watchTransfer ActionHook 的底层实现含完整的返回类型与参数签名token.transfer Action发起 TIP20 转账的写操作可配合监听实现发起后确认到账Tempo 入门指南了解 Tempo 链、TIP20 标准与整体接入流程Tempo Hooks 索引查看Hooks.token.*全部 Hook 清单。小结token.useWatchTransfer将 Tempo 链上的 TIP20 转账事件以声明式 Hook 的形式接入 React内部由useEffect生命周期托管订阅与清理参数面完整继承了底层 Action 的onTransfer、token、args过滤器、fromBlock、onError、poll、pollingInterval并额外提供config与enabled两个 React 层控制项。理解其Hook → Core Action → viem Client的三层委托链即可在需要时自由地在声明式 Hook 与命令式 Action 之间切换构建出健壮的链上实时监控应用。【免费下载链接】wagmiReactive primitives for Ethereum apps项目地址: https://gitcode.com/GitHub_Trending/wa/wagmi创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考
觉得有用,分享给同行:

为您的企业打造数字门面

稳重轻奢商务风格,端正雅致视觉,长效耐看不易过时。

立即咨询 →