
wagmi Tempo 中 token.watchBurn 完全指南订阅 TIP20 代币销毁事件【免费下载链接】wagmiReactive primitives for Ethereum apps项目地址: https://gitcode.com/GitHub_Trending/wa/wagmi本篇技术指南以 wagmi 仓库中 token.watchBurn 文档 为主体深入讲解如何在 Tempo 链上通过Actions.token.watchBurn订阅 TIP20 代币的销毁Burn事件。读完本文你将掌握该监听 API 的完整调用签名、全部可选参数的含义与默认行为、事件回调的数据结构并理解它在wagmi/core底层是如何借助 viem 实现的以及 React 侧Hooks.token.useWatchBurn的对应封装与测试用例验证。背景Tempo 与 TIP20 代币销毁事件Tempo 是一条专注于支付的 Layer 1 区块链协议内直接内建了代币管理TIP20、Fee AMM、稳定币 DEX 等能力。TIP20 是 Tempo 上的代币标准其合约会在代币被销毁时发出Burn事件——无论是用户主动调用token.burn销毁自己的余额还是由burnBlocked等受限操作触发。token.watchBurn就是 wagmi 为订阅这类事件提供的监听 Action。在 wagmi 中Tempo 相关能力通过两个入口暴露Reactimport { Actions } from wagmi/tempoCoreimport { Actions } from wagmi/core/tempo两者导出同一套Actions.token命名空间其中包含watchBurn、watchMint、watchCreate、watchTransfer等事件监听方法可参见 site/tempo/actions/index.md 的完整索引。在开始之前需要先按 Tempo 快速上手指南 完成项目初始化并确保 viem 版本满足要求。基本用法注册与注销 Burn 事件监听Actions.token.watchBurn的典型用法如下来源于 原文档 的示例import { Actions } from wagmi/tempo import { config } from ./config const unwatch Actions.token.watchBurn(config, { token: 1n, // or token address onBurn(args, log) { console.log(args:, args) }, }) // Later, stop watching unwatch()其中config是 wagmi 的配置对象直接复用仓库中的 config-tempo.ts 示例 即可import { 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(), }, })注意该配置的两个关键点chains: [tempo]将 Tempo 链挂载进 configtransports[tempo.id]使用http()作为默认 JSON-RPC 传输通道multiInjectedProviderDiscovery: false关闭多注入提供方探测只显式使用tempoWallet()连接器避免非 Tempo 钱包干扰事件监听所依赖的连接。token参数既可以是代币 IDbigint如1n也可以是代币合约地址Address两种形式等价地定位到目标 TIP20 代币。返回类型一个用于退订的函数Actions.token.watchBurn的返回类型是() void。调用后立即返回一个取消订阅函数调用它即可停止监听、释放底层轮询或订阅资源。因此推荐的用法是像上面的示例一样把返回值保存为unwatch在组件卸载、页面离开或业务不再需要时调用它避免事件监听持续泄漏。在 React Hook 封装中见下文这个退订函数由useEffect的清理函数接管开发者无需手动管理。参数详解token.watchBurn接收一个参数对象各字段如下均继承自 原文档 并补充了类型与行为说明。onBurn必填类型function签名declare function onBurn(args: Args, log: Log): void type Args { /** Address whose tokens were burned */ from: Address /** Amount burned */ amount: bigint }args.from被销毁代币的持有者地址即销毁事件的触发来源args.amount销毁数量以bigint表示单位遵循代币自身的小数位数例如测试中使用的parseUnits(10, 6)表示销毁 10 个 6 位小数的代币log对应的原始日志对象Log类型包含区块号、交易哈希、日志索引等链上元信息。回调在每次监听到新的Burn事件时被触发args已解析为结构化数据无需手动解码 ABI。token必填类型Address | bigint含义TIP20 代币的合约地址或代币 ID。args可选类型object签名type Args { /** Filter by burner address */ from?: Address | Address[] | null }from按销毁者地址过滤事件。可以传单个地址、地址数组或null。传入后只有from匹配的事件才会触发onBurn回调。当需要同时监听多个账户的销毁时使用地址数组最方便。fromBlock可选类型bigint含义从哪个区块开始监听。不传时通常从最新区块开始适合“从现在起监听新事件”的场景若需要回看历史销毁记录则指定起始区块号。onError可选类型function签名declare function onError(error: Error): void含义当尝试获取新区块轮询模式下或拉取日志失败时调用的错误回调。事件监听属于持续运行的任务网络抖动、RPC 节点故障都可能抛出错误务必提供onError以捕获并记录异常避免静默失败。poll可选类型true含义启用轮询模式。token.watchBurn默认采用基于 RPC 的订阅机制当运行环境不支持订阅如某些 HTTP-only 传输时将poll: true打开即可切换到定时轮询新区块的方式。pollingInterval可选类型number含义轮询频率毫秒。仅在轮询模式下生效默认值取 Client 上配置的pollingInterval。也就是说如果全局 Client 已统一设置了轮询间隔可以省略该参数它会自动继承。源码实现从 wagmi Config 到 viem 的透传token.watchBurn在wagmi/core中的实现非常精简位于 packages/core/src/tempo/actions/token.ts#L2447-L2459export function watchBurnconfig extends Config( config: config, parameters: watchBurn.Parametersconfig, ) { const { chainId, ...rest } parameters const client config.getClient({ chainId }) return Actions.token.watchBurn(client, rest) } export declare namespace watchBurn { export type Parametersconfig extends Config ChainIdParameterconfig Actions.token.watchBurn.Parameters }从源码结构可以看出它的调用链与设计意图参数拆分从参数对象中解构出chainId其余全部参数token、onBurn、args、fromBlock、onError、poll、pollingInterval等原样透传获取客户端通过config.getClient({ chainId })拿到对应链的 viem Client。不传chainId时使用当前激活链的 Client因此多链配置下监听会自动跟随当前链委托给 viem最终调用 viem 的Actions.token.watchBurn(client, rest)完成实际的日志订阅。这意味着 wagmi 层不重复实现订阅逻辑事件解码、轮询调度、退订清理全部由 viem 负责wagmi 只负责把Config与链绑定关系正确接入。测试用例验证仓库为watchBurn提供了端到端测试位于 packages/core/src/tempo/actions/token.test.ts#L1113-L1160完整覆盖了“注册监听 → 触发事件 → 断言回调参数 → 退订”的闭环describe(watchBurn, () { test(default, async () { await connect(config, { connector: config.connectors[0]! }) // Create a new token const { token: tokenAddr } await token.createSync(config, { currency: USD, name: Watch Burn Token, symbol: WATCHBURN, }) // Grant issuer role and mint tokens await token.grantRolesSync(config, { token: tokenAddr, roles: [issuer], to: account.address, }) await token.mintSync(config, { token: tokenAddr, to: account.address, amount: parseUnits(1000, 6), }) const events: any[] [] const unwatch token.watchBurn(config, { token: tokenAddr, onBurn: (args) { events.push(args) }, }) // Trigger burn event await token.burnSync(config, { token: tokenAddr, amount: parseUnits(10, 6), }) await vi.waitFor(() { expect(events.length).toBeGreaterThan(0) }) unwatch() expect(events[0]?.from).toBe(account.address) expect(events[0]?.amount).toBe(parseUnits(10, 6)) }) })这段测试可以印证三个事实事件驱动是异步的burnSync提交销毁交易后需要配合vi.waitFor等待事件异步到达回调参数被收集进events数组回调参数结构断言events[0].from等于执行销毁的账户地址、events[0].amount等于parseUnits(10, 6)与文档中Args的from/amount字段一一对应退订有效性unwatch()调用后监听停止事件收集过程随之结束。测试还展示了完整的前置流程创建代币createSync→ 授权发行人角色grantRolesSync→ 铸币mintSync→ 销毁burnSync说明watchBurn监听的事件正是burnSync/burn这类销毁交易上链后发出的日志。React 侧封装Hooks.token.useWatchBurn对于 React 应用不需要手动管理unwatch。仓库在 packages/react/src/tempo/hooks/token.ts#L2619-L2650 提供了Hooks.token.useWatchBurn把监听生命周期交给useEffectexport function useWatchBurn config extends Config ResolvedRegister[config], (parameters: useWatchBurn.Parametersconfig {}) { const { enabled true, onBurn, token, ...rest } parameters const config useConfig({ config: parameters.config }) const configChainId useChainId({ config }) const chainId parameters.chainId ?? configChainId useEffect(() { if (!enabled) return if (!onBurn) return if (!token) return return Actions.token.watchBurn(config, { ...rest, chainId, onBurn, token, }) }, [config, enabled, chainId, token, onBurn, rest.fromBlock, rest.onError, rest.poll, rest.pollingInterval]) }该 Hook 的使用示例来源于 site/tempo/hooks/token.useWatchBurn.md 对应的源码 JSDocimport { Hooks } from wagmi/tempo function App() { Hooks.token.useWatchBurn({ onBurn(args) { console.log(Burn:, args) }, }) return divWatching for burns.../div }从源码可以提炼出 Hook 的四个行为细节自动依赖跟踪useEffect的依赖数组显式列出fromBlock、onError、poll、pollingInterval这些参数变化时会自动重订阅惰性启动enabled默认true、onBurn、token三者缺一即不启动监听可用来实现“连接钱包后才开始监听”等条件订阅场景链跟随未显式传chainId时使用useChainId的当前激活链链切换时自动重订阅自动清理useEffect返回Actions.token.watchBurn的unwatch函数作为清理函数组件卸载时自动退订杜绝内存泄漏。相关资源事件监听同族 APItoken.watchMint.md、token.watchCreate.md、token.watchTransfer.md、token.watchApprove.md销毁交易入口token.burn.md主动销毁、token.burnBlocked.md受限地址销毁Tempo 系列总览site/tempo/actions/index.md、site/tempo/hooks/index.md环境准备Tempo 快速上手、React 入门指南、Core 入门指南源码与测试core 实现、core 测试、React Hook 实现【免费下载链接】wagmiReactive primitives for Ethereum apps项目地址: https://gitcode.com/GitHub_Trending/wa/wagmi创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考