All direct viem dependencies now resolve to 2.47.12, adding chain
definitions for Mezo Testnet (31611), MegaETH (4326), Stable (988/2201),
and others that were missing from earlier locked versions.
Lockfile-only change. No package.json range changes โ all existing ^2.x
ranges already accept 2.47.12.
* 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
* Migrate to @signinwithethereum/siwe
Migrate the SIWE dependency to the Ethereum Identity Foundation package. package.json now depends on @signinwithethereum/siwe; evm.ts import was updated to import SiweMessage from the new package. Added a changeset describing the migration. (pnpm lock updated to reflect the dependency change.)
* Add siwe v4.1.0 entries to pnpm-lock
Update examples/typescript/pnpm-lock.yaml to add @signinwithethereum/siwe@4.1.0 and @signinwithethereum/siwe-parser@4.1.0. Adds package resolutions and snapshot entries, registers peerDependencies (ethers and viem marked optional), and removes the older siwe@2.3.2 entry in the importer. This pins the example project to the siwe v4 parser/runtime and records its dependency graph in the lockfile.
* add self-facilitation example
* fix: regenerate examples/typescript lockfile against public npm registry
Lockfile had tarball URLs pointing to internal Coinbase Artifactory, causing
pnpm install to fail with ENOTFOUND in CI where that host is unreachable.
* 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>
* Add Fastify framework adapter for x402 payment middleware
* fix(fastify): preserve settlement response bytes and resource URLs
* chore(fastify): regenerate lockfiles for @x402/fastify workspace package
The pnpm-lock.yaml files in typescript/ and examples/typescript/ were missing
entries for the @x402/fastify package, causing CI to fail with
ERR_PNPM_OUTDATED_LOCKFILE on every workflow.
* feat(fastify): add e2e test server
Adds a Fastify server to the e2e test suite, following the same pattern as
Express and Hono. The test framework auto-discovers it via test.config.json.
Includes all standard endpoints: /protected (EVM), /protected-svm, /protected-aptos,
/protected-permit2, /protected-permit2-erc20, /protected-stellar, /health, /close.
* ci(fastify): add npm publishing workflow
Adds workflow_dispatch publishing workflow for @x402/fastify, matching the
pattern used by @x402/express and @x402/hono.
* feat(go): add net/http standard library adapter for payment middleware
* feat(go): add PaymentMiddlewareFromHTTPServer, example server, and e2e tests
* fix(siwx): generate nonce/issuedAt in declareSIWxExtension for auth-only endpoints
`declareSIWxExtension()` now generates `nonce`, `issuedAt`, and
`expirationTime` directly. Previously these were only populated by the
enrichment pipeline, which doesn't run for auth-only endpoints
(`accepts: []`). Clients detecting the SIWX extension couldn't sign a
valid proof without these fields.
Safe for the enrichment pipeline โ it builds a fresh info object
per-request, overwriting the pre-generated values.
Also adds convenience functions for the auth-only flow:
- `signSIWxChallenge(extension, signer)` โ header string
- `verifySIWxHeader(header, resourceUri)` โ { valid, address }
And an auth-only `/profile` endpoint in the SIWX example.
* refactor(siwx): separate createSIWxChallenge from declareSIWxExtension
Revert declareSIWxExtension to static-only. Add createSIWxChallenge
for auth-only endpoints that need per-request nonce/issuedAt.
* feat(siwx): auth-only routes through the enrichment pipeline
accepts: [] routes now go through the same pipeline as paid routes.
createSIWxRequestHook detects auth-only via routeConfig and grants
access on valid SIWX alone. nonce replay protection included.
server example /profile moved from manual handler to declarative config.
* chore: add changeset for siwx auth-only pipeline
* fix(siwx): address review feedback on auth-only examples
Server: replace verifySIWxHeader with parseSIWxHeader in /profile
handler โ the SIWX hook already verified the signature, so the handler
only needs to decode the header to extract the wallet address.
Client: replace manual two-step challenge flow with fetchWithPayment,
which handles auth-only routes transparently through the same hook
pipeline as paid routes. This demonstrates the key design point: callers
don't need to distinguish between paid and auth-only endpoints.
* refactor(siwx): remove standalone utilities, keep PR focused
Remove createSIWxChallenge, signSIWxChallenge, and verifySIWxHeader โ
convenience wrappers that aren't needed now that auth-only routes go
through the existing enrichment pipeline via accepts: [].
The core change is the isAuthOnly check in createSIWxRequestHook.
Everything else (challenge generation, nonce tracking, signature
verification) is already handled by the pipeline and hooks.
* fix: add JSDoc to test helper to satisfy lint
* docs(siwx): align auth-only docs and examples
* docs(siwx): clarify server example prerequisites
* chore: bump @stellar/stellar-sdk and remove the now unneeded fix
* Update getEstimatedLedgerCloseTimeSeconds to receive the rpc latest ledger, thus reducing by one the rpc calls needed
* Update getEstimatedLedgerCloseTimeSeconds to use horizon, which is way more efficient than rpc for this particular request
* Add changeset
* 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>
* 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 @x402/stellar mechanism package with exact scheme
Implement Stellar support for the x402 protocol covering:
- Types, constants (network IDs, USDC contracts), and utility functions
- Ed25519 signer with client/facilitator variants
- Soroban transaction simulation and auth entry handling
- Client: builds transfer calls, signs auth entries, serializes XDR
- Server: parses prices, enhances payment requirements
- Facilitator: verify (structure, amounts, signatures, events) and
settle (fee sponsorship, multi-signer round-robin, submission)
* Add unit tests for the Stellar mechanism
Cover signer, constants, utils, shared helpers, client/server
scheme logic, and facilitator verify/settle/getExtra flows.
150 tests across 9 test files.
* Add integration tests for Stellar exact scheme
End-to-end flows against Stellar testnet covering both the core
x402Client/Server/Facilitator and the HTTP middleware variants.
Includes resilience to testnet resets via automatic re-funding.
* Add Stellar README and cross-reference from evm/svm
Document the package API, usage examples, fee sponsorship model,
and multi-signer facilitator setup. Link back from evm and svm.
* Wire up Stellar in the advanced examples
Register Stellar client/server/facilitator schemes alongside EVM
and SVM in the all_networks examples. Guarded by env var presence
so existing setups keep working without Stellar credentials.
* Document Stellar setup in the advanced example READMEs
Add STELLAR_PRIVATE_KEY / STELLAR_ADDRESS env vars to .env-local
templates and update the example READMEs with Stellar usage notes.
* Add Stellar to the e2e test suite
Extend the test framework with Stellar network support, add
protected-stellar endpoints to express/hono/next servers, register
Stellar signers in axios/fetch clients and the TS facilitator.
Includes test configs, lockfile, and the Stellar family in the
test runner. All 8 serverรclient combos pass against testnet.
* Update e2e docs with Stellar setup and trustline instructions
Add STELLAR env vars to .env-local templates, document the Stellar
testnet account setup process (keypair, USDC trustline, faucet),
and update all server/client/facilitator READMEs.
* Add npm publish workflow for @x402/stellar
Manual-dispatch GitHub Actions workflow to publish the Stellar
package to npm with provenance, matching the pattern used by
the other mechanism packages.
* Add CHANGELOG for @x402/stellar v2.5.0
* chore(svm): move @solana/kit to peerDependencies for v5/v6 compatibility
* chore(svm): update examples lockfile for peerDependencies change
* chore: bump @solana/kit to ^6.1.0 across examples, e2e, and packages
Bumps all consuming packages from ^2.1.1 to ^6.1.0 to align with the
SVM mechanism's >=5.1.0 peerDependency range.
Also fixes a pre-existing type error in the e2e facilitator where
DiscoveredResource union type was accessed without narrowing.
* refactor(aptos): remove registerExactAptosScheme helpers, use builder pattern directly
Remove the backwards-compat register helpers introduced with the Aptos
package (registerExactAptosScheme for client/server/facilitator). New
packages should use the builder pattern (.register("aptos:*", new
ExactAptosScheme(...))) directly rather than wrapping it.
- Delete exact/{client,server,facilitator}/register.ts
- Simplify exact/{client,server,facilitator}/index.ts to re-export only ExactAptosScheme
- Simplify exact/index.ts to export only ExactAptosScheme from client (matching EVM/SVM)
- Update all e2e servers, clients, and facilitator to direct .register() calls
- Update test imports to use ExactAptosScheme aliases from scheme subpaths
- Update README examples to use builder pattern
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
* refactor: replace registerExact{Evm,Svm}Scheme helpers with direct .register() calls
Remove all usage of the backwards-compat register helpers outside of
their source definitions. Every consumer now uses the builder pattern
directly (.register("eip155:*", new ExactEvmScheme(signer))) which
matches the Aptos pattern and is more explicit.
- e2e servers (express, hono, next): server.register("eip155:*" / "solana:*", new Exact*Scheme())
- e2e clients (fetch, axios): client.register with ExactEvmScheme / ExactSvmScheme
- e2e facilitator (typescript): facilitator.register with both EVM and SVM schemes
- examples/clients (fetch, axios, sign-in-with-x, payment-identifier, advanced/all_networks): direct register
- examples/facilitator/basic: facilitator.register preserving deployERC4337WithEIP6492 option
- examples/fullstack (next proxy, miniapp route, miniapp page): direct register
- paywall package (EvmPaywall, SolanaPaywall): direct register
The registerExact{Evm,Svm}Scheme helpers remain available in the package
for backwards compat (used only in "simple" examples for new-user DX).
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
* chore: run go mod tidy on Go client examples
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
* fix: e2e tests
---------
Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
* 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(go): Add payment-identifier constants to shared types
Add extension identifier and validation constants for the
payment-identifier extension to the shared types package.
* feat(go): Add payment-identifier core types, utils, and schema
Add foundational components for the payment-identifier extension:
- doc.go: Package documentation
- types.go: PaymentIdentifierInfo, PaymentIdentifierExtension, ValidationResult
- utils.go: GeneratePaymentID, IsValidPaymentID
- schema.go: JSON Schema (Draft 2020-12) for validation
* feat(go): Add payment-identifier server-side declaration
Add server-side components for resource servers to declare
support for the payment-identifier extension:
- server.go: PaymentIdentifierResourceServerExtension
- resource_service.go: DeclarePaymentIdentifierExtension
* feat(go): Add payment-identifier client-side append function
Add client-side utility for appending payment identifiers to
extension payloads when the server has declared support.
* feat(go): Add payment-identifier facilitator extraction and validation
Add facilitator-side functions for extracting and validating
payment identifiers from payment payloads:
- IsPaymentIdentifierExtension, ValidatePaymentIdentifier
- ExtractPaymentIdentifier, ExtractPaymentIdentifierFromBytes
- ExtractAndValidatePaymentIdentifier, HasPaymentIdentifier
- IsPaymentIdentifierRequired, ValidatePaymentIdentifierRequirement
- ExtractPaymentIdentifierFromPaymentRequired
* test(go): Add payment-identifier extension tests
Add comprehensive test coverage for the payment-identifier extension:
- Constants validation matching TypeScript implementation
- ID generation and validation
- JSON Schema structure
- Server-side declaration
- Client-side append functionality
- Facilitator extraction and validation
- Full integration workflow tests
- JSON round-trip serialization tests
* docs(go): Add payment-identifier extension examples
Add usage examples for the payment-identifier extension:
- examples/go/servers/payment-identifier/: Standalone server example
- examples/go/clients/payment-identifier/: Standalone client example
- examples/go/facilitator/advanced/payment-identifier.go: Facilitator example
Structure matches TypeScript examples with dedicated directories
for client and server examples.
* Format
* Changelog
* test(go): Add payment-identifier tests for uncovered logic paths
Cover additional branches: invalid extension structure in append,
empty ID extraction, missing key with non-nil extensions map, and
V2 PaymentRequired with nil extensions.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix(go): Fix client example compilation error and add go.sum files
* refactor(go): Extract parseExtension helper and use DetectVersion
* fix(go): Remove debug logging and skip_settlement from gin middleware
* feat(go): Add PayloadFingerprint for 409 Conflict detection
SHA-256 hash of the serialized payload enables servers to distinguish
a legitimate retry from a misuse of the same payment ID with different
content.
* feat(ts): Add payloadFingerprint for 409 Conflict detection
Parity with Go SDK. Uses sorted-key JSON.stringify for deterministic
serialization before SHA-256 hashing.
* feat(go): Return 409 Conflict for duplicate ID with different payload
Example server now compares payload fingerprints on duplicate payment
IDs: matching fingerprints return the cached 200, mismatches return 409.
* feat(ts): Return 409 Conflict in example server for duplicate ID with different payload
* refactor(go): Move PayloadFingerprint out of core library into example
PayloadFingerprint is an application-level convenience for 409 Conflict
detection, not a protocol primitive. The spec defines the expected
behavior but not the implementation strategy.
* refactor(ts): Move payloadFingerprint out of core library into example
Mirrors the Go-side change โ payloadFingerprint is an application-level
convenience for 409 Conflict detection, not a protocol primitive.
* refactor(go): Extract getPaymentIdentifierExtension helper to reduce duplication
Consolidate the repeated nil-check + map-lookup pattern for extracting
the payment-identifier extension from a PaymentPayload into a single
shared helper, used by ExtractPaymentIdentifier,
ExtractAndValidatePaymentIdentifier, and HasPaymentIdentifier. Also
add missing payment-identifier pattern to the facilitator example
dispatcher comments.
* fix: Exclude payment proof from fingerprint hash
The payload field contains per-attempt cryptographic signatures that
are unique on every retry. Hashing them caused legitimate retries
(same ID, same intent) to trigger 409 Conflict. Now only the intent
fields (x402Version, accepted, resource, extensions) are hashed.
* fix: Revert intent-only fingerprint, cache payment header for true retries
The fingerprint should hash the full PaymentPayload including the
cryptographic signature. A proper retry resends the exact same signed
payload, so hashing everything is correct โ and a genuinely different
request (different signer/amount) correctly triggers 409.
The client example now caches the PAYMENT-SIGNATURE header from the
first successful attempt and replays it on subsequent requests,
instead of creating a new payment each time.
fix: Move idempotency check before payment middleware, cache payment header
The settlement hooks (OnBeforeSettle abort) don't properly short-circuit
the middleware โ the abort error isn't handled by OnSettleFailure, so the
middleware returns 402 for duplicate requests.
Fix: move the idempotency check to a gin middleware that runs BEFORE the
payment middleware (matching the TS onProtectedRequest pattern). Duplicate
payment IDs are detected and served from cache without entering the
payment pipeline at all.
Also fixes the client to cache and replay the PAYMENT-SIGNATURE header
on retry instead of creating a new payment each time.
Fingerprint is now a hash of the raw PAYMENT-SIGNATURE header string,
which is simpler and correct โ a true retry sends identical bytes.
* Lint
---------
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
* feat(python): add payment-identifier extension types and constants
- Add PaymentIdentifierInfo and PaymentIdentifierExtension Pydantic models
- Add constants: PAYMENT_IDENTIFIER, PAYMENT_ID_MIN_LENGTH, PAYMENT_ID_MAX_LENGTH, PAYMENT_ID_PATTERN
- Define PaymentIdentifierSchema type alias
* feat(python): add payment-identifier utility functions
- Add generate_payment_id() to create UUID v4-based payment IDs
- Add is_valid_payment_id() to validate ID format (16-128 chars, alphanumeric + hyphens/underscores)
* feat(python): add payment-identifier JSON Schema definition
- Add payment_identifier_schema compliant with JSON Schema Draft 2020-12
- Schema validates required boolean and optional id string field
* feat(python): add payment-identifier validation and extraction functions
- Add ValidationResult dataclass for validation results
- Add is_payment_identifier_extension() type guard
- Add validate_payment_identifier() for full extension validation
- Add extract_payment_identifier() to extract ID from PaymentPayload
- Add extract_and_validate_payment_identifier() combined function
- Add has_payment_identifier() to check extension presence
- Add is_payment_identifier_required() to check requirement flag
- Add validate_payment_identifier_requirement() for requirement compliance
* feat(python): add payment-identifier client utilities
- Add append_payment_identifier_to_extensions() to append payment ID to extensions dict
- Only appends if server declared the extension
- Generates new ID if not provided
* feat(python): add payment-identifier resource server utilities
- Add declare_payment_identifier_extension() to create extension declaration
- Add PaymentIdentifierResourceServerExtension class implementing ResourceServerExtension protocol
- Add payment_identifier_resource_server_extension singleton instance
* feat(python): add payment-identifier extension main module
- Export all public APIs from payment-identifier extension
- Add comprehensive usage documentation with examples for servers, clients, and idempotency
* feat(python): export payment-identifier extension from extensions module
- Add payment-identifier imports and exports to main extensions __init__.py
- Export all constants, types, functions, and classes for public API
* fix(python): resolve ValidationResult type mismatch in extensions module
- Export payment_identifier.ValidationResult as ValidationResult (matches payment_identifier function return types)
- Export bazaar.ValidationResult as BazaarValidationResult for explicit bazaar usage
- Both ValidationResult classes are structurally equivalent (same dataclass fields)
- Fixes type mismatch where payment_identifier functions returned payment_identifier.ValidationResult but ValidationResult imported from x402.extensions was bazaar.ValidationResult
* refactor(python): rename payment_identifier ValidationResult to PaymentIdentifierValidationResult
- Rename ValidationResult class to PaymentIdentifierValidationResult in payment_identifier/validation.py
- Update all function return types and usages throughout validation.py
- Update exports in payment_identifier/__init__.py
- Update imports/exports in extensions/__init__.py
- Keep ValidationResult from bazaar as default export for backward compatibility
- Export PaymentIdentifierValidationResult separately for explicit payment_identifier usage
- Makes naming consistent with BazaarValidationResult pattern
* test(python): add comprehensive test suite for payment_identifier extension
- Add test_types.py: Test constants and Pydantic models
- Add test_utils.py: Test ID generation and validation functions
- Add test_validation.py: Test all validation and extraction functions
- Add test_client.py: Test client-side utilities
- Add test_server.py: Test server-side utilities
- Tests cover all major functionality including edge cases and error handling
- Follows same structure as bazaar extension tests
* fix(python): fix payment_identifier test helper and assertions
- Fix create_extension_with_id helper to handle invalid IDs for testing
- Update test assertion to check for 'identifier' in error message
- All 67 tests now passing
* fix(python): add ValidationResult alias for backward compatibility
- Add ValidationResult = BazaarValidationResult alias after bazaar import
- Fixes AttributeError when importing ValidationResult from x402.extensions
- ValidationResult was imported as BazaarValidationResult but exported in __all__
- Now both ValidationResult and BazaarValidationResult are available
* test(python): add test to verify __all__ exports are importable
- Add test_exports.py to verify all items in __all__ can be imported
- Tests that ValidationResult alias works correctly
- Tests that 'import *' works as expected
- This would have caught the ValidationResult AttributeError bug
* fix(python): make jsonschema import lazy in payment_identifier validation
- Remove module-level jsonschema import that raised ImportError
- Import jsonschema lazily only when schema validation is needed
- Return validation error instead of raising ImportError at module level
- Allows payment_identifier extension to be imported without jsonschema
- Users can still use non-validation functions without optional dependency
* fix(python): fix linting errors
- Remove unused variable in test_types.py
- Fix import sorting in extensions/__init__.py
- Add noqa comment for intentional E402 (import after alias)
* Lint
* docs(python): add payment-identifier extension examples
Add client and server examples demonstrating how to use the
payment-identifier extension for idempotent payment processing.
Client example shows:
- Generating payment IDs with generate_payment_id()
- Using on_before_payment_creation hook to inject the ID
- Making duplicate requests to demonstrate cache behavior
Server example shows:
- Declaring extension support with declare_payment_identifier_extension()
- Extracting payment IDs with extract_payment_identifier()
- Caching responses after settlement for idempotency
* Lint
* Format
* Changelog
* feat: added mcp submodule to go
* feat: added unit tests
* feat: added mcp client example
* feat: added mcp server example
* feat: added mcp client chatbot example
* feat: go changelog
* feat: pr feedback
* fix: format
* fix: lint
* feat(cloudfront-lambda-edge): Add CDP facilitator authentication and mainnet support
- Add facilitator-auth.ts module with CDP authentication helpers for mainnet payments
- Introduce FacilitatorType configuration to support both testnet and mainnet facilitators
- Add getAuthHeaders() function in config.ts for dynamic authentication based on facilitator type
- Update README with comprehensive mainnet setup instructions and CDP integration guide
- Add Solana network configurations (Devnet and Mainnet) to supported networks list
- Expand documentation with production secrets management best practices for Lambda@Edge
- Reorganize config.ts to separate facilitator configuration from payment settings
- Update tsconfig.json to support new authentication module compilation
- Enhance middleware library structure with index.ts for better package organization
- Add security warnings about Lambda@Edge environment variable limitations and AWS Secrets Manager recommendations
* refactor(cloudfront-lambda-edge): Simplify facilitator auth and improve documentation
- Remove dedicated facilitator-auth.ts module and integrate auth into config
- Update README with clearer mainnet setup instructions using facilitator packages
- Simplify config.ts to remove CDP-specific type and credentials
- Refactor origin-request.ts and origin-response.ts to accept facilitatorConfig parameter
- Update package.json dependencies and build configuration
- Improve documentation structure with consolidated setup steps
- Make facilitator authentication flexible by accepting custom createAuthHeaders function
- Reduce complexity by removing hardcoded CDP authentication logic in favor of generic config approach
* revert tsconfig.json
* revert tsconfig
* feat(extensions): add payment-identifier types and schema
Add core type definitions and JSON Schema for the payment-identifier
extension which enables client-provided idempotency keys.
- PAYMENT_IDENTIFIER constant and length constraints
- PaymentIdentifierInfo, PaymentIdentifierExtension interfaces
- PaymentIdentifierDeclaration for server-side use
- JSON Schema Draft 2020-12 compliant schema
* feat(extensions): add payment-identifier utility functions
Add utility functions for generating and validating payment identifiers.
- generatePaymentId(): creates UUID v4 with optional prefix
- isValidPaymentId(): validates ID format (16-128 chars, alphanumeric/hyphens/underscores)
* feat(extensions): add payment-identifier client helper
Add createPaymentIdentifierPayload() for clients to include
idempotency keys in their PaymentPayload.extensions.
- Auto-generates ID if not provided
- Validates custom IDs before use
- Returns extension object ready for PaymentPayload
* feat(extensions): add payment-identifier resource server support
Add server-side functions for advertising payment-identifier support.
- declarePaymentIdentifierExtension(): creates declaration for PaymentRequired
- paymentIdentifierResourceServerExtension: ResourceServerExtension implementation
* feat(extensions): add payment-identifier validation and extraction
Add validation and extraction utilities for processing payment identifiers.
- validatePaymentIdentifier(): validates extension structure and ID format
- extractPaymentIdentifier(): extracts ID from PaymentPayload
- extractAndValidatePaymentIdentifier(): combined extraction with validation
- hasPaymentIdentifier(): checks for extension presence
* feat(extensions): add payment-identifier barrel export
Add index.ts with all public exports and usage documentation.
* feat(extensions): export payment-identifier from package
Update package exports and build configuration for payment-identifier.
- Add ./payment-identifier export path to package.json
- Add payment-identifier entry to tsup.config.ts
- Re-export payment-identifier from main index.ts
* test(extensions): add payment-identifier unit tests
Add comprehensive test coverage for the payment-identifier extension.
- Constants and type exports
- ID generation (prefix, uniqueness, format)
- ID validation (length, characters, edge cases)
- Client payload creation
- Server declaration
- Extension validation
- PaymentPayload extraction
- 37 tests covering all functionality
* Lint
* feat: add required & refactor client logic to append to extensions
* feat: added examples
* fix: lint
* fix: cleanup
---------
Co-authored-by: CarsonRoscoe <carsonroscoe7@gmail.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>
* feat(examples): Add CloudFront Lambda@Edge x402 payment handler
feat(examples): add CloudFront Lambda@Edge server example
Reference implementation for adding x402 payments at the edge without
modifying backend code.
- Add complete Lambda@Edge handler implementation for x402 payment verification
- Include configuration system for route-based pricing and payment settings
- Add payment verification and settlement logic via x402 facilitator
- Include response formatting for 402 Payment Required and success cases
- Include advanced patterns for WAF integration, caching optimization, and cookie-based sessions
* docs(cloudfront-lambda-edge): Update package.json for monorepo development
- Change @x402/core dependency to use workspace:* for monorepo development
- Add documentation note explaining workspace dependency usage
- Include migration instructions for standalone project setup
- Clarify version replacement needed when copying example outside monorepo
* Minimze type defenition, use x402/core built it types
* refactor(examples): Restructure CloudFront Lambda@Edge to use x402HTTPResourceServer
- Add `adapter.ts` with `CloudFrontHTTPAdapter` to translate CloudFront requests to standard HTTPAdapter interface
- Add `server.ts` with `x402HTTPResourceServer` setup and route configuration using `@x402/core` types
- Remove `config.ts` and `payment.ts` โ functionality now handled by x402HTTPResourceServer
- Update `index.ts` to use new server architecture with lazy initialization
- Update `responses.ts` with Lambda@Edge response helpers
- Add `@x402/evm` dependency to `package.json`
- Expand README with detailed configuration examples, route setup, and advanced patterns
- Update file structure documentation to reflect new adapter and server modules
- Consolidate payment configuration into `server.ts` for single source of truth
- Ensure consistency with other x402 implementations by using shared `RouteConfig` type
* refactor(examples): Restructure CloudFront Lambda@Edge with middleware pattern
- Split monolithic handler into origin-request and origin-response handlers for verify โ execute โ settle pattern
- Extract configuration into dedicated config.ts file for easier customization
- Create reusable middleware layer in lib/ directory with createX402Middleware and createX402Server factories
- Reorganize library code (adapter, responses, middleware, server) for future @x402/lambda-edge package
- Implement fair billing: customers only charged when origin returns success (status < 400)
- Update README with sequence diagram showing two-phase Lambda@Edge flow and deployment instructions
- Add origin-response handler to settle payments only after successful origin responses
- Improve code organization and separation of concerns between configuration, handlers, and reusable utilities
* chore(examples): Update pnpm lock file for CloudFront Lambda@Edge server
- Add CloudFront Lambda@Edge server entry to pnpm-lock.yaml
* docs(cloudfront-lambda-edge): Restructure README with improved clarity
- Add mermaid diagram showing CloudFront + Lambda@Edge architecture
- Reorganize "Why This Approach?" section with em-dash formatting for consistency
- Add "Getting Started" section with guidance for existing and new users
- Create table of key files with their purposes for quick reference
- Add collapsible details section documenting Lambda@Edge constraints and quotas
- Simplify "Quick Start" instructions with clearer step descriptions
- Remove verbose sequence diagram in favor of concise architecture overview
- Update configuration examples to be more concise and actionable
- Improve navigation and readability with better section hierarchy
- Consolidate AWS documentation links for CloudFront and Lambda@Edge learning