123 Commits

Author SHA1 Message Date
phdargen
f420044dca
chore: version typescript packages (#2019)
* fix workspace settings

* fix avm/fastify changelogs

* chore: version typescript packages
2026-04-14 01:28:36 +09:00
Ryan R. Fox
9424291a00
chore(typescript): bump viem to 2.47.12 across all packages (#2013)
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.
2026-04-13 14:33:41 +09:00
Andrew Barnes
b123f3979e
docs(examples): clarify facilitator signer roles (#1937) 2026-04-11 19:16:08 +09:00
MG
a25800efed
feat(avm): Add Algorand (AVM) blockchain exact spec implementation and networks support for Typescript (#1560)
* 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
2026-04-11 08:01:20 +09:00
caveman.eth
a4e49114e1
chore(extensions): migrate to @signinwithethereum/siwe (#1917)
* 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.
2026-04-09 21:19:45 +09:00
Carson Roscoe
5033781a8b
feat: add upto readme and client examples (#1963) 2026-04-09 00:28:06 +09:00
Ethan Oroshiba
13928348ec
feat: add self-facilitation example (#1942)
* 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.
2026-04-06 10:36:26 -07:00
Carson Roscoe
2250caec83
feat: refactor coinbase/x402 references to x402-foundation/x402 (#1912)
* feat: refactor coinbase/x402 references to x402-foundation/x402

* fix: format

* chore: changeset fragments for typescript, python and go
2026-04-02 12:59:07 -07:00
Carson Roscoe
fc11152c47
feat: add upto to go sdk (#1833)
* feat: add upto to go sdk

* feat: cleanup PR

* feat: added HTTPTransportContext to Go SDK

* fix: ai reviewer feedback

* fix: typescript tests

* fix: header parsing for HTTPTransportContext in Typescript

* feat: cleanup pr

* feat: pr cleanup

* feat: pr review

* feat: update e2e go.mod for upto debs

* fix: lint
2026-03-27 18:19:18 -07:00
Carson Roscoe
d352574bd5
feat: add upto to typescript sdk (#1773)
* 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>
2026-03-25 16:10:04 -07:00
Elliot Padfield
bd424988aa
Add Fastify framework adapter for x402 payment middleware (#1512)
* 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.
2026-03-24 15:24:06 +09:00
wonjoon
8eda857c9f
feat(go/http): add Echo framework middleware adapter (#1424)
* feat(go/http): add Echo framework middleware adapter for x402 payment handling

* feat(go): add example server and e2e tests for echo
2026-03-24 14:37:56 +09:00
wonjoon
7f837ea413
feat(go): add net/http standard library adapter for payment middleware (#1421)
* feat(go): add net/http standard library adapter for payment middleware

* feat(go): add PaymentMiddlewareFromHTTPServer, example server, and e2e tests
2026-03-24 14:35:58 +09:00
Carson Roscoe
067f29705f
feat: add dynamic routing to bazaar (#1664)
* feat: add dynamic routing to bazaar

* feat: fixed format/linter errors

* fix: access routeConfig.config.settlementFailedResponseBody after getRouteConfig return type change

getRouteConfig now returns { config: RouteConfig; pattern: string } instead of RouteConfig
directly. The buildSettlementFailureResponse call site was not updated, causing
settlementFailedResponseBody callbacks to be silently skipped after settlement failures.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix: updated param logic

* feat: added typescript, python and go bazaar server examples

* feat: updated e2e bazaar facilitators

* fix: add pathParams if not set

* fix: lint in python

* fix: typescript examples lock

* feat: pr feedback

* feat: pr feedback

---------

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-23 08:49:46 -07:00
phdargen
5135fab5e7
Fix extra: null incompatibility between python facilitator and TS zod schema (#1762)
* Fix extra: null incompatibility between Python facilitator and TypeScript Zod schema

* fix optional strings

* fixed outdated eth_account._utils.typed_transactions import
2026-03-23 08:41:51 -07:00
Sam Ragsdale
4f2f4f33da
fix(siwx): generate nonce/issuedAt in declareSIWxExtension for auth-only endpoints (#1140)
* 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
2026-03-17 18:06:08 +09:00
Marcelo Salloum dos Santos
c92c0d12e0
stellar: Bump @stellar/stellar-sdk dependency and improve API call for better performance (#1598)
* 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
2026-03-16 10:18:21 +09:00
phdargen
d1ad494421
fix ts changeset version bumps (#1588) 2026-03-14 01:41:14 +09:00
Alfred Tom
f2bbb5cb25
feat(extensions): add optional signed Offer & Receipt extension (draft, addresses #496) (#935)
* 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>
2026-03-12 14:20:36 +09:00
phdargen
1a6e08b291
EVM verify simulation and improved smart account handling (#1474)
* fix evm sim

* fix EIP-6492 deployment info check

* fix implementation-dependent verifyTypedData

* same for v1

* update multicall

* update errors

* refactor

* minor fixes

* add go equivalent

* add py equivalent

* fix #1388 for go/py

* fix #1139 for py/go

* fix go signer
2026-03-10 10:04:52 -07:00
Carson Roscoe
8b731cb590
feat: improve permit2 and extensions sdks (#1487)
* feat: improve typescript implementation

* feat: improve go implementation

* feat: update examples

* chore: update e2e clients

* feat: improve typescript sdk for permit2 & gas sponsoring extensions

* feat: improve go sdk for permit2 & gas sponsoring extensions

* feat: update e2e tests accordingly

* fix: lock/format/lint

* chore: added changelog fragments

* fix: x402.org usage of permit2 extensions

* feat: pr feedback
2026-03-09 17:51:52 -07:00
Notorious D.E.V.
7cd93d8bf5
Add in-memory cache for in-flight Solana txs (#1468)
* 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
2026-03-05 16:16:09 -08:00
phdargen
aeef1bff66
Custom settlement failures responses (#1430)
* py fix for 1176

* fix settle response body

* same for go/py

* fix format
2026-03-05 09:46:39 +09:00
Marcelo Salloum dos Santos
013754554a
Add Stellar Blockchain Support (#711)
* 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
2026-03-04 13:56:52 -08:00
phdargen
205257b634
Cleanup dependencies and fix example builds (#1355)
* clean up dep

* fix examples
2026-03-02 17:09:27 -08:00
Maximilian Hubert
703a5415ac
fix: typo in README.md (#1390)
Corrected the spelling of 'convenience' in the README.
2026-03-01 12:22:24 +09:00
Misha Kolesnik
a70db066dc
chore(svm): move @solana/kit to peerDependencies for v5/v6 compatibility (#1334)
* 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.
2026-02-26 14:35:30 +09:00
Carson Roscoe
62d0e749c0
feat: Aptos fast follow updates (#1266)
* 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>
2026-02-20 11:54:02 -05:00
Jon
57a5488bcb
Add Aptos payment mechanism (#966)
* 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
2026-02-19 15:29:43 -05:00
A. McDermott
59c9c66e5f
feat: Payment Identifier SDK - Golang (#1113)
* 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>
2026-02-19 15:28:05 -05:00
Carson Roscoe
018181b14a
feat: eip2612 gas sponsorship extension implementations (#1208)
* feat: typescript implementation

* feat: typescript unit & integration tests

* feat: go implementation

* feat: go unit & integration tests

* feat: typescript example

* feat: update e2e tests for eip2612 extension

* feat: added go & typescript changelog fragments

* fix: format
2026-02-18 11:32:46 -05:00
A. McDermott
e9d9b3a5ba
feat: Payment Identifier Extension SDK - Python (#1111)
* 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
2026-02-11 18:46:46 -05:00
Carson Roscoe
dd49a43618
chore: version typescript/go/python packages (#1163)
* chore: version typescript packages

* chore: version python package

* chore: version go package

* chore: update lock files
2026-02-11 16:30:47 -05:00
Carson Roscoe
65d968c366
feat: e2e testing for mcp transport - Typescript, Python & Golang (#1149)
* feat: add mcp support to e2e test suite

* feat: add mcp go client to e2e tests

* feat: add mcp go server to e2e tests

* feat: add mcp python client to e2e tests

* feat: add mcp python server to e2e tests

* feat: add mcp typescript client to e2e tests

* feat: add mcp typescript server to e2e tests

* fix: go mcp sdk

* fix: python mcp sdk

* fix: typescript mcp sdk

* feat: refactor go mcp sdk

* feat: refactor python mcp sdk

* fix: format & lint python

* feat: format & lint go

* fix: python unit tests

* feat: added missing go changeset fragment

* feat: added Python export for MCPToolResult

* fix: pr feedback
2026-02-11 13:43:31 -05:00
Carson Roscoe
4861b61b80
Add MCP submodule to Python SDK (#1131)
* feat: added MCP module in Python

* feat: added tests

* feat: added mcp client example

* feat: added mcp server example

* feat: mcp client chatbot example

* feat: added changelog entry

* fix: readme

* feat: pr feedback
2026-02-10 13:39:59 -05:00
Carson Roscoe
3b2434d105
Feat/x402 mcp go (#1132)
* 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
2026-02-09 18:09:24 -05:00
Eitav Arditti
de9f9f53b2
feat(cloudfront-lambda-edge): Add CDP facilitator authentication and โ€ฆ (#1102)
* 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
2026-02-07 03:08:03 +09:00
phdargen
f93fc09f52
add svm to siwx examples and add solanakit support (#1091)
* add svm to siwx examples and add solanakit support

* fix format

* add READMEs
2026-02-05 15:44:28 -08:00
phdargen
330abc9b08
Adding chains guidelines (#1090)
* add guidelines for adding new chains

* add new all_networks examples

* fixes
2026-02-05 15:31:18 -08:00
Carson Roscoe
93dbae6d8e
chore: version typescript packages (#1098)
* feat: fix changesets config & backfill changeset fragments

* feat: update package dependency relations

* feat: update locks after e2e tests

* chore: version typescript packages
2026-02-05 12:53:59 -08:00
A. McDermott
d15c3f44a9
feat: Payment identifier extension - TS (#1079)
* 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>
2026-02-05 11:15:19 -08:00
Carson Roscoe
ddd8009fbb
Simplifying MCP SDK (#1083)
* feat: improved MCP SDK interfaces

* feat: added mcp server example, mcp client example, and mcp client chatbot example

* fix: lint
2026-02-04 10:15:40 -08:00
Carson Roscoe
0e99914cee
feat: updated @x402/mcp to match updated spec (#1076)
* feat: updated @x402/mcp to match updated spec

* feat: updated  to remove embdedded errors
2026-02-03 17:06:12 -08:00
Carson Roscoe
09b529ae00
feat: added x402MCPClient, x402MCPServer, middleware, and examples (#1056)
* feat: added x402MCPClient, x402MCPServer, middleware, and examples

* feat: expanded examples to simple & advanced mcp examples

* fix: format/lint

* feat: added npm deploy workflow and set version to 2.2.0-alpha

* feat: client side PR feedback

* feat: pr feedback

* fix: merge to main

* fear: pr feedback

* feat: added integration teast with SSE MCP

* feat: expose timeout, abort signal and reset timeout on progress options to x402MCPClient

* fix: rebased main

* fix: examples linting

* fix: remove unknown directive
2026-02-02 17:50:40 -08:00
Sam Ragsdale
fe42994900
feat(extensions): SIWX Extension (#921)
* 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>
2026-02-03 08:39:02 +09:00
phdargen
29aa4135c4
New hooks for extensions to enrich payment-required and payment-response (#1003)
* new extension hooks

* updated hook args

* update tests

* remove verify hook

* fix workflows

* update specs
2026-01-23 11:24:20 -08:00
Eitav Arditti
825c692a1d
Feature/examples cloudfront and lambda as x402 seller middleware (#980)
* 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
2026-01-24 00:16:02 +09:00
Carson Roscoe
ca7f38e5e7
chore: version python package (#1005) 2026-01-21 16:47:16 -08:00
Carson Roscoe
30a847d7d1
feat: New Python SDK with v2 support (#841)
* chore: renamed python/x402 to python/legacy

* feat: initial Python core SDK

* feat: added core HTTP wrappers

* feat: added core types

* feat: added evm mechanism for exact v1/v2

* feat: added httpx client

* feat: added requests client

* feat: added fastapi middleware

* feat: added flask middleware

* feat: added integration tests

* feat: added Python SDK to e2e tests

* python-v2: fix workflow checks (#863)

* fix format

* fix lint

* fix build

* fix pytest

* Fix syntax errors and missing imports in manual integration example (#902)

- Add missing imports (base64, json, Response, JSONResponse, PaymentPayload, FacilitatorClient)
- Fix function signature syntax error
- Fix dict initialization syntax (colon to equals)
- Add missing return statement after successful payment
- Remove trailing whitespace

* feat: add Python SDK v2 server examples (FastAPI, Flask)  (#879)

* feat: add fastapi example project configuration

* feat: add fastapi example with x402 payment middleware

* docs: add comprehensive README for fastapi example

* feat: add flask example project configuration

* feat: add flask example with x402 payment middleware

* docs: add comprehensive README for flask example

* feat: add test clients for fastapi and flask examples

* docs: add test client usage to READMEs

* chore - remove python-version and test-client.py

* docs - remove test client guide from README.md

* chore - remove license and classifier

* feat - add description and mime type

* feat - update .env-local

* feat: add Python v2 client examples (httpx & requests) (#857)

* feat: add Python v2 client examples (httpx & requests)

Add simple client examples demonstrating httpx (async) and requests (sync) usage with the x402 Python v2 SDK.

- examples/python/clients/example.py - Simple example showing both httpx and requests
- Uses EthAccountSigner with register_exact_evm_client helper
- Minimal configuration required

* refactor: split Python client examples into separate directories

Address PR review feedback:
- Separate httpx/ and requests/ directories
- Add pyproject.toml for uv sync support
- Add environment variable validation
- Add payment response header extraction
- Use context manager for requests session cleanup

Tested on Base Sepolia testnet:
- httpx: tx 0xce49f668aba01c4b0b1af2eb0d9a381f4c62295506a91f20af479e0e834ef350
- requests: tx 0xb83b6feefa5a744b7779ba5b37df33f9c7241f58119454d66102acd97a92f024

* Update examples/python/clients/httpx/main.py

Co-authored-by: phdargen <pdargent@icloud.com>

* Update examples/python/clients/requests/main.py

Co-authored-by: phdargen <pdargent@icloud.com>

---------

Co-authored-by: phdargen <pdargent@icloud.com>

* feat(python): Make v2 framework and client dependencies optional extras (#901)

* python-v2: add svm mechanism (#904)

* add svm mechanism

* add unit tests

* add integration tests

* update server examples

* add e2e tests

* update clients

* make EVM/SVM dependencies optional extras

* fix legacy uv paths

* V2 python bazaar (#929)

* add bazaar extension

* strip query params for discovery

* fix 862

* updated e2e tests

* Add advanced Python client examples (#947)

* Add advanced Python client examples

Implements 5 advanced patterns demonstrating x402 SDK v2 features:
- hooks.py: Payment lifecycle hooks (before, after, failure)
- preferred_network.py: Custom network preference selector
- builder_pattern.py: Network-specific registration with wildcards
- error_recovery.py: Error classification and recovery strategies
- custom_transport.py: Custom httpx transport with retry/timing

Includes:
- CLI entry point (index.py) for running examples
- Comprehensive test suite (40 unit tests)
- E2E integration tests
- README documentation

All tests passing.

* Remove tests and examples beyond TypeScript SDK parity

Address PR review feedback:
- Remove tests directory (tests belong in SDK, not examples)
- Remove custom_transport.py (runtime error, beyond TS parity)
- Remove error_recovery.py (duplicate of hooks.py, beyond TS parity)
- Update index.py, README.md, pyproject.toml accordingly

* Address PR feedback: add SVM support and use optional deps

- Update pyproject.toml to use x402[evm,svm,httpx] instead of
  listing dependencies separately
- Add Solana/SVM network examples to preferred_network.py
- Support both EVM and SVM signers for cross-chain flexibility
- Update .env-local with SOLANA_PRIVATE_KEY option

* Python-v2: facilitator example + e2e (#950)

* add facilitator example

* improve svm signer

* add description to DiscoveredResource

* add facilitator e2e

* add paywall builder (#953)

* Add Python custom client example (#954)

Demonstrates manual x402 v2 payment flow without convenience wrappers.

Shows the 6-step process:
1. Initialize client and register payment schemes
2. Make initial request, receive 402
3. Decode PAYMENT-REQUIRED header
4. Create signed payment payload
5. Retry with PAYMENT-SIGNATURE header
6. Handle success/failure response

Useful for integrating with non-standard HTTP libraries or implementing
custom retry logic.

* feat(v2-sdk): support async dynamic hooks for price and metadata (#900)

* feat(http): implement dual class design for sync/async support

- Add x402HTTPResourceServer (async) for FastAPI/Starlette
- Add x402HTTPResourceServerSync (sync) for Flask/Django
- Share common logic via _x402HTTPServerBase
- Remove dynamic description/resource (keep only dynamic price/payTo)
- Update Flask middleware to use sync server directly
- Integrate with enrich_extensions for bazaar support
- Add per-route hook_timeout_seconds configuration

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* fix(types): add missing Awaitable import and fix test import sorting

- Add Awaitable import to types.py for DynamicPayTo/DynamicPrice type hints
- Fix import block sorting in test_async_hooks.py and test_core.py

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* refactor: simplify API by removing unused types and making timeout opt-in

Address reviewer feedback from @phdargen:
- Remove SyncDynamicPayTo/SyncDynamicPrice (unused types that would require SyncPaymentOption to be useful)
- Change hook_timeout_seconds default to None (opt-in, matching TS/Go parity)
- Export x402HTTPResourceServerSync from http/__init__.py

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>

* python-v2: make create_facilitator_config work with both V1 and V2 (#968)

* make create_facilitator_config work with both V1 and V2

* fix lint

* feat: add Python SDK v2 server advanced example (FastAPI) (#952)

* feat - add pyproject.toml, uv.lock for advanced example

* feat - add bazaar extension

* feat - add hooks

* feat - add x402 extensions to pyproject.toml

* feat - add dynamic pricing feature

* feat - add dynamic pay-to and custom money parser features

* docs - add README for advanced server example

* style - apply lint

* chore - add comments for bazaar extension code

* fix: python v2 x402HTTPAdapter retry logic (#978)

* fix: fix consecutive payment bug in x402HTTPAdapter

- Replace instance-level _is_retry flag with per-request header
  to prevent state leakage between consecutive 402 requests.

* tests - add test case for consecutive payment with x402HTTPAdapter

* style - apply lint

* Python-v2: async lifecycle hooks (#975)

* add dual sync/async classes for server/client/facilitator

* update integration/e2e tests

* add unit tests for core, http and implement wrapHttpxWithPaymentFromConfig/wrapRequestsWithPayment

* refactor core server/client/facilitator

* refactor x402_http_server/facilitator_client/x402_http_client

* update exmamples

* add utility function that takes care of html-safe escaping

* add sdk readmes

* add retry unit tests to httpx client

* Update Python SDK Docs for v2 (#976)

* Porting docs and updating for v2 changes (#813)

* porting docs and updating for v2 changes

* update quickstart for sellers

* update quickstarts, miniapps, and mcp docs

* update doc links

* update FAQs

* fix getting started docs

* update core concepts

* remove miniapps guide

* update extensions

* fix bazaar code examples

* fix broken links and yaml file

* remove unnecessary protocol layer doc

* add migration guide

* update documentation for python v2 sdk

* testing pr preview

* docs(python): remove unused os imports and align with TS tab patterns

- Remove unused 'import os' from FastAPI and Flask examples in quickstart-for-sellers
- Update bazaar-discovery-layer Python example to use hardcoded '0xYourPrivateKey' to match TypeScript tab consistency

* update migration doc

* cleanup comments

* cleanup readme

* fix: Python facilitator e2e code

* fix: lint

---------

Co-authored-by: phdargen <p.dargent@cern.ch>
Co-authored-by: somesome <57699892+sohw400@users.noreply.github.com>
Co-authored-by: Logan Kang <kcs93023@gmail.com>
Co-authored-by: 1bcMax <viewitter@gmail.com>
Co-authored-by: phdargen <pdargent@icloud.com>
Co-authored-by: Vladimir Sotnikov <bubert9@gmail.com>
Co-authored-by: Shuhei <shuhei0866@gmail.com>
Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
Co-authored-by: Faris Habib <faris.habib@coinbase.com>
2026-01-21 16:32:07 -08:00
Carson Roscoe
be253a872d
chore: version typescript packages (#944) 2026-01-09 14:27:04 -08:00