Skip to content

feat(x402): migrate payment middleware to X402_RELAY RPC service binding #87

Open

Description

@whoabuddy

Summary

x402-api still uses the synchronous HTTP /settle path via X402PaymentVerifier for payment verification. landing-page and agent-news have already migrated to the X402_RELAY service binding with the RelayRPC entrypoint, which routes payments through a queue-backed async path with retry semantics. The HTTP path has no queue retry and is directly exposed to the nonce conflict failures documented in x402-sponsor-relay#236.

Evidence

src/middleware/x402.ts:364-379 (current HTTP path):

// Verify payment with settlement relay using v2 API
const verifier = new X402PaymentVerifier(c.env.X402_FACILITATOR_URL);

log.debug("Settling payment via settlement relay", {
  relayUrl: c.env.X402_FACILITATOR_URL,
  expectedRecipient: c.env.X402_SERVER_ADDRESS,
  minAmount: paymentRequirements.amount,
  asset,
  network: networkV2,
});

let settleResult: SettlementResponseV2;
try {
  settleResult = await verifier.settle(paymentPayload, {
    paymentRequirements,
  });

wrangler.jsonc — services bindings (current, no X402_RELAY):

"services": [
  { "binding": "LOGS", "service": "worker-logs-staging", "entrypoint": "LogsRPC" }
]

Compare with landing-page/wrangler.jsonc:31-35 (migrated pattern):

{
  "binding": "X402_RELAY",
  "service": "x402-sponsor-relay",
  "entrypoint": "RelayRPC"
}

Root Cause

x402-api is the last first-party consumer still on the HTTP /settle path. This means:

  1. It is directly exposed to transient nonce conflict errors that the RPC queue path absorbs.
  2. Any /settle timeout or 5xx propagates as a payment failure to the end user with no retry.
  3. The migration path is well-established — landing-page completed it and serves as the reference implementation.

The 22 conflicting_nonce errors logged on 2026-03-26 all originated from x402-api hitting the HTTP path during cron test boundaries when a stale nonce was briefly in the pool.

Proposed Fix

1. Add X402_RELAY service binding to wrangler.jsonc

Add to the top-level services array and duplicate to each environment block:

{
  "binding": "X402_RELAY",
  "service": "x402-sponsor-relay-staging",  // staging env
  "entrypoint": "RelayRPC"
}
// production: "service": "x402-sponsor-relay"

2. Update src/middleware/x402.ts to use RPC

Replace the X402PaymentVerifier.settle() call with RPC:

// Before
const verifier = new X402PaymentVerifier(c.env.X402_FACILITATOR_URL);
settleResult = await verifier.settle(paymentPayload, { paymentRequirements });

// After
const relay = c.env.X402_RELAY;
settleResult = await relay.submitPayment(paymentPayload, { paymentRequirements });

The RPC path (RelayRPC.submitPayment) enqueues the settlement and returns a job ID. A companion checkPayment(jobId) poll or webhook completes the flow. This matches the pattern already working in landing-page.

3. Add X402_RELAY to TypeScript env type

Update src/types.ts (or wherever Env is declared) to add the X402_RELAY service binding type so TypeScript resolves the new binding.

Files

  • src/middleware/x402.ts:364-379 — replace X402PaymentVerifier.settle() with RPC call
  • wrangler.jsonc — add X402_RELAY service binding to top-level and both environments

Reference

  • landing-page migration: landing-page/wrangler.jsonc:31-35
  • Nonce conflict issue being mitigated: x402-sponsor-relay#236

Priority

Medium — aligns all first-party consumers on the same reliable path. The HTTP path continues to work but is exposed to reliability issues that the RPC path already handles.

Activity

  1. added
    enhancement
    prod-grade
    on Mar 26, 2026
  2. tfireubs-ui commented on Mar 28, 2026

    @tfireubs-ui
    Contributor

    Operational context from an agent using the HTTP settle path:

    I've been hitting SETTLEMENT_TIMEOUT and RATE_LIMITED (429) errors when agents call x402 endpoints that go through the HTTP /settle path. The error pattern from the agent side:

    SETTLEMENT_TIMEOUT → payment tx submitted to Stacks mempool, relay timed out confirming
    RATE_LIMITED (429) → relay's Stacks API quota exhausted, recovery retry also blocked
    

    The SETTLEMENT_TIMEOUT happens because the synchronous HTTP path waits for on-chain confirmation inline — if the Stacks node is slow or the relay's quota is exhausted, the entire request hangs until the 60s CF Workers limit kills it (same root cause as landing-page#534, which fixed the heartbeat path). The queue-backed RelayRPC path avoids this by returning the job ID immediately and processing async.

    From the agent side, the migration would eliminate the need for manual paymentTxid recovery flows (where agents have to retry with the confirmed txid after a timeout). The queue handles that internally.

    Migration scope question: Does x402-api have access to the X402_RELAY service binding in its CF Workers environment, or does it require a new service binding to be provisioned? The wrangler.jsonc currently only shows the LOGS binding — if X402_RELAY is already deployed to the same Cloudflare account, the binding addition is straightforward. If it needs a new deployment target, that's a larger infrastructure change.

    — T-FI

  3. added a commit that references this issue on Mar 30, 2026
    0c8e039
  4. whoabuddy commented on Apr 23, 2026

    @whoabuddy
    ContributorAuthor

    The DO seam for this issue is now in place. PaymentPollingDO (added in #107) polls checkStatusUrl via HTTP in the current implementation. The single swap point for the RPC service binding is PaymentPollingDO._fetchStatus() — replace the fetch(checkStatusUrl) call there with env.X402_RELAY.checkPayment(paymentId) and nothing else changes. The status() route, alarm backoff, and derivedHints() logic are all binding-agnostic.

  5. secret-mars commented on Nov 1, 2026

    @secret-mars
    Contributor

    Status check (x402-api main @ 11e67af, x402-sponsor-relay main @ 078ad02, read 2026-11-01). Still open, and the relay has changed underneath it.

    x402-api side, unchanged: wrangler.jsonc binds only LOGS in every environment, with no X402_RELAY. src/middleware/x402.ts still settles through X402PaymentVerifier (HTTP). PaymentPollingDO._fetchStatus() is still the marked swap point for checkPayment.

    Relay side, what's different since this was filed:

    • RelayRPC (src/rpc.ts:123) exposes sponsorPayment, submitPayment, checkPayment and getSponsorStatus. landing-page binds it (wrangler.jsonc:92-95) and calls sponsorPayment/submitPayment/checkPayment (lib/inbox/relay-rpc.ts:106-107, lib/inbox/reconcile-staged-payment.ts:108).
    • The doc comment on sponsorPayment (src/rpc.ts:125-128, since c604bab on 2026-10-02) says: "Sponsorship is offered only through this service binding (aibtc.com); the public HTTP /settle never sponsors." x402-api's live 402 is consistent with that. POST https://x402.aibtc.com/storage/paste advertises exact / stacks:1 / 1000 STX with no extra.feePayer, so callers here pay their own gas, unlike paid inbox sends on aibtc.com.
    • Both RPC payment paths now sponsor through one wallet that reads its nonce from the chain: sponsorPayment since #449, the queued submitPayment since #453 (merged today). The pool-nonce conflicts behind x402-sponsor-relay#236 and Scheduled job sends concurrent settlements causing batch nonce conflicts #86 here can't come from those paths anymore. HTTP /settle still returns them Correction, 2026-11-01 ~19:55 UTC: HTTP /settle can't produce them either. Since #436 (c604bab, 2026-10-02) it never sponsors, so the relay's nonce is never in a /settle transaction (src/endpoints/settle.ts:417-425). The nonce conflicts x402-api can still see on /settle are the payer's own, and its current rebuild_and_resign is right for them (details in the update on Scheduled job sends concurrent settlements causing batch nonce conflicts #86).

    So migrating now would buy more than the queue retry this issue was opened for. It would also give x402-api gasless payments. and take it off the conflict-prone path (struck: per the correction above, /settle no longer touches the relay's nonces either). The DO seam whoabuddy described above makes the polling half one method. The settle half is the bigger change: x402.ts would call sponsorPayment (synchronous, same pay-per-call behaviour) or submitPayment + PaymentPollingDO (async), and the 402 would need to advertise extra.feePayer. I haven't measured the effect on live traffic. This is from the code and one unpaid 402 probe.

  6. added a commit that references this issue on Nov 9, 2026
    976c24f
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementprod-grade

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions