Repository navigation
feat(x402): migrate payment middleware and polling DO to X402_RELAY RPC binding - #150
khoap1220-hue wants to merge 27 commits into
Conversation
…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.
|
One release-blocking difference from the synchronous path at Reproduction: return
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. |
|
One config issue not covered above, at The production binding names the wrong relay worker. { "binding": "X402_RELAY", "service": "x402-sponsor-relay", "entrypoint": "RelayRPC" }The relay's own
A service binding targets a Worker by its deployed name (Cloudflare service bindings). With an explicit 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 Smaller point: the HTTP fallback covers only a binding that is absent from the config ( |
… 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.
|
In
|
|
Thanks for the quick turnaround. The production binding is fixed and the pending gate is in. I read 1. A confirmed payment can be replayed in the same isolate. On the confirmed branch ( 2. The same replay works across isolates for 300s, because the correlation id is now deterministic. 3. Recovery by caller-supplied id skips the price check. When 4. Smaller: 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 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 |
…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.
|
In
|
|
I ran the revised 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]>
|
In
|
|
Re-read at
What's left: 1. The consumed-payment guard is per-isolate, but the comment says it covers other instances too.
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 2. Body binding fails open. 3. The binding hash is computed before the early returns. Minor: the "already settled and consumed" 402 is built four times ( |
…nd recovery helper dedup
…nd recovery helper dedup
…nd recovery helper dedup
|
In
|
|
Checked
Minor: |
…nd recovery helper dedup
|
In
|
secret-mars
left a comment
There was a problem hiding this comment.
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). addBoundedSetEntryreturns 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
|
In
Verification: |
secret-mars
left a comment
There was a problem hiding this comment.
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.
- A failed
bindTxPaymentis 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 callssubmitPaymentagain. 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. - The relay's own idempotency is switched off (
x402.ts:1104).settlementAttemptId = "pay_" + crypto.randomUUID()is new on every attempt. The relay'spaymentIdentifier+ 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 thatmarkTxConsumedmakes serving durable, the stablerequestCorrelationIdyou already compute is the safer thing to send. A retry after a timed-outsubmitPaymentwould then get the relay's cachedacceptedresult and the originalpay_ID back, instead of a duplicate-nonce rejection. - Two calls race between check and bind (
x402.ts:1116onward).readTxGuardFromDOandbindTxPaymentInDOare separate DO calls withsubmitPaymentbetween them. Two overlapping requests for the same tx can both see no record and both submit. AclaimTxmethod on the DO, a check-and-set that returns any existing binding, would close this. 2 above also covers most of it. clearBoundTxdoesn't check which payment it is clearing (PaymentPollingDO.ts:522-532). When the row isn't consumed, it runsDELETE FROM tx_guard WHERE id = 1unconditionally. A slow request clearing after its ownpay_Afailed can delete a newer binding to a livepay_B. Passing therelayPaymentIdand deleting only on a match would avoid that.
Smaller:
tx:DO instances are never cleaned up. Thetx_guardrow 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
minAmountwith 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
|
In
Verification: |
secret-mars
left a comment
There was a problem hiding this comment.
Re-checked at 871a2f3. The four double-submit gaps from my last review are closed:
- A failed bind returns 503 and releases the claim.
settlementAttemptIdis now stable.claimTxserializes 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'spay_relayXYZ, and the client gets 402 pending. - Retry with the identical payload:
callerSuppliedPaymentIdis stillpay_client123, andbyTxHashfinds the entry withrelayPaymentId = pay_relayXYZ. That fails at:1376with 400SENDER_MISMATCH.hydrateFromDORecorddoes 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.
|
Addressed all three points in
Verification after the final edit:
|
secret-mars
left a comment
There was a problem hiding this comment.
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
markTxConsumedInDOfails 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-isolateCONSUMED_PAYMENTSknows. - On main, each attempt sent
"pay_" + crypto.randomUUID()as its payment-identifier. This PR sendssettlementAttemptId = 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-relaysrc/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
_fetchStatuspassescheckPayment's status straight through, andnot_foundis inTERMINAL_STATUSES. - The middleware got a 90 s
NOT_FOUND_ENQUEUE_GRACE_MSfor 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_foundand never polled again, so/payment-statusreportsnot_foundfor a payment that later confirms. - Suggest the same grace in the DO: treat
not_foundas non-terminal untilnow - created_at > NOT_FOUND_ENQUEUE_GRACE_MS.
3. A reused X-PAYMENT-ID header blocks a new transaction (:1198)
isPaymentConsumed(txHash, callerSuppliedPaymentId)also matchesCONSUMED_PAYMENTS.byRelayIdon the caller's header. A client that echoes thepay_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
txHashhere, 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:
readTxGuardFromDOnow runs before settlement on every request and returns 503 on a DO error even whenX402_RELAYisn't bound (:1212), so a plain HTTP deployment now depends on the DO.- The
getTxGuardread beforeclaimTxis an extra DO round trip, sinceclaimTxalready returns consumed or bound.
I didn't run the suite this time. Every line ref above is at 15f0626.
|
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. |
|
Correction to point 2 in my review above (5933381654, at e3b0b24): I said the removed test covered the no- |
|
In
|
…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
ee9cc50 to
4c0f6df
Compare
secret-mars
left a comment
There was a problem hiding this comment.
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 atpossible_next_nonceboth land. Is the relay guaranteed to have dropped it too? If not,pendingis the safer reading.- The guard is skipped when
canonicalStatus === "replaced"(:2556). Can the relay report the original asreplacedwhen the replacement is its own re-sponsored copy of the same origin tx? If so,doesExecutedTxMatchSubmittedOriginwould sayconfirmed, 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
|
In
Verified locally with |
secret-mars
left a comment
There was a problem hiding this comment.
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_paymentis safe (that's already theunusedbranch); - nonce consumed but unreadable, or nonce state unknown: a non-retryable "verify on chain" outcome (for example
terminalReason: "internal_error"withnextStepsthat says check the payer's nonce N before re-signing), notstart_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
clearBoundTxreturnscleared: falsefor a bindingId mismatch, the middleware still treats the payment as released (:2410). - On the non-released path,
pending→retry_laterkeeps the 4xxrebuild_and_resigncode, 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
|
In
Verified locally with |
secret-mars
left a comment
There was a problem hiding this comment.
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_resignpath,unavailablenow becomes uncappedretry_later. verify_nonce_on_chainships with HTTP 402,retryable: falseandterminalReason: "internal_error". A generic x402 client that only readsretryable: falsewill 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
|
In
Verified locally with |
secret-mars
left a comment
There was a problem hiding this comment.
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_chainand gap-cap responses,checkStatusUrlstill points at the released relay record, which reportsfailed→start_new_payment. unusedcomes from a Hiro snapshot. ReturningmustUseNonce = Non 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)
|
In
Verified with |
secret-mars
left a comment
There was a problem hiding this comment.
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-IDsuppression 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 readingmustUseNonce, so a copied client ignores theunusedpin. - 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.
|
In
Verified locally with |
secret-mars
left a comment
There was a problem hiding this comment.
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)
|
In
|
secret-mars
left a comment
There was a problem hiding this comment.
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_chainstop with nomustUseNonce(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
mempoolElapsedMsand a badminMempoolStallMsnow fail closed (:455-464). - The files are LF again, with
.gitattributes* text=auto eol=lf.git ls-files --eolshowsi/lfforsrc/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.jsonpublicStatesdon't include the status the 409 body now sends; - a client that validates
body.statuswith tx-schemas'PaymentStateSchema, or against the advertisedpublicStates, rejects the 409 body or falls into its unknown-state branch.
Two ways out:
- (a) Add
unverifiedto tx-schemas (PAYMENT_STATES+PAYMENT_STATE_TO_CATEGORY, asterminal-failureor a new category) and bump it here. That's the cleaner contract, but it's a cross-repo change. - (b) Keep
statusoff the 409 body.code: PAYER_NONCE_UNVERIFIED+nextSteps: verify_nonce_on_chain+retryable: falsealready 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.txtstill describesverify_nonce_on_chainas "Nonce outcome unreadable" (ax-discovery.ts:692), and the 409 row at:663doesn'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.tsnow lists"unverified"inTERMINAL_STATUSESunder "must match PaymentPollingDO", butPaymentPollingDO.tsTERMINAL_STATUSES(around:168) doesn't have it. Either add it there too or reword the comment.- The
payment.failedlog for the same request still hard-codesstatus: "failed"(x402.ts:3260), so a log query forunverifiedfinds 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
|
In
Verified with |
secret-mars
left a comment
There was a problem hiding this comment.
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
paymentIdfrom the body whenguardSuppressesStatusPointersis set, and tell the client how to get the resource once N confirms (resubmitting the same signed tx lets the guard'sconfirmedverdict settle it); or - record the guard outcome on the DO row, so
/payment-statuscan'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 sendsverify_nonce_on_chaintohandleTerminal. Its rebuild path usesmustUseNonce, which the 409 deliberately omits, so a copied client either stalls or re-signs at a fresh nonce. It should readpayerNonceand 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). Thepayer_nonce_verification_unavailablebranch (:511) returns the same 409 code and still says only "check payer nonce on-chain before re-signing". - The
CALLER_FACING_PUBLIC_STATUSESgate drops any non-public status silently, not justunverified. 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
|
In
Verified with |
secret-mars
left a comment
There was a problem hiding this comment.
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 omitspaymentIdwhenguardSuppressesStatusPointersis set (x402.ts), so a client can no longer reach a/payment-statussnapshot 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 setssuccess: trueand delivers the resource. The confirmed verdict requires the executed tx to match the submitted one (doesExecutedTxMatchSubmittedOrigin; anything else at that nonce isreplaced), so another tx at N cannot unlock the resource. - Unavailable branch and retry sample: the
payer_nonce_verification_unavailablemessage now carries the same keep-the-nonce guidance, and the client sample branches onverify_nonce_on_chainwithpayerNonce. - 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.
In
wrangler.jsonc,src/types.ts,src/services/payment-contract.ts,src/durable-objects/PaymentPollingDO.ts, andsrc/middleware/x402.ts, this PR migrates payment submission and status polling to theX402_RELAY(RelayRPC) service binding while preserving HTTP fallback whenX402_RELAYis not bound in local/test environments.Changes
wrangler.jsonc:{ "binding": "X402_RELAY", "service": "x402-sponsor-relay-staging", "entrypoint": "RelayRPC" }toenv.staging.servicesand{ "binding": "X402_RELAY", "service": "x402-sponsor-relay-production", "entrypoint": "RelayRPC" }toenv.production.services(omitted at top level so standalonewrangler devexercises the HTTP facilitator path without requiring a local relay worker).src/types.ts&src/services/payment-contract.ts:RelayRPC(submitPayment,checkPayment),RelaySettleOptions,RelaySubmitPaymentResult, andRelayCheckPaymentResulttypes, addedX402_RELAY?: RelayRPCtoEnv, and re-exportedRpcCheckPaymentResultSchema,RpcSubmitPaymentResultSchema,RpcErrorCodeSchema, andRPC_ERROR_CODESfrom@aibtc/tx-schemas/rpc.src/durable-objects/PaymentPollingDO.ts:_fetchStatus(paymentId, checkStatusUrl)to invokeawait this.env.X402_RELAY.checkPayment(paymentId)validated viaRpcCheckPaymentResultSchemawhenthis.env.X402_RELAYis bound (loggingRelaySchemaMismatchErrordistinctly from transient network errors), falling back tofetch(checkStatusUrl)withHttpPaymentStatusResponseSchemaotherwise, and added durabletx_guard/tx_retry_guardcoordination across isolates.src/middleware/x402.ts:c.env.X402_RELAY.submitPayment(txHex, settleOptions, paymentIdentifier)andcheckPayment(relayPaymentId)whenc.env.X402_RELAYis bound, falling back toverifier.settle(paymentPayload, { paymentRequirements })when unbound.Closes #87