* fix(paywall): use dynamic token decimals instead of hardcoding 6
The EVM paywall displays incorrect amounts for any token that does not
use 6 decimal places. An 18-decimal token priced at 0.001 raw units
renders as $1,000,000,000 because the code divides by 10^6 everywhere.
Root cause: the paywall was built assuming USDC (6 decimals) is the
only payment token. This assumption appears in three places:
1. Server-side HTML generation (index.ts) divides the raw amount by
a hardcoded 10^6 to produce the display value injected into the
template.
2. Client-side balance display (EvmPaywall.tsx) calls formatUnits
with a hardcoded 6 and reads the token address from a 3-chain
USDC lookup table that returns 0 for any other chain.
3. The balance utility (utils.ts) only knows USDC addresses on
Ethereum, Base, and Base Sepolia — every other chain silently
shows a zero balance.
Fix:
Server-side (index.ts): look up the token's decimal precision from a
known-decimals map aligned with DEFAULT_STABLECOINS. Only non-6-decimal
chains need entries; everything else falls back to 6. This keeps the
server-side path simple with no RPC calls.
Client-side (EvmPaywall.tsx): read the token contract address from
the payment requirement's `asset` field (which the server already
populates) and query the standard ERC-20 decimals() function on-chain.
This works for any compliant token without maintaining a lookup table.
utils.ts: replace the USDC-specific getUSDCBalance (internal helper,
not part of the public API) with generic getTokenBalance and
getTokenDecimals functions that accept a token address parameter.
The function signature changes from 2 args to 3, but no external
consumer can import it — it is only used by the bundled React
component inside the paywall HTML template.
**Breaking change note:** the internal helper getUSDCBalance in utils.ts
is removed and replaced by getTokenBalance (different signature: takes
an explicit token address instead of looking it up by chain ID). This
function is not exported from the package's public API — it is only
consumed by the bundled EvmPaywall React component inside the paywall
HTML template. No server operator code calls it directly. However,
anyone who has forked the paywall and imports from the file path
(bypassing package exports) would need to update their import and
call site.
Regenerated Go, Python, and TS paywall templates.
**AI disclosure:** This PR was prepared with the assistance of a coding agent and
reviewed by Ryan R. Fox (an actual human) before submission.
* style: ruff format paywall templates
* fix(paywall): use DEFAULT_STABLECOINS lookup + BigInt formatUnits
Removes the parallel KNOWN_DECIMALS map in @x402/paywall/src/evm/index.ts
that mirrored DEFAULT_STABLECOINS from @x402/evm. The paywall now resolves
token decimals through the same registry that scheme implementations and
@x402/core's inline scheme dispatch already read from.
evmPaywall.generateHtml changes:
* getDefaultTokenDecimals helper looks up requirement.network directly in
@x402/evm's DEFAULT_STABLECOINS, with a 6 (USDC default) fallback when
the network is unknown.
* Atomic-to-display conversion uses Number(formatUnits(BigInt(amount),
decimals)) instead of parseFloat(amount) / 10**decimals. parseFloat
silently rounds sub-cent precision on real 18-decimal amounts before
the divide; BigInt + formatUnits preserves precision through the
conversion. BigInt also rejects non-integer atomic strings, which
matches the spec's atomic-integer contract.
@x402/paywall package.json: @x402/evm moves from devDependencies to
dependencies because the new server-side import of DEFAULT_STABLECOINS is
on the runtime path emitted into dist/.
@x402/evm now publicly re-exports DEFAULT_STABLECOINS from
./shared/defaultAssets so consumers can read the canonical default-asset
registry directly. Both @x402/evm and @x402/paywall get a minor bump
for the additive public API.
Adds 6 unit tests:
* getDefaultTokenDecimals returns 18 for Mezo Testnet (registry path)
* getDefaultTokenDecimals returns 6 for Base mainnet, asserted alongside
DEFAULT_STABLECOINS so an empty registry would fail the test
* getDefaultTokenDecimals falls back to 6 for unknown networks
* evmPaywall.generateHtml renders 1e15-atomic Mezo mUSD as
'amount: 0.001,' end-to-end (regression test for the /1e6 bug)
* evmPaywall.generateHtml renders 1e6-atomic Base USDC as 'amount: 1,'
* evmPaywall.generateHtml throws on a non-integer atomic ('1.5'),
pinning the BigInt strictness so a future revert to parseFloat fails
Closes#1979.
* refactor(paywall): generate evm decimals at build time, drop @x402/evm runtime dep
Addresses @phdargen's review: rather than promoting @x402/evm to a
runtime dependency of @x402/paywall, keep it a devDependency and
emit a codegen'd `src/evm/gen/decimals.ts` that mirrors just the
per-network `decimals` field of `DEFAULT_STABLECOINS`.
Pattern-consistent with the existing `src/evm/gen/template.ts` codegen
(HTML bundle) — same build step (`src/evm/build.ts`), same "AUTO-GENERATED
DO NOT EDIT" banner, same commit-the-generated-file workflow. The CI
drift check queued in #2054 (`check_paywall_template.yml`) will pick up
`decimals.ts` under the existing `typescript/packages/http/paywall/**`
trigger glob once that PR merges; in the meantime an in-process drift
invariant test in `network-handlers.test.ts` asserts `NETWORK_DECIMALS`
matches `DEFAULT_STABLECOINS` key-for-key.
Runtime behaviour is unchanged. `getDefaultTokenDecimals` now reads the
generated `NETWORK_DECIMALS` map instead of reading `DEFAULT_STABLECOINS`
at runtime; the same Mezo-18, Base-6, unknown→6 cases still hold, and
the existing 6 regression tests in `network-handlers.test.ts` pass
without modification. A seventh test pins the drift invariant described
above.
package.json: `@x402/evm` moved from `dependencies` to `devDependencies`.
Runtime module graph for `@x402/paywall` no longer pulls `@x402/evm`;
the only surviving `@x402/evm` references in paywall src are:
* `browserAdapter.ts` — `import type { ClientEvmSigner }` (type-only,
erased at build time)
* `EvmPaywall.tsx` — `ExactEvmScheme` (bundled into `gen/template.ts`
by esbuild, not part of the server-side runtime path)
* `build.ts` and `network-handlers.test.ts` — build-time / test-time
consumers; devDep is available in both.
Both the root `typescript/pnpm-lock.yaml` and `examples/typescript/pnpm-lock.yaml`
are updated to reflect the dep move — both workspaces reference the
paywall package manifest via `workspace:~`.
* feat(hedera): add @x402/hedera package with exact payment scheme
- New @x402/hedera package implementing the x402 v2 exact scheme
- Uses @hiero-ledger/sdk for signing and submission
- Onchain preflight transfer check before settlement
- Settlement receipt validation (USDC + HBAR coverage)
- HEDERA_ACCOUNT_ID / HEDERA_PRIVATE_KEY / HEDERA_NETWORK env vars
- Integrated with advanced clients (axios, fetch), facilitators, and HTTP adapters (hono, fastify, next)
- E2E tests for Hono, Next.js, and Fastify servers
- Testnet faucet docs and token association notes
Signed-off-by: Piotr Swierzy <piotr.swierzy@blockydevs.com>
* refactor: use convertToAtomicAmount function from @x402/core/utils
Signed-off-by: Piotr Swierzy <piotr.swierzy@blockydevs.com>
---------
Signed-off-by: Piotr Swierzy <piotr.swierzy@blockydevs.com>
* add mcp discovery support
* ci fixes and changelog
* rename changelog
* fix failing test
* fail in TS on transport mismatch, return extension info on settlement failure in python
* add e2e
* fix mcp payment payload parsing
* fix python parsing
* add transport to examples and docs
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>