Skip to content

feat(x402): migrate payment middleware and polling DO to X402_RELAY RPC binding - #150

Open
khoap1220-hue wants to merge 27 commits into
aibtcdev:mainfrom
khoap1220-hue:feat/x402-relay-rpc-service-binding-87
Open

khoap1220-hue wants to merge 27 commits into
aibtcdev:mainfrom
khoap1220-hue:feat/x402-relay-rpc-service-binding-87

Conversation

@khoap1220-hue

@khoap1220-hue khoap1220-hue commented Nov 9, 2026 •

Copy link
Copy Markdown

In wrangler.jsonc, src/types.ts, src/services/payment-contract.ts, src/durable-objects/PaymentPollingDO.ts, and src/middleware/x402.ts, this PR migrates payment submission and status polling to the X402_RELAY (RelayRPC) service binding while preserving HTTP fallback when X402_RELAY is not bound in local/test environments.

Changes

  1. wrangler.jsonc:
    • Added { "binding": "X402_RELAY", "service": "x402-sponsor-relay-staging", "entrypoint": "RelayRPC" } to env.staging.services and { "binding": "X402_RELAY", "service": "x402-sponsor-relay-production", "entrypoint": "RelayRPC" } to env.production.services (omitted at top level so standalone wrangler dev exercises the HTTP facilitator path without requiring a local relay worker).
  2. src/types.ts & src/services/payment-contract.ts:
    • Added RelayRPC (submitPayment, checkPayment), RelaySettleOptions, RelaySubmitPaymentResult, and RelayCheckPaymentResult types, added X402_RELAY?: RelayRPC to Env, and re-exported RpcCheckPaymentResultSchema, RpcSubmitPaymentResultSchema, RpcErrorCodeSchema, and RPC_ERROR_CODES from @aibtc/tx-schemas/rpc.
  3. src/durable-objects/PaymentPollingDO.ts:
    • Wired _fetchStatus(paymentId, checkStatusUrl) to invoke await this.env.X402_RELAY.checkPayment(paymentId) validated via RpcCheckPaymentResultSchema when this.env.X402_RELAY is bound (logging RelaySchemaMismatchError distinctly from transient network errors), falling back to fetch(checkStatusUrl) with HttpPaymentStatusResponseSchema otherwise, and added durable tx_guard / tx_retry_guard coordination across isolates.
  4. src/middleware/x402.ts:
    • Routed settlement through c.env.X402_RELAY.submitPayment(txHex, settleOptions, paymentIdentifier) and checkPayment(relayPaymentId) when c.env.X402_RELAY is bound, falling back to verifier.settle(paymentPayload, { paymentRequirements }) when unbound.

Closes #87

…PC binding

Resolve aibtcdev#87 across `wrangler.jsonc`, `src/types.ts`, `src/durable-objects/PaymentPollingDO.ts`, and `src/middleware/x402.ts`:

- Add `X402_RELAY` service binding (`entrypoint: "RelayRPC"`) to `wrangler.jsonc` top-level, `staging` (`x402-sponsor-relay-staging`), and `production` (`x402-sponsor-relay`).
- Add `RelayRPC`, `RelaySettleOptions`, `RelaySubmitPaymentResult`, and `RelayCheckPaymentResult` interfaces and `X402_RELAY?: RelayRPC` on `Env` in `src/types.ts`.
- Update `PaymentPollingDO._fetchStatus()` (`src/durable-objects/PaymentPollingDO.ts:287`) to query `this.env.X402_RELAY.checkPayment(paymentId)` when `X402_RELAY` is bound, with graceful fallback to HTTP `fetch(checkStatusUrl)`.
- Route `x402PaymentMiddleware` settlement in `src/middleware/x402.ts` through `c.env.X402_RELAY.submitPayment()` when `X402_RELAY` is bound, falling back to `X402PaymentVerifier.settle()` when unbound.
@epistemedeus

Copy link
Copy Markdown

One release-blocking difference from the synchronous path at 976c24fa: an RPC enqueue is being treated as settlement. I mounted the exact x402Middleware in Hono, with an inert relay and a handler counter. No worker deployment or transaction.

Reproduction: return {accepted: true, status: 'queued', paymentId: 'pay_<relay-id>', checkStatusUrl: '<relay-url>'} from submitPayment using an ID distinct from its third argument, as the relay does for a new payment. The same happens for queued_with_warning.

  • Expected: a pending response with the canonical relay ID, no payment.confirmed event, no paid-handler invocation.
  • Observed: HTTP 200, one paid-handler invocation, one payment.confirmed event, and PAYMENT-RESPONSE.success: true with the relay job ID in transaction. The DO and X-PAYMENT-ID use the locally minted ID instead, and tracking gets the HTTP fallback URL for that ID. checkPayment looks up the relay ID, not the caller's identifier.
  • Payer control: omit the outer payer field and the handler receives the seller's address. Change only that unsigned field and the handler receives the supplied string. The unbound synchronous control still uses the verifier-returned payer and actual transaction ID; explicit RPC refusal does not execute or fall back.

I would keep these as three separate fields: a stable request correlation key, the relay-returned job ID, and a confirmed transaction with a verified origin. Gate the paid handler on confirmed, bound settlement, not enqueue. A focused regression should cover queued → confirmed recovery using the relay ID, caller payer changes, and timeout after enqueue with no HTTP resubmit. The pinned relay also requires sponsored transactions; keep an explicit compatibility case for callers using the existing non-sponsored quote.

@secret-mars

secret-mars commented Nov 9, 2026 •

Copy link
Copy Markdown
Contributor

One config issue not covered above, at 976c24f.

The production binding names the wrong relay worker. wrangler.jsonc env.production adds:

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

The relay's own wrangler.jsonc (main e0fe7f0) names its production worker x402-sponsor-relay-production. Its staging worker is x402-sponsor-relay-staging, which this PR gets right. x402-sponsor-relay is only the top-level name, used when the relay is deployed without --env. The other production callers bind the -production name:

  • agent-news wrangler.jsonc:183: "service": "x402-sponsor-relay-production"
  • landing-page wrangler.jsonc:93 and :225: the same

A service binding targets a Worker by its deployed name (Cloudflare service bindings). With an explicit name per environment, that is the env's name (Wrangler environments). So in production this binds to the non-env relay worker, if one is deployed, instead of the relay at x402-relay.aibtc.com. I can't see from public code whether a worker named x402-sponsor-relay exists on the account, so I can't tell whether that means a failed deploy or payments going to the wrong relay. Either way it should be x402-sponsor-relay-production.

Combined with the enqueue-as-settlement problem epistemedeus showed, the paid handler would run for a payment queued on a relay that may not be the one whose status checkPayment later reads.

Smaller point: the HTTP fallback covers only a binding that is absent from the config (X402_RELAY undefined). A binding that is configured but points at the wrong or a missing worker is still defined, so the code takes the RPC branch, and any failure there goes to the catch block below, not the fallback. A one-line log of which path ran (RPC or HTTP) would make the migration easy to check after deploy.

… and fix prod binding

Gate paid handler and payment.confirmed on confirmed RPC settlement with verified Stacks transaction origin, separate requestCorrelationId/relayPaymentId/confirmedTxid, add non-sponsored quote compatibility fallback on NOT_SPONSORED, and point production X402_RELAY service binding to x402-sponsor-relay-production.
@khoap1220-hue

Copy link
Copy Markdown
Author

In src/middleware/x402.ts, src/types.ts, wrangler.jsonc, and tests/payment-middleware.unit.test.ts (commit 6278a4b6), all findings from @epistemedeus and @secret-mars have been resolved and covered by regression tests:

  1. Gate Paid Handler on Confirmed, Bound Settlement (src/middleware/x402.ts):

    • c.env.X402_RELAY.submitPayment returning status: "queued" or "queued_with_warning" no longer invokes next() or emits payment.confirmed.
    • Middleware polls c.env.X402_RELAY.checkPayment(relayPaymentId) using the relay-assigned paymentId. While the status remains in-flight ("queued", "queued_with_warning", "broadcasting", "mempool") or if checkPayment times out after enqueue, middleware tracks the canonical relayPaymentId and relayCheckStatusUrl in PaymentPollingDO, sets X-PAYMENT-ID: <relayPaymentId>, emits payment.pending, and returns HTTP 402 (X402_ERROR_CODES.TRANSACTION_PENDING) without invoking the route handler and without performing any HTTP /settle resubmit.
  2. Separate requestCorrelationId, relayPaymentId, and confirmedTxid (src/middleware/x402.ts, src/types.ts):

    • requestCorrelationId (deriveRequestCorrelationId) is derived deterministically from the transaction and payment requirements and passed as payment-identifier / 3rd argument to submitPayment.
    • relayPaymentId (rpcResult.paymentId) is used for checkPayment(relayPaymentId), PaymentPollingDO.idFromName(relayPaymentId), PaymentPollingDO.track(), X-PAYMENT-ID, and extractCheckStatusUrl() (which now checks top-level checkStatusUrl before extensions.checkStatusUrl).
    • confirmedTxid (checkResult.txid, required to be non-empty and distinct from relayPaymentId) is used for settleResult.transaction only when status === "confirmed".
  3. Verified Transaction Origin & Payer Control (extractVerifiedTransactionOrigin):

    • Transaction origin (payerAddress, authType, nonce) is extracted directly from deserializeTransaction(cleanHex) (tx.auth.spendingCondition via addressHashModeToVersion and Address.stringify).
    • Middleware never reads the unsigned outer paymentPayload.payer field and never falls back to c.env.X402_SERVER_ADDRESS. Recovery attempts that mismatch the bound transaction hash or verified signer are rejected with HTTP 400 (X402_ERROR_CODES.SENDER_MISMATCH).
  4. Explicit Compatibility for Non-Sponsored Quotes (NOT_SPONSORED):

    • When the 402 quote does not advertise a sponsor and a caller submits a standard (AuthType.Standard) non-sponsored transaction that submitPayment rejects with code === "NOT_SPONSORED", middleware explicitly settles via verifier.settle(). All other RPC rejections (INVALID_TRANSACTION, SENDER_NONCE_STALE, etc.) do not fall through or execute the handler.
  5. Production X402_RELAY Service Binding Target & Transport Logging (wrangler.jsonc):

    • Updated env.production.services in wrangler.jsonc from "service": "x402-sponsor-relay" to "service": "x402-sponsor-relay-production" to match the deployed production relay worker name.
    • Added explicit settlementTransport: "rpc" | "http" logging on payment initiation.

@secret-mars

Copy link
Copy Markdown
Contributor

Thanks for the quick turnaround. The production binding is fixed and the pending gate is in. I read 6278a4b against relay main e0fe7f0. I found these by reading the code and did not run them. Three of them let one payment be served more than once.

1. A confirmed payment can be replayed in the same isolate. On the confirmed branch (x402.ts:1029-1060), the bound entry is kept. removeBoundPayment runs only on payer mismatch (:1001, :1043) and on terminal failure (:1066). Send the same payment-signature again: byTxHash matches at :810 (same recipient, amount and asset), submitPayment is skipped, checkPayment(relayPaymentId) returns confirmed with the same txid, and the handler runs again. That repeats for as long as the isolate lives. Suggest deleting the entry when the payment confirms. The relay can't stop this case, because submitPayment is never called.

2. The same replay works across isolates for 300s, because the correlation id is now deterministic. deriveRequestCorrelationId hashes tx + recipient + amount + asset, and the result is sent as the relay paymentIdentifier. The relay's RPC path returns its cached response on an id+payload hit (rpc.ts:257-263, PAYMENT_ID_TTL_SECONDS = 300 in services/payment-identifier.ts). So a replay of the same tx within 5 minutes, landing on a fresh isolate, gets the original accepted result and the same paymentId. checkPayment then says confirmed, and the handler runs. The HTTP path has the same window, since /settle uses the same cache (payid:settle:, 300s). main used pay_ + crypto.randomUUID() per attempt (x402.ts:484 on 11e67af), so this replay couldn't happen there. Neither layer keeps a "this payment was already served" record. Either keep the per-attempt random id for settlement and use the correlation key only for lookup, or record served txids (KV/DO, keyed by txid) and refuse a second serve.

3. Recovery by caller-supplied id skips the price check. When X-PAYMENT-ID or the payment-identifier extension finds an entry (:789-806), only payer and txHash are compared. The byTxHash path at :810-815 also checks expectedRecipient, minAmount and asset against the current request. On the dynamically priced /inference/openrouter/chat route, a tx paid against a small prompt's price can then be recovered on a larger prompt whose price is higher. Apply the same three checks on the caller-id path.

4. Smaller: rpcResult.retryable is dropped on rejection (:892-902). Every non-NOT_SPONSORED rejection becomes status: "failed", and only codes in RPC_CODE_TO_TERMINAL_REASON get a terminal reason. A transient relay error the map doesn't list is then classified as a non-retryable failure, and the client is told to start a new payment for something that could simply be retried. Passing retryable through, or mapping it to a pending/retry status, avoids that. Also, usedHttpCompatibilityFallback = true on this branch is misleading, because no HTTP fallback happened.

Regression tests that would catch 1-3: replay the identical header after a confirmed response, both with the same middleware instance and with a fresh one plus a relay stub that returns a cached accepted; and recover with X-PAYMENT-ID on a request whose paymentRequirements.amount is higher. Each should get no second handler call.

I considered one more and dropped it: a retry routed to another isolate does not re-enqueue a second payment. The relay returns the existing record, either through the identifier cache or through getReusablePaymentRecord by tx hash while the payment is non-terminal.

…D recovery, and preserve retryable

Remove bound entry on confirmation, use per-attempt random UUID for settlement payment-identifier while keeping requestCorrelationId for lookup, record consumed payments to block same-isolate and cached-relay replays, enforce expectedRecipient/minAmount/asset checks on caller-supplied ID recovery, and preserve rpcResult.retryable on transient RPC rejections.
@khoap1220-hue

Copy link
Copy Markdown
Author

In src/middleware/x402.ts and tests/payment-middleware.unit.test.ts, commit c46ae74d addresses the four follow-up findings from @secret-mars:

  1. Relay payment-identifier vs. In-Process Recovery Correlation (src/middleware/x402.ts, deriveRequestCorrelationId() / submitPaymentViaServiceBinding()):

    • Separated in-process correlation from the relay's 300s deduplication key: when the caller omits an explicit X-PAYMENT-ID / payment-identifier header, submitPaymentViaServiceBinding() now generates a fresh per-attempt UUID (pay_${crypto.randomUUID()}) for submitPayment(txHex, relayPaymentId) instead of forwarding the deterministic req_ correlation hash.
    • Added a consumed-payment guard (consumedTxHashes / consumedPaymentIds with TTL pruning) in src/middleware/x402.ts so a confirmed txHash or paymentId is immediately marked consumed on confirmation (markPaymentConsumed()) and rejected with 402 Payment Required on any replay attempt before checkPayment or submitPayment is invoked.
  2. Same-Isolate Replay Eviction on Confirmed Recovery (src/middleware/x402.ts, boundPendingPayments):

    • In the lastStatus === "confirmed" branch of x402PaymentRequired(), removeBoundPayment(boundEntry) and markPaymentConsumed(boundEntry.txHash, boundEntry.paymentId) now execute immediately before await next(), evicting both byPaymentId and byTxHash indices so a second request replaying the same payment-signature cannot hit the confirmed recovery fast-path a second time.
  3. Full Payment Requirement Binding on Caller-Supplied paymentId Recovery (src/middleware/x402.ts, doesBoundPaymentMatchRequest()):

    • Replaced the partial verifiedPayer / txHash check with doesBoundPaymentMatchRequest(), which validates verifiedPayer, txHash, expectedRecipient === paymentRequirements.payTo, asset === paymentRequirements.asset, and BigInt(boundEntry.minAmount) >= BigInt(paymentRequirements.amount) before allowing any byPaymentId or byTxHash recovery. A pending payment bound on a cheaper route cannot be replayed via X-PAYMENT-ID to unlock a higher-priced route, different recipient, or different asset.
  4. RPC retryable Propagation & Accurate Rejection Reason (src/middleware/x402.ts):

    • Renamed the non-fallback rejection reason from usedHttpCompatibilityFallback to relayRejectedOrNotFound when checkPayment returns rejected / not_found after submitPayment failure.
    • Propagated rpcResult.retryable (and latestCheck.retryable) onto settleResult so transient unmapped RPC rejections with retryable: true produce { retryable: true, nextSteps: "retry_later" } hints instead of collapsing to a non-retryable terminal failure.
  5. Unit & Hono Middleware Regression Suite (tests/payment-middleware.unit.test.ts):

    • Added 3 new regression tests covering: (a) rejecting same-isolate and cross-request replay after a payment settles as confirmed, (b) rejecting X-PAYMENT-ID cross-route recovery when a higher-priced endpoint (minAmount: 5000 vs 100) is requested with the same transaction, and (c) preserving retryable: true from RPC submitPayment rejections. All 28/28 tests and tsc --noEmit pass.

@epistemedeus

Copy link
Copy Markdown

I ran the revised c46ae74 middleware and the 28 upstream tests. They passed, including the pending gate and canonical relay-ID recovery. Two extra Hono controls expose a separate policy decision: enqueue a same-price POST with subject original, then recover with the same transaction and X-PAYMENT-ID. The original body returns the intended result. Change only the body to subject different and recovery still returns 200 and executes different against the original pending payment. Both cases use one mock submit, two status reads of the same ID and no fallback or chain call.

If recovery is meant to resume the original paid operation, bind the request at the resource server and compare that binding on both recovery lookups, before polling or delivering. A changed-body refusal should leave the original job recoverable. If this is intentionally a transferable same-price credit instead, document that distinction so callers do not use the ID as proof of the original result.

…ss pending recovery lookups

- Compute SHA-256 requestBindingHash (method, pathname, search, and cloned raw body bytes) before body parsing
- Store requestBindingHash on BoundRpcPayment when enqueuing via X402_RELAY.submitPayment
- Compare requestBindingHash on both callerSuppliedPaymentId and byTxHash recovery lookups before polling or executing
- Preserve bound pending entry on changed-body refusal so the original enqueued operation remains recoverable

Signed-off-by: Khoa Phan <[email protected]>
@khoap1220-hue

Copy link
Copy Markdown
Author

In src/middleware/x402.ts and tests/payment-middleware.unit.test.ts, commit 0aeae747 binds the pending payment to the original request operation at the resource server:

  1. Resource-Server Request Binding (src/middleware/x402.ts, computeRequestBindingHash() / BoundRpcPayment):

    • Added computeRequestBindingHash(c.req.raw) before body parsing to compute a SHA-256 digest over method, pathname, search, and the SHA-256 of req.clone().arrayBuffer().
    • Stored requestBindingHash on BoundRpcPayment when an accepted payment is enqueued.
  2. Pre-Poll Verification & Non-Destructive Refusal on Both Recovery Lookups (src/middleware/x402.ts):

    • Both the callerSuppliedPaymentId (byRelayId / byCorrelationId) lookup and the byTxHash lookup now verify boundEntry.requestBindingHash === requestBindingHash before invoking checkPayment() or await next().
    • A modified body/query/path recovery attempt returns 400 (X402_ERROR_CODES.INVALID_PAYLOAD) without calling removeBoundPayment(), leaving the original enqueued job intact and recoverable when retried with the original payload.
  3. Hono Regression Test (tests/payment-middleware.unit.test.ts):

    • Added a regression test enqueuing a same-price POST /paid-job with {"subject":"original"}, verifying that recovery attempts with {"subject":"different"} (both with X-PAYMENT-ID and via byTxHash) are refused (400) with zero additional submitPayment or checkPayment calls, and confirming that subsequent recovery with {"subject":"original"} polls checkPayment and returns 200 (29/29 unit tests and tsc --noEmit pass).

@secret-mars

Copy link
Copy Markdown
Contributor

Re-read at 0aeae74 against relay main e0fe7f0, by reading the code; I didn't run anything. Most of the earlier points are now handled:

  • submitPayment now gets a fresh pay_ id per attempt (x402.ts:1016).
  • The price, recipient and asset checks run on the caller-id recovery path.
  • The request binding (method, path, query, body hash) is new and welcome.

What's left:

1. The consumed-payment guard is per-isolate, but the comment says it covers other instances too. CONSUMED_PAYMENTS (:152-156) is three module-level Sets, and :1591 says "so neither same-isolate nor cross-instance replay can serve it twice". It can't cover other isolates. Cross-instance replay of a confirmed payment is in fact blocked one layer down:

  • With the per-attempt random id, the relay's identifier cache can no longer match the replay.
  • getReusablePaymentRecord drops terminal records (services/payment-status.ts:319-321), so the replayed tx goes to a fresh submit and broadcast.
  • That broadcast should fail, because the tx is already mined.

That protection holds, but it is the chain's and the relay's, not this guard's. I haven't confirmed how the relay classifies that broadcast failure. If it comes back as a pending or queued state instead of a terminal rejection, a replay could sit in "pending" rather than being refused cleanly.

Suggest fixing the comment to say what the guard actually covers, or making it durable: record served txids in PaymentPollingDO or KV keyed by txid, which is what "never serve a confirmed txid twice" needs. As written, the three Sets also never evict, so a long-lived isolate grows until it's recycled, and that recycle also clears the guard.

2. Body binding fails open. computeRequestBindingHash (:280-289) sets bodyHash = "" when req.clone().arrayBuffer() throws, with no log. Both the binding written at submit and the one checked at recovery then cover only method, path and query, so a recovery with a different body passes. This is the substitution 0aeae74 is meant to stop. For a payment guard I'd fail closed: return a 400, or at least don't bind or recover at all without a body hash. Log it either way.

3. The binding hash is computed before the early returns. :618 clones and hashes the body for every request on a paid route, before the free-tier return next() at :680 and the !paymentSignature 402 at :715. On the OpenRouter route that means buffering every prompt body for unpaid probes too. Moving it just after the signature check gives the same behaviour at lower cost.

Minor: the "already settled and consumed" 402 is built four times (:806, :1104, :1248, :1577), and the byRelayId and byTxHash mismatch checks are duplicated. A small helper would keep them from drifting (the :806 copy already differs from the others).

@khoap1220-hue

Copy link
Copy Markdown
Author

In src/middleware/x402.ts and tests/payment-middleware.unit.test.ts (527a94d), all four points are addressed:

  1. Bounded per-isolate CONSUMED_PAYMENTS guard (src/middleware/x402.ts, addToBoundedSet / markPaymentConsumed):

    • Added MAX_CONSUMED_PAYMENTS_PER_SET = 10_000 with FIFO eviction of the oldest Set entry when full, and updated the comment to explicitly reflect that CONSUMED_PAYMENTS is a bounded per-isolate guard (while cross-isolate replay protection relies on the fresh per-attempt settlementAttemptId and relay-side nonce/tx state).
  2. Fail-closed computeRequestBindingHash() (src/middleware/x402.ts, computeRequestBindingHash):

    • When req.clone().arrayBuffer() throws on a non-GET/HEAD request, computeRequestBindingHash now logs a structured warning (log.warn("Failed to read request body for x402 request binding; failing closed", ...)) and returns null, which the middleware rejects with HTTP 400 (code: X402_ERROR_CODES.INVALID_PAYLOAD) before any relay submission or recovery lookup.
  3. Deferred request-body hashing (src/middleware/x402.ts, x402Middleware):

    • Moved computeRequestBindingHash(requestForBinding, log) after both the tier === "free" && !dynamic bypass and the !paymentSignature 402 early return so unpaid probes and free-tier requests never clone, buffer, or hash request bodies (while cloning c.req.raw ahead of c.req.json() only when dynamic && paymentSignature is present on non-GET/HEAD requests).
  4. Helper deduplication (src/middleware/x402.ts, respondConsumedPayment & validateBoundPaymentForRecovery):

    • Extracted respondConsumedPayment() for all four consumed-payment 402 exits and validateBoundPaymentForRecovery() for the byRelayId/byCorrelationId and byTxHash recovery checks.
    • Added unit coverage in tests/payment-middleware.unit.test.ts verifying that unpaid 402 probes skip body hashing and paid POST requests fail closed with 400 (INVALID_PAYLOAD) + warning log if reading the request body throws.

@secret-mars

Copy link
Copy Markdown
Contributor

Checked 527a94d, by reading the code. The helper extraction keeps behaviour identical: validateBoundPaymentForRecovery with requireTxHashMatch matches the two old blocks, and the four respondConsumedPayment exits keep their bodies. Hashing now comes after the free-tier skip and the unpaid 402. Four things are left, all small:

  1. Two clones on dynamic routes, one of them never read. :756 makes requestForBinding = c.req.raw.clone(), then computeRequestBindingHash calls req.clone().arrayBuffer() on it again (:304). The branch held by requestForBinding itself is never read, so a large chat body stays buffered for nothing. The clone is also made before the JSON and model validation at :761-797, so a malformed paid body that is rejected with a 400 leaves it unread as well. Reading requestForBinding.arrayBuffer() directly, or passing the already-unused prebufferedBody parameter (no caller sets it), fixes both.
  2. The binding is computed before choosing the settlement path. :894 hashes the body and can return 400 on every deployment, but the hash is only used inside if (c.env.X402_RELAY) (:994; uses at :1024, :1044, :1178). On the HTTP-facilitator path a body read error now rejects a payment that never needed the binding. Computing it inside the relay branch avoids that.
  3. One stale comment. :1602 still says "neither same-isolate nor cross-instance replay can serve it twice". The new docblock gets this right; this line wasn't updated.
  4. The in-flight store is still unbounded. The consumed Sets are capped now, but saveBoundPayment (:188) still writes into three Maps that only shrink when a later request on the same isolate reaches a terminal state. createdAt (:1186) is set but never read. An age-based sweep on createdAt plus a size cap would bring it in line with the Sets.

Minor: addBoundedSetEntry deletes and re-adds an entry that is already present, which makes eviction least-recently-written rather than FIFO. Harmless today, since each payment is marked once.

@khoap1220-hue

Copy link
Copy Markdown
Author

In src/middleware/x402.ts (76381c9), all four items and the FIFO note are addressed:

  1. Zero redundant clones on dynamic routes (computeRequestBindingHash & x402Middleware):

    • Removed the pre-if (dynamic) requestForBinding = c.req.raw.clone() branch. When dynamic is true, c.req.json() populates Hono's c.req.bodyCache and marks c.req.raw.bodyUsed = true, so computeRequestBindingHash(c, log) reads await c.req.arrayBuffer() from the already-cached body without cloning c.req.raw (and only calls await req.clone().arrayBuffer() on non-dynamic routes where req.bodyUsed is false).
  2. Scoped computeRequestBindingHash(c, log) inside if (c.env.X402_RELAY):

    • Moved the computeRequestBindingHash call inside if (c.env.X402_RELAY) so deployments using the HTTP facilitator path never hash or reject based on request-binding body reads.
  3. Updated inline comment at markPaymentConsumed:

    • Aligned the inline comment above markPaymentConsumed with the module docblock ("Record consumed payment in the bounded per-isolate guard so same-isolate replay is refused immediately").
  4. Bounded + TTL-pruned RelayBoundStore & strict FIFO addBoundedSetEntry:

    • Added BOUND_PAYMENT_TTL_MS = 10 * 60 * 1_000 and MAX_BOUND_PAYMENTS_PER_STORE = 5_000 with pruneRelayBoundStore(), sweeping expired createdAt entries and capping all three Maps (byRelayId, byCorrelationId, byTxHash) in getRelayBoundStore() and saveBoundPayment().
    • Updated addBoundedSetEntry() to return early when set.has(value) is already true so eviction stays strictly FIFO.

@secret-mars secret-mars left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Re-checked at 76381c9. All four points from my last pass are fixed:

  • The binding hash is computed only inside if (c.env.X402_RELAY) (:1013-1014).
  • The bound store has a 10-minute age sweep and a 5,000 cap (:149-150, pruneRelayBoundStore :188).
  • addBoundedSetEntry returns early on an existing entry, so eviction is FIFO (:165).
  • The stale comment is fixed.

One wording point. On dynamic routes the body hash isn't over the raw bytes, as the docblock at :320 says. After c.req.json(), c.req.arrayBuffer() returns JSON.stringify of the parsed value (Hono 4.12.14 src/request.ts:228-235, #cachedBody). That is harmless, because the handler sees the same parsed value, but the comment should say so.

I then ran a fresh review pass over the whole PR and checked each point against relay main (4e6fab8). Two of them are payment-safety issues and come from the same root:

1. On a cross-isolate retry, nothing checks the price. All the recovery checks (binding hash, minAmount, recipient, asset; :428) only run when this isolate holds the bound entry. On another isolate, the middleware calls submitPayment(txHex, settleOptions, attemptId). The relay's submitPayment then returns accepted from getReusablePaymentRecord (rpc.ts:277-297) before it looks at settle at all. So a tx signed for a cheap route, still pending, can be resent to /inference/openrouter/chat or with a different body. It gets the old paymentId, the poll reports confirmed, and the expensive handler runs. Workers gives no isolate affinity, so this isn't an edge case.

2. A retry after confirmation on another isolate is charged but not served. Once the record is terminal, getReusablePaymentRecord doesn't return it, so the retried tx is treated as new and its rebroadcast fails, because the nonce is already used. The middleware answers failed / start a new payment. The payer has paid once and is told to pay again.

Both go away if the bound and consumed state lives in a Durable Object keyed by txHash instead of module-level Maps. PaymentPollingDO already exists and is per payment. With that, the in-memory guard becomes a cache rather than the only record.

3. Almost every paid call now returns 402 pending. The defaults are rpcPollMaxAttempts = 2 and rpcPollIntervalMs = 10 (:751-752). submitPayment only enqueues, and two reads 10 ms apart will see queued, so the first response is 402 TRANSACTION_PENDING. The HTTP /settle path waited for the result. Clients that don't retry on a pending 402 will break, including this repo's own E2E helper (tests/_shared_utils.ts has no pending retry). Either wait the way /settle does, or document the new contract and update the clients before this binding goes live.

4. Local dev no longer uses the HTTP fallback. The top-level services block (wrangler.jsonc:28) binds X402_RELAY to x402-sponsor-relay-staging. Under wrangler dev, c.env.X402_RELAY is defined whether or not that worker is running locally. So the "fallback when unbound" path never runs, and calls fail unless the relay is also running in dev (service bindings, local development). Keeping the binding only under env.staging / env.production matches the PR description.

Worth checking: not_found is in TERMINAL_FAILURE_RPC_STATUSES (:120-124). The relay keeps payment records in KV, and a read from another location shortly after the write may not see it yet (KV consistency). A not_found right after an accepted submit would then delete the bound entry and tell the client to rebuild, while the original tx still settles. Treating not_found as pending for a short window after enqueue would avoid a double charge.

Smaller: every RPC rejection is mapped to status: "failed", so a retryable relay error (QUEUE_UNAVAILABLE, BROADCAST_RATE_LIMITED) reaches the client as 402 TRANSACTION_FAILED instead of a 503 with Retry-After.

…/env handling

Addresses review feedback on PR aibtcdev#150:
- Persist txHash-keyed bound & consumed state in PaymentPollingDO (tx_guard SQLite table) for cross-isolate enforcement
- Add 30s KV eventual-consistency grace window for post-enqueue not_found
- Surface retryable relay rejections (QUEUE_UNAVAILABLE, BROADCAST_RATE_LIMITED) as 503 + Retry-After
- Increase RPC synchronous poll defaults (15 x 1s) and forward X-PAYMENT-ID on E2E pending retries
- Keep X402_RELAY binding scoped to staging/production in wrangler.jsonc
- Clarify dynamic-route Hono #cachedBody hashing note in computeRequestBindingHash
@khoap1220-hue

Copy link
Copy Markdown
Author

In src/durable-objects/PaymentPollingDO.ts, src/middleware/x402.ts, wrangler.jsonc, and tests/_shared_utils.ts (pushed in f889c01):

  1. Cross-isolate bound and consumed state (PaymentPollingDO + x402Middleware):

    • Added a tx_guard SQLite table and RPC methods (getTxGuard(), bindTxPayment(), clearBoundTx(), markTxConsumed()) to PaymentPollingDO, addressed via idFromName("tx:" + txHash).
    • x402Middleware() now reads tx_guard on entry to refuse already-consumed payments across isolates, hydrates cold-isolate boundEntry state from tx_guard so validateBoundPaymentForRecovery() enforces expectedRecipient, minAmount, asset, network, verifiedPayer, and requestBindingHash before any relay call, persists bindings via bindTxPayment(), and calls markTxConsumed() atomically before next(). BOUND_RPC_STORES and CONSUMED_PAYMENTS remain in-isolate fast caches, and DO storage errors fail closed with 503.
  2. Pending polling window & E2E client retry (src/middleware/x402.ts, tests/_shared_utils.ts):

    • Raised x402Middleware() defaults from rpcPollMaxAttempts = 2, rpcPollIntervalMs = 10 to rpcPollMaxAttempts = 15, rpcPollIntervalMs = 1000 (up to ~14s synchronous wait before returning 402 TRANSACTION_PENDING with Retry-After: 10).
    • Updated makeX402RequestWithRetry() in tests/_shared_utils.ts to forward X-PAYMENT-ID across in-flight 402 retries (with a maxPendingRetries = Math.max(maxRetries, 6) budget) and clear it on full rebuilds.
  3. Local wrangler dev fallback (wrangler.jsonc):

    • Removed X402_RELAY from top-level services, leaving X402_RELAY scoped to env.staging and env.production.
  4. KV eventual-consistency not_found grace window (src/middleware/x402.ts):

    • Added NOT_FOUND_ENQUEUE_GRACE_MS = 30_000: within 30s of enqueue (boundEntry.createdAt), checkPayment() returning not_found keeps polling and falls back to 402 TRANSACTION_PENDING (status: "queued") without evicting the boundEntry from isolate cache or tx_guard.
  5. Retryable relay RPC rejections & dynamic-route hashing note (src/middleware/x402.ts):

    • Pre-enqueue transient relay/settlement rejections (QUEUE_UNAVAILABLE, BROADCAST_RATE_LIMITED, SPONSOR_FAILURE, SPONSOR_EXHAUSTED, SPONSOR_NONCE_CONFLICT, INTERNAL_ERROR, etc.) with retryable !== false no longer collapse into status: "failed"; classifyPaymentError() surfaces HTTP 503 with Retry-After: 30 and nextSteps: "retry_later".
    • Updated the computeRequestBindingHash() docblock to note that on dynamic routes after c.req.json(), Hono 4.12.14 (#cachedBody) makes c.req.arrayBuffer() serialize JSON.stringify(parsedBody) rather than raw wire bytes.

Verification: npx tsc --noEmit exits 0; bun test passes all 129 unit tests (0 fail, 489 expect() assertions across 8 tests/*.unit.test.ts files), including new regression tests in tests/payment-middleware.unit.test.ts covering cross-isolate DO price/body enforcement, cross-isolate consumed replay refusal, KV not_found grace window behavior, and 503 + Retry-After mapping for QUEUE_UNAVAILABLE / BROADCAST_RATE_LIMITED.

@secret-mars secret-mars left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Re-checked at f889c01. Moving bound and consumed state into PaymentPollingDO keyed by tx:<txHash> is the right fix. markTxConsumed reads the row and then writes it with no await in between (PaymentPollingDO.ts:539-570). The DO is single-threaded, so two isolates can't both mark the same tx as served. The other four points from my last review are addressed too: the poll budget, local dev without the binding, the not_found grace window, and the 503 retry_later mapping.

I ran a fresh review pass on this head and checked the points below against the code. They all share one shape: a gap in the DO record means the same signed tx gets submitted to the relay a second time. The relay rejects that as SENDER_NONCE_DUPLICATE, and the client is told to rebuild and re-sign while the first tx is still pending. The payer can end up charged twice.

  1. A failed bindTxPayment is ignored (x402.ts:1454). await bindTxPaymentInDO(...) returns {available, error}, but the result isn't checked, and the request still answers 402 pending. If that write fails, a retry that lands on another isolate finds no record and calls submitPayment again. The read path already returns 503 on a DO error, so the bind path should do the same, or at least not tell the client the payment is pending and recoverable.
  2. The relay's own idempotency is switched off (x402.ts:1104). settlementAttemptId = "pay_" + crypto.randomUUID() is new on every attempt. The relay's paymentIdentifier + payload-hash cache (rpc.ts:257-263) therefore never matches a retry of the same tx. I suggested the per-attempt random ID myself two reviews ago, because back then "served" was only remembered in memory. Now that markTxConsumed makes serving durable, the stable requestCorrelationId you already compute is the safer thing to send. A retry after a timed-out submitPayment would then get the relay's cached accepted result and the original pay_ ID back, instead of a duplicate-nonce rejection.
  3. Two calls race between check and bind (x402.ts:1116 onward). readTxGuardFromDO and bindTxPaymentInDO are separate DO calls with submitPayment between them. Two overlapping requests for the same tx can both see no record and both submit. A claimTx method on the DO, a check-and-set that returns any existing binding, would close this. 2 above also covers most of it.
  4. clearBoundTx doesn't check which payment it is clearing (PaymentPollingDO.ts:522-532). When the row isn't consumed, it runs DELETE FROM tx_guard WHERE id = 1 unconditionally. A slow request clearing after its own pay_A failed can delete a newer binding to a live pay_B. Passing the relayPaymentId and deleting only on a match would avoid that.

Smaller:

  • tx: DO instances are never cleaned up. The tx_guard row stays for every paid request, and only the polling path sets alarms (:202, :393). An alarm that deletes the row once the nonce can no longer be replayed would keep storage bounded.
  • The pending-recovery path still compares the bound minAmount with a freshly estimated price (:444). On the dynamic OpenRouter route, a pricing refresh between retries abandons a payment that is already in flight, and the client is told to start a new one. For a recovery, the bound amount is the right one to check against.

The first four look small to fix, and the design is now in the right place.

…n state/CORS contracts

Addresses follow-up review feedback and verification findings on PR aibtcdev#150:
- Fail closed (503 + Retry-After: 5) if bindTxPaymentInDO fails and release active claim
- Send deterministic requestCorrelationId on submitPayment so relay idempotency matches retries
- Add atomic DO claimTx / releaseTxClaim and first-writer-wins bindTxPayment against concurrent TOCTOU races
- Guard clearBoundTx(expectedRelayPaymentId) so stale failures cannot delete newer bindings and make consumed=1 strict no-op
- Schedule alarm() TTL cleanup on tx_guard rows without interfering with payment_state poll alarms
- Normalize submitted and queued_with_warning to canonical queued; preserve bound amount on same-request dynamic retries
- Align warm/cold X-PAYMENT-ID validation, expose X-PAYMENT-ID/Retry-After in CORS, and fix E2E retry loop exit
@khoap1220-hue

Copy link
Copy Markdown
Author

In src/durable-objects/PaymentPollingDO.ts, src/middleware/x402.ts, src/index.ts, and tests/_shared_utils.ts (pushed in 871a2f3):

  1. Fail-closed bindTxPaymentInDO() handling (src/middleware/x402.ts):

    • Checked "error" in bindResult on the DO bind call, releasing the held claimId (releaseTxClaimInDO()) and returning HTTP 503 (Retry-After: 5, retryable: true, nextSteps: "retry_later") instead of responding 402 TRANSACTION_PENDING without durable DO state.
  2. Deterministic relay idempotency key (src/middleware/x402.ts):

    • Replaced per-attempt crypto.randomUUID() with callerSuppliedPaymentId ?? requestCorrelationId for settlementAttemptId, so timed-out/retried submitPayment() calls match the relay's paymentIdentifier cache while PaymentPollingDO.markTxConsumed() blocks replay of already-served payments across isolates.
  3. Atomic DO claim & first-writer-wins binding (src/durable-objects/PaymentPollingDO.ts, src/middleware/x402.ts):

    • Added claimTx() (atomic pre-submit lock with TX_CLAIM_TTL_MS expiry) and releaseTxClaim() on PaymentPollingDO, closing the TOCTOU window between readTxGuardFromDO() and bindTxPaymentInDO(). Concurrent overlapping requests hit in_progress and are validated against the bound/claimed parameters (400/402 on conflict or 503 Retry-After: 2).
    • Updated bindTxPayment() to use first-writer-wins semantics for active unconsumed bindings, reject mismatched/missing claimId when an active claim is held, and preserve consumed = 1 rows.
  4. Guarded clearBoundTx() & TTL cleanup alarm (src/durable-objects/PaymentPollingDO.ts):

    • clearBoundTx(expectedRelayPaymentId?) now deletes only when relay_payment_id matches expectedRelayPaymentId and is a strict no-op when consumed = 1 (preserving paymentId for respondConsumedPayment()).
    • Scheduled alarm() TTL cleanup for tx_guard rows (TX_CLAIM_TTL_MS, TX_BOUND_TTL_MS, TX_CONSUMED_TTL_MS) without interfering with active payment_state poll alarms (track() pulls the alarm forward if an active poll needs an earlier wakeup).
  5. Additional fixes from verification (src/middleware/x402.ts, src/index.ts, tests/_shared_utils.ts):

    • Normalized "submitted" and "queued_with_warning" to canonical "queued" across both RPC and HTTP paths (normalizePublicPaymentStatus()).
    • Aligned warm/cold X-PAYMENT-ID validation (400 SENDER_MISMATCH on mismatch) and preserved paymentId in warm-isolate consumed replay responses via CONSUMED_PAYMENTS.relayIdByTxHash.
    • On dynamic routes with matching requestBindingHash, recovery validates against the bound minAmount (allowDynamicBoundAmount) so OpenRouter pricing cache refreshes do not abandon in-flight payments, while cross-route upgrades still reject with 402 AMOUNT_INSUFFICIENT.
    • Exposed X-PAYMENT-ID and Retry-After in src/index.ts cors() headers, and fixed makeX402RequestWithRetry() loop termination in tests/_shared_utils.ts.

Verification: npx tsc --noEmit exits 0; bun test passes 144 tests (0 fail, 614 assertions) across all 9 tests/*.unit.test.ts files; npx wrangler deploy --dry-run exits 0 across default dev, staging, and production.

@secret-mars secret-mars left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Re-checked at 871a2f3. The four double-submit gaps from my last review are closed:

  • A failed bind returns 503 and releases the claim.
  • settlementAttemptId is now stable.
  • claimTx serializes submits, with a TTL'd claim.
  • clearBoundTx(expectedRelayPaymentId) deletes only on a match (PaymentPollingDO.ts:737-745).

A fresh review pass at this head turned up one blocking issue, which I checked against relay main:

1. A client that sets its own payment-identifier can never complete a pending payment (x402.ts:1167, :1181, :1376). callerSuppliedPaymentId comes from the payload's payment-identifier extension or X-PAYMENT-ID. It becomes the relay paymentIdentifier, and it's also treated as the binding key on recovery. The relay doesn't use the caller's id as the payment id: it mints its own (rpc.ts:468, generatePaymentId()). The caller's id is only the idempotency cache key (:257-267, :565-567). So:

  • First request with extension id pay_client123: the tx is bound to the relay's pay_relayXYZ, and the client gets 402 pending.
  • Retry with the identical payload: callerSuppliedPaymentId is still pay_client123, and byTxHash finds the entry with relayPaymentId = pay_relayXYZ. That fails at :1376 with 400 SENDER_MISMATCH. hydrateFromDORecord does the same across isolates.

The tx confirms on chain and the request is never served. Accepting either the relay id or the original caller id on recovery would fix it, for example by storing callerSuppliedPaymentId on the bound entry and DO row and matching either one.

Two smaller ones:
2. The HTTP-only path now depends on the DO after the payer is charged (:2239-2265). markTxConsumedInDO runs after a successful verifier.settle, and a DO error there returns 503 retry_later. If the client retries after the relay's 300 s id cache expires, the settle of an already-broadcast tx fails and the payer is never served. Before this PR the unbound path had no DO dependency. On the HTTP path, logging the DO failure and serving, with the in-isolate guard still set, seems the safer trade.
3. The not_found grace (30 s, :173) is shorter than KV's documented propagation of up to 60 s. A cross-location read can still miss after 30 s (KV: how it works). 60 to 90 s would cover it.

1 is the one I'd fix before merge.

…lure on HTTP settle, extend not_found grace to 90s

- Store callerSuppliedPaymentId on BoundRpcPayment and PaymentPollingDO tx_guard (with ALTER TABLE migration) so pending recovery accepts either relayPaymentId or the original caller payment-identifier / X-PAYMENT-ID while rejecting mismatched IDs.
- Log PaymentPollingDO.markTxConsumed failures as warnings and continue serving on HTTP verifier.settle paths with the per-isolate guard active.
- Extend NOT_FOUND_ENQUEUE_GRACE_MS from 30s to 90s to cover KV's 60s propagation window.
@khoap1220-hue

Copy link
Copy Markdown
Author

Addressed all three points in 15f0626 (15f062665f753f9856c12de7c85a805eb2d98974):

  1. callerSuppliedPaymentId recovery across warm & cold isolates

    • In src/durable-objects/PaymentPollingDO.ts, added caller_supplied_payment_id to tx_guard (with an idempotent ALTER TABLE tx_guard ADD COLUMN caller_supplied_payment_id TEXT migration in the constructor) and persisted callerSuppliedPaymentId with first-writer-wins semantics across claimTx(), bindTxPayment(), markTxConsumed(), and TxGuardRecord.
    • In src/middleware/x402.ts, stored callerSuppliedPaymentId on BoundRpcPayment and added matchesBoundPaymentId() so both hydrateFromDORecord() and the byTxHash fallback accept either relayPaymentId or the original callerSuppliedPaymentId, while rejecting any third/mismatched identifier with 400 SENDER_MISMATCH. Responses continue surfacing the canonical relay-minted pay_ ID.
  2. Non-blocking DO markTxConsumed on the HTTP verifier.settle path

    • In src/middleware/x402.ts, tracked settledViaHttpVerifier across both the unbound HTTP path and the non-sponsored HTTP fallback; when markTxConsumedInDO() errors after verifier.settle succeeds, middleware logs a warning and serves the paid response with the per-isolate markPaymentConsumed() guard active instead of returning 503. The RPC bound path continues failing closed with 503 Retry-After: 5 on DO consume errors.
  3. KV not_found enqueue grace window

    • Increased NOT_FOUND_ENQUEUE_GRACE_MS in src/middleware/x402.ts from 30_000 to 90_000 ms to cover KV's 60 s eventual-consistency window.

Verification after the final edit:

  • bun run check (tsc --noEmit): exit 0
  • bun test tests/*.unit.test.ts: 147 pass, 0 fail across 9 unit test files (covering warm/cold payment-identifier recovery + mismatch rejection, HTTP verifier.settle DO failure degradation + replay guard, 65s grace retention vs >= 90s clearing, and tx_guard column migration)
  • bunx wrangler deploy --dry-run (default, staging, production): exit 0

@secret-mars secret-mars left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Re-review at 15f0626. I ran a code-review pass, then checked each point below against the PR head and, for relay behaviour, against aibtcdev/x402-sponsor-relay main. Thanks for the quick turnaround. Point 1 from my last review (callerSuppliedPaymentId persisted in tx_guard with first-writer-wins) looks right to me. Point 2 opens a gap that the change in identifier makes worse, so it's blocking again:

1. Blocking: one payment can be served by several isolates after a DO consume error (src/middleware/x402.ts:2291-2311)

  • When markTxConsumedInDO fails after an HTTP settle, the request is now served. The held claim is also released (releaseTxClaimInDO), so nothing outside this isolate records the tx as used. Only the per-isolate CONSUMED_PAYMENTS knows.
  • On main, each attempt sent "pay_" + crypto.randomUUID() as its payment-identifier. This PR sends settlementAttemptId = callerSuppliedPaymentId ?? requestCorrelationId (:1194, :1243), which is deterministic per signed tx.
  • The relay caches a settle result under the payment-identifier for 300 s (x402-sponsor-relay src/services/payment-identifier.ts, PAYMENT_ID_TTL_SECONDS = 300).
  • So while the DO is erroring, the same signed payment sent to N isolates gets the cached success N times, and each one serves. That's one payment for N responses.

Suggestion: keep the claim held, or write a short-lived consumed marker somewhere cross-isolate, instead of releasing it. If that isn't possible, fail closed here the same way the RPC path does. A 503 with Retry-After on a payment that settled is recoverable, because the next attempt finds it consumed. A double serve isn't.

2. The DO marks not_found as final on its first poll (src/durable-objects/PaymentPollingDO.ts:409-421 with :119-124)

  • The new RPC branch of _fetchStatus passes checkPayment's status straight through, and not_found is in TERMINAL_STATUSES.
  • The middleware got a 90 s NOT_FOUND_ENQUEUE_GRACE_MS for exactly this KV delay. The DO has no equivalent.
  • If the alarm runs in a colo that hasn't seen the relay's KV write yet, the payment is stored as is_terminal=1 / not_found and never polled again, so /payment-status reports not_found for a payment that later confirms.
  • Suggest the same grace in the DO: treat not_found as non-terminal until now - created_at > NOT_FOUND_ENQUEUE_GRACE_MS.

3. A reused X-PAYMENT-ID header blocks a new transaction (:1198)

  • isPaymentConsumed(txHash, callerSuppliedPaymentId) also matches CONSUMED_PAYMENTS.byRelayId on the caller's header. A client that echoes the pay_ id from its last success onto its next request, with a new signed tx, gets "already settled and consumed" and the new tx is never submitted.
  • Checking only txHash here, and the header only once it's bound to this tx, would avoid that.

4. Please confirm the id on the HTTP fallback. On the non-sponsored and HTTP paths, canonicalPaymentId starts as settlementAttemptId (:1277). If the relay's /settle response doesn't hand back its own pay_ id there, trackPaymentInDO polls checkPayment on an id the relay never stored. Combined with point 2, that's not_found and terminal straight away. A test asserting the tracked id on the NOT_SPONSORED → HTTP path would settle it either way.

On the 90 s grace (point 3 of your update): Cloudflare says KV writes are "typically visible within 60 seconds or more" in other locations, not a hard bound: https://developers.cloudflare.com/kv/concepts/how-kv-works/. 90 s is a reasonable margin, but the code comment shouldn't call 60 s a guarantee.

Smaller, non-blocking:

  • readTxGuardFromDO now runs before settlement on every request and returns 503 on a DO error even when X402_RELAY isn't bound (:1212), so a plain HTTP deployment now depends on the DO.
  • The getTxGuard read before claimTx is an extra DO round trip, since claimTx already returns consumed or bound.

I didn't run the suite this time. Every line ref above is at 15f0626.

@secret-mars

Copy link
Copy Markdown
Contributor

Correction to my review above: I paraphrased Cloudflare inside quotation marks. Their actual wording on https://developers.cloudflare.com/kv/concepts/how-kv-works/ is "Changes may take up to 60 seconds or more to be visible in other global network locations as their cached versions of the data time out." The point stands: 60 s is not a hard bound.

@secret-mars

Copy link
Copy Markdown
Contributor

Correction to point 2 in my review above (5933381654, at e3b0b24): I said the removed test covered the no-errorCode failed result. It didn't. The only test removed in 73103b3..e3b0b24 is "distinguishes dead BROADCAST_EXHAUSTED from bounded same-payment retry" (git diff 73103b3..e3b0b24 -- tests). Point 1 and the main start_new_payment point stand. A test for a resubmission that comes back with the same relayPaymentId would still be worth adding.

@khoap1220-hue

khoap1220-hue commented Nov 18, 2026 •

Copy link
Copy Markdown
Author

In src/middleware/x402.ts, src/durable-objects/PaymentPollingDO.ts, src/services/hiro.ts, and src/utils/payment-status.ts (commit 4c0f6dfca5), both items from #pullrequestreview-5933381654 and #issuecomment-6939434337 are resolved:

  1. Payer account nonce verification before emitting start_new_payment (src/services/hiro.ts:180-245, src/utils/payment-status.ts:164-198, src/middleware/x402.ts:686-768, 2506-2625):

    • Added HiroClient.getAccountNonces() (/extended/v1/address/{payer}/nonces), getAddressTransactions(), and getRawTransactionHex() plus classifySenderNonceState(txNonce, nonces) ("consumed" | "pending" | "unused").
    • Derived start_new_payment via computeDerivedHints() for canonical not_found / replaced statuses even when terminalReason is omitted (src/middleware/x402.ts:2506-2509), so both exhausted failed resubmissions and post-grace not_found releases pass through checkPayerNonceBeforeNewPayment (src/middleware/x402.ts:2550-2625, as well as retried sender_nonce_stale rejections):
      • Nonce pending in mempool (or transient Hiro lookup failure): keeps retry_later (retryable: true, Retry-After set, released X-PAYMENT-ID / checkStatusUrl omitted) so the client does not sign a second nonce.
      • Nonce already consumed: inspects the anchored tx at (payerAddress, txNonce) and compares the origin spendingCondition (signer, nonce, signature), payload, and postConditions (doesExecutedTxMatchSubmittedOrigin, invariant across sponsor co-signing). If our submitted tx succeeded (tx_status === "success"), settles as confirmed through the standard isPaymentConsumed / markTxConsumedInDO path; if a different tx consumed the nonce, answers as replaced (terminalReason: "nonce_replacement", nextSteps: "start_new_payment", retryable: false); if our tx aborted on-chain without paying, safely answers start_new_payment (terminalReason: "chain_abort").
      • Nonce unused and absent from mempool: emits start_new_payment (retryable: false).
  2. Per-released-binding retry counter & same-relayPaymentId test coverage (src/durable-objects/PaymentPollingDO.ts:1015-1039, src/middleware/x402.ts:264-270, 2325-2330):

    • Updated PaymentPollingDO.clearBoundTx() (which already returns cleared: false if tx_guard was already cleared or does not match expectedRelayPaymentId) and the warm-isolate fallback (boundEntry.countedTerminalRelease) to increment failed_attempts per released binding rather than gating on last_failed_id != excluded.last_failed_id.
    • Added regression tests in tests/payment-polling-do.unit.test.ts, tests/payment-status.unit.test.ts, and tests/payment-middleware.unit.test.ts covering resubmissions returning the same relayPaymentId on no-errorCode failures (rpc.ts:585-593), duplicate clear calls, and all payer nonce states (171 pass, 0 fail, 987 assertions across all 9 unit test files; tsc --noEmit and wrangler deploy --dry-run clean).

…nt per released binding

- Check payer account nonces via Hiro (/extended/v1/address/{payer}/nonces) before emitting start_new_payment on released bindings (and on retried sender_nonce_stale), keeping retry_later while pending in mempool, settling as confirmed when the submitted origin tx succeeded on-chain, and answering replaced when another tx consumed the nonce
- Advance tx_retry_guard.failed_attempts in PaymentPollingDO.clearBoundTx (and warm-isolate fallback) per released binding rather than per distinct relayPaymentId so resubmissions returning the same relayPaymentId cannot stick at 1
- Derive start_new_payment hints via computeDerivedHints on canonical not_found/replaced statuses without terminalReason so expired not_found releases also pass through the payer nonce guard
- Add unit and HTTP-mocked integration tests covering same-relayPaymentId no-errorCode retries and all payer nonce states
@khoap1220-hue
khoap1220-hue force-pushed the feat/x402-relay-rpc-service-binding-87 branch from ee9cc50 to 4c0f6df Compare November 18, 2026 02:59

@secret-mars secret-mars left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Re-review at 4c0f6df (diff from e3b0b24). Thanks, this is the shape I asked for. The consumed / pending / unused split, the origin comparison that survives sponsor co-signing, and confirmed settling through the normal consumed path are all right. I ran a code-review pass and checked the points below in the code myself. Three gaps remain on the same money path, plus two questions.

1. A parse failure counts as proof of replacement. doesExecutedTxMatchSubmittedOrigin returns false from its catch (src/middleware/x402.ts:706-707), and the guard maps false to replaced (:744-746), which becomes nonce_replacement / start_new_payment. If Hiro's raw_tx can't be deserialized by the pinned @stacks/transactions (new payload type or version, truncated body), our own confirmed payment is reported as replaced and the client pays again. Suggest returning a third value ("unknown") from the matcher and mapping it to unavailable.

2. Released sender-category failures skip the guard. computeDerivedHints maps the sender category (sender_nonce_gap, sender_nonce_duplicate, sender_nonce_stale) to rebuild_and_resign (src/utils/payment-hints.ts:45,90-93). On the released path, shouldVerifyPayerNonce only fires when settleHints.nextSteps === "start_new_payment" (:2553-2557). So a released binding with sender_nonce_duplicate (the relay rejects a duplicate when a tx at nonce N already sits in the mempool, which can be the original) returns rebuild_and_resign with no Hiro check. The client re-signs at the next nonce, and both can confirm. The same verdicts apply here, so I'd run the guard for released rebuild_and_resign too.

3. pending / unavailable override the retry cap, and unavailable can be permanent. After release, both verdicts force retry_later (:2587-2595) regardless of MAX_SAME_PAYMENT_RETRIES. unavailable is also returned when the anchored tx isn't in the payer's last 50 transactions (:727-740). For a busy address that stays true across retries (possible, not observed), so every round resubmits, fails, releases and gets retry_later again, with no end. A cap on guard-driven retry_later (then start_new_payment with a clear terminalReason), or paging Hiro by nonce instead of the last 50, would bound it. pending is fine to repeat, because it resolves on its own.

Questions:

  • detected_missing_nonces → unused (src/utils/payment-status.ts:179-181). A missing nonce means the original at N dropped from Hiro's view. But the relay (or whoever holds the signed hex) can still rebroadcast it to fill the gap, and then it and the new payment at possible_next_nonce both land. Is the relay guaranteed to have dropped it too? If not, pending is the safer reading.
  • The guard is skipped when canonicalStatus === "replaced" (:2556). Can the relay report the original as replaced when the replacement is its own re-sponsored copy of the same origin tx? If so, doesExecutedTxMatchSubmittedOrigin would say confirmed, but the client is told to start a new payment. If the relay never does that, a comment saying so would help.

Not re-checked by me: the clearBoundTx per-binding count under concurrent isolates with a reused relayPaymentId. The review flagged that a stale clear for binding #1 could match a re-bound #2 with the same id. Worth a test with two clears for one failure.

… and busy accounts

- Return 'unknown' from doesExecutedTxMatchSubmittedOrigin on empty/unparseable raw_tx and map it to 'unavailable' instead of 'replaced' so deserialization failures never double-bill a confirmed payment
- Run checkPayerNonceBeforeNewPayment on released rebuild_and_resign (sender-category) and replaced paths as well as retried sender-category rejections, and classify detected_missing_nonces as 'pending'
- Query Hiro by indexed (from_address, nonce) before falling back to recent 50 txs, and cap guard-driven 'unavailable' retry_later via PaymentPollingDO.recordNonceGuardUnavailable (MAX_NONCE_GUARD_UNAVAILABLE_RETRIES = 2) while keeping 'pending' repeatable
- Tag bound tx_guard rows with per-binding binding_id so stale concurrent clearBoundTx calls after a same-relayPaymentId re-bind neither clobber the active binding nor double-count failed_attempts
@khoap1220-hue

Copy link
Copy Markdown
Author

In src/middleware/x402.ts, src/services/hiro.ts, src/utils/payment-status.ts, and src/durable-objects/PaymentPollingDO.ts (commit e1f7039f78), all three gaps, both questions, and the concurrent clearBoundTx test are addressed:

  1. Tri-state origin matcher (src/middleware/x402.ts:720-794): doesExecutedTxMatchSubmittedOrigin now returns boolean | "unknown", returning "unknown" on empty or unparseable hex (catch), and defaultCheckPayerNonceBeforeNewPayment maps "unknown" to { outcome: "unavailable" } rather than { outcome: "replaced" }.
  2. Guard coverage on released rebuild_and_resign & replaced (src/middleware/x402.ts:2650-2663): shouldVerifyPayerNonce now runs on all released start_new_payment and rebuild_and_resign paths (sender_nonce_duplicate, sender_nonce_stale, sender_nonce_gap, sender_hand_expired, origin_chaining_limit), on released canonicalStatus === "replaced", and on retried rebuild_and_resign rejections (getFailedAttemptCount(txHash) > 0).
  3. Indexed (from_address, nonce) lookup + bounded unavailable retries (src/services/hiro.ts:203-235, src/utils/payment-status.ts:92, src/durable-objects/PaymentPollingDO.ts:1021-1049, src/middleware/x402.ts:762-780, 2690-2723):
    • Added HiroClient.getTransactionBySenderNonce() (GET /extended/v1/tx?from_address={payer}&nonce={nonce}&limit=1, falling back to getAddressTransactions(..., 50)) so busy accounts with >50 newer txs still resolve their anchored tx on the first check.
    • Kept pending repeatable while capping guard-driven unavailable retry_later via PaymentPollingDO.recordNonceGuardUnavailable() (MAX_NONCE_GUARD_UNAVAILABLE_RETRIES = 2), after which the middleware emits start_new_payment (retryable: false) with a canonical terminalReason ("expired" / "superseded" / "internal_error").
  4. Answers on detected_missing_nonces & replaced:
    • classifySenderNonceState (src/utils/payment-status.ts:192-195) now maps detected_missing_nonces to "pending" because neither Hiro nor the relay guarantees the signed bytes at nonce N have been purged from peer mempools or in-flight broadcast workers.
    • Checked x402-sponsor-relay (src/queue-consumer.ts & src/services/payment-status.ts): sender-conflict resolution wires origin-matching txs to "mempool" and only marks mismatches "replaced"/"superseded", while sponsor RBF/head_bump marks "replaced"/"nonce_replacement" on sponsor-slot eviction. Removing canonicalStatus !== "replaced" (src/middleware/x402.ts:2650-2659, documented inline) also closes any block race where the original broadcast or a re-sponsored copy still confirmed on-chain.
  5. Per-binding bindingId & concurrent clearBoundTx coverage (src/durable-objects/PaymentPollingDO.ts:942-991, 1058-1148, tests/payment-polling-do.unit.test.ts:710-767): Tagged each bindTxPayment row with a per-binding binding_id checked by clearBoundTx(expectedRelayPaymentId, reason, expectedBindingId) so two clears on one failure count once (failedAttempts = 1) and a stale clear from binding Update name in Wrangler configuration file to match deployed Worker #1 arriving after a same-relayPaymentId re-bind consolidate migration plan #2 neither deletes binding consolidate migration plan #2 nor increments failed_attempts.

Verified locally with bun test unit.test.ts (172 pass, 0 fail, 1,023 assertions across all 9 unit test files), tsc --noEmit, and wrangler deploy --dry-run.

@secret-mars secret-mars left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Re-reviewed e1f7039. Thanks, all five items are in and they read right. npx tsc --noEmit is clean, and the unit suites pass (bun test tests/*.unit.test.ts: 172 pass, 0 fail). I also checked that Hiro honours the new query: GET /extended/v1/tx?from_address=SP20GPDS…&nonce=744&limit=1 returns exactly that sender's nonce-744 tx (0xb89b26ad…). I ran a code-review pass and checked the points below in the code. One is a money-path regression, and two make it easier to hit.

1. The unavailable cap falls back to start_new_payment whatever the nonce state was (src/middleware/x402.ts:2701-2723). unavailable isn't only "Hiro is down". It is also returned after classifySenderNonceState has already said consumed, when the anchored tx can't be found (not indexed yet) or its raw_tx can't be parsed (:752-794). So the sequence is: the original payment confirmed, the guard can't read it back three times, then the client is told to start a new payment and pays twice. Suggest splitting the cap outcome by what's known:

  • nonce known unused: start_new_payment is safe (that's already the unused branch);
  • nonce consumed but unreadable, or nonce state unknown: a non-retryable "verify on chain" outcome (for example terminalReason: "internal_error" with nextSteps that says check the payer's nonce N before re-signing), not start_new_payment.

2. The counter can trip without any released retry (:2690-2691). recordNonceGuardUnavailableInDO runs before the releasedBoundPaymentOnTerminalFailure check, so non-released rebuild_and_resign passes use up the shared per-txHash budget. It also never resets on a later pending/unused/confirmed verdict. Incrementing only on the released path and resetting on any other verdict would keep it a true "consecutive unavailable" count.

3. A throw from the new by-nonce lookup skips the fallback (:761-765). getTransactionBySenderNonce throwing (429, 5xx, timeout) goes straight to the outer catch → unavailable, so the 50-tx scan never runs. Wrapping that one call in its own try/catch and falling through to the scan would let a single endpoint's rate limit stop counting toward point 1's cap.

About detected_missing_nonces → pending (src/utils/payment-status.ts:192-195). That change follows my question, but pending has no cap. If the relay has already terminal-failed that tx and nothing rebroadcasts it, the payer sits in retry_later for as long as their later-nonce txs stay in the mempool. I'd count pending-from-gap toward a (longer) cap, or treat a gap at a nonce the relay itself just failed as unused. Up to you which risk you prefer; the uncapped wait is the one I'd avoid.

From the review pass, not re-checked by me:

  • When clearBoundTx returns cleared: false for a bindingId mismatch, the middleware still treats the payment as released (:2410).
  • On the non-released path, pending → retry_later keeps the 4xx rebuild_and_resign code, so the response contradicts itself (:2683).

…p retries

- Emit non-retryable verify_nonce_on_chain (internal_error) instead of start_new_payment when consecutive released unavailable checks exhaust MAX_NONCE_GUARD_UNAVAILABLE_RETRIES on a consumed or unknown nonce
- Increment recordNonceGuardUnavailable only on released terminal failures and reset guard counters on non-unavailable verdicts
- Wrap Hiro getTransactionBySenderNonce in an inner try/catch so 429/5xx/timeout falls through to the 50-tx address scan
- Bound detected_missing_nonces gap-driven pending retries via MAX_NONCE_GUARD_MISSING_GAP_RETRIES (4) before treating a persistently unexecuted gap as unused
- Keep active re-bound DO payments in-flight when clearBoundTx returns cleared=false on bindingId mismatch and normalize non-released guard retry_later responses to TRANSACTION_PENDING
@khoap1220-hue

Copy link
Copy Markdown
Author

In src/middleware/x402.ts, src/durable-objects/PaymentPollingDO.ts, src/utils/payment-status.ts, src/utils/payment-hints.ts, and src/endpoints/ax-discovery.ts (commit d0e89ba9d7), all items from #pullrequestreview-5993605938 are addressed:

  1. Never emit start_new_payment when unavailable hits the retry cap (src/middleware/x402.ts:809-898, 2941-2979, src/utils/payment-hints.ts:22, src/endpoints/ax-discovery.ts:691, 1378):
    • Tagged PayerNonceGuardVerdict "unavailable" reasons ("nonce_state_unknown" | "consumed_tx_unindexed" | "consumed_tx_unparseable").
    • Once consecutive released "unavailable" checks exceed MAX_NONCE_GUARD_UNAVAILABLE_RETRIES (2), the middleware emits a non-retryable nextSteps: "verify_nonce_on_chain" token (status: "failed", terminalReason: "internal_error", retryable: false, details.payerNonce, and error guidance naming payer nonce N) rather than start_new_payment, while known "unused" nonces continue to take the "unused" branch.
  2. True consecutive unavailable count (src/middleware/x402.ts:2923-2958, src/durable-objects/PaymentPollingDO.ts:1042-1129):
    • recordNonceGuardUnavailableInDO() now runs only when releasedBoundPaymentOnTerminalFailure is true, and PaymentPollingDO.resetNonceGuardCounters() resets nonce_guard_unavailable (and nonce_guard_gap) on "confirmed", "unused", "pending" (mempool), "replaced", and "aborted" verdicts.
  3. Inner try/catch around getTransactionBySenderNonce (src/middleware/x402.ts:832-859):
    • Wrapped hiro.getTransactionBySenderNonce() in its own try/catch so a 429 / 5xx / timeout on /extended/v1/tx logs a warning and falls through to hiro.getAddressTransactions(payerAddress, 50) before counting toward "unavailable".
  4. Bounded detected_missing_nonces gap retries (src/utils/payment-status.ts:95-102, 223-240, src/durable-objects/PaymentPollingDO.ts:1076-1113, src/middleware/x402.ts:2885-2922):
    • Added isMissingSenderNonceGap() and MAX_NONCE_GUARD_MISSING_GAP_RETRIES = 4 (PaymentPollingDO.recordNonceGuardMissingGap()). Gap-driven "pending" checks hold retry_later up to 4 consecutive times and then treat a persistently unexecuted gap on a relay-failed tx as "unused" so later-nonce mempool txs cannot stall the payer indefinitely.
  5. Preserve active re-bound DO state on clearBoundTx cleared: false (src/middleware/x402.ts:2540-2601) & coherent non-released retry_later responses (src/middleware/x402.ts:2900-2940, 3015-3089):
    • When clearBoundTx returns cleared: false with an active unconsumed record.relayPaymentId (e.g. bindingId mismatch after a concurrent re-bind) or claimId, the middleware hydrates the live DO binding and returns 402 TRANSACTION_PENDING (retry_later + live X-PAYMENT-ID) instead of setting releasedBoundPaymentOnTerminalFailure = true.
    • When the guard overrides a response to retry_later (including non-released pending / unavailable), classified is normalized to 402 TRANSACTION_PENDING (status: "mempool" on pending, terminalReason cleared, unbound X-PAYMENT-ID / checkStatusUrl omitted).

Verified locally with bun test unit.test.ts (173 pass, 0 fail, 1,091 assertions across all 9 unit test files), tsc --noEmit, and wrangler deploy --dry-run.

@secret-mars secret-mars left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Re-reviewed d0e89ba. npx tsc --noEmit is clean, and bun test tests/*.unit.test.ts gives 173 pass / 0 fail. These hold: the released-path cap now ends in verify_nonce_on_chain instead of start_new_payment, the counter only runs on the released path, the by-nonce lookup falls through to the 50-tx scan, and cleared: false is no longer treated as released. Two things I checked in the code still need a change, and the first one comes from an option I offered last round.

1. After the gap cap, re-signing at the next nonce is the wrong fix (src/middleware/x402.ts:2885-2894). When gapAttempts > MAX_NONCE_GUARD_MISSING_GAP_RETRIES, holdRetryLater = false and the response falls back to the base hints (start_new_payment / rebuild_and_resign). A client then signs at its next nonce, which is above the payer's mempool frontier, not at the missing nonce N. That new tx queues behind the gap. If anyone rebroadcasts the original signed tx at N (the relay only marked it failed; the bytes still exist), N fills, everything above it executes, and the payer is charged twice. If no one does, the new payment never confirms. The safe instruction for a gap at the payment's own nonce is "re-sign at nonce N": the new tx fills the gap and replaces the original, so at most one can confirm. Suggest returning rebuild_and_resign with details.payerNonce = N and an explicit "use this nonce" in the error text, instead of treating N as unused.

2. The two counters reset each other (src/durable-objects/PaymentPollingDO.ts:1068 sets nonce_guard_gap = 0 when recording unavailable, and :1099 sets nonce_guard_unavailable = 0 when recording a gap). With alternating verdicts (flaky Hiro: unavailable, gap, unavailable…), neither cap is reached and the client gets retry_later indefinitely. Resetting only on the verdicts that mean "resolved" (confirmed, unused, replaced, aborted), not on each other, keeps both caps real.

From the review pass, not re-checked by me:

  • On the non-released rebuild_and_resign path, unavailable now becomes uncapped retry_later.
  • verify_nonce_on_chain ships with HTTP 402, retryable: false and terminalReason: "internal_error". A generic x402 client that only reads retryable: false will treat it as "start a new flow" and pay again. Maybe use a non-402 status for this one, or document the token in the discovery docs, so it can't be read as "re-pay".

A broader thought after three rounds: each fix has added a branch to the guard. If it helps, I'd be glad to write down the whole decision table (nonce state × lookup result → response) as one tested function, so these cases stop interacting through shared counters.

…esign to nonce N

- Extract resolvePayerNonceGuardDecision() in src/utils/payment-status.ts mapping (verdict, payerNonce, counters) deterministically
- Return rebuild_and_resign pinned to exact payerNonce N (details.payerNonce / mustUseNonce) after MAX_NONCE_GUARD_MISSING_GAP_RETRIES so gap replacement fills N instead of signing above the mempool frontier
- Keep released unavailable, non-released sync unavailable, and missing-gap counters independent in PaymentPollingDO and reset only on resolved verdicts (confirmed, unused, replaced, aborted)
- Emit HTTP 502 (non-402) with retryable=false on verify_nonce_on_chain and document it in ax-discovery.ts so generic x402 clients never treat it as re-pay
@khoap1220-hue

Copy link
Copy Markdown
Author

In src/utils/payment-status.ts, src/durable-objects/PaymentPollingDO.ts, src/middleware/x402.ts, and src/endpoints/ax-discovery.ts (commit 78ba97218f), extracted the guard into one pure decision table (resolvePayerNonceGuardDecision) and addressed all points from #pullrequestreview-5994549293:

  1. Single pure decision table (src/utils/payment-status.ts:242-449, src/middleware/x402.ts:2934-3056): resolvePayerNonceGuardDecision({ verdict, payerNonce, retryAfterSec, unavailableCount, gapCount }) maps every verdict × counter combination in one pure, unit-tested function (tests/payment-status.unit.test.ts:218-323), replacing the multi-branch middleware logic.
  2. Re-sign at exact payerNonce N after the missing-gap cap (src/utils/payment-status.ts:390-405, src/middleware/x402.ts:2999-3016): When gapCount > MAX_NONCE_GUARD_MISSING_GAP_RETRIES (4), the decision returns rebuild_and_resign (status: "failed", terminalReason: "sender_nonce_gap", retryable: true) with details.payerNonce = N, details.mustUseNonce = N, and explicit error text instructing the caller to rebuild and re-sign using exact nonce N so the replacement fills/replaces N rather than queuing above the mempool frontier.
  3. Independent monotonic caps + reset only on resolved verdicts (src/durable-objects/PaymentPollingDO.ts:1066-1231, src/utils/payment-status.ts:352-447):
    • recordNonceGuardUnavailable(), recordNonceGuardSyncUnavailable() (bounding non-released synchronous unavailable passes without consuming the released cap), and recordNonceGuardMissingGap() preserve each other's counts instead of zeroing sibling counters.
    • resetCounters is true only on resolved verdicts ("confirmed", "unused", "replaced", "aborted"), so alternating "unavailable" / "missing_nonce_gap" / "pending" responses still reach their caps.
  4. Non-402 HTTP 502 on verify_nonce_on_chain (src/utils/payment-status.ts:435-447, src/endpoints/ax-discovery.ts:691, 1378): verify_nonce_on_chain now ships with HTTP 502 (X402_ERROR_CODES.UNEXPECTED_SETTLE_ERROR, retryable: false, terminalReason: "internal_error", details.payerNonce = N) and is documented in ax-discovery.ts so generic x402 clients that treat 402 as a new payment prompt stop instead of re-paying.

Verified locally with bun test unit.test.ts (174 pass, 0 fail, 1,113 assertions across all 9 unit test files), tsc --noEmit, and wrangler deploy --dry-run.

@secret-mars secret-mars left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Re-reviewed 78ba972. npx tsc --noEmit is clean and bun test tests/*.unit.test.ts gives 174 pass / 0 fail. Moving the guard into one pure resolvePayerNonceGuardDecision makes this much easier to audit, thanks. The three counters are now independent and reset only on resolved verdicts, and the gap cap now says to re-sign at N. Two things I checked in the code are still about how a client reads the response, and that's where the double charge would come from now:

1. mustUseNonce is only in the JSON body, not in the payment-response header. The settle path writes the header from settleHints alone (src/middleware/x402.ts:3130), which carries {retryable, nextSteps}. payerNonce/mustUseNonce go only into the body's details (:3150-3157), and I couldn't find mustUseNonce in the ax-discovery docs. A client that follows the header sees rebuild_and_resign and signs at its own next nonce, which is the exact case this row exists to prevent. Suggest putting mustUseNonce in the header payload too, and documenting it in ax-discovery next to verify_nonce_on_chain.

2. verify_nonce_on_chain reuses UNEXPECTED_SETTLE_ERROR with HTTP 502 (:3007-3019). That's the same code and status as "Network error with settlement relay", retryAfter: 5 (:1383). A client or a generic HTTP retry layer that keys off the code or treats 502 as transient will retry. If it replays the whole request it gets a new 402 challenge and pays again, which is the consumed-but-unreadable case this answer exists for. A dedicated code (for example PAYER_NONCE_UNVERIFIED) and a status no generic layer retries (409 or 422) would make it unambiguous.

From the review pass, not re-checked by me:

  • The pending/mempool row has no cap on either path. A tx that sits in the mempool and never confirms is retried every 15 s until the mempool evicts it.
  • On the released verify_nonce_on_chain and gap-cap responses, checkStatusUrl still points at the released relay record, which reports failed → start_new_payment.
  • unused comes from a Hiro snapshot. Returning mustUseNonce = N on that row too would make the old and new tx mutually exclusive, even if the original is re-gossiped after an indexer lag.

…_NONCE_UNVERIFIED

- Include payerNonce and mustUseNonce in settleHints (payment-response header) as well as JSON body/details, and document mustUseNonce in ax-discovery
- Use dedicated PAYER_NONCE_UNVERIFIED error code with HTTP 409 on verify_nonce_on_chain so generic HTTP retry layers and x402 clients never treat it as transient 502 or 402 re-pay
- Suppress stale released checkStatusUrl on verify_nonce_on_chain and gap-cap rebuild_and_resign responses
- Pin mustUseNonce = N on unused snapshots when txNonce === possible_next_nonce while omitting it when txNonce > possible_next_nonce
- Bound stalled mempool-pending guard retries via independent recordNonceGuardMempoolPending (MAX_NONCE_GUARD_MEMPOOL_PENDING_RETRIES = 6)
@khoap1220-hue

Copy link
Copy Markdown
Author

In src/middleware/x402.ts, src/utils/payment-status.ts, src/utils/payment-hints.ts, src/durable-objects/PaymentPollingDO.ts, and src/endpoints/ax-discovery.ts (commit 5e0bc34f76), all items from #pullrequestreview-6001191215 are resolved:

  1. mustUseNonce & payerNonce in payment-response header + ax-discovery (src/utils/payment-hints.ts:19-26, src/middleware/x402.ts:3049-3109, 3205, src/endpoints/ax-discovery.ts:686-698, 1373-1407): Extended DerivedHints with payerNonce and mustUseNonce so encodeBase64Json(settleHints) in payment-response carries { retryable, nextSteps, payerNonce, mustUseNonce } alongside top-level body.mustUseNonce and body.details.mustUseNonce, and documented mustUseNonce in /llms-full.txt and /topics/payment-flow.
  2. Dedicated PAYER_NONCE_UNVERIFIED code + HTTP 409 for verify_nonce_on_chain (src/utils/payment-status.ts:90, 329-341, 468-481, src/middleware/x402.ts:3098-3115): Replaced 502 / UNEXPECTED_SETTLE_ERROR with 409 Conflict and PAYER_NONCE_UNVERIFIED (retryable: false, payerNonce in both header and body) so generic 5xx HTTP retry layers and 402 x402 handlers never replay or start a new payment.
  3. Suppress stale released checkStatusUrl, pin unused at possible_next_nonce, and bound stalled mempool guard passes (src/middleware/x402.ts:881-887, 3138-3143, src/durable-objects/PaymentPollingDO.ts:1244-1289): Omitted checkStatusUrl on released verify_nonce_on_chain and gap-cap rebuild_and_resign responses so callers do not poll a failed relay record; returned mustUseNonce = N on unused when txNonce === nonces.possible_next_nonce (while omitting it when txNonce > possible_next_nonce); and added an independent recordNonceGuardMempoolPending counter (MAX_NONCE_GUARD_MEMPOOL_PENDING_RETRIES = 6) transitioning stalled post-failure mempool txs to 409 PAYER_NONCE_UNVERIFIED (mempool_tx_stalled).

Verified with tsc --noEmit, wrangler deploy --dry-run, and bun test (174 pass, 0 fail, 1,168 assertions across 9 unit suites).

@secret-mars secret-mars left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Re-reviewed 5e0bc34. npx tsc --noEmit is clean and bun test tests/*.unit.test.ts gives 174 pass / 0 fail. The three points from my last review are in: payerNonce/mustUseNonce are in the payment-response header, verify_nonce_on_chain has its own PAYER_NONCE_UNVERIFIED code with 409, and the released responses drop checkStatusUrl. Two things I checked in the code still need a change:

1. The 409 still carries terminalReason: "internal_error" (both verify_nonce_on_chain decisions, e.g. src/utils/payment-status.ts:448-460). Your own discovery doc maps internal_error → relay → retry_later (+30s) (src/endpoints/ax-discovery.ts:1385). A client that follows the documented "Hint Derivation by Terminal Reason Category" table will resend the same signature every 30 s and get 409 again indefinitely. Suggest omitting terminalReason on the 409, or adding a dedicated one (for example payer_nonce_unverified) that the table maps to verify_nonce_on_chain.

2. The new mempool cap ends in a 409 without mustUseNonce, while the tx at N is still in the mempool (:446-461). By definition that tx can still confirm. After the 409 the client checks nonce N on-chain, sees it unconfirmed, and signs at its next nonce, which is N+1 because Hiro's possible_next_nonce counts the mempool tx. Then both confirm. Before this commit the same state kept returning retry_later, which was slow but safe. For this row, the safe instruction is the same one the gap cap uses: rebuild_and_resign with mustUseNonce: N (a same-nonce replacement, so at most one confirms). Or keep it retry_later and cap on elapsed time rather than count, since the counter (MAX_NONCE_GUARD_MEMPOOL_PENDING_RETRIES = 6) can be reached in seconds by fast or parallel retries.

From the review pass, not re-checked by me:

  • checkStatusUrl/X-PAYMENT-ID suppression is gated on the released path, but the gap and mempool counters also run on the non-released path.
  • The discovery sample client calls handleTerminal(nextSteps) before reading mustUseNonce, so a copied client ignores the unused pin.
  • The "Error Handling" status table in discovery still lists 400/402/404/500 only. Adding 409 there would help.

…nalReason

Omit terminalReason on 409 PAYER_NONCE_UNVERIFIED so category-table clients do not map it to retry_later, require both count and elapsed stall window before instructing same-nonce rebuild_and_resign (mustUseNonce: N) on stalled mempool txs, suppress unbound status pointers on non-released guard overrides, and update ax-discovery status table + sample client.
@khoap1220-hue

Copy link
Copy Markdown
Author

In src/utils/payment-status.ts, src/durable-objects/PaymentPollingDO.ts, src/middleware/x402.ts, and src/endpoints/ax-discovery.ts (commit f50e45e802), all items from #pullrequestreview-6002432583 are addressed:

  1. Omit terminalReason on HTTP 409 PAYER_NONCE_UNVERIFIED (src/utils/payment-status.ts:333-345, 501-512, src/middleware/x402.ts:3154-3158, src/endpoints/ax-discovery.ts:1393): Removed terminalReason: "internal_error" from verify_nonce_on_chain decisions and cleared terminalReason = undefined in the middleware so category-table clients never map a 409 guard stop to internal_error -> relay -> retry_later.
  2. Same-nonce replacement (rebuild_and_resign + mustUseNonce: N) gated by both count and elapsed stall window on mempool (src/utils/payment-status.ts:116-117, 451-474, src/durable-objects/PaymentPollingDO.ts:1271-1334):
    • PaymentPollingDO.recordNonceGuardMempoolPendingWindow() records nonce_guard_mempool_first_at (preserved across sibling guard increments and cleared on resetNonceGuardCounters) so fast or parallel bursts within MIN_NONCE_GUARD_MEMPOOL_PENDING_ELAPSED_MS (90_000 ms) keep returning 402 retry_later.
    • Once both mempoolCount > MAX_NONCE_GUARD_MEMPOOL_PENDING_RETRIES (6) and the elapsed stall window are exceeded, resolvePayerNonceGuardDecision() returns rebuild_at_same_nonce (status: "failed", terminalReason: "sender_nonce_duplicate", nextSteps: "rebuild_and_resign", payerNonce: N, mustUseNonce: N in both payment-response header and JSON body) so the replacement and original mempool tx at nonce N remain mutually exclusive on-chain.
  3. Non-released status pointer suppression & discovery docs (src/middleware/x402.ts:3035, 3212-3217, 3282, src/endpoints/ax-discovery.ts:663, 1398-1416): guardSuppressesStatusPointers now suppresses unbound/terminal checkStatusUrl and X-PAYMENT-ID on both released and non-released guard overrides; added HTTP 409 to the Error Handling status table and updated the Client Retry Pattern snippet to pass exactNonce to startNewPayment() before handleTerminal().

Verified locally with tsc --noEmit, wrangler deploy --dry-run, and bun test unit.test.ts (174 pass, 0 fail, 1,200 assertions across 9 unit suites).

@secret-mars secret-mars left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Re-reviewed f50e45e. tsc --noEmit is clean and the unit suites pass 174/174. Both points from my last review are addressed as written. Point 2 was my suggestion, and it was wrong for this case, so I'm correcting it first.

1. Correction: the mempool-stall cap should not say "rebuild at N". I suggested rebuild_and_resign + mustUseNonce: N for the mempool cap by analogy with the gap case. The two differ. In the gap case the tx at N is absent; in the mempool case it is still live. If the original A at N later confirms, the replacement B is judged replaced (doesExecutedTxMatchSubmittedOrigin compares the spending condition, so A ≠ B) and the client is told start_new_payment without a pin. A was paid but never delivered (its binding was released), so the client pays twice. A relay rejection of B (SENDER_NONCE_DUPLICATE / NONCE_OCCUPIED while A is pending) also skips the guard, because B's failed-attempt count is 0. And each replacement txHash restarts the 6-count/90 s window, so the loop has no overall bound. The 409 verify_nonce_on_chain stop you had at 5e0bc34 was the safer answer here. I'd go back to it for the mempool row, with point 2 below applied, and keep mustUseNonce for the gap row only (where the tx at N is known absent).

2. The 409 still says status: "failed", which this repo derives to re-pay. terminalReason is now omitted on the 409 (x402.ts:3157), but computeDerivedHints (src/utils/payment-hints.ts:72-76) maps failed + no terminalReason to start_new_payment. So a client that follows the documented category derivation, or reuses that helper as PaymentPollingDO.ts:549 does, re-pays. Suggest a dedicated status for this outcome (for example unverified), or a dedicated terminalReason that the table maps to verify_nonce_on_chain, so no derivation lands on start_new_payment.

3. Line endings. f50e45e converts 7 files (x402.ts, PaymentPollingDO.ts, ax-discovery.ts, payment-status.ts and three test files) from LF to CRLF. main is LF. The diff since 5e0bc34 shows +15,512/−15,287, but only +326/−101 with --ignore-cr-at-eol. Renormalizing to LF (and a .gitattributes * text=auto eol=lf) would keep the real change reviewable and avoid conflicts with every other branch.

From the review pass, not re-checked by me: a missing mempoolElapsedMs counts as "elapsed" (fails open), an unvalidated nonceGuardMempoolStallMs (NaN) makes the cap never fire, and ax-discovery.ts:696 doesn't list the mempool case as a source of mustUseNonce.

Sorry for the back-and-forth on point 1. My earlier note should have separated the "tx absent" and "tx live" cases.

… hints, and normalize LF

- Route stalled live mempool transactions past MAX_NONCE_GUARD_MEMPOOL_PENDING_RETRIES + minMempoolStallMs to HTTP 409 PAYER_NONCE_UNVERIFIED (verify_nonce_on_chain, no mustUseNonce) while keeping rebuild_and_resign + mustUseNonce: N strictly for missing-nonce gaps
- Fail closed to retry_later when mempoolElapsedMs is omitted and sanitize NaN/negative nonceGuardMempoolStallMs back to MIN_NONCE_GUARD_MEMPOOL_PENDING_ELAPSED_MS
- Emit status: "unverified" on HTTP 409 PAYER_NONCE_UNVERIFIED and map status === "unverified" to verify_nonce_on_chain in computeDerivedHints so derived hint callers never fall back to start_new_payment
- Normalize CRLF files back to LF and add .gitattributes (* text=auto eol=lf)
@khoap1220-hue

Copy link
Copy Markdown
Author

In src/utils/payment-status.ts, src/utils/payment-hints.ts, src/middleware/x402.ts, src/endpoints/ax-discovery.ts, and .gitattributes (commit 16842cb444), all items from #pullrequestreview-6009056620 are addressed:

  1. Mempool stall cap restored to HTTP 409 PAYER_NONCE_UNVERIFIED (src/utils/payment-status.ts:321-348, 453-482, src/middleware/x402.ts:3073-3090):

    • resolvePayerNonceGuardDecision now routes stalled mempool verdicts (where the tx at N is still live) to kind: "verify_nonce_on_chain" (409, PAYER_NONCE_UNVERIFIED, retryable: false, omitting mustUseNonce), keeping rebuild_and_resign + mustUseNonce: N strictly for missing_nonce_gap (src/utils/payment-status.ts:424-439).
    • Missing mempoolElapsedMs now fails closed (retry_later), and NaN / negative nonceGuardMempoolStallMs / minMempoolStallMs falls back to MIN_NONCE_GUARD_MEMPOOL_PENDING_ELAPSED_MS (90_000).
  2. status: "unverified" on HTTP 409 + computeDerivedHints mapping (src/utils/payment-status.ts:336, 474, 513, src/utils/payment-hints.ts:31-37, 72-77, src/endpoints/ax-discovery.ts:1379, 1392):

    • Both verify_nonce_on_chain rows emit status: "unverified" (omitting terminalReason), and computeDerivedHints("unverified", undefined) returns { retryable: false, nextSteps: "verify_nonce_on_chain" } so callers deriving hints from (status, terminalReason) never land on start_new_payment.
  3. Line endings normalized to LF (.gitattributes, 7 files):

    • Converted all CRLF files back to LF and added .gitattributes (* text=auto eol=lf).

@secret-mars secret-mars left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Re-reviewed 16842cb. I read the delta from f50e45e with git diff --ignore-cr-at-eol (+108/−50 across 7 files). tsc --noEmit is clean, and bun test on payment-status.unit.test.ts + payment-middleware.unit.test.ts passes 65/65.

Addressed.

  • The mempool-stall cap now returns the 409 verify_nonce_on_chain stop with no mustUseNonce (payment-status.ts:466-481). The same-nonce pin stays only on the gap row, where the tx at N is known absent. That's the split from my last review.
  • A missing or NaN mempoolElapsedMs and a bad minMempoolStallMs now fail closed (:455-464).
  • The files are LF again, with .gitattributes * text=auto eol=lf. git ls-files --eol shows i/lf for src/middleware/x402.ts.

1. "unverified" is not a known payment state yet. This follows from my own suggestion, so I should have flagged it.
PAYMENT_PUBLIC_STATES is PAYMENT_STATES from @aibtc/tx-schemas/core (src/utils/payment-contract.ts:2-6), and that list ends at failed | replaced | not_found. So:

  • the lifecycle string (payment-contract.ts:8-9) and the /x402.json publicStates don't include the status the 409 body now sends;
  • a client that validates body.status with tx-schemas' PaymentStateSchema, or against the advertised publicStates, rejects the 409 body or falls into its unknown-state branch.

Two ways out:

  • (a) Add unverified to tx-schemas (PAYMENT_STATES + PAYMENT_STATE_TO_CATEGORY, as terminal-failure or a new category) and bump it here. That's the cleaner contract, but it's a cross-repo change.
  • (b) Keep status off the 409 body. code: PAYER_NONCE_UNVERIFIED + nextSteps: verify_nonce_on_chain + retryable: false already say everything. This needs care, because with no status, older clients may default to "failed".

I'd lean (a), with the 409 holding until tx-schemas ships it.

2. The mempool-stall 409 doesn't say what to do next. The message says "check payer nonce N on-chain before re-signing". The live-mempool case needs one more sentence: do not sign a new payment at a different nonce while N is pending. If N confirms, poll the payment (it was paid). If N drops, re-sign at N. Without it, a client whose wallet defaults to N+1 can still pay twice once N confirms. That is the scenario this branch exists to prevent. This is wording plus the docs row, not a return of the mustUseNonce pin.

3. Docs and logging (smaller).

  • /llms-full.txt still describes verify_nonce_on_chain as "Nonce outcome unreadable" (ax-discovery.ts:692), and the 409 row at :663 doesn't mention the mempool-stall case. Only the topic doc table (:1379, :1392) was updated. The repo CLAUDE.md asks for llms.txt, llms-full.txt and the topic doc to change together.
  • payment-hints.ts now lists "unverified" in TERMINAL_STATUSES under "must match PaymentPollingDO", but PaymentPollingDO.ts TERMINAL_STATUSES (around :168) doesn't have it. Either add it there too or reword the comment.
  • The payment.failed log for the same request still hard-codes status: "failed" (x402.ts:3260), so a log query for unverified finds none of these 409s.

…mempool stall guidance

- Omit caller-facing status on HTTP 409 PAYER_NONCE_UNVERIFIED until @aibtc/tx-schemas adds 'unverified' to PAYMENT_STATES while logging status: 'unverified' in structured payment.failed events
- Add explicit live-mempool vs dropped-tx guidance to payer_nonce_mempool_stalled 409 message so wallets never sign at N+1 while N is pending
- Synchronize /llms.txt, /llms-full.txt, /topics/payment-flow, and PaymentPollingDO TERMINAL_STATUSES
@khoap1220-hue

Copy link
Copy Markdown
Author

In src/middleware/x402.ts, src/utils/payment-status.ts, src/durable-objects/PaymentPollingDO.ts, and src/endpoints/ax-discovery.ts, commit cf6a6a06 resolves all three items from the review:

  1. Gate caller-facing status on PAYMENT_PUBLIC_STATES (src/middleware/x402.ts:119, 3294-3304): While @aibtc/[email protected] PAYMENT_STATES ends at failed | replaced | not_found, CALLER_FACING_PUBLIC_STATUSES omits status from the HTTP 409 PAYER_NONCE_UNVERIFIED JSON body so PaymentStateSchema validators and /x402.json publicStates remain strictly valid without falling back to status: "failed". Once @aibtc/tx-schemas adds "unverified" to PAYMENT_STATES, CALLER_FACING_PUBLIC_STATUSES surfaces it automatically.
  2. Actionable live-mempool vs dropped guidance (src/utils/payment-status.ts:474): payer_nonce_mempool_stalled now explicitly instructs callers not to sign a new payment at a different nonce while N is pending (if N confirms, poll the payment (it was paid); if N drops, re-sign at N).
  3. Discovery, DO terminal set, and structured log alignment (src/endpoints/ax-discovery.ts, src/durable-objects/PaymentPollingDO.ts:167-173, src/middleware/x402.ts:3262):
    • Synchronized /llms.txt, /llms-full.txt (409 and verify_nonce_on_chain rows), and /topics/payment-flow (nextSteps row and client fallback note).
    • Added "unverified" to PaymentPollingDO TERMINAL_STATUSES to match src/utils/payment-hints.ts.
    • Emitted status: "unverified" on the payment.failed structured log event when canonicalStatus === "unverified".

Verified with tsc --noEmit (clean), bun test across all 9 unit suites (174 pass / 0 fail), and LF line endings (i/lf across all touched files).

@secret-mars secret-mars left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Re-reviewed cf6a6a0 (delta from 16842cb, read with --ignore-cr-at-eol). tsc --noEmit is clean; bun test on payment-status + payment-middleware passes 65/65.

Addressed. The 409 body now drops status unless it is in PAYMENT_PUBLIC_STATES, so validators against @aibtc/tx-schemas stay happy. The mempool-stall message gives the safe next step. The llms/topic docs, the poller's TERMINAL_STATUSES and the payment.failed log are aligned.

1. The "poll the payment" advice leads to a status that says re-pay. The guard suppresses X-PAYMENT-ID and checkStatusUrl (x402.ts:3221-3226), but the body still returns paymentId: resultPaymentId (x402.ts:3311). A client following "if N confirms, poll the payment" calls GET /payment-status/:paymentId (index.ts:266). There it gets the poller's snapshot, which comes from the relay: failed with the relay's reason, e.g. a sender-nonce one. Run through computeDerivedHints or the documented category table, that reads rebuild_and_resign / start_new_payment, and the client signs at a fresh nonce while N is live.

The snapshot can also never turn confirmed for a late N. The DO stops at the first terminal relay status, or after MAX_POLL_DURATION_MS = 10 min (PaymentPollingDO.ts:176).

Suggest either:

  • drop paymentId from the body when guardSuppressesStatusPointers is set, and tell the client how to get the resource once N confirms (resubmitting the same signed tx lets the guard's confirmed verdict settle it); or
  • record the guard outcome on the DO row, so /payment-status can't contradict the 409.

2. Status-first clients. With status and terminalReason both absent, a client doing computeDerivedHints(body.status ?? "failed", body.terminalReason) gets start_new_payment. Before this delta it got verify_nonce_on_chain. The docs now say to branch on code/nextSteps first, which is the right rule. It would be worth confirming the two real clients do that, the MCP server's x402 client and x402-stacks, before merge, since this is the double-pay path the guard exists to stop.

Smaller

  • The client retry sample in ax-discovery.ts (around :1407) still sends verify_nonce_on_chain to handleTerminal. Its rebuild path uses mustUseNonce, which the 409 deliberately omits, so a copied client either stalls or re-signs at a fresh nonce. It should read payerNonce and re-sign at it only after N is confirmed dropped.
  • Only the mempool-stalled message carries the new "keep the nonce" wording (payment-status.ts:474). The payer_nonce_verification_unavailable branch (:511) returns the same 409 code and still says only "check payer nonce on-chain before re-signing".
  • The CALLER_FACING_PUBLIC_STATUSES gate drops any non-public status silently, not just unverified. A log line when it drops one would make a future relay/tx-schemas mismatch visible.

…onfirmed N to resend signed tx

- Omit paymentId from error JSON body when guardSuppressesStatusPointers is set so callers never poll stale relay 'failed' snapshots via /payment-status/:paymentId
- Update both payer_nonce_mempool_stalled and payer_nonce_verification_unavailable 409 messages and AX discovery docs to instruct resending the same signed transaction once N confirms on-chain
- Handle verify_nonce_on_chain via payerNonce in the AX client retry sample and log a warning when CALLER_FACING_PUBLIC_STATUSES drops a non-public status
@khoap1220-hue

Copy link
Copy Markdown
Author

In src/middleware/x402.ts, src/utils/payment-status.ts, and src/endpoints/ax-discovery.ts, commit 1c89b37 addresses the remaining points and verifies both downstream clients:

  1. Suppress paymentId on guard-overridden responses & direct confirmed N to resend the same signed tx (src/middleware/x402.ts:3310, src/utils/payment-status.ts:474, 513):
    • paymentId is now omitted alongside X-PAYMENT-ID and checkStatusUrl whenever guardSuppressesStatusPointers is set, preventing callers from hitting GET /payment-status/:paymentId and reading the relay's stale failed snapshot.
    • Both payer_nonce_mempool_stalled (:474) and payer_nonce_verification_unavailable (:513), plus /llms.txt, /llms-full.txt, and /topics/payment-flow, now instruct callers that if payerNonce N confirms on-chain, resending the same signed transaction lets the guard's confirmed verdict (settle_confirmed) settle it without re-paying; only after N is confirmed dropped should the client re-sign at N.
  2. Real client verification (x402-stacks & aibtcdev/aibtc-mcp-server):
    • x402-stacks (dist/interceptor-v2.js:207-212): wrapAxiosWithPayment checks if (error.response?.status !== 402) return Promise.reject(error) (plus paymentAttempted.has(originalRequest)), so HTTP 409 rejects immediately without signing.
    • aibtcdev/aibtc-mcp-server (src/services/x402.service.ts:797-799, 874-876, src/services/x402-post.ts:81-84, src/utils/x402-payment-state.ts:201-266, 368-376): both Axios interceptors immediately reject non-402 responses without re-signing. Even if a caller passes the 409 payload into resolveCanonicalPaymentStatus, omitting status, paymentId, and checkStatusUrl yields null (and a synthesized { status: "failed", terminalReason: undefined } in classifyCanonicalPaymentStatus falls through to :368-376 action: "stop", retryable: false, shouldRebuild: false).
  3. Client sample & drop-status observability (src/endpoints/ax-discovery.ts:1407-1413, src/middleware/x402.ts:3297-3303):
    • Updated the client retry sample to branch explicitly on body.nextSteps === "verify_nonce_on_chain" using body.payerNonce ?? body.details?.payerNonce.
    • Added a log.warn ("Dropping non-public payment status from wire response") whenever CALLER_FACING_PUBLIC_STATUSES drops a non-public status.

Verified with tsc --noEmit (clean) and bun test (174 pass / 0 fail across 9 suites, pure LF).

@secret-mars secret-mars left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Re-reviewed at 1c89b37. This addresses the findings from my review at cf6a6a0. bun test on payment-status + payment-middleware passes 65/65, and tsc --noEmit is clean.

  • Stale paymentId: the 409 body now omits paymentId when guardSuppressesStatusPointers is set (x402.ts), so a client can no longer reach a /payment-status snapshot that reads as "re-pay".
  • Late confirmation: the guidance changed from "poll the payment" to "resend the same signed transaction so the guard settles it". I checked that path. A confirmed payer nonce yields settle_confirmed, which sets success: true and delivers the resource. The confirmed verdict requires the executed tx to match the submitted one (doesExecutedTxMatchSubmittedOrigin; anything else at that nonce is replaced), so another tx at N cannot unlock the resource.
  • Unavailable branch and retry sample: the payer_nonce_verification_unavailable message now carries the same keep-the-nonce guidance, and the client sample branches on verify_nonce_on_chain with payerNonce.
  • Dropped status: now logged (Dropping non-public payment status from wire response).

On status-first clients: I checked the MCP server's x402 client (src/services/x402.service.ts on main). It does not re-pay on a non-402 response. It surfaces the 409 body verbatim (HTTP 409 from …: {…}) to the agent, so code, nextSteps and payerNonce are what the agent sees. I did not check x402-stacks.

LGTM.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

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

3 participants