* Add escrow scheme specification
Introduces the `escrow` scheme for x402, built on Base's Commerce Payments
Protocol. Supports two settlement paths: authorize (funds held in escrow)
and charge (direct to receiver), both refundable post-settlement.
Refs: #834, #1011
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* Address review feedback on escrow scheme specs
- Generalize scheme_escrow.md to be network-agnostic
- Tighten verification: strict amount equality, tokenCollector
recipient check, settlement simulation
- Add error codes section and assetTransferMethod note
- Simplify nonce derivation explanation
* Rename scheme to commerce and align spec with implementation
- Rename escrow → commerce per reviewer feedback
- Add expiry fields to PaymentRequirements example
- Align expiry field descriptions and example values
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* spec: rename escrow/commerce scheme to authCapture, add EVM payload schema
Renames the scheme directory from commerce/ to authCapture/ and rewrites
the EVM spec to cover both ERC-3009 and Permit2 payment-collector paths.
Key spec additions:
- extra field schema (captureAuthorizer, captureDeadline, refundDeadline,
feeRecipient, min/maxFeeBps, autoCapture, assetTransferMethod)
- Wire format + EIP-712 derivation tables for ERC-3009 and Permit2
- Spec -> on-chain PaymentInfo field mapping (preserves canonical Solidity
names so EIP-712 typehash matches the AuthCaptureEscrow contract)
- Universal contract addresses block (CREATE2-deterministic)
- Verification step list aligned with facilitator implementation:
preApprovalExpiry <= captureDeadline <= refundDeadline (>= allowed,
matching contract _validatePayment)
* spec: use canonical base/commerce-payments addresses
Defer to the live deployment from base/commerce-payments@v1.0.0 instead
of redeploying via CREATE2. Drop the now-obsolete inline address tables
and salt-scheme paragraph; the Canonical Addresses annex now links to
the upstream release notes (and Uniswap deployments docs for Permit2),
matching scheme_exact_evm.md's third-party 'Canonical Permit2' annex
pattern.
---------
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
* Adding batch settlement details, plus a general cleanup of some stale content and onchain vs on-chain typos
* Additional minor polishing updates
* Merging SDK features mechanisms table with main and adding batch-settlement to resolve conflict
* batch-settlement on EVM
* update refund flow and payloads
* move corrective 402 info from errorDetails to requirements.extra.ChannelState and compute channelID from EIP712Hash
* align payment-response for all payloads
* post audit updates
* add deposit collector addresses
* update error codes
* specs(exact): propose TON exact scheme for x402 v2 (spec-only)
Adds scheme_exact_ton.md defining the exact payment scheme for TON blockchain.
Uses W5 wallet internal_signed messages for gasless Jetton (TEP-74) transfers.
Updates scheme_exact.md with TON-specific validation rules.
* specs(exact/ton): address review feedback — exact amounts, commission bounds, stateInit verification
- Change amount verification from >= to == (exact match), aligning with
all other chain specs (SVM, Stellar, EVM). The relay commission is a
separate jetton_transfer in the W5 batch, not bundled into the payment.
- Add extra.maxRelayCommission field to PaymentRequirements, allowing
resource servers to cap the relay commission amount.
- Add stateInit verification rule: when seqno == 0, facilitator must
verify contract code against a known W5 wallet code hash allowlist.
- Tighten action count: W5 message must contain exactly the payment
transfer and optionally a relay commission transfer, nothing else.
* specs(exact/ton): rewrite to self-relay architecture — address all review comments
* chore(spec): simplify TON spec — remove external_signed, condense references
- Remove external_signed (0x7369676e) mode — all x402 payments use
gasless internal_signed. External mode deferred to future extension.
- Remove on-chain proof table (7 tx links) — promotional, not normative.
Proofs already linked in PR comments.
- Condense Reference Implementations to 3 lines (was 20+).
- Settlement Logic now single-path (no dual-mode branching).
- 349 → 320 lines. Closer to SVM/Stellar spec size.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix(spec): remove 50% gas buffer — emulation is already worst-case
* specs(exact/ton): address all review comments — remove /prepare, add RPC
Changes:
- Remove /prepare endpoint: client resolves seqno + jetton wallet via
TON RPC directly (same pattern as SVM/Stellar/Aptos)
- Remove nonce field: dedup uses BoC hash, not nonce
- Transfer amount: strict equality (== not >=)
- Add jetton wallet verification: recipient MUST match
get_wallet_address(payTo) on the asset master
- Seqno check: MUST NOT be less than on-chain seqno (was SHOULD)
- Add client balance check requirement
- Move simulation to /verify (was optional pre-settlement)
- Remove HTTP header references (transport-agnostic)
- Replace hardcoded 600s with maxTimeoutSeconds
- Add Client RPC Requirements appendix section
* specs(exact/ton): add facilitator safety, explicit jetton wallet check
- Add section 3 (Facilitator Safety): facilitator address MUST NOT
appear as sender or Jetton transfer source. Matches SVM/Stellar.
- Make get_wallet_address check explicit per @skywardboundd: the
destination in the deserialized BoC must match the resolved wallet.
- Align verification intro phrasing with SVM/Stellar style.
* specs(exact/ton): add areFeesSponsored flag per Stellar pattern
Follows Stellar's approach: extra.areFeesSponsored boolean, currently
always true. Non-sponsored flow (client pays gas) to be added later.
* specs(exact/ton): fix validUntil duplication, add stateInit code hash check
- Remove duplicate validUntil check from section 2 (already in section 5)
- Add stateInit code hash verification for seqno==0 deployments
(per arjun215-eng's earlier feedback)
* specs(exact/ton): add payload.to and source Jetton wallet checks
Per @skywardboundd review:
1. payload.to MUST equal requirements.payTo (explicit metadata check)
2. Source Jetton wallet (W5 internal msg destination) MUST match
get_wallet_address(from) — prevents substitute source contract
3. jetton_transfer body destination MUST equal requirements.payTo
Tested against deployed facilitator with real on-chain data.
Facilitator commit: ohld/x402-ton-facilitator@6f92320
* specs(exact/ton): remove facilitatorUrl, fix dedup TTL, add canonical W5R1 hash
- Remove facilitatorUrl from extra (implementation detail, not protocol field)
- Fix dedup TTL: use fixed 300s instead of per-request maxTimeoutSeconds
- Add canonical W5R1 code hash for stateInit verification
- Note simulation as alternative to code hash checks for seqno>0
Per @phdargen review on coinbase/x402#1455
* specs(exact/ton): internal message BoC, minimal payload, strict seqno
Major rework based on TON Core team review:
- settlementBoc is now an internal message (not external)
- Payload reduced to {settlementBoc, asset}, all fields derived from BoC
- Public key derived from stateInit or on-chain get_public_key
- Seqno check changed to strict equality (TON requirement)
- Internal message must be bounceable
- Removed facilitatorUrl, nonce, walletPublicKey
- Clarified simulation in /verify, extensibility for non-gasless flows
- Updated parent scheme_exact.md TON section
* spec: address skywardboundd review -- account states, asset clarification, simulation chain
- Replace seqno==0 with proper TON account states (nonexist/uninit) for stateInit condition
- Clarify that payload.asset is a JSON field, not a BoC-internal field (TEP-74 has no asset)
- Add full TEP-74 transfer chain verification to simulation section
- Remove non-normative timing note from settlement step 7
- Add W5 gasless transactions reference link
* spec: address remaining review comments from skywardboundd
- Narrow wallet scope to W5 v5r1 (not v5r1+), only version that exists today
- Remove redundant "x402 protocol-level requirement" sentence
- Add get_jetton_data hint for decimal resolution
- Add walletId to derived fields list
- Rename section 2 to "Message and signature verification"
- Move balance check from Replay protection to Payment intent
- Remove redundant seqno explanation sentence
* spec: clarify TON exact flow for optional jetton transfer params
Refine the TON `exact` scheme spec to better describe how client-signed W5 jetton transfers are verified and relayed by the facilitator.
This update expands the TON payment requirements and verification rules to account for optional jetton transfer parameters exposed through `extra`, and clarifies how those parameters are interpreted when they are omitted.
Changes included:
- add optional `extra.forwardPayload` and `extra.forwardTonAmount` to TON
`PaymentRequirements` and define their effective defaults as zero-bit payload and `"0"`
- add optional `extra.responseDestination` and define its effective default as `addr_none`
- require facilitators to compare the effective values of `responseDestination`, `forwardPayload`, and `forwardTonAmount` between `accepted.extra` and `requirements.extra`
- extend payment intent validation so the facilitator derives and checks `response_destination`, `forward_payload`, and `forward_ton_amount` from the signed W5 action
- clarify that the facilitator-funded relay must cover both outer relay execution and the value expected by the client-signed inner transfer
- clarify that the client-signed inner message must carry enough TON to fund payer-side execution from the payer jetton wallet to the source jetton wallet
- specify that the outbound internal message from the client W5 wallet to the source jetton wallet must be bounceable
- specify that the `settlementBoc` wrapper itself does not need to be bounceable
- clean up terminology and consistency across the document: `BoC`, `zero-bit`, `forwardPayload`, `forwardTonAmount`, and derived field descriptions
This is a spec clarification/update only. It does not introduce a new TON payment scheme, but makes the existing gas-sponsored W5 relay flow more precise.
* specs(exact/ton): clarify W5 account states and extra field semantics
* soec(exact/ton): clarify code hash check
* spec(exact/ton): update reference implementations
* spec(exact/ton): allow sending mode 3
---------
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Co-authored-by: Arkadiy Stena <arkadiystena@gmail.com>
* feat: add auth-hints extension to streamline scheme-level authentication
- Described general auth scheme for x402, mainly on HTTP transports
- Initial support for two auth method types: oauth2 (Bearer/DPoP) and sign-in-with-x
- Defined scheme and acceptIndex hints.
* feat: settle on acceptIndexes, schemeAuth->authRequirements, remove references to scheme-based hints
* Migrate all code from branch-algorand-v2-typescript-algokit
* Update format and lint pass on core and examples
* Reformat template files
* Update: Coinbase review changes applied
* Fix Paywall builder pattern
* Update: Reverted e2e/legacy, Remove: src/exact/v1 and src/v1
* Add Faucets URLs to AVM README
* Optimizing and shrinking PR
* Remove dead import
* Add optimization changes related unit tests
* Update coinbase review changes applied
* Update avm e2e, rebased to latest, linted and formatted
* Fix avm template format
* Remove python and Go AVM templates, Made AVM optional to facilitator and Add SERVER_ADDRESS
* Lint and format
* Update: made AVM optional in proxy.ts
* Rebased and Replayed some commits
* Reset e2e pnpm-lock.yaml
* Replayed correct updated lockfiles
* Reverted accidentally overwritten files during rebase replay
* Revert accidental overwritten files in examples
* feat(specs): add Keeta exact scheme
* feat(schemes/keeta): add transaction simulation to verification step
This adds a few cheap checks to simulate the transaction and catch
invalid blocks early on to prevent the server from doing expensive work
unnecessarily.
* feat(evm): add upto payment scheme TypeScript SDK
Implement the upto payment scheme for EVM, enabling usage-based payments
where a client authorizes a maximum amount via Permit2 and the server
settles for the actual amount used (which may be less).
Covers all three roles:
- Client: creates Permit2 payloads with max authorized amount
- Server: builds payment requirements, forces permit2 transfer method
- Facilitator: verifies permitted >= required, settles actual usage,
supports zero-settlement path for no-charge responses
Key design decisions:
- Permit2 only (no EIP-3009, per spec)
- Shared Permit2 witness struct with exact scheme
- Re-exports shared utilities from exact (approval helpers, extensions, RPC)
- V2 protocol only
Resolves: CDPAI-714
* chore(evm): add JSDoc descriptions and fix lint errors in upto SDK
Add comprehensive JSDoc descriptions, @param, and @returns tags to all
upto scheme files to satisfy eslint jsdoc rules. Remove unused imports
in facilitator test file.
* refactor(evm): extract shared permit2 helpers to reduce duplication between exact and upto facilitators
* refactor(evm): consolidate client-side createPermit2Payload into shared helper
* refactor(evm): extract shared trySignEip2612Permit and trySignErc20Approval from scheme classes
* refactor(evm): split shared/permit2-helpers into permit2.ts and extensions.ts
* test(evm): add upto server, register, and types tests; expand client and facilitator coverage
Add 3 new test files (server.test.ts, register.test.ts, types.test.ts)
covering upto-specific server behaviors (permit2 forcing, facilitator
address injection, price parsing), registration helpers for all three
roles, and type guard validation. Expand existing client and facilitator
tests with additional edge cases.
Also includes in-progress source changes: shared permit2 helper
refactoring, upto facilitator hardening, spec clarifications, and
defaultAssets extraction.
* fix(evm): resolve lint errors for CI — add missing JSDoc descriptions and fix unused vars
* fix(evm): address PR review — align upto verify flow with exact, update spec, remove createEvmClient
* refactor(evm): move shared utils to shared/, remove upto register pattern
- Move validateErc20ApprovalForPayment to shared/erc20approval.ts
(was in exact/facilitator/, used by both exact and upto)
- Move RPC utilities to shared/rpc.ts, rename types to drop Exact prefix
(EvmSchemeConfig, EvmSchemeOptions, etc.) with deprecated aliases
- Remove registerUptoEvmScheme from client, facilitator, and server
(v1 legacy pattern not needed for v2-only upto scheme)
- Backward-compat re-exports preserved at original paths
* test(e2e): add upto payment scheme e2e test coverage
Add full e2e test suite for the upto payment scheme mirroring exact
permit2 coverage: direct settle, EIP-2612 gas sponsoring, and ERC-20
approval gas sponsoring endpoints.
- Add 3 upto endpoints to Express e2e server with UptoEvmScheme
- Register UptoEvmScheme in TypeScript facilitator
- Register UptoEvmClientScheme in fetch and axios e2e clients
- Add upto Permit2 approve/revoke cycle handling in test runner
- Add upto entry points to @x402/evm tsup.config.ts
- Update test.config.json files for all components
* fix(evm): harden upto type guard, add time window validation, improve settlement comments
- Add validAfter check to isUptoPermit2Payload for stricter exact/upto discrimination
- Add deadline > validAfter guard in client permit2 payload creation
- Default simulateInSettle to true for settlement re-verification
- Expand settlement re-verification comment for reviewer clarity
- Add no-register.ts comments explaining V1 compat is not needed for upto
- Clarify e2e test config description for upto endpoint
- Add tests for validAfter type guard and buildUptoPermit2SettleArgs
* feat: added SettlementOverride
* fix: examples lock
* feat: Added upto to hono/next e2e tests
* feat: update upto tests
* feat: update tests to support fallback facilitator for non-SDK parity testing
* fix: format/lint
* fix: add linting to upto example
---------
Co-authored-by: Fabrice Cheng <fabrice.cheng@coinbase.com>
The SVM exact scheme spec was out of date with the implementation
(PR #1048 added Memo instruction support without updating the spec).
This change:
- Updates instruction layout from 3-5 to 3-6 instructions
- Documents SPL Memo as an allowed optional program alongside Lighthouse
- Adds optional extra.memo field for seller-defined memo content
- Specifies client and facilitator behavior for memo verification
The extra.memo field enables sellers to attach payment references
(e.g., invoice IDs) to on-chain transactions, allowing payment
reconciliation on a single payTo address without requiring unique
deposit addresses (ATAs) per payment.
The protocol flow previously sent directly to /settle and declared
/verify as optional. Per maintainer feedback on PR #1575, verify is
required — it prevents the resource server from doing unnecessary work
for invalid payloads. This aligns the Stellar spec with the SVM and
Hedera exact scheme specs.
* Add new folders and READMEs to spec folder to support future settlement types and extensions.
* Add the EIP-3009/Signed Transfer spec.
* Added initial draft of offer and receipt extension.
* feat(extensions): Add client and server code to support signed offers and receipts.
Server:
- offerReceiptResourceServerExtension for signing offers/receipts
- JWS and EIP-712 signature format support
- Signer factories for both formats
Client:
- createOfferReceiptExtractor() callback for wrapFetchWithPayment
- Extracts offers, acceptedOffer, receipt, and settlementResponse
- Attaches metadata to response.offerReceipt
- Generic user review attestation with receipt/offer fallback, with optional OMATrust implementation
- Receipt-attestation client demonstrating full flow
* Update PR based on feedback:
- Add network field to receipt
- Add optional transaction field to receipt
- Move offers and receipt to extensions field
- Add version
- Removed settlement field from offer (refers to a future extension).
* Move signed payload version from info into the signed offer/receipt payload.
* Move version into signed payload. Replace issuedAt + maxTimeoutSeconds with validUntil.
* Add acceptIndex to signed offers as unsigned envelope field
- Add acceptIndex to offer envelope (not signed payload)
- Update examples and JSON schemas
* chore: remove outdated settlements folder
* chore: reset core/http to main for hooks integration
* feat(offer-receipt): implement v1.0 spec for signed offers and receipts
Implements the offer-receipt extension per extension-offer-and-receipt.md v1.0 spec.
Key changes from phdargen offer-receipt implementation:
- Pass down schema to comply with extensions spec
- Add more library functions for both servers and clients
- Remove server-side offer extraction (offers flow server→client only)
- Remove OMATrust integration code (deferred to future PR)
- Client example uses raw flow, not wrapper which still needs extension hook integration
- Add comprehensive test coverage (68 tests)
* chore: fix linter errors and update pnpm-lock.yaml
* chore: add lint/format config files to receipt-attestation example
* Address PR feedback: improve offer-receipt documentation and minor code cleanup:
- Rename .env.example to .env-local for consistency
- Move verbose code comments to README (use cases, security, verification)
- Add wrapFetchWithPayment example showing offer/receipt capture
- Remove unused createOfferReceiptExtractor
* refactor(offer-receipt): rename maxTimeoutSeconds to offerValiditySeconds
* fix(offer-receipt): simplify extractResourceUrl and import HTTPRequestContext from core
* feat(offer-receipt): rename Signer to Issuer and add server example
- Rename OfferReceiptSigner to OfferReceiptIssuer (more accurate naming)
- Rename signOffer/signReceipt to issueOffer/issueReceipt
- Rename createJWSOfferReceiptSigner to createJWSOfferReceiptIssuer
- Rename createEIP712OfferReceiptSigner to createEIP712OfferReceiptIssuer
- Add offer-receipt server example in examples/typescript/servers/offer-receipt
* fix(offer-receipt): make EIP-712 signing chain-agnostic
- Hardcode chainId to 1 in EIP-712 domain
- Change payTo type from address to string to support non-EVM networks
- Update spec §3.2, §4.3, §4.5, §5.5 as well as code and tests
* feat(offer-receipt): add signature verification and DID resolution
- Add 4 verification functions to signing.ts (verifyOfferSignatureEIP712,
verifyReceiptSignatureEIP712, verifyOfferSignatureJWS, verifyReceiptSignatureJWS)
- Add @noble/curves and @scure/base dependencies for crypto operations
- Add did.ts with extractPublicKeyFromKid supporting did:key, did:jwk, did:web
- Modify clients/offer-receipt example demonstrating full verification flow
- Change folder name of clients example to be more consistent
- Update tests with verification coverage
* Update examples/typescript/servers/offer-receipt/README.md
Co-authored-by: phdargen <pdargent@icloud.com>
* fix: produce valid JWS compact serialization in signJWS
- Fixed signJWS to output proper base64url-encoded JWS compact serialization
- Updated tests to actually verify JWS output, surfacing the broken serialization
- Renamed misleading function names discovered during the fix
* fix: enable local did:web verification
- Change resolveDidWeb to use HTTP for localhost/127.0.0.1 (per did:web spec)
- Server example now serves /.well-known/did.json with public key
- SERVER_DOMAIN env var is now required, expects did:web identifier format
- Added tests for localhost HTTP resolution
* feat(examples): add EIP-712 signing support to offer-receipt server
- Add eip712-signer.ts using viem privateKeyToAccount
- Update jws-signer.ts to handle both PEM and DER base64 formats
- Update README with signing format table and key generation commands
- Update environment variables
* refactor(offer-receipt): use transportContext from PR #1101 instead of enrichDeclaration
* chore: update pnpm-lock.yaml for new dependencies
* Address PR feedback:
- Fix: use HTTPTransportContext instead of HTTPRequestContext
- Remove extractResourceUrl helper, inline transportContext access
- Remove specs/extensions/README.md
- Add getPaymentSettleResponse logging to offer-receipt client example
- Add changeset for @x402/extensions minor release
* fix: regenerate examples lockfile for broken solana dependency entry
---------
Co-authored-by: phdargen <pdargent@icloud.com>
* feat: remove facilitator from exact scheme witness struct
The facilitator field in the witness was only needed for the upto scheme
where settlement amounts are variable. For exact, the amount is always
the full permitted amount so no facilitator binding is necessary.
Co-authored-by: Cursor <cursoragent@cursor.com>
* feat: re-mine vanity salts and deploy updated contracts to Base Sepolia
Exact: 0x402085c248EeA27D92E8b30b2C58ed07f9E20001
Upto: 0x402039b3d6E6BEC5A02c2C9fd937ac17A6940002
Co-authored-by: Cursor <cursoragent@cursor.com>
---------
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix: add duplicate settlement mitigation for SVM across all SDKs
Introduce an in-memory SettlementCache to prevent a race condition on
Solana where the same payment transaction could be settled multiple
times before on-chain confirmation. The cache is shared across V1 and
V2 facilitator schemes so that cross-version duplicates are caught.
- Add SettlementCache with 120s TTL in TypeScript, Python, and Go
- Integrate cache check into facilitator settle paths (V1 and V2)
- Add unit tests for duplicate detection in all three languages
- Share cache across V1/V2 in Go facilitator example
- Add duplicate settlement spec to scheme_exact_svm.md
- Document SettlementCache in SVM READMEs for all three SDKs
- Document the race condition in go/FACILITATOR.md Security section
- Add merchant-facing guidance in docs/core-concepts/client-server.md
and docs/core-concepts/facilitator.md for self-settling servers
- Fix JSDoc lint errors in TypeScript settlement-cache.ts
* refactor: optimize SettlementCache prune with early break on ordered entries
Leverage insertion-order guarantees of Map (TS) and dict (Python) to
break early once a non-expired entry is encountered, avoiding a full
scan of the cache on every isDuplicate call. Go is left unchanged since
map iteration order is not guaranteed.
Also adds prune-specific unit tests for all three SDKs covering:
- mixed expired/fresh entries
- all expired
- none expired
- insertion-order early-break correctness (Python)
* docs: add changelog entries for SVM duplicate settlement fix
* Add upto payment scheme specification for EVM
Introduces the upto scheme which enables usage-based payments where
clients authorize a maximum amount and servers settle for the actual
amount used. This is ideal for variable-cost resources like LLM token
generation, bandwidth metering, or time-based access.
Key features:
- Uses Permit2 exclusively (permitWitnessTransferFrom)
- Client signs for max amount, server settles for actual usage
- Settlement amount can be 0 to amount (inclusive)
- Adds settledAmount field to SettlementResponse
- Reuses existing x402Permit2Proxy contract
* Link to existing x402Permit2Proxy contract instead of duplicating
* Clarify error codes: standard vs scheme-specific
- List standard x402 error codes that apply to upto scheme
- Add scheme-specific error codes following naming convention
- Add missing error codes for recipient mismatch and time validation
* Simplify error codes section and add SettlementResponse link
- Link to base SettlementResponse schema in main spec
- Reference standard error codes instead of duplicating
- Keep only the truly upto-specific error code: settlement_exceeds_amount
* docs(upto): add explicit MUST requirements for cross-network properties
- Add Core Properties (MUST) section with single-use, time-bound,
recipient binding, and max amount enforcement requirements
- Add Out of Scope section clarifying what upto does NOT support
- Remove invalid use cases: streaming, time-based access, API rate metering
- Clarify remaining use cases as single-request patterns
Addresses PR feedback from @phdargen and @notorious-d-e-v
* docs(upto): rename settledAmount to amount in SettlementResponse
Rename for consistency with planned addition of amount field to base
SettlementResponse schema in x402-specification-v2.md (per PR feedback)
* docs(upto): clarify phase-dependent amount semantics in PaymentRequirements
The amount field in PaymentRequirements has different semantics at verify vs settle time for the upto scheme. At verification, it represents the max authorized amount. At settlement, it represents the actual amount to settle. This was ambiguous in the spec and is now explicitly documented across scheme_upto.md, scheme_upto_evm.md, and the main x402 v2 spec.
All four SDK implementations (TypeScript, Go, Go legacy, Python) include
x402Version as a top-level field in the facilitator /verify and /settle
request bodies, but neither the v1/v2 specs nor the TypeScript types
document it.
This adds x402Version to:
- v2 spec section 7.1 (POST /verify) request schema
- v1 spec section 7.1 (POST /verify) request schema
- VerifyRequest and SettleRequest types in @x402/core
- VerifyRequestV1 and SettleRequestV1 types in @x402/core
Closes#1176
* fix(exact): enforce strict amount equality per spec
The exact scheme spec states the transferred amount MUST equal
PaymentRequirements.amount exactly. All four facilitators used < instead
of !==, silently accepting overpayments.
Changes:
- SVM V2: amount !== BigInt(requirements.amount), reason: amount_mismatch
- SVM V1: amount !== BigInt(requirementsV1.maxAmountRequired), reason: amount_mismatch
- EVM EIP-3009: authorization.value !== requirements.amount, reason: authorization_value_mismatch
- EVM Permit2: permitted.amount !== requirements.amount, reason: amount_mismatch
Error reasons renamed from _insufficient to _mismatch to cover both
directions (underpayment and overpayment).
Closes#1378
* fix(exact): also enforce strict amount equality in v1 EVM facilitator
Applies the same < to !== comparison change to the v1 EVM facilitator
for consistency with the v2 EVM and SVM facilitators.
* docs(spec): correct exact scheme amount validation description
Two inaccuracies in x402-specification-v2.md relative to the authoritative
scheme contract in specs/schemes/exact/scheme_exact.md:
- §6.1.2 step 3: 'meets or exceeds' -> 'exactly matches'
The exact scheme requires strict equality (scheme_exact.md L24,
scheme_exact_svm.md L143). This section describes the EVM implementation
of the exact scheme, not the upto scheme.
- §9 error table: rename invalid_exact_evm_payload_authorization_value
to invalid_exact_evm_payload_authorization_value_mismatch and update
description from 'insufficient' to 'does not exactly match'.
These error codes are EVM-scheme-layer codes; the table is updated
to reflect the renamed code in the accompanying implementation change.
* style(evm): wrap long if condition in permit2.ts for prettier compliance
* feat(bazaar): add MCP tool support to discovery extension spec
Add documentation for cataloging MCP tools alongside HTTP endpoints.
MCP tools use a simpler structure with just tool name and inputSchema,
without the method/body/queryParams split needed for HTTP.
* Clarify waht kind of tools
* Update spec and resource notes
* Add Aptos mechanism implementation for x402
* Revert go changes
* Fix go revert
* Fix e2e imports
* Add aptos to all server e2e tests, make optional
* Make aptos optional on site
* Fix lint / format issues
* Add workflow for x402 aptos package
* Update e2e tests
* Fix facilitator manager
* feat: Implement exact payment scheme specification for Hedera HTS FT and HBAR token
Signed-off-by: Piotr Swierzy <piotr.swierzy@blockydevs.com>
* docs: Update Hedera exact scheme specification to include amount transfer details and account alias handling- Added clarification on the field for HBAR and HTS fungible tokens.- Specified that the decompiled transaction must be a directly.- Introduced a section on account aliases and auto-account creation, outlining potential risks and facilitator options.
Signed-off-by: Piotr Swierzy <piotr.swierzy@blockydevs.com>
---------
Signed-off-by: Piotr Swierzy <piotr.swierzy@blockydevs.com>
* feat(extensions): add Sign-In-With-X (SIWX) extension
Implements CAIP-122 compliant wallet-based identity assertions for x402 v2.
- Add SIWX types following CAIP-122 standard
- Server-side: declareSIWxExtension() for 402 response generation
- Client-side: createSIWxPayload() for proof creation and signing
- Message construction following CAIP-122 format
- Header encoding/parsing (base64 per x402 v2 spec)
- Validation: temporal, domain binding, nonce checking
- Verification: cryptographic signature validation via siwe library
- JSON Schema generation for payload validation
- Test coverage for core flows
* simplify; remove future looking code
* add integration test
* address own comments
* update readme, rm TODO.md
* add SIWS
* cleanup
* further cleanup
* split code path btwn evm and solana
* mv solana constants
* fmt
* lint
* rm .claude
* smart wallet verifier
* add domain param; support outside EVM verifier for contract wallets; Solana CAIP-2 compliant; rm clockskew slop
* fix missing type field; update lock file
* Add Sign-In-With-X extension spec
* server & client siwx examples
* chore: update pnpm-lock.yaml for sign-in-with-x examples
Update lockfile to include @types/node added to client example.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude <noreply@anthropic.com>
* Add wrapFetchWithSIWx helper to @x402/extensions
Adds a fetch wrapper for SIWX authentication that mirrors the
wrapFetchWithPayment pattern from @x402/fetch. The wrapper
automatically handles 402 responses with SIWX extension info.
Changes:
- Add fetch.ts with wrapFetchWithSIWx function
- Export wrapFetchWithSIWx from sign-in-with-x index
- Add DOM lib to tsconfig for Request/Response types
- Simplify client example to use the new wrapper
- Add .prettierignore and eslint globals to match other examples
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude <noreply@anthropic.com>
* feat(extensions/siwx): Add lifecycle hooks for simplified DevX
Adds pre-built hooks that integrate SIWX with x402's lifecycle system:
- SIWxStorage interface + InMemorySIWxStorage for tracking paid addresses
- createSIWxSettleHook: records payments after settlement
- createSIWxRequestHook: validates SIWX auth before payment processing
- createSIWxClientHook: automatically tries SIWX auth on 402 responses
Simplifies examples dramatically by removing custom middleware in favor
of composable hooks that plug into the standard x402 lifecycle.
* fix(extensions/siwx): Improve hooks robustness and add tests
- Extract payer address from multiple payload formats (EVM, Solana)
- Add onEvent callback for logging/debugging
- Handle header case-insensitivity
- Add comprehensive tests for storage and all three hooks
* fix(extensions/siwx): Only record payment if settlement succeeded
Previously, createSIWxSettleHook would record payments even when
settlement failed, allowing free access to users who attempted
payment but failed. Now checks ctx.result.success before recording.
* style: Fix JSDoc and lint errors
* style: Fix formatting and JSDoc in examples
* refactor(extensions/siwx): Migrate to supportedChains[] architecture
Implements reviewer feedback (phdargen) on multi-chain architecture for
SIWX extension, separating message metadata from authentication capabilities.
- **NEW**: SupportedChain interface with chainId, type, signatureScheme
- **CHANGED**: SIWxExtensionInfo no longer includes chainId/type/signatureScheme
- **CHANGED**: SIWxExtension now has supportedChains[] array
- **CHANGED**: declareSIWxExtension accepts string|string[] for network param
- **CHANGED**: expirationTime (absolute) → expirationSeconds (relative)
- **server.ts**: siwxResourceServerExtension with enrichDeclaration hook
- Refreshes nonce, issuedAt, expirationTime per request
- Fixes critical bug where time-based fields never updated after startup
- **NEW**: CompleteSIWxInfo type = SIWxExtensionInfo + chain fields
- **CHANGED**: createSIWxClientHook uses exact chain matching via supportedChains
- **CHANGED**: fetch wrapper matches signer chain with supportedChains
- Updated utility functions (message, evm, solana) to use CompleteSIWxInfo
- All 65 SIWX tests updated for supportedChains[] structure
- Added multi-chain test coverage
- All tests passing (120/120 total)
- Updated spec with supportedChains[] examples
- Added multi-chain example in spec
- Updated README with hook-based approach (recommended)
- Added manual usage examples for advanced use cases
- Updated API reference with new parameters
- Server example updated to use siwxResourceServerExtension
- Client example unchanged (hook handles supportedChains internally)
- ✅ Single shared nonce (correct replay semantics)
- ✅ No metadata duplication (domain/uri/statement shared)
- ✅ Exact chain matching (no heuristics)
- ✅ 83% wire size reduction for 10-chain configurations
- ✅ Aligns with CAIP-122 mental model
- Extension structure: info no longer has chainId/type
- Clients must use supportedChains to find matching chain
- declareSIWxExtension: expirationTime → expirationSeconds
- Servers must call .registerExtension(siwxResourceServerExtension)
BREAKING CHANGE: First version - no migration needed
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
* fix(examples): Add getChainId() to signer for proper SIWX chain matching
Without this method, the client hook falls back to eip155:1 which doesn't
match the server's eip155:84532 (Base Sepolia), preventing SIWX auth from
working.
* refactor(extensions/siwx): Extract duplicated getSignerChainId helper
- Extract getSignerChainId to sign.ts (shared location)
- Remove duplicate from hooks.ts (-16 lines)
- Remove duplicate from fetch.ts (-14 lines)
- Net: -5 lines, eliminates code duplication
Co-locates all signer utilities (getEVMAddress, getSolanaAddress,
signEVMMessage, signSolanaMessage, getSignerChainId) in sign.ts for
better discoverability and maintainability.
* feat(examples/siwx): Add payment header logging to client
Shows whether each request used payment settlement or SIWX auth
by checking for PAYMENT-RESPONSE header. Helps debug auth flow.
* fix(examples/siwx): Improve payment flow logging
- Properly distinguish between payment success, payment failure, and SIWX auth
- Check body.error to detect payment failures (no PAYMENT-RESPONSE header)
- Bug investigation: Rapid successive payments fail with transaction_failed
Investigation findings:
- Wallet has sufficient funds (0.009 ETH, 0.984 USDC)
- EIP-3009 nonces are randomly generated (no collisions possible)
- Issue only occurs with rapid successive requests
- 2-second delay between requests works around the issue
- Facilitator returns generic 'transaction_failed' without detailed error
Likely cause: Race condition in facilitator's blockchain transaction
submission when handling concurrent payment authorizations.
Next steps: Need facilitator-level debugging to see actual error details.
* fix(examples/siwx): Add 300ms delay to avoid facilitator race condition
Testing shows 300ms is sufficient to work around the rapid payment issue.
Without delay: second payment fails with transaction_failed.
With 300ms: both payments succeed consistently.
This minimal delay allows the facilitator to properly handle concurrent
payment authorizations without blockchain transaction nonce conflicts.
* refactor(extensions/siwx): Use payment network instead of signer chain detection
Simplify SIWX by deriving chain from paymentRequired.accepts[0].network
instead of requiring signers to implement getChainId(). This removes
the need for the Object.assign hack in client code.
- Update createSIWxClientHook to use network from payment requirements
- Update wrapFetchWithSIWx similarly
- Remove unused getSignerChainId helper
- Simplify example client code
* refactor(extensions/siwx): Auto-derive network/domain/uri from context
Make declareSIWxExtension fields optional - they're now derived automatically
from request context by siwxResourceServerExtension:
- network: from accepts[].network in route config
- resourceUri: from request URL
- domain: parsed from resourceUri
This eliminates redundant configuration and reduces chance of mismatches.
Explicit values still override automatic derivation.
* refactor(extensions/siwx): Remove time-based fields from declareSIWxExtension
Time-based fields (nonce, issuedAt, expirationTime) are now generated
per-request by enrichPaymentRequiredResponse instead of at declaration
time. This ensures fresh nonces and accurate timestamps for each request.
- Remove nonce/issuedAt generation from declareSIWxExtension
- Store expirationSeconds in _options for per-request calculation
- Update tests to use generateTimeBasedFields helper to simulate
server extension behavior
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
* docs(extensions/siwx): Add smart wallet docs, align signature schemes
- Remove sep10 and eip712 from supported signature schemes (not implemented)
- Add documentation for EIP-1271/EIP-6492 smart wallet verification
- Show how to use verifyOptions with createSIWxRequestHook
- Fix domain validation to use hostname instead of host (removes port)
- Add logging to example server for SIWX events
- Add tests for siwxResourceServerExtension
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
* chore: regenerate pnpm lockfile
Fixes ERR_PNPM_LOCKFILE_CONFIG_MISMATCH error in CI where the
"overrides" configuration didn't match the lockfile.
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
* fix(examples/siwx): Add missing JSDoc to onEvent function
* fix(extensions/siwx): Use result.payer instead of extracting from payload
The SVM payment payload is just `{ transaction: string }` with no payer
field. The payer address is extracted by the facilitator during settlement
and returned in the SettleResponse.payer field.
This fix:
- Removes extractPayerAddress() which incorrectly assumed payload.payer exists
- Uses ctx.result.payer from the facilitator's settle response
- Updates tests to pass payer in result object
This ensures SIWX works correctly for both EVM and SVM payment flows.
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
* feat(extensions/siwx): Add optional nonce tracking to prevent replay attacks
Adds optional hasUsedNonce/recordNonce methods to SIWxStorage interface
to prevent signature replay attacks. When a valid SIWX signature is
intercepted, it could be reused by an attacker to access resources
without paying.
Changes:
- Add optional hasUsedNonce?(nonce) and recordNonce?(nonce) to SIWxStorage
- Update createSIWxRequestHook to check/record nonces if methods exist
- Add nonce_reused event type for logging
- InMemorySIWxStorage unchanged (servers implement if they want protection)
This is opt-in: servers that want replay protection implement the
nonce methods in their storage. Servers without nonce tracking continue
to work as before.
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
* chore: Add changeset for SIWX extension
* fix(examples/siwx): Add missing JSDoc params for onEvent function
* fix(extensions/siwx): Require both nonce methods or neither
Throw error at hook creation if only one of hasUsedNonce/recordNonce
is implemented, preventing silent failure of replay protection.
---------
Co-authored-by: Claude <noreply@anthropic.com>
* Add Stellar scheme specification for x402 v2 exact
* Add link to the sequence number definition, and remove unused link
* Polish flow based on internal review from the Stellar Development Foundation
1. Remove `maxLedgerOffset` and calculate expiration ledger based on `maxTimeoutSeconds`.
2. Make it clear that facilitator's `/settle` should not assume prior validation and the flow doesn't need to go through `/validate`
3. Add an important check that ensures the simulation emits the expected transfer/balance events
* Updated scheme_exact.md with the latest changes of scheme_exact_stellar.md
* Address review suggestions.
Phantom and Solflare wallets inject Lighthouse program instructions for user
protection on Solana mainnet transactions. This causes x402 verification to fail
because the scheme expects exactly 3 instructions.
This change allows optional 4th and 5th instructions specifically from the
Lighthouse program (L2TExMFKdjpN9kozasaurPirfHy9P8sbXoAN1qA3S95):
- 4th instruction: Phantom wallet protection (1 Lighthouse instruction)
- 5th instruction: Solflare wallet protection (adds 2 Lighthouse instructions)
Changes:
- Add LIGHTHOUSE_PROGRAM_ADDRESS constant (TypeScript and Go)
- Update ExactSvmScheme verify to allow 3-5 instructions
- Update ExactSvmSchemeV1 verify to allow 3-5 instructions
- Reject any 4th/5th instruction that is not from Lighthouse program
- Add error constants for unknown 4th/5th instructions
- Update scheme_exact_svm.md spec to reflect changes
Fixes: #828
* Add Aptos exact scheme specification
Adds the exact payment scheme specification for Aptos blockchain:
- Uses Aptos fungible asset transfer (0x1::primary_fungible_store::transfer)
- Supports sponsored transactions via extra.sponsored field
- Facilitators can implement as direct fee payer or gas station service
- Follows x402 v2 protocol with CAIP-2 network identifiers (aptos:1, aptos:2)
- Includes security notes on fee payer mechanism
* Update Aptos spec to use sponsored: true instead of gasStation URL
- Replace gasStation URL with simple sponsored: true boolean in extra
- Clarify facilitator can use direct fee payer or gas station service internally
- Add security note about fee payer mechanism
- Link to Aptos sponsored transactions documentation
- Remove version field from PAYMENT-RESPONSE (consistent with other chains)
- Separate sponsored vs non-sponsored flows in appendix
* Adjust spec