AI Agent 付款前先查證交易對手,付款後記錄處理結果
Before Our Agent Pays, It Phones a Friend - and After It Pays, It Writes Down What Happened
團隊為以加密貨幣支付 x402 API 呼叫的 AI Agent 加入付款前查證及付款後記錄:簽署前向獨立服務 vet402 核對賣家與實際付款條款,結算後則把處理結果寫入經濟帳本。vet402 提供 ALLOW、WARN、BLOCK 等判定,但不代替團隊作政策決定;條款不符或服務無法連線時不會猜測放行,付款結果不確定則由人工核對。
Canonical post lives at https://agentbadge.xyz/blog/arc-c58-counterparty-trust
Before Our Agent Pays, It Phones a Friend - and After It Pays, It Writes Down What Happened
Short answer: an AI agent paying for an API call with crypto is flying blind - the money leaves before anyone asks "is this seller real, and is this the same deal I was quoted yesterday?" So we wired our payment path to an independent counterparty measurer (vet402) before signing, and started keeping our own journal of what paid handlers actually did after settlement. Two evidence loops, one before the money, one after. Neither trusts the other side's word.
This is part of the Arc campaign series. Previous episode: we let an agent swap EURC for USDC into its own budget vault (EPIC-254 - crash-safe DEX funding). This article is EPIC-257: counterparty trust for x402 payments.
The problem: an x402 payment is a coin flip you cannot take back
For a junior: x402 is the protocol where an API answers your request with 402 Payment Required - "pay this much crypto to this address, come back with a receipt, and I'll give you the answer." Our agent does this dozens of times a day.
Here is the uncomfortable part. Everything in that flow is self-reported by the seller: the price, the address, the asset. Until now our agent read the challenge and paid it, no questions asked. That is three separate risks wearing one coat:
- Is this seller real? Anyone can host a 402 endpoint, collect a payment, and return garbage or nothing. Crypto has no chargeback.
- Is this the same deal as before? A seller that was honest last week can answer today's challenge with a different address or a 10x price. Checking "reputation by URL" does not catch a swapped destination account.
- What happened after we paid? On the seller side, settlement proves the money moved - it says nothing about whether the content was actually delivered. That fact existed nowhere.
The measurer, not the judge
vet402 is an independent service that does one thing: it buys from catalog-listed x402 endpoints itself, records what happened, and serves those measurements over a keyless public API. No keys, no accounts, no "trust us."
Important distinction, because it shapes everything downstream: vet402 is a measurer, not a judge. It reports a verdict (ALLOW / WARN / BLOCK) plus the terms it actually paid and verified - the real payTo, asset, amount, network, scheme. What we do with those facts is our own policy decision. Their job is evidence. Our job is the consequence.
Loop one: check before you pay
The gate sits in buyPay after the envelope checks and before the CLI spawn - meaning before signing, where refusing costs nothing:
-
Sanitize first. Before a single byte goes to vet402, the resource URL is scrubbed: query strings, fragments, embedded credentials, and secret-looking path segments are all refused locally. A URL carrying
?api_key=...produces zero outbound calls and parks itself for the owner. Nothing secret ever leaves. - Resolve and decide. The client asks vet402 for the endpoint's resource id, then for the payer-side decision. Caches, singleflight (ten parallel checks on one URL produce one outbound call), a per-process rate limiter, and hard timeout budgets - because this sits in a payment path.
-
Compare the deal, not the vibes. We take the actual
accepts[]offer the CLI will sign and compare it field-by-field against the terms vet402 verified - exact equality in v1. DifferentpayTo: denied. Higher amount: denied. Lower amount: also denied - a substituted deal is a substituted deal. -
Apply the matrix. Verdict × terms-match → four outcomes:
allow(pay now),hold(park for the owner),deny(refuse),unavailable(vet402 unreachable - a retryable preflight, never a reason to guess).
The matrix is deliberately fail-closed. A BLOCK verdict beats every combination of terms state - even when vet402 reports its own data as degraded. An unknown seller is not a silent pass; it is a hold, and a human decides.
Approvals are bound to the exact deal
Here is the part I would have gotten wrong. A WARN parks an approval request for the owner. Naively, that approval is "the owner allowed a payment from this wallet" - which an attacker (or a drifting seller) could redeem against any offer.
Ours is fingerprint-bound: the approval carries sha256:v1 over (wallet, url, the exact offer). When the owner approves and the payment retries, the permit is consumed atomically only if this quote's fingerprint re-derives to the same value. Approved deal A, deal becomes B: the consume refuses without consuming anything. Two parallel payments racing the same permit: exactly one wins - the transition is a single-use atomic approved → consumed, enforced all the way down to a Postgres partial unique index on (wallet, fingerprint, pending).
And because money is involved, one more rule: unavailable is a preflight answer. It can be retried - as a fresh check. What is never retried through this machinery is money movement itself. Once the permit is consumed and the payment CLI dies mid-flight, the record says uncertain - humans reconcile, code does not re-sign.
Loop two: our own journal of what happened next
vet402 can never see the second contour: what our handlers did with our paid requests. So we keep the fact ourselves - an x402_fulfillment event appended to the economic ledger after the paid handler returns, keyed ev:x402:{usageRecordId}~fulfill:1 so replays deduplicate.
The honest part is the outcome vocabulary. The event records what we observed, nothing more:
-
handler_completed- the handler returned a fully materialized 2xx -
upstream_error- a 5xx or a thrown handler -
stream_aborted- only on a real client-abort signal -
unknown- anything without a reliable completion signal. A streaming response (SSE, chunked) whose headers say 200 isunknown, nothandler_completed- headers going out is not proof the stream delivered.unknownis never quietly upgraded to success.
Two properties worth calling out. The event is deliberately not a trust edge: it carries no counterparty and no amount, so it cannot leak into exposure aggregation or revenue math - it is evidence, not a vote. And emission is truly fire-and-forget: if the ledger write fails, the paid response is still 200, the complete serialized event lands in the warn log, x402_fulfillment_emit_failed_total ticks up, and a replay script re-appends the record verbatim - deduplicated by the same idempotency key.
How we rolled it out
COUNTERPARTY_CHECK_MODE=off | shadow | enforce. Shadow mode evaluates and logs every decision - the same decision enforce would apply - but lets the payment through: that is the canary for a rollout that wants one. We went straight to enforce - the matrix had already been exercised end-to-end, and fail-closed is the honest default for code that gates money. Dev and test still default to off so unrelated suites never depend on the network.
What production showed on day one — enforce mode, real traffic:
- An unknown seller was held before signing: the CLI reported
not_in_catalog → unmeasured → holdand exited without producing a signature. No catalog listing means friction, not a silent pass - exactly what the matrix says. - A real $0.02 USDC payment settled on Arc mainnet through the GatewayWalletBatched rail (tx
8f3a3d9d-…), the handler returned 200, and the ledger gained exactly onex402_fulfillmentrow:handler_completed, httpStatus 200, anchored to the settlement id as its requestId. Zero trust edges were created from it; revenue totals (kind='pay') are untouched.
Externally reviewed
Arc Studio audited the counterparty path before ship. Verdict: request changes - 2 criticals, 8 highs, 10 mediums. The criticals were real, and both were the kind of bug a green test suite will never show you:
-
"Signed ≠ vetted." The CLI picked which
accepts[]entry to sign after the terms check - so it could pay a different deal than the one that was vetted. Now the whole selected offer is bound into the fingerprint. -
Approval lifecycle races. Parked approvals could livelock, and a consume that wasn't atomic across processes let two payments redeem one permit. Now park/commit is explicit and the
approved → consumedtransition is atomic all the way down to a Postgres partial unique index.
The highs were the same genre: the URL sanitizer missed capability-URL forms (privacy boundary), a "refused" classification that could auto-retry after signature (money-path taxonomy), and a stream-detector that quietly upgraded streamed 200s to handler_completed (fulfillment honesty). All criticals, highs and mediums landed across seven remediation slices; what remains is documented nits. The audit did its job - it found the holes our own review was blind to.
The honest limits
- vet402 only measures endpoints in the public catalogs it syncs (CDP Bazaar, Circle discovery, MPP directory). If a seller is not listed, there is no assessment to read - the answer is a hold, not a pass. Visibility is earned through the catalogs, not applied for.
- Terms matching is exact in v1. A seller quoting a lower price than verified still mismatches - deliberate: any substitution is a new deal that deserves a new look.
- Fulfillment evidence is advisory in v1. It does not auto-block sellers and it does not gate settlement - it builds the record those future decisions can stand on.
What is verified today
25 end-to-end tests run the full buyer path against a real Vet402Client pointed at a hermetic mock vet402 server - every row of the acceptance matrix: exact-offer pay, payTo/amount substitution denials, multi-offer selection, WARN→hold→approve→consume→pay, parallel holds deduplicating to one approval, fingerprint-mismatch consumes refusing, timeout/429/500 → retryable unavailable, cache and singleflight outbound counts, secret-URL zero-outbound, and the two-payments-one-fingerprint race ending in exactly one consume. On the seller side: 5xx records upstream_error, SSE streams record unknown, and a failed ledger append still returns 200 with the full replayable event in the log. 46 buy-domain tests, 47 gateway tests, 169 package counterparty/buyer tests, 33 policy-matrix cells, 124 schema tests, 72 approval-backend tests underneath it all.
What is not here: a replay drill against a synthetic ledger failure on production (the warn-log/replay machinery is tested locally), and the WARN→hold→approve→pay dance with a real external seller - the one case production has not produced yet, because our first real seller was not in vet402's catalog at all.
Read the arc: x402 payment gateway · agent commerce · trust layers · A2A settlement · EURC→USDC funding
來源:DEV Community · dev.to







