Cancel Stale Wallet Prompts with Async Generation Checks

本文为原文前 6,000 字符的节选翻译,完整内容请查看原文。

Cancel Stale Wallet Prompts with Async Generation Checks

Originally published on Fone. A canceled authorization review should never open a wallet prompt a moment later. That can happen when a page waits for simulation or an account check, the user cancels, and the old asynchronous function resumes with values it captured before cancellation.

最初发布于 Fone。已取消的授权审查绝不应在稍后弹出钱包提示。当页面等待模拟或账户检查时,如果用户取消操作,而旧的异步函数使用取消前捕获的值恢复执行,就会发生这种情况。

This lab builds a small asynchronous controller that reproduces that race and prevents the stale prompt. The result is a Python program with deterministic tests, including cancellation during the final wallet read. It uses fake callbacks and contains no signing keys, RPC calls or transactions. Download the complete runnable lab.

本实验构建了一个小型异步控制器,用于重现该竞态条件并防止过期的提示。其成果是一个包含确定性测试的 Python 程序,其中包括在最终钱包读取期间的取消操作。它使用模拟回调,不包含任何签名密钥、RPC 调用或交易。请下载完整的可运行实验代码。

The engineering question comes from Agent Wallet Guard’s Owner authorization flow. A source review on 29 October 2026 found a generation check after simulation and another after the final wallet checks, immediately before the transaction path. Its historical local acceptance report also records a cancellation fix. Here we isolate that narrow behavior so you can inspect the timing without running the application stack.

该工程问题源自 Agent Wallet Guard 的所有者授权流程。2026 年 10 月 29 日的源代码审查发现,在模拟之后以及最终钱包检查之后(即交易路径之前),各存在一次代际检查。其历史本地验收报告也记录了一个关于取消操作的修复。在此,我们将这一特定行为隔离出来,以便您无需运行整个应用程序栈即可检查其时序。

Run the race locally Use Python 3.13.3, the version used for this lab’s verification. There are no packages to install. Extract the ZIP, open its directory and run the following commands. python3 preflight.py python3 -m unittest -v

在本地运行竞态测试:请使用本实验验证所用的 Python 3.13.3 版本。无需安装任何软件包。解压 ZIP 文件,打开目录并运行以下命令:python3 preflight.py 和 python3 -m unittest -v。

The demo pauses simulation using an event, cancels the review, then releases simulation. Its output reports stale, zero wallet prompts and the idle phase. No sleep duration determines the result. The test controls exactly when the delayed work is allowed to finish. That detail matters during debugging. A test that waits ten milliseconds and hopes cancellation wins may pass on one machine and fail on another. An event gives the test a specific observation point. The simulated preflight has started, its result has not returned, and cancellation happens inside that interval.

该演示使用事件暂停模拟,取消审查,然后释放模拟。其输出报告为过期状态、零钱包提示以及空闲阶段。结果不由任何睡眠时长决定。测试精确控制了延迟任务何时可以完成。这一细节在调试时至关重要。如果测试仅等待十毫秒并寄希望于取消操作先完成,可能会在某台机器上通过而在另一台机器上失败。事件为测试提供了一个明确的观察点:模拟的预检已经开始,结果尚未返回,而取消操作恰好发生在该时间间隔内。

Capture what the Owner actually reviewed The controller uses a frozen context containing an Owner label, chain ID, deployment label and Session label. These are synthetic identifiers. An integration would use the actual account and contract context required by its authorization protocol. @dataclass(frozen=True) class Context: owner: str chain: int deployment: str session: str

捕获所有者实际审查的内容:控制器使用一个冻结的上下文,其中包含所有者标签、链 ID、部署标签和会话标签。这些是合成标识符。实际集成时,将使用其授权协议所需的真实账户和合约上下文。@dataclass(frozen=True) class Context: owner: str chain: int deployment: str session: str

A chain ID alone cannot describe the entire review. Two deployments can use the same local chain ID, while a page can switch to another Session without changing the connected account. Comparing all four fields lets the exercise detect those separate changes. Each review also receives an increasing generation number. Canceling a review advances that number. Old work can still finish, but it no longer owns the right to open a prompt or reset the current interface. This distinction lets the page begin a new review while an older request is still returning. The number is local control state. It does not travel to a contract and does not grant spending permission. Agent Wallet Guard’s actual Session validation remains a separate part of execution. The existing spending limit article explains that other boundary.

仅凭链 ID 无法描述完整的审查。两个部署可以使用相同的本地链 ID,而页面可以在不更改已连接账户的情况下切换到另一个会话。比较所有四个字段使练习能够检测到这些独立的变更。每次审查还会获得一个递增的代际编号。取消审查会推进该编号。旧任务仍可完成,但它不再拥有打开提示或重置当前界面的权限。这种区分使得页面可以在旧请求仍在返回时开始新的审查。该编号属于本地控制状态,不会传输到合约,也不授予支出权限。Agent Wallet Guard 实际的会话验证仍是执行的独立部分。现有的支出限额文章解释了该边界。

Check again after the last wait The following method is the complete prompt gate from the downloadable controller. simulate, read_wallet and prompt are injected callbacks, which lets the test stop each stage independently. async def confirm(self, ticket, simulate, read_wallet, prompt): generation, reviewed = ticket if generation != self.generation or self.phase != “review”: return “stale” self.phase = “preflight” try: await simulate(reviewed) if generation != self.generation: return “stale” current = await read_wallet() if generation != self.generation: return “stale” if current != reviewed or self.context != reviewed: self.phase = “idle” return “context_changed” # There is no await between the final guard and entering wallet phase. self.phase = “wallet” await prompt(reviewed) self.phase = “submitted” return “submitted” except Exception: if generation == self.generation: # Once invoked, a failed provider response may hide a broadcast. self.phase = “uncertain” if self.phase == “wallet” else “idle” raise

在最后一次等待后再次检查:以下方法是可下载控制器中完整的提示门控。simulate、read_wallet 和 prompt 是注入的回调,这使得测试可以独立停止每个阶段。async def confirm(self, ticket, simulate, read_wallet, prompt): generation, reviewed = ticket if generation != self.generation or self.phase != “review”: return “stale” self.phase = “preflight” try: await simulate(reviewed) if generation != self.generation: return “stale” current = await read_wallet() if generation != self.generation: return “stale” if current != reviewed or self.context != reviewed: self.phase = “idle” return “context_changed” # 在最终防护与进入钱包阶段之间没有 await。 self.phase = “wallet” await prompt(reviewed) self.phase = “submitted” return “submitted” except Exception: if generation == self.generation: # 一旦调用,失败的提供程序响应可能会掩盖广播。 self.phase = “uncertain” if self.phase == “wallet” else “idle” raise

The first check rejects a duplicate confirm call as soon as another call enters preflight. The next check runs after simulation. A further check runs after reading the wallet, because cancellation could have happened during that read too. Passing the earlier check gives no guarantee about later suspended work. Immediately before invoking the prompt, the code compares the returned context with the reviewed context and the controller’s current context. It then moves into the wallet phase without another wait between the final guard and that transition. Within this single asyncio event loop, another task cannot slip a cancellation into that synchronous segment. This is a control-flow guarantee inside the teaching model. A browser wallet and a chain remain separate systems. A real integration must also handle provider account changes and validate the actual transaction. The small controller helps reviewers locate one race; it cannot prove every race in those other systems is absent.

第一次检查会在另一个调用进入预检时立即拒绝重复的 confirm 调用。下一次检查在模拟之后运行。在读取钱包后还会进行进一步检查,因为取消操作也可能发生在该读取期间。通过之前的检查并不能保证后续挂起的任务安全。在调用提示之前,代码会将返回的上下文与审查的上下文以及控制器的当前上下文进行比较。随后,它会进入钱包阶段,且在最终防护与该转换之间没有额外的等待。在当前的 asyncio 事件循环中,其他任务无法在该同步段中插入取消操作。这是教学模型内部的控制流保证。浏览器钱包和链仍然是独立的系统。实际集成还必须处理提供程序账户变更并验证实际交易。这个小型控制器有助于审查者定位一个竞态条件;它无法证明其他系统中不存在所有竞态条件。

Test the latest possible cancellation The most revealing test pauses the final wallet read. Simulation has already passed, which catches an implementation that checks cancellation only after simulation. async def test_cancel_during_last_wallet_read_blocks_prompt(self): entered, release = asyncio.Event(), asyncio.Event() async def slow(): entered.set() await release.wait() return self.context task = asyncio.create_task(self.run_ticket(self.flow.review(), wallet=slow)) await entered.wait() self.flow.cancel() release.set() self.assertEqual(await task, “stale”) self.assertEqual(self.prompts, [])

测试最晚可能的取消操作:最具启发性的测试是暂停最终的钱包读取。模拟已经通过,这可以捕获那些仅在模拟后检查取消操作的实现。async def test_cancel_during_last_wallet_read_blocks_prompt(self): entered, release = asyncio.Event(), asyncio.Event() async def slow(): entered.set() await release.wait() return self.context task = asyncio.create_task(self.run_ticket(self.flow.review(), wallet=slow)) await entered.wait() self.flow.cancel() release.set() self.assertEqual(await task, “stale”) self.assertEqual(self.prompts, [])

Run this test alone while changing the controller. If you remove the generation check after read_wallet, the old continuation can incorrectly open a prompt when the returned context still matches. The test expects zero prompts and therefore fails on the unsafe behavior. Another test delays an old simulation until a fresh review exists, th

在修改控制器的同时单独运行此测试。如果您移除 read_wallet 之后的代际检查,当返回的上下文仍然匹配时,旧的延续任务可能会错误地打开提示。该测试预期零提示,因此会在不安全行为发生时失败。另一个测试将旧的模拟延迟到新的审查存在为止,th