Free-Riding in the AI Economy:
Demystifying Logic Flaws in x402-Enabled Payment Systems
May 29, 2026
The agentic economy demands programmatic financial rails, positioning the x402 protocol as the de facto standard for machine-to-machine payments. However, bridging synchronous HTTP requests with asynchronous blockchain finality introduces profound state synchronization challenges. In this work, we perform the first comprehensive security analysis of the x402 ecosystem. By formalizing five Security Invariants, we reveal that current implementations fail to enforce transactional atomicity and cryptographic context binding, leading to systemic vulnerabilities.
We identify a semantic gap in signature design enabling cross-resource substitution, where payment proofs are transplanted to other unauthorized contexts. Furthermore, we expose a temporal gap where concurrency race conditions allow probabilistic service duplication. In the AI inference domain, we demonstrate how dynamic pricing models are vulnerable to allowance overdrafts and infrastructure rate limits. We validate these vulnerabilities against official SDKs and live deployments. Specifically, we show that attackers can exploit the synchronization gap in dynamic authorization schemes to force merchants to subsidize compute costs, achieving a resource leakage ratio of up to 100% on production middleware. Finally, we propose architectural mitigations, advocating for request-bound signatures and pessimistic state locking to secure the financial rails of autonomous agents. All discovered issues have been disclosed to Coinbase and ThirdWeb.
The rapid evolution of Large Language Models (LLMs) is catalyzing a paradigm shift from human-centric web interaction to an agent-to-agent (A2A) economy, where autonomous systems dynamically compose services, negotiate access, and procure computational resources without human intervention. In this nascent ecosystem, traditional authentication mechanisms, which are reliant on persistent sessions, manual approvals, or centralized credit rails, create friction that hinders true autonomy.
To address this, the x402 protocol [1] has emerged as a critical infrastructure. By standardizing the HTTP 402 “Payment Required” status code with cryptographic primitives, x402 provides a stateless, permissionless economic interface, enabling agents to programmatically authorize resource transfer using digital assets. This infrastructure transforms payment from a distinct post-service settlement event into an intrinsic part of the resource negotiation.
The significance of x402 extends beyond theoretical utility; it has established itself as the de facto financial standard for the agentic web. Since its publication by Coinbase in May 2025 [3], the protocol has garnered support from major industry partners including Google Cloud [4], AWS [5], Cloudflare [6], and Anthropic [7], alongside financial integration with Visa [8]. Empirical data underscores this extensive adoption. According to on-chain analytics from Dune [2], x402 transaction volume has exhibited exponential growth, surging from a mere 725 transactions in its launch month (May 2025) to approximately 50 million transactions by the end of 2025 (Fig. 1). This represents a staggering month-over-month growth rate, peaking at over \(10,000\%\). This rapid ascent transforms x402 from a niche experiment into a critical economic rail processing substantial value. Consequently, any security vulnerability in this layer creates a systemic risk, potentially affecting millions of transactions and exposing service providers to scalable economic exploitation.
| Threat | Invariant violated | Vulnerable layer | Impact | Section |
|---|---|---|---|---|
| Onchain front-running attack | Payment Integrity (I1) | Blockchain state | Settlement failure | Sec. 4.1 |
| Cross-resource substitution | Context Binding (I3) | Verification logic | Resource swapping | Sec. 4.2 |
| Probabilistic service duplication | Authorization Uniqueness (I4) | Backend concurrency | Resource duplication | Sec. 4.3 |
| Allowance overdraft | ||||
| Execution Conservation (I5) | Authorization state | Subsidized compute | Sec. 5.2 | |
| Denial of settlement | Payment Integrity (I1) | Infrastructure config | Free-riding | Sec. 5.3 |
However, the operationalization of this protocol introduces profound challenges in distributed system coordination. Implementing x402 requires bridging two disparate state machines: 1) the synchronous, ephemeral request-response cycle of web servers, and 2) the asynchronous, probabilistic finality of public blockchains. To reconcile these conflicting latency requirements, implementations typically adopt a decoupled, tripartite architecture mediated by a third-party “Facilitator”. This intermediary layer orchestrates the asynchronous transition from off-chain logical verification of payment intent to on-chain immutable settlement of funds, effectively abstracting trivial blockchain interactions away from the merchant’s path. While this design facilitates the high throughput for AI inference and web APIs, it compromises the atomicity guarantees traditionally afforded by database transactions. This research uncovers that this architectural dissonance creates a state synchronization gap, exposing the payment logic to race conditions and semantic inconsistencies that systematically undermine the protocol’s security guarantees.
To rigorously and systematically evaluate the security posture of such payment systems, we propose that a secure implementation must uphold a set of five fundamental Security Invariants. Specifically, the system must guarantee Payment Integrity (delivery implies on-chain settlement), Value Consistency, Context Binding (payment is bound to the specific resource), Authorization Uniqueness, and Execution Conservation (computational work is backed by secured value). Violation of these invariants can break the economic trust model: merchants may deliver resources without payment, or shoppers may have their authorized credits misappropriated for unintended services.
Guided by this formal framework, we perform the first comprehensive security audit of the x402 protocol. We demonstrate that the violation of these security invariants effectively dismantles the economic trust model in multiple aspects. Specifically, we contrast the theoretical requirements against the operational reality of official SDKs and live AI-agent middlewares. Our analysis reveals that current implementations systematically violate these invariants.
Protocol design flaws: We identify a critical semantic gap in the payment authorization standard. Cryptographic signatures in x402 are context-agnostic, binding funds only to a merchant address rather than a specific resource identifier.
This allows attackers to bypass Context Binding (I3) by transplanting valid proofs from one request to another target (Section 4.2).
Concurrency logic failures: At the implementation level, we reveal that the decoupling of verification and settlement introduces a temporal race window. By exploiting the lack of atomic locking in the Facilitator, attackers can concurrently
utilize a single nonce to procure multiple service instances, violating Authorization Uniqueness (I4) with a significant success probability (Section 4.3).
AI-specific state drifts: In the emerging AI economy, we find that the necessary shift to dynamic pricing (using upto allowances) fundamentally breaks Value Consistency (I2) and Execution Conservation
(I5). We demonstrate two additional security flaws where attackers weaponize the discrepancy between verification and asynchronous settlement to force merchants into subsidizing unlimited compute costs at scale (Section 5.2).
Our findings are summarized in Table 1. We highlight that these issues allow attackers to arbitrarily manipulate payment intent, duplicate service delivery, and exhaust computational resources at scale. We have responsibly disclosed these issues to the relevant vendors and protocol maintainers, including Coinbase and Thirdweb.
In summary, this paper makes the following contributions:
We formalize the x402 protocol’s workflow and define a set of five Security Invariants necessary to ensure security in hybrid agentic systems.
We uncover two critical logic flaws, revealing the gap between protocol design and SDK implementations: cross-resource substitution (intent manipulation via context-agnostic signatures) and probabilistic service duplication (nonce reuse via concurrency races).
We extend our analysis to the dynamic pricing model of AI agents, identifying novel attack surfaces in the upto authorization scheme. We demonstrate how these features can be weaponized to trigger deterministic allowance
overdrafts.
We propose architectural mitigations with different tradeoffs, spanning protocol enhancements for context binding, pessimistic state locking for atomicity, and failure-closed patterns for resilience.
The remainder of this paper is organized as follows. Section 2 provides the background on the x402 protocol and literature related work in payment system security. Section 3 formalizes the system model and defines the security invariants. We then analyze the logic vulnerabilities in the core protocol and SDKs in Section 4, followed by a dedicated study on the AI inference economy in Section 5. Section 6 discusses mitigation strategies and security recommendations. Finally, Section 7 concludes the paper.
The emergence of the agent economy necessitates a payment infrastructure distinct from human-centric e-commerce. Traditional “authorize-capture” models, which rely on asynchronous credit card holds and manual dispute resolution (chargebacks), are ill-suited for the high-frequency and automated nature of AI agents.
To address this, Coinbase introduced the x402 protocol in 2025 [3], leveraging the HTTP 402 “Payment Required” status code to embed payment instructions directly within the application layer. This proposal enables a pay-per-call model through the following interaction steps (Fig. 2):
Payment initiation (steps 1-2): When a client requests a protected resource, the server responds with an HTTP 402 status. The response body includes a PaymentRequirements JSON object, which specifies access terms such
as the token contract, recipient address, required amount, and a cryptographic nonce.
Payload construction (step 3): The client constructs a payment payload adhering to EIP-712, and then resubmits the request to the server with the signed payload in the HTTP headers.
Verification, execution, and settlement (steps 4-11): The server delegates verification of the signature and on-chain balance to a centralized Facilitator (steps 4-5). Upon successful verification, the server initiates the work or resource preparation (step 6) before or concurrently with the settlement process (steps 7-10).
The concept of embedding payments into the HTTP was first operationalized by the L402 protocol (formerly LSAT) [9]. Built upon the Bitcoin Lightning Network, L402 combines Macaroons (bearer tokens) with payment preimages to enforce a strictly “pay-to-access” model. In this architecture, the cryptographic proof of a micro-payment serves directly as the authentication credential, eliminating the need for accounts or API keys.
While L402 pioneered the semantics of stateless, machine-to-machine payments, it has faced significant hurdles in mass adoption. The complexity of managing Lightning Network channels (liquidity management), the limited programmability of Bitcoin scripting compared to smart contracts, and the high friction of specialized wallet infrastructure have constrained its utility primarily to Bitcoin-native niches.
The security of the emerging agent economy sits at the intersection of e-commerce payment logic and agentic system infrastructure. We review the literature across these domains to contextualize our contributions.
The tripartite interaction model within the e-commerce system (i.e., Merchant, Shopper, and Cashier) is a perennial source of logic flaws. Wang et al. [10] first formalized the “Cashier-as-a-Service (CaaS)” threat model, demonstrating how the lack of atomic state synchronization allows shoppers to exploit semantic gaps (e.g., price alteration, transaction ID reuse) for free shopping. Subsequent studies [11], [12] proposed defense mechanisms using invariant monitoring and symbolic execution to detect state inconsistencies. Yang et al. [13] extended this to mobile ecosystems, i.e., Android in-app payments, revealing that developers frequently misunderstand SDK documentation, leading to insecure client-side verification. Similarly, Lou et al. [14] analyzed the misuse of personal transfer interfaces for commercial payments, identifying several vulnerability patterns; Do et al. [15] analyzed W3C Web Payment APIs, identifying specification flaws that allowed overcharging. More recently, Pagey et al. [16] showed that multi-tenant SaaS platforms often fail to enforce resource-level access control, allowing cross-merchant price manipulation.
Our work revisits these classic integration vulnerabilities but within the novel x402 context. Here, the centralized “Cashier” is replaced by a hybrid of a Facilitator and a Blockchain, introducing new variables such as gas limits, block latency, and infrastructural rate limits that were not present as first-class considerations in prior studies.
As AI agents evolve, the integrity of their interaction protocols becomes paramount. The Model Context Protocol (MCP) [17] has emerged as a standard for tool interoperability, yet recent analyses [18] highlight that this design prioritizes connectivity over security boundaries. This exposes agents to tool poisoning attacks, where malicious metadata hijacks the agent’s reasoning process to exfiltrate data. Benchmarks like AgentHarm [19] evaluate an agent’s propensity for malice or resistance to jailbreaks across multi-step tasks. However, these studies do not account for infrastructure-level fragility, and the underlying settlement logic remains under-scrutinized.
Our work bridges this gap by auditing the financial rails directly. We demonstrate that even benign, compliant agents can cause catastrophic economic loss due to semantic gaps. By formalizing the x402 state machine, we extend structural auditing to identify invariant violations specific to this automated economic interface.
In this section, we formalize the x402 payment workflow and define the security invariants that a secure implementation must satisfy. We adopt a modeling approach inherited from Wang et al. [10], formalize the interactions into a state transition system constrained by logical properties.
We model the payment system as a tuple \(\langle \mathcal{S}, \mathcal{M}, \mathcal{F}, \mathcal{B} \rangle\), representing the Shopper, Merchant, Facilitator, and the Blockchain, respectively. As depicted in Fig. 2, \(\mathcal{S}\) initiates the interaction (steps 1–3), \(\mathcal{M}\) manages the resource lifecycle (steps 6, 11), and \(\mathcal{F}\) acts as the bridge for off-chain verification (steps 4–5) and on-chain settlement (steps 7–10).
Merchant (\(\mathcal{M}\)): Holds a set of resources \(\mathcal{R}\). Each resource \(r \in \mathcal{R}\) is associated with a pricing function \(P(r)\) and a unique identifier \(ID_r\).
Shopper (\(\mathcal{S}\)): Seeks to access \(r\). \(\mathcal{S}\) holds a key pair \((pk_s, sk_s)\) and an on-chain balance \(Bal(pk_s)\). To authorize payment, \(\mathcal{S}\) generates a signed payload \(\sigma\), which encapsulates the payment metadata.
Facilitator (\(\mathcal{F}\)): Acts as an oracle for \(\mathcal{M}\). \(\mathcal{F}\) provides two functions: \(Verify(\sigma)\) which checks the cryptographic validity and balance of \(\mathcal{S}\), and \(Settle(\sigma)\) which settles the transaction on \(\mathcal{B}\).
Blockchain (\(\mathcal{B}\)): The source of truth for asset ownership. It maintains the global state of balances and nonces.
The protocol is understood as a state transition where \(\mathcal{M}\) transitions the state of a request from PENDING to DELIVERED upon receiving a valid proof of payment \(\sigma\) from \(\mathcal{S}\).
For the payment system to be secure, we propose that the transition to the DELIVERED state must strictly adhere to the following logic invariants. These invariants consolidate the granular checks required by the protocol into five
fundamental safety properties.
Invariant 1: Payment Integrity (I1). The delivery of resource \(r\) necessitates that a valid transaction \(Tx\) is confirmed on \(\mathcal{B}\). This transaction must strictly bind to the intended merchant \(\mathcal{M}\) to prevent man-in-the-middle or relay attacks. \[\begin{align} \forall Tx
\in \mathcal{B} : (Sender=pk_s \land Receiver=\mathcal{M})
\end{align}\]
Invariant 2: Value Consistency (I2). The monetary value carried by the transaction must satisfy the pricing logic of the requested resource. \[v_{tx} \ge P(r)\]
Invariant 3: Context Binding (I3). The payment authorization \(\sigma\) generated by \(\mathcal{S}\) must be cryptographically bound to the specific resource
\(ID_r\). This ensures that a payment intended for one context cannot be repurposed for another. \[\forall \sigma, r : Valid(\sigma, r) \implies Binding(\sigma) = ID_r\]
Invariant 4: Authorization Uniqueness (I4). A payment authorization \(\sigma\) containing a specific nonce \(n\) can only be used to settle a resource
request exactly once. Regardless of how many concurrent HTTP requests \(req_1 \dots req_k\) carry \(\sigma\), the protocol must ensure that the nonce \(n\)
is consumed exactly once on \(\mathcal{B}\). \[\sum_{req \in Requests} \mathbb{I}(req, n) \le 1,\] where \(\mathbb{I}\) is the indicator function.
Invariant 5: Execution Conservation (I5). This invariant addresses the specific risks in the AI economy where server-side computation is costly (e.g., GPU inference). To prevent Denial-of-Sustainability attacks,
the system must guarantee that significant computational work is not initiated unless the payment is secured (either confirmed or locked). \[v(r) > \epsilon \implies Status(Tx) \in \{\texttt{CONFIRMED},
\texttt{LOCKED}\},\] where \(\epsilon\) represents the negligible marginal cost threshold. For high-cost AI services, verifying balance is insufficient; the asset must be effectively encumbered before execution
begins.
We consider a malicious client, referred to as the adversary (\(\mathcal{A}\)). In the context of the AI economy, \(\mathcal{A}\) acts as a programmatic agent capable of interacting with the Merchant \(\mathcal{M}\) and the Blockchain \(\mathcal{B}\) at machine speed.
We rely on the standard hardness assumptions of the underlying cryptographic primitives (e.g., ECDSA signatures and Keccak256 hashing). We assume the Blockchain \(\mathcal{B}\) guarantees liveness and persistence. The Facilitator \(\mathcal{F}\) is considered a trusted oracle for stateless verification functions (i.e., it correctly validates signatures and queries balances at a given snapshot); however, we do not assume \(\mathcal{F}\) maintains stateful awareness of \(\mathcal{M}\)’s concurrent HTTP sessions unless an external locking mechanism is explicitly employed.
\(\mathcal{A}\) has full control over the client-side execution environment and the network channel to \(\mathcal{M}\). Specifically, \(\mathcal{A}\) is capable of:
Traffic manipulation: \(\mathcal{A}\) can intercept, suppress, replay, and modify all HTTP traffic generated by the client, including the X-PAYMENT headers and payload bodies (targeting the interfaces in
steps 1–3).
Concurrency and synchronization: \(\mathcal{A}\) can spawn multiple concurrent threads to issue parallel requests to \(\mathcal{M}\), aiming to exploit probabilistic race conditions in the time window between verification and settlement.
Direct mempool interaction: \(\mathcal{A}\) has direct read-write access to \(\mathcal{B}\), indicated by the red dotted line in Fig. 2. This allows \(\mathcal{A}\) to monitor the mempool for pending settlement transactions from \(\mathcal{M}\) and broadcast competing transactions (\(Tx_{drain}\)) to manipulate transaction ordering, bypassing the application-level logic of \(\mathcal{F}\).
The objective of \(\mathcal{A}\) is to violate the security invariants defined above. This includes 1) obtaining resources without sufficient valid payment (violating I1,
I2, I3, I4), and 2) denial of sustainability (violating I5) by forcing \(\mathcal{M}\) to expend
computational resources on tasks that eventually fail to settle.
In this section, we present the potential threats identified within the x402 protocol. By analyzing both the protocol specification and its implementations (SDKs), we demonstrate how the security invariants defined in Section 3 are systematically violated. Our analysis distinguishes between semantic gaps in the protocol design and atomicity failures in the integration logic.
I1)↩︎The x402 protocol adopts an architecture that deliberately decouples verification (steps 4-5 in Fig. 2) and settlement (steps 7-10). This separation is best understood as a feature, not a bug: it allows for flexible implementation strategies, enabling high-throughput interactions where the verification of intent (signature/balance checks) allows the service to proceed while the slower blockchain settlement happens asynchronously.
However, this design also introduces a critical synchronization gap. It places the responsibility of defining payment finality fully on the implementation logic. Our analysis reveals that misinterpreting this gap creates a theoretical Time-of-Check to Time-of-Use (TOCTOU) vulnerability targeting Payment Integrity (Invariant 1).
In the standard workflow (Fig.2), the Facilitator’s Verify interface confirms that the user currently has funds. The vulnerability manifests if a developer, aiming for minimum latency, misinterprets this
Verify signal as a guarantee of payment. If the Merchant delivers the resource (step 11) immediately after verification (step 5) but before settlement confirmation (step 10), an adversary \(\mathcal{A}\) can
exploit the race window. We term this pattern optimistic execution. By broadcasting a conflicting \(Tx_{drain}\) with a higher gas fee immediately after receiving the resource, \(\mathcal{A}\) can invalidate the pending settlement nonce, effectively obtaining the service for free.
To evaluate whether this theoretical threat applies to standard deployments, we conducted front-running attacks against the official Coinbase’s x402 SDKs across 8 distinct blockchain networks, selected based on Total Value Locked (TVL): Base Sepolia, Solana Devnet, Ethereum Sepolia, BNB Smart Chain Testnet, Arbitrum Sepolia, Avalanche Fuji, Polygon Amoy, and Optimism Sepolia. The experimental setup involved an automated client that initiates a valid payment request and, immediately upon receiving the HTTP 200 OK response (signaling resource delivery), broadcasts a conflicting drain transaction with a significantly higher (typically 100 times of the previous transaction) gas fee (on EVM blockchains) or priority fee (on Solana).
Our experiments showed that the front-running attempts were consistently unsuccessful. Regardless of the network speed or gas fees used by the attacker, the settlement transaction was invariably confirmed before the resource was fully released.
To understand the resilience of the standard implementation, we audited the SDK source code. As shown in Fig. 3, the settlement routine explicitly enforces a confirmation wait, i.e., a pessimistic synchronization
strategy by default. The settle function does not merely broadcast the transaction; it explicitly blocks execution (delivery) until the transaction is indexed on-chain (waitForTransactionReceipt). This implementation choice
re-couples the “verify-settle” gap. On high-performance blockchains (like Base and Solana), this wait time is negligible (approximately 1 second), making the security-latency trade-off acceptable for merchants, thereby closing the TOCTOU window by
design.
None
Figure 3: Settlement logic in x402 SDK implementation..
Additionally, on L2 networks like Base, the sequencer typically operates on a First-Come-First-Served (FCFS) basis for transaction ordering within the sub-second blocks (e.g., Flashblocks with 200ms slots). Unlike Ethereum L1’s Priority Gas Auctions (PGA), where higher gas fees can reorder pending transactions, the L2 sequencer respects the arrival order. Since \(Tx_{settle}\) arrives at the sequencer before \(\mathcal{A}\) can react to the HTTP response, the payment is effectively pre-confirmed.
While the official SDKs are secure in this case, they highlight a critical lesson for the ecosystem: this security is achieved by enforcing a blocking wait for transaction indexing (e.g., waitForTransactionReceipt). While
effective, this implementation explicitly contradicts the protocol’s goal of asynchronous high-throughput processing. On L2 networks like Base, this introduces a latency penalty of approximately 1 second per request; on L1s like Ethereum, it can exceed 12
seconds. For real-time AI agents requiring millisecond-level responsiveness, this latency is often insufficient. Consequently, developers are structurally incentivized to bypass this wait (e.g., adopting optimistic execution), inadvertently activating the
TOCTOU vulnerability. Thus, the current ecosystem offers a binary choice: high latency or broken integrity.
I3)↩︎A core feature of x402 is its stateless design, allowing resource access via a standalone payment proof. While efficient, we identify that this design introduces an inherent ambiguity: the Context Binding (Invariant 3) is implicit rather than cryptographic. This allows a valid payment authorization to be decoupled from its original intent and applied against any other resource sharing the same price parameters.
The root of this issue is the semantic decoupling between the payment layer and the application layer. The x402 protocol relies on EIP-3009 and EIP-712 signatures, where the signed message tuple \(\sigma\) commits to the payment parameters: \[\sigma = \text{Sign}_{sk}(\langle \mathcal{M}, v, n, \text{expiry} \rangle),\] where \(\sigma\) is agnostic to the resource identifier \(ID_r\) (step 3). Consequently, the signature functions as a “floating authorization”: while the monetary value is fixed to the merchant, the payment intent is decoupled from the specific resource negotiation. This allows \(\sigma\) to be detached from the original request (for \(r_a\)) and re-attached to any other request (for \(r_b\)) sharing the same price parameters. The protocol design delegates the responsibility of binding this financial proof to the specific HTTP resource entirely to the SDK implementation. Our audit of the official reference implementations reveals that this delegation systematically fails due to flawed verification logic.
Specifically, let \(r_a\) and \(r_b\) be two distinct resources owned by \(\mathcal{M}\) with \(P(r_a) = P(r_b) = v\). \(\mathcal{A}\) exploits this as follows:
User \(\mathcal{A}\) intends to access resource \(r_a\).
\(\mathcal{M}\) returns the payment requirements.
\(\mathcal{A}\) generates a valid signature \(\sigma_{a}\).
\(\mathcal{A}\) constructs a new request for another premium or restricted resource \(r_{b}\), attaching \(\sigma_{a}\) in the payment header.
\(\mathcal{M}\) validates that \(\sigma_{a}\) transfers the correct amount to the correct merchant address, i.e., satisfies \(Verify(\sigma_a, v, \mathcal{M})\).
\(\mathcal{M}\) accepts the payment, as \(\sigma_a\) satisfies the financial constraints (value \(v\)), effectively treating the payment for \(a\) as valid for \(b\).
Since the protocol layer does not enforce resource binding, the burden of access control shifts to the implementation layer. Secure implementations must implicitly bind the payment context (e.g., via session cookies or metadata checks). However, our audit reveals that official SDKs systematically fail to bridge this semantic gap. We analyzed all four official SDKs (i.e., TypeScript, Python, Java, Go), and categorized their verification failures into three distinct patterns of logic errors, illustrated in Fig. 4.
None
Figure 4: Logic failures across official x402 SDKs..
Pattern 1: predicate incompleteness (TypeScript & Python). In these implementations, the verification logic iterates through available payment requirements to find a match for the incoming request. However, the matching predicate
relies exclusively on network parameters. As observed in the findMatchingPaymentRequirements routine, the logic validates that \(req.network \equiv pay.network\) and \(req.scheme
\equiv pay.scheme\), but explicitly omits the resource identifier from the comparison. This allows a payment intended for any resource in the same network/scheme tuple to satisfy the requirement for other resource.
Pattern 2: verification against malleable metadata (Java). The Java SDK attempts to enforce context binding but fails to distinguish between authenticated data and malleable metadata. The validation logic checks if the request path
matches the value in the JSON payload (payload.get("resource")). However, this check is performed against the unsigned outer JSON wrapper. Since the EIP-712 signature only covers the inner typed data (which lacks the resource field),
an adversary can intercept a valid payload, modify the plaintext resource field to match a target restricted endpoint, and forward it. The signature remains valid, and the SDK’s superficial check passes.
Pattern 3: blind trust (Go). The Go implementation acts as a transparent proxy, forwarding the payment payload directly to the Facilitator’s API for verification. Because the Facilitator is designed as a stateless service to verify signatures and balances, it lacks awareness of the merchant’s local routing context (i.e., which resource was actually requested). By offloading the verification entirely without a local assertion of the resource context, the SDK effectively treats a valid balance check as an authorization for resource access.
To quantify the severity of these flaws, we conducted controlled experiments using two resources (\(r_A, r_B\)) with identical pricing. In 100 rounds of tests, we achieved a 100% success rate in using a signature generated for \(r_A\) to access \(r_B\).
Furthermore, when this semantic gap is exploited in tandem with the race conditions described in the following Section 4.3, the impact escalates. We use a signature generated for \(r_A\) to simoutanously access \(r_A\) and \(r_B\). In 48% of concurrent trials, we observed “resource swapping”, where a payment intent for \(r_A\) was consumed to deliver \(r_B\). In 6% of cases, the race condition allowed “service duplication”, unlocking both resources with a single signature. These results confirm that the lack of cryptographic binding in Invariant 3 effectively breaks the non-repudiation properties of the commerce protocol.
It is important to note that the direct economic impact of this vulnerability is constrained that the adversary can only substitute resources \(r_A\) and \(r_B\) if \(P(r_A) = P(r_B)\). However, in complex business logic, price is rarely the sole determinant of value. Resources with identical nominal prices often possess disparate secondary attributes that can be exploited:
For instance, an adversary could bypass purchase limits on a “sold out” limited-edition item by forging a payment made for a readily available item. In another case, a public resource and a KYC-restricted resource might share the same price tier, where reusing a signature from the public context could bypass the identity verification gates associated with the restricted asset. Therefore, while the monetary value remains conserved, the business intent and access control policies are fundamentally subverted.
This demonstrates that relying solely on x402 payment proofs for access control is insufficient for applications with differentiated resource policies. The fungibility of payments undermines specific business logic constraints (e.g., inventory, identity) unless supplementary bindings are enforced.
I4)↩︎The protocol’s economic security hinges on Invariant 4, which asserts that a unique payment authorization (identified by its nonce) must be consumed atomically to settle exactly one service request. However, our analysis reveals that the x402 implementation fails to enforce this atomicity, allowing a single valid signed payload to unlock multiple resource instances concurrently. Since the blockchain network correctly rejects duplicate nonces, only one payment settles, but the merchant inadvertently delivers the service multiple times. We term this vulnerability Probabilistic Service Duplication.
The vulnerability exploits a classic TOCTOU race condition in the Merchant-Facilitator interaction. The workflow for processing a request \(req\) with payload \(\sigma\) consists of three logical phases:
Verification phase: The Merchant calls the Facilitator to validate the signature and check if the nonce \(n\) is currently unused on the Blockchain \(\mathcal{B}\).
Execution phase: The Merchant executes the business logic (e.g., retrieving data or running inference).
Settlement phase: The Merchant requests the Facilitator to settle and confirm the transaction to \(\mathcal{B}\).
The critical flaw is that, see Fig. 2, the step 4 (verify) is strictly a read-only operation on the blockchain state. It does not place a lock on the nonce \(n\). Consequently, if an adversary \(\mathcal{A}\) broadcasts \(N\) concurrent requests with the same \(\sigma\), and the Merchant processes them in parallel threads \(T_1 \dots T_N\), multiple threads can pass step 5 check (verified) simultaneously before the first thread successfully triggers step 8 to update the nonce state on-chain.
The adversary \(\mathcal{A}\) constructs a single valid signed payload \(\sigma\) and concurrently sends \(N\) identical HTTP requests to \(\mathcal{M}\). The vulnerability manifests when the server processes these requests via parallel threads (or concurrent asynchronous tasks) \(T_1 \dots T_N\), resulting in an interleaved execution flow:
Concurrent requests: Threads \(T_1\) and \(T_2\) both query to the Facilitator. Since the nonce state on the blockchain has not yet changed, both receive a valid response.
Race to settle: \(T_1\) proceeds to the settlement phase; \(T_2\) completes its verification check before \(T_1\)’s transaction gets settled (confirmed) on the blockchain. Consequently, \(T_2\) also proceeds to the settlement phase.
Result: \(T_1\)’s transaction is confirmed on-chain, while \(T_2\)’s subsequent settlement attempt results in a duplicate transaction hash. Therefore, both threads believe that the settlement succeeds thus deliver the resource.
We audited the reference Facilitator implementation (TypeScript) and identified the absence of stateful deduplication. As illustrated in Fig. 5, the “verify” and “settle” functions operate independently without a shared lock manager.
None
Figure 5: Facilitator logic: the absence of nonce locking..
Since the blockchain state updates asynchronously (block time latency), all concurrent threads see the nonce as “unused”. They all proceed to broadcast the transaction. Since the transaction parameters (e.g., nonce, signature) are identical, they result in the same transaction hash. The blockchain network naturally deduplicates these into a single confirmed transaction, but the Merchant, observing a successful broadcast in each thread, delivers the service \(N\) times.
We constructed a proof-of-concept environment using the official x402 Express server on the Base Sepolia testnet. The server was configured to return a random temperature value to distinguish independent executions. \(\mathcal{A}\) constructed a single valid payment header and broadcast 20 concurrent HTTP requests. We repeated this experiment for 50 rounds.
In 3 out of 50 rounds (6%), we successfully triggered service duplication. Among these successful rounds, we received two distinct HTTP 200 responses containing different temperature data (e.g., \(77^\circ F\) and \(62^\circ F\)), confirming that the handler executed twice. One the other hand, tracking the settlement transaction hashes confirmed that only one transaction was included on-chain. While a 6% success rate implies the attack is probabilistic (dependent on network jitter and server load), it poses a systemic risk. For automated AI agents capable of executing thousands of transactions per hour, this represents a scalable arbitrage opportunity that directly undermines the protocol’s economic viability.
Analysis of the probability. We attribute the constrained success rate (6%) and bounded multiplicity (typically \(\leq2\) successful requests per round) to the tight temporal constraints of the race
window. The vulnerability exists solely during the execution latency between the Verify response and the Settle confirmation. Once the first thread successfully submits the transaction, the underlying RPC node updates its pending
nonce view effectively immediately, thereby preventing subsequent threads from reusing the same nonce. Consequently, only threads that complete their verification check exactly within this milliseconds-long window can bypass the protection. Further, The
vulnerability is exploitable only when concurrent requests are routed to distinct Facilitator instances or RPC nodes that share a stale view of the mempool. Also, in the majority of trials, natural network jitter and OS-level request serialization
desynchronize the batch sufficiently to close this window, thereby limiting the scale of the exploit.
The security risks analyzed in Section 4 primarily concern the exchange of static resources (e.g., API data, digital files, e-commerce items) where the price is fixed ex-ante. In such scenarios, the
“settle-first” principle (regarding Execution Conservation (I5)) serves as a robust defense mechanism, ensuring payment finality before resource delivery.
However, the emerging AI economy presents a fundamentally different paradigm: computational indeterminism. The cost of an LLM inference task is not intrinsic to the request parameters; rather, it is a function of the generated output tokens, which remains unknown until the execution completes. This constraint renders “settle-first” operationally infeasible, as the merchant cannot settle a transaction for an undetermined value. Consequently, the protocol must pivot from an atomic delivery model to a speculative execution model. In this paradigm, step 6 (work) and step 11 (deliver) are initiated before the settlement transaction (step 8) is finished, creating a new class of attack surfaces that exploit the friction between high-latency blockchains and low-latency, streaming AI services.
While the core x402 protocol specification currently focuses on static payments, the integration of dynamic authorization schemes like upto is an inevitable evolutionary step to support the variable-cost nature of AI workloads. To this end,
Thirdweb’s implementation [20] serves as a pioneering case study of this future state. By analyzing this vanguard deployment, we aim to preemptively
identify the security pitfalls that will confront the broader ecosystem as standard bodies move to adopt dynamic pricing primitives.
In this section, we examine the Thirdweb x402-agent implementation, a representative middleware powering the decentralized AI agent economy. We demonstrate how the necessary adaptations for dynamic pricing systematically dismantle the security invariants established in static payments.
We identify two distinct classes of attack surfaces that emerge from this paradigm shift.
To accommodate non-deterministic costs, the protocol shifts from an exact payment scheme (where authorised amount equals the price) to an upto authorization scheme (analogous to EIP-5216). Specifically, the Shopper signs an
authorization with a spending cap \(V_{max}\). The Merchant is authorized to pull any amount \(v \in [0, V_{max}]\) upon task completion.
Unfortunately, this fundamentally alters the security properties of the user’s signature. Unlike exact payments where the user signs a specific amount and a globally unique nonce for a specific transaction, the upto scheme
involves the user signing a delegated capability, i.e., an allowance. However, the actual settlement transactions do not carry a user-signed nonce specific to that specific deduction event. Therefore, security degrades from “cryptographic
proof of event” (user signed a specific value \(v\) for transaction \(Tx\)) to “stateful check of limit” (user authorized up to \(V_{max}\) total). This
makes the system vulnerable to state drifts, as the enforcement relies entirely on the blockchain’s current state rather than a cryptographically unique instruction.
This exposes a lesson for future protocols: relying solely on “stateful checks of limit” without cryptographic linkage to specific execution events creates an inherent vulnerability to state drift. As x402 evolves to support native dynamic pricing, it must properly address this gap.
In static scenarios, the merchant verifies payment eligibility and settles before delivery, as proven in Section 4.1. However, AI inference mandates a “verify-execute-settle” workflow to satisfy user experience requirements (e.g., token streaming):
Verification (\(t_{start}\)): The Facilitator validates that the user’s on-chain allowance and balance exceed a safety threshold (e.g., 1000 wei1). This is a stateless check against the ledger at block height \(H\).
Optimistic execution (\(t_{start} \to t_{end}\)): The Merchant executes the inference and streams tokens (effectively merging step 6 and step 11). To minimize perceived latency, the output tokens are streamed to the client in real-time.
Settlement (\(t_{end}\)): Once the generation ends and the final cost \(v\) is calculated, the Merchant attempts to settle the transaction on-chain (steps 7–8) at block height \(H + k\).
This architecture creates a temporal vulnerability window: \(\Delta t = t_{end} - t_{start}\). During \(\Delta t\), the resource is consumed and delivered, but the payment is unsecured. In this situation, the Merchant effectively acts as an unsecured creditor, extending micro-loans to the Shopper for the duration of the inference.
This inversion creates a sustainability gap. Unlike static assets where access can be withheld cost-free, the computational work (GPU cycles, electricity) in AI inference is irreversibly consumed during the execution phase. An adversary can exhaust the merchant’s compute resources by initiating requests that pass the initial verification snapshot but fail the final settlement (e.g., by front-running with an allowance revocation or balance transfer), effectively launching a denial of sustainability attack.
I2) & Execution Conservation (I5)↩︎We first examine the vulnerability that exploits the cryptographic surface. With the upto design, the verification is merely a snapshot check determining if the user can pay a minimum amount, whereas the settlement is a state
transition that transfers the actual amount. We identified a critical vulnerability where an adversary exploits the concurrency race between these two states to orchestrate an overdraft attack.
The vulnerability stems from the fact that the Merchant verifies solvency based on the blockchain state at \(t_{start}\), which remains static across concurrent requests until one of these transactions is confirmed on-chain.
In the upto authorization model, the Merchant must verify that the Shopper has authorized a spending cap (\(V_{max}\)) sufficient to cover the potential cost of an inference task. However, because the
subsequent actual costs are unknown at \(t_{start}\), the verification logic simplifies to a threshold check: \(V_{rem} \ge C_{min}\), where \(V_{rem}\) is
the remaining allowance and \(C_{min}\) is a safety floor (e.g., 1000 wei as set by Thirdweb). The vulnerability arises because this check is performed against a blockchain snapshot at block height \(H\). Crucially, the check is non-binding and does not lock funds. An adversary \(\mathcal{A}\) can construct an “overdraft” scenario:
\(\mathcal{A}\) sets the on-chain allowance to \(V\), where \(V \ge C_{min}\).
\(\mathcal{A}\) launches \(N\) concurrent inference requests such that the total projected consumption \(\sum v_i \gg V\).
Since pending transactions in the mempool (or equivalents) do not affect the allowance view until confirmed, every concurrent request reads the same state during verification (step 5). All pass the check.
Irreversible leakage: The Merchant begins optimistic execution for all \(N\) tasks (step 6). Due to the streaming nature of LLM inference, output tokens are delivered to the adversary in real-time (step 11). Crucially, this delivery occurs parallel to the execution, well before the final cost is determined.
Settlement failure: At the end of generation (\(t_{end}\)), the Merchant attempts to settle the costs (step 8). Since the aggregate value \(\sum v_i\) exceeds the on-chain allowance \(V\), the blockchain processes the first \(k\) transactions and reverts the remaining \(N-k\). However, the merchant has already delivered the full output for all \(N\) requests, resulting in a theft of service for the failed transactions.
This represents a classic TOCTOU vulnerability, exacerbated by the fact that the upto scheme lacks a cryptographic nonce to bind specific allowance portions to specific requests. Unlike the probabilistic service duplication issue
(Section 4.3) which is limited by race windows, this exhaustion attack is deterministic once the aggregate cost exceeds the quota. It exploits the protocol’s inability to cryptographically isolate portions of
a shared allowance for specific requests without on-chain locking. Moreover, enforcing nonce-based uniqueness for each deduction is structurally infeasible, as the merchant can hardly pre-allocate nonces for future, variable-cost inference events.
Beyond concurrency, the specific nature of LLM workloads allows for a non-concurrent exploit vector. An adversary can manipulate the cost magnitude of a single request. By constructing a prompt with a massive context window or demanding a verbose output (e.g., 5,000 tokens), the adversary ensures the dynamic cost \(v_{req}\) significantly exceeds the remaining allowance \(V_{rem}\), provided \(V_{rem} \ge C_{min}\). This triggers a deterministic settlement reversion after the expensive computation is fully consumed, achieving a high leverage ratio without requiring network-level race conditions.
I1)↩︎We then examine the vulnerability arising from the temporal surface, i.e., the rate-limit asymmetry of Thirdweb Facilitator between the service ingress and the settlement egress, where its own protective mechanism is paradoxically weaponized to dismantle its economic security.
Consider a Facilitator with a settlement rate limit \(L_{settle}\) (e.g., 10 tx/s). An adversary can exploit this by flooding the Merchant with a burst of valid requests \(\lambda \gg
L_{settle}\). The verification step (step 4), typically with mismatched limits, accepts the burst. The Merchant proceeds to execute and stream (steps 6 and 11). However, when the Merchant attempts to batch-settle these payments (step 7), the
Facilitator’s API Gateway rejects the traffic exceeding \(L_{settle}\) with 429 Too Many Requests. Since the resource has already been delivered optimistically, this infrastructure-level rejection results in a
deterministic loss for the Merchant, effectively allowing the adversary to “free-ride” on the service’s throughput capacity.
It is important to note that this vulnerability manifests primarily in self-hosted or third-party deployments relying on standard templates. While the official hosted services may be provisioned with significantly higher throughput limits that mask this race condition, the basic configuration for third-party developers imposes a strict settlement limit (i.e., \(L_{settle} = 10/s\)). Furthermore, the system design fails to synchronize the ingress verification rate (\(L_{verify}\)) with this egress settlement constraint (\(L_{verify} \gg L_{settle}\)). This asymmetry creates an insecure default posture: a third-party service provider deploying the standard template inherits a system where concurrency levels exceeding 10 requests per second will automatically trigger this issue, leading to revenue loss and resource exhaustion. We argue that low-tier rate limits should result in service degradation (refusing requests), not security degradation (delivering service for free).
To quantify the severity of the vulnerabilities identified in the AI inference workflow, we conducted a series of controlled experiments targeting both 1) the official deployment of the Thirdweb x402-agent middleware on Arbitrum mainnet, and 2) a locally-deployed server with the open-sourced implementation on Arbitrum Sepolia Testnet. The blockchain selection is determined by Thirdweb by default.
Our evaluation focuses on measuring the discrepancy between service delivery (tokens generated and delivered) and payment settlement (USDC transferred on-chain). Although the absolute value in this validation appears small, the vulnerability allows for unconstrained automation. An adversary can scale this attack to exhaust the merchant’s API quotas and cloud credits within minutes, translating to significant operational losses beyond the direct token value. It is notable that we carefully designed the experiment to minimize any potential impact on the service, and terminated the test immediately once the effectiveness of the approach was demonstrated.
We utilized a testbed consisting of:
Target: A standard Thirdweb agent deployment (both officially- and locally-deployed) using the upto authorization scheme.
Adversary: A client capable of managing on-chain allowances and generating concurrency request bursts.
Metrics: We define the Leakage Ratio \(\rho\) as the proportion of delivered compute resources that failed to settle: \[\rho = 1 - \frac{\text{Total settled value}}{\text{Total delivered value}}\]
We configured the adversary with an initial allowance of 10,000 wei and launched a burst of 50 concurrent inference requests. The total expected cost of these requests exceeded the allowance cap.
Verification: All 50 requests were successfully verified.
Execution: All 50 requests were successfully executed, consuming a total of 47,277 tokens (equals 47,277 wei, i.e., 1 wei for 1 token).
Settlement: Only 4 transactions were successfully settled, totally paid only 1,057 wei. The remaining 46 reverted on-chain due to allowance overdraft.
Impact: The adversary obtained 47,277 wei worth of resources while paying only 1,057 wei. This represents a leakage ratio of \(\boldsymbol{\rho = 97.76}\)%.
Even more seriously, this vulnerability enables a deterministic long-context attack. In extreme scenarios, a single request can be engineered with a massive context window or complex prompt to consume tokens costing more than the entire remaining allowance (\(v>V_{rem}\)). Since the settlement transaction consistently reverts without decrementing the on-chain allowance, the adversary can replay this heavy workload semi-indefinitely (subject to the signature expiry, 24 hours by default), driving the leakage ratio \(\boldsymbol{\rho \to 100}\)%.
To validate the infrastructure-level failure, we executed a high-velocity burst of 50 requests per second against the official instance with standard settlement rate limits (i.e., 10 requests per second by default).
Service delivery: 100% of requests (50/50) were processed and streamed to the client.
Payment failure: Only 10% of the corresponding transactions (5/50) were successfully settled.
Impact: The adversary obtained 14,761 tokens (equals 14,761 wei) of output with effectively 1,926 wei cost. This represents a leakage ratio of \(\boldsymbol{\rho = 86.95}\)%.
In an extreme case, we achieved a scenario where 50 requests were successfully verified and delivered, but 0 settlement transactions were successfully finalized (i.e., all were blocked by the rate limiter). This resulted in the adversary obtaining 11,101 wei worth of inference resources at an absolute cost of 0 USDC, the leakage ratio is \(\boldsymbol{\rho = 100}\)%.
Our analysis demonstrates that the vulnerabilities in x402-enabled systems are not isolated implementation bugs, but symptoms of architectural misalignments between stateless web protocol and stateful financial ledgers. Securing the A2A economy requires moving beyond simple patches to adopting rigorous design patterns that enforce the invariants defined in Section 3. We propose four hierarchical defense strategies, each entailing distinct tradeoffs.
The root cause of cross-resource substitution (Section 4.2) is the semantic gap between the payment authorization and the resource intent. To enforce Context Binding (I3), the
protocol must eliminate the ambiguity of signatures.
Recommendation: request-bound signatures. We propose extending the EIP-712 schema to explicitly include the request context. Instead of signing generic parameters \(\langle \mathcal{M}, v, n, expiry \rangle\), the agent should sign: \[\sigma = \text{Sign}_{sk}\left( \mathcal{M}, v, n, expiry, \mathcal{H}(Req) \right),\] where \(Req = (\text{Method} \parallel \text{URI} \parallel \text{Body})\) represents the complete HTTP request context. By committing to the hash of the HTTP request (\(\mathcal{H}\)), the signature becomes mathematically invalid if replayed against a different resource or a modified payload. This renders the verification logic deterministic and independent of the developer’s implementation quality, effectively closing the semantic gap at the protocol level.
The probabilistic service duplication attack (Section 4.3) exploits the atomicity gap between the off-chain verification (read) and on-chain settlement (write). To enforce Authorization Uniqueness
(I4), the verification logic must transition from a stateless “Check-then-Act” model to a stateful “Check-and-Set” model.
Recommendation: pending state. We propose implementing a lightweight, ephemeral state layer (e.g., a distributed lock) at the Facilitator ingress to track the lifecycle of a nonce beyond simple binary states. We define the state transition function as follows:
Atomic check-and-lock: Upon receiving a request with nonce \(n\), the system executes an atomic SETNX operation. \[\text{Lock}(n) = \begin{cases} \text{Reject}, & \text{if
} State(n) \in \{\texttt{pending}, \texttt{used}\} \\ \text{Accept}, & \text{if } State(n) = \text{Null}, \\ & \quad State(n) \leftarrow \texttt{pending} \end{cases}\]
State propagation: The state remains Ppending until the transaction hash is returned from the mempool, at which point it transitions to used (on-chain confirmed).
This mechanism acts as a linearization barrier. Even if \(N\) concurrent requests pass the cryptographic signature check, only the first request to acquire the atomic lock can proceed to settlement and delivery. This eliminates the race condition window \(\Delta t\) entirely, ensuring that off-chain processing adheres to the strict serialization guarantees of \(\mathcal{B}\).
For static assets, the defense is straightforward: enforce strict ordering where settlement confirmation precedes delivery. However, for AI inference (Section 5), the core challenge is the “dynamic pricing paradox” where
exact costs are unknown ex-ante. To satisfy Execution Conservation (I5), we propose a series of defense strategies based on the trade-off between user experience (latency) and financial risk.
For standard AI inference, we recommend a deferred delivery model. Unlike the current insecure implementation which streams tokens immediately (immediate loss), the Merchant could buffer the inference output during execution. \[\text{Verify} \to \text{Execute (Buffer)} \to \text{Settle} \to \text{Deliver}\] The buffered content is released if and only if the settlement transaction is successfully confirmed. While this strategy does not prevent the
consumption of server-side compute resources (thus strictly still violating I5), it effectively neutralizes the rational economic incentive for the attack. By ensuring the adversary derives zero utility (no data) from a failed
payment, this mechanism downgrades the threat from “theft of service” (profitable) to “griefing” (irrational), significantly reducing the attack surface against profit-driven agents.
For high-stakes computations where even the cost of wasted GPU cycles is unacceptable (violating I5), systems could revert to a pessimistic “Reserve-Commit” pattern.
Phase 1 (Reserve): Before execution (\(t_{start}\)), the Facilitator places a “hold” on the user’s funds by transferring the maximum cap (\(V_{max}\)) to a temporary escrow contract (or a distinct vault). This atomizes the allowance check and prevents state drift (e.g., concurrent overdrafts).
Phase 2 (Commit): Upon task completion (\(t_{end}\)), the Merchant triggers the settlement. The escrow contract releases the actual cost \(v\) to the Merchant and refunds the remainder \((V_{max} - v)\) to the user.
While this introduces on-chain interaction latency and cost at the start, it guarantees that computational work is never effectively subsidized by the merchant. For high-frequency use cases, this can be optimized using state channels (similar to L402) to amortize the locking cost over a session.
While deferred delivery neutralizes the incentive for theft, it remains vulnerable to resource griefing, where an adversary intentionally triggers expensive computations that fail settlement, forcing the merchant to incur GPU and gas costs. To enforce a truly sustainable agent economy, protocols must incorporate sybil-resistant metering.
Cryptographic service bonds. We propose modifying the handshake to require a Proof of Stake for the client session. Before allocating inference resources, the Merchant verifies that the agent has locked a sufficient “gas bond” in a specified smart contract: \[\text{Auth}(Req) \iff \text{Verify}(\sigma) \land Bal_{\text{bond}} > (C_{\text{gas}} + v),\] where \(Bal_{\text{bond}}\) denotes the agent’s staked balance, and \(C_{\text{gas}}\) represents the maximum gas cost for settlement (including potential reverts). If the settlement transaction reverts due to client-side state drift (e.g., allowance removal), the Merchant can submit a fraud proof (e.g., the signed request and the revert receipt) to slash the agent’s bond. This is expected to effectively monetize the griefing attack, realigning economic incentives to favor honest behavior.
A rigid application of pessimistic locking incurs significant gas overhead and latency, potentially negating the performance benefits of x402 for micro-transactions. To reconcile security with scalability, we propose a risk-adaptive authorization model. In this model, security policies are not strictly binary but tiered based on the reputation of the agent and the value at risk of the session.
Sybil-resistant staking: Agents wishing to utilize optimistic execution modes must stake a security deposit proportional to their requested throughput. This introduces a quantifiable cost of misbehavior. If a malicious agent is detected, their stake is slashed to compensate the merchant.
Dynamic tiering:
Tier 0 (unknown): Enforce two-phase locking.
Tier 1 (staked): Allow optimistic execution with atomic delivery (buffered).
Tier 2 (reputed): Allow optimistic streaming.
This hybrid approach shifts the defense burden from pure cryptographic enforcement to cryptoeconomic game theory, effectively managing the trade-off between the cost of protection and the cost of potential leakage.
The Denial of Settlement attack (Section 5.3) highlights the danger of decoupling service delivery from billing. When infrastructure constraints (e.g., rate limits) clash with business logic, the system defaults to an insecure state (free service).
Recommendation: synchronous gatekeeping. To maintain Payment Integrity (I1), middleware architectures must adopt a “dailure-closed” design. The rate limiter and billing service must be coupled synchronously
with the request ingress, not the egress. Specifically, the Facilitator should verify rate limits and reserve billing capacity before the request is forwarded to the AI inference engine. If the settlement API is likely to reject the transaction
due to load, the request should be rejected immediately with 429 Too Many Requests, rather than processed and served for free. This ensures that infrastructure reliability issues result in denial of service, not denial of
payment.
The x402 protocol aims to serve as the economic foundation for the agentic web, yet our analysis exposes a fundamental fragility in its structural decoupling of verification from settlement to bridge web latency and blockchain finality. We demonstrated that this lack of atomicity creates systemic vulnerabilities across the stack; securing this machine-to-machine economy requires a paradigm shift from ergonomic looseness to rigorous cryptographic binding and pessimistic state locking.
Ultimately, our findings highlight a fundamental impedance mismatch when overlaying stateless web protocols (HTTP) onto stateful financial ledgers. We argue that the agentic web cannot simply adopt optimistic web patterns; it requires a new class of state-aware middleware that explicitly manages the synchronization gap between milliseconds-latency inference and seconds-latency settlement. Without such architectural rigor, the AI economy risks building its foundation on financial rails that are prone to systemic free-riding.
This research investigates security vulnerabilities in financial protocols and AI infrastructure. To uphold ethical standards and prevent harm to the broader ecosystem, we adhered to the following principles throughout our study:
Responsible disclosure. We have responsibly disclosed all identified vulnerabilities to the relevant stakeholders, including the Coinbase Developer Platform team (maintainers of the x402 protocol and SDKs) and the ThirdWeb security team. We are actively coordinating with these vendors to facilitate patch deployment and have provided them with detailed reproduction steps.
Controlled experimentation. All attacks described in this paper, including the cross-resource substitution and allowance overdraft exploits, were conducted against resources and accounts owned and controlled by the authors. At no point did we exploit third-party services, steal funds from other users, or disrupt public infrastructure.
Minimization of impact. For blockchain interactions, we primarily utilized test networks (e.g., Base Sepolia, Arbitrum Sepolia) to avoid financial impact. For the limited validation performed on the Arbitrum One mainnet, we used minimal value transactions (i.e., less than 100,000 wei) for minimization of impact.
Due to the critical nature of the vulnerabilities, specifically the ability to force merchants to subsidize compute costs at scale (up to 100% leakage ratio), and the fact that patches are currently being rolled out by the affected vendors, we have decided to temporarily withhold the public release of the attack code. Releasing these artifacts immediately poses a significant safety risk to live AI agents and payment processors currently using the x402 stack.
We are maintaining an active communication channel with Coinbase and ThirdWeb. We pledge to release the full source code and data to the public domain immediately after the vendors confirm that the vulnerabilities have been mitigated or sufficient time has passed for the ecosystem to upgrade.
While “wei” strictly denotes \(10^{-18}\) ETH, we adopt the common EVM developer convention in this paper to use “wei” to denote the smallest atomic unit of the specific ERC-20 token being used (i.e., \(10^{-6}\) for USDC).↩︎